ia64/xen-unstable

view tools/ioemu/vl.c @ 10078:345464c2fd47

Allow to specify different time-of-day clock offsets for HVM guests.

There are some usage scenarios in which differing user domains want
to be using different base TOD clocks. This patch adds the ability
to specify the base TOD time difference. The patch also adds a
hook point to notify another entity when the domain changes this
offset. This might occur, for instance, on a Linux domain using
hwclock -w.

Signed-off-by: Ben Thomas <ben@virtualiron.com>
author kaf24@firebug.cl.cam.ac.uk
date Wed May 17 23:43:32 2006 +0100 (2006-05-17)
parents 1b55b85f8cb2
children 61e2ea81bd65
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 "exec-all.h"
80 //#define DO_TB_FLUSH
82 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
84 #if !defined(CONFIG_SOFTMMU)
85 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
86 #else
87 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
88 #endif
90 #ifdef TARGET_PPC
91 #define DEFAULT_RAM_SIZE 144
92 #else
93 #define DEFAULT_RAM_SIZE 128
94 #endif
95 /* in ms */
96 #define GUI_REFRESH_INTERVAL 30
97 #define POLLING_INTERVAL 5
99 /* XXX: use a two level table to limit memory usage */
100 #define MAX_IOPORTS 65536
102 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
103 char phys_ram_file[1024];
104 CPUState *global_env;
105 CPUState *cpu_single_env;
106 void *ioport_opaque[MAX_IOPORTS];
107 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
108 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
109 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
110 int vga_ram_size;
111 int bios_size;
112 static DisplayState display_state;
113 int nographic;
114 int usevnc; /* 1=vnc only, 2=vnc and sdl */
115 long vncport; /* server port */
116 const char* vncconnect; /* do a reverse connect to this host*/
117 const char* keyboard_layout = 0;
118 int64_t ticks_per_sec;
119 int boot_device = 'c';
120 uint64_t ram_size;
121 int domid = -1;
122 static char network_script[1024];
123 int pit_min_timer_count = 0;
124 int nb_nics;
125 char bridge[16];
126 char domain_name[1024] = { 'H','V', 'M', 'X', 'E', 'N', '-'};
127 NetDriverState nd_table[MAX_NICS];
128 QEMUTimer *gui_timer;
129 QEMUTimer *polling_timer;
130 int vm_running;
131 int audio_enabled = 0;
132 int nic_ne2000 = 0;
133 int vcpus = 1;
134 int sb16_enabled = 1;
135 int adlib_enabled = 1;
136 int gus_enabled = 1;
137 int pci_enabled = 1;
138 int prep_enabled = 0;
139 int rtc_utc = 1;
140 int cirrus_vga_enabled = 1;
141 int vga_accelerate = 1;
142 int graphic_width = 800;
143 int graphic_height = 600;
144 int graphic_depth = 15;
145 int full_screen = 0;
146 int repeat_key = 1;
147 TextConsole *vga_console;
148 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
149 int xc_handle;
150 time_t timeoffset = 0;
152 /***********************************************************/
153 /* x86 ISA bus support */
155 target_phys_addr_t isa_mem_base = 0;
157 uint32_t default_ioport_readb(void *opaque, uint32_t address)
158 {
159 #ifdef DEBUG_UNUSED_IOPORT
160 fprintf(stderr, "inb: port=0x%04x\n", address);
161 #endif
162 return 0xff;
163 }
165 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
166 {
167 #ifdef DEBUG_UNUSED_IOPORT
168 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
169 #endif
170 }
172 /* default is to make two byte accesses */
173 uint32_t default_ioport_readw(void *opaque, uint32_t address)
174 {
175 uint32_t data;
176 data = ioport_read_table[0][address](ioport_opaque[address], address);
177 address = (address + 1) & (MAX_IOPORTS - 1);
178 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
179 return data;
180 }
182 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
183 {
184 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
185 address = (address + 1) & (MAX_IOPORTS - 1);
186 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
187 }
189 uint32_t default_ioport_readl(void *opaque, uint32_t address)
190 {
191 #ifdef DEBUG_UNUSED_IOPORT
192 fprintf(stderr, "inl: port=0x%04x\n", address);
193 #endif
194 return 0xffffffff;
195 }
197 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
198 {
199 #ifdef DEBUG_UNUSED_IOPORT
200 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
201 #endif
202 }
204 void init_ioports(void)
205 {
206 int i;
208 for(i = 0; i < MAX_IOPORTS; i++) {
209 ioport_read_table[0][i] = default_ioport_readb;
210 ioport_write_table[0][i] = default_ioport_writeb;
211 ioport_read_table[1][i] = default_ioport_readw;
212 ioport_write_table[1][i] = default_ioport_writew;
213 ioport_read_table[2][i] = default_ioport_readl;
214 ioport_write_table[2][i] = default_ioport_writel;
215 }
216 }
218 /* size is the word size in byte */
219 int register_ioport_read(int start, int length, int size,
220 IOPortReadFunc *func, void *opaque)
221 {
222 int i, bsize;
224 if (size == 1) {
225 bsize = 0;
226 } else if (size == 2) {
227 bsize = 1;
228 } else if (size == 4) {
229 bsize = 2;
230 } else {
231 hw_error("register_ioport_read: invalid size");
232 return -1;
233 }
234 for(i = start; i < start + length; i += size) {
235 ioport_read_table[bsize][i] = func;
236 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
237 hw_error("register_ioport_read: invalid opaque");
238 ioport_opaque[i] = opaque;
239 }
240 return 0;
241 }
243 /* size is the word size in byte */
244 int register_ioport_write(int start, int length, int size,
245 IOPortWriteFunc *func, void *opaque)
246 {
247 int i, bsize;
249 if (size == 1) {
250 bsize = 0;
251 } else if (size == 2) {
252 bsize = 1;
253 } else if (size == 4) {
254 bsize = 2;
255 } else {
256 hw_error("register_ioport_write: invalid size");
257 return -1;
258 }
259 for(i = start; i < start + length; i += size) {
260 ioport_write_table[bsize][i] = func;
261 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
262 hw_error("register_ioport_read: invalid opaque");
263 ioport_opaque[i] = opaque;
264 }
265 return 0;
266 }
268 void isa_unassign_ioport(int start, int length)
269 {
270 int i;
272 for(i = start; i < start + length; i++) {
273 ioport_read_table[0][i] = default_ioport_readb;
274 ioport_read_table[1][i] = default_ioport_readw;
275 ioport_read_table[2][i] = default_ioport_readl;
277 ioport_write_table[0][i] = default_ioport_writeb;
278 ioport_write_table[1][i] = default_ioport_writew;
279 ioport_write_table[2][i] = default_ioport_writel;
280 }
281 }
283 void pstrcpy(char *buf, int buf_size, const char *str)
284 {
285 int c;
286 char *q = buf;
288 if (buf_size <= 0)
289 return;
291 for(;;) {
292 c = *str++;
293 if (c == 0 || q >= buf + buf_size - 1)
294 break;
295 *q++ = c;
296 }
297 *q = '\0';
298 }
300 /* strcat and truncate. */
301 char *pstrcat(char *buf, int buf_size, const char *s)
302 {
303 int len;
304 len = strlen(buf);
305 if (len < buf_size)
306 pstrcpy(buf + len, buf_size - len, s);
307 return buf;
308 }
310 int strstart(const char *str, const char *val, const char **ptr)
311 {
312 const char *p, *q;
313 p = str;
314 q = val;
315 while (*q != '\0') {
316 if (*p != *q)
317 return 0;
318 p++;
319 q++;
320 }
321 if (ptr)
322 *ptr = p;
323 return 1;
324 }
326 /* return the size or -1 if error */
327 int get_image_size(const char *filename)
328 {
329 int fd, size;
330 fd = open(filename, O_RDONLY | O_BINARY);
331 if (fd < 0)
332 return -1;
333 size = lseek(fd, 0, SEEK_END);
334 close(fd);
335 return size;
336 }
338 /* return the size or -1 if error */
339 int load_image(const char *filename, uint8_t *addr)
340 {
341 int fd, size;
342 fd = open(filename, O_RDONLY | O_BINARY);
343 if (fd < 0)
344 return -1;
345 size = lseek(fd, 0, SEEK_END);
346 lseek(fd, 0, SEEK_SET);
347 if (read(fd, addr, size) != size) {
348 close(fd);
349 return -1;
350 }
351 close(fd);
352 return size;
353 }
355 void cpu_outb(CPUState *env, int addr, int val)
356 {
357 #ifdef DEBUG_IOPORT
358 if (loglevel & CPU_LOG_IOPORT)
359 fprintf(logfile, "outb: %04x %02x\n", addr, val);
360 #endif
361 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
362 }
364 void cpu_outw(CPUState *env, int addr, int val)
365 {
366 #ifdef DEBUG_IOPORT
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outw: %04x %04x\n", addr, val);
369 #endif
370 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
371 }
373 void cpu_outl(CPUState *env, int addr, int val)
374 {
375 #ifdef DEBUG_IOPORT
376 if (loglevel & CPU_LOG_IOPORT)
377 fprintf(logfile, "outl: %04x %08x\n", addr, val);
378 #endif
379 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
380 }
382 int cpu_inb(CPUState *env, int addr)
383 {
384 int val;
385 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
386 #ifdef DEBUG_IOPORT
387 if (loglevel & CPU_LOG_IOPORT)
388 fprintf(logfile, "inb : %04x %02x\n", addr, val);
389 #endif
390 return val;
391 }
393 int cpu_inw(CPUState *env, int addr)
394 {
395 int val;
396 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
397 #ifdef DEBUG_IOPORT
398 if (loglevel & CPU_LOG_IOPORT)
399 fprintf(logfile, "inw : %04x %04x\n", addr, val);
400 #endif
401 return val;
402 }
404 int cpu_inl(CPUState *env, int addr)
405 {
406 int val;
407 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
408 #ifdef DEBUG_IOPORT
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "inl : %04x %08x\n", addr, val);
411 #endif
412 return val;
413 }
415 /***********************************************************/
416 void hw_error(const char *fmt, ...)
417 {
418 va_list ap;
420 va_start(ap, fmt);
421 fprintf(stderr, "qemu: hardware error: ");
422 vfprintf(stderr, fmt, ap);
423 fprintf(stderr, "\n");
424 if (logfile) {
425 fprintf(logfile, "qemu: hardware error: ");
426 vfprintf(logfile, fmt, ap);
427 fprintf(logfile, "\n");
428 }
429 va_end(ap);
430 abort();
431 }
433 /***********************************************************/
434 /* keyboard/mouse */
436 static QEMUPutKBDEvent *qemu_put_kbd_event;
437 static void *qemu_put_kbd_event_opaque;
438 static QEMUPutMouseEvent *qemu_put_mouse_event;
439 static void *qemu_put_mouse_event_opaque;
441 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
442 {
443 qemu_put_kbd_event_opaque = opaque;
444 qemu_put_kbd_event = func;
445 }
447 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
448 {
449 qemu_put_mouse_event_opaque = opaque;
450 qemu_put_mouse_event = func;
451 }
453 void kbd_put_keycode(int keycode)
454 {
455 if (qemu_put_kbd_event) {
456 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
457 }
458 }
460 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state, int x, int y)
461 {
462 if (qemu_put_mouse_event) {
463 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
464 dx, dy, dz, buttons_state, x, y);
465 }
466 }
468 /***********************************************************/
469 /* timers */
471 #if defined(__powerpc__)
473 static inline uint32_t get_tbl(void)
474 {
475 uint32_t tbl;
476 asm volatile("mftb %0" : "=r" (tbl));
477 return tbl;
478 }
480 static inline uint32_t get_tbu(void)
481 {
482 uint32_t tbl;
483 asm volatile("mftbu %0" : "=r" (tbl));
484 return tbl;
485 }
487 int64_t cpu_get_real_ticks(void)
488 {
489 uint32_t l, h, h1;
490 /* NOTE: we test if wrapping has occurred */
491 do {
492 h = get_tbu();
493 l = get_tbl();
494 h1 = get_tbu();
495 } while (h != h1);
496 return ((int64_t)h << 32) | l;
497 }
499 #elif defined(__i386__)
501 int64_t cpu_get_real_ticks(void)
502 {
503 int64_t val;
504 asm volatile ("rdtsc" : "=A" (val));
505 return val;
506 }
508 #elif defined(__x86_64__)
510 int64_t cpu_get_real_ticks(void)
511 {
512 uint32_t low,high;
513 int64_t val;
514 asm volatile("rdtsc" : "=a" (low), "=d" (high));
515 val = high;
516 val <<= 32;
517 val |= low;
518 return val;
519 }
521 #elif defined(__ia64__)
522 #include "ia64_intrinsic.h"
523 #define cpu_get_real_ticks() \
524 __ia64_getreg(_IA64_REG_AR_ITC)
526 #else
527 #error unsupported CPU
528 #endif
530 static int64_t cpu_ticks_offset;
531 static int cpu_ticks_enabled;
532 int64_t cpu_virt_tsc;
534 static inline int64_t cpu_get_ticks(void)
535 {
536 if (!cpu_ticks_enabled) {
537 return cpu_ticks_offset;
538 } else {
539 return cpu_get_real_ticks() + cpu_ticks_offset;
540 }
542 }
544 /* enable cpu_get_ticks() */
545 void cpu_enable_ticks(void)
546 {
547 if (!cpu_ticks_enabled) {
548 cpu_ticks_offset -= cpu_get_real_ticks();
549 cpu_ticks_enabled = 1;
550 }
551 }
553 /* disable cpu_get_ticks() : the clock is stopped. You must not call
554 cpu_get_ticks() after that. */
555 void cpu_disable_ticks(void)
556 {
557 if (cpu_ticks_enabled) {
558 cpu_ticks_offset = cpu_get_ticks();
559 cpu_ticks_enabled = 0;
560 }
561 }
563 static int64_t get_clock(void)
564 {
565 #ifdef _WIN32
566 struct _timeb tb;
567 _ftime(&tb);
568 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
569 #else
570 struct timeval tv;
571 gettimeofday(&tv, NULL);
572 return tv.tv_sec * 1000000LL + tv.tv_usec;
573 #endif
574 }
576 void cpu_calibrate_ticks(void)
577 {
578 int64_t usec, ticks;
580 usec = get_clock();
581 ticks = cpu_get_real_ticks();
582 #ifdef _WIN32
583 Sleep(50);
584 #else
585 usleep(50 * 1000);
586 #endif
587 usec = get_clock() - usec;
588 ticks = cpu_get_real_ticks() - ticks;
589 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
590 }
592 /* compute with 96 bit intermediate result: (a*b)/c */
593 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
594 {
595 union {
596 uint64_t ll;
597 struct {
598 #ifdef WORDS_BIGENDIAN
599 uint32_t high, low;
600 #else
601 uint32_t low, high;
602 #endif
603 } l;
604 } u, res;
605 uint64_t rl, rh;
607 u.ll = a;
608 rl = (uint64_t)u.l.low * (uint64_t)b;
609 rh = (uint64_t)u.l.high * (uint64_t)b;
610 rh += (rl >> 32);
611 res.l.high = rh / c;
612 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
613 return res.ll;
614 }
616 #define QEMU_TIMER_REALTIME 0
617 #define QEMU_TIMER_VIRTUAL 1
619 struct QEMUClock {
620 int type;
621 /* XXX: add frequency */
622 };
624 struct QEMUTimer {
625 QEMUClock *clock;
626 int64_t expire_time;
627 QEMUTimerCB *cb;
628 void *opaque;
629 struct QEMUTimer *next;
630 };
632 QEMUClock *rt_clock;
633 QEMUClock *vm_clock;
635 static QEMUTimer *active_timers[2];
636 #ifdef _WIN32
637 static MMRESULT timerID;
638 #else
639 /* frequency of the times() clock tick */
640 static int timer_freq;
641 #endif
643 QEMUClock *qemu_new_clock(int type)
644 {
645 QEMUClock *clock;
646 clock = qemu_mallocz(sizeof(QEMUClock));
647 if (!clock)
648 return NULL;
649 clock->type = type;
650 return clock;
651 }
653 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
654 {
655 QEMUTimer *ts;
657 ts = qemu_mallocz(sizeof(QEMUTimer));
658 ts->clock = clock;
659 ts->cb = cb;
660 ts->opaque = opaque;
661 return ts;
662 }
664 void qemu_free_timer(QEMUTimer *ts)
665 {
666 qemu_free(ts);
667 }
669 /* stop a timer, but do not dealloc it */
670 void qemu_del_timer(QEMUTimer *ts)
671 {
672 QEMUTimer **pt, *t;
674 /* NOTE: this code must be signal safe because
675 qemu_timer_expired() can be called from a signal. */
676 pt = &active_timers[ts->clock->type];
677 for(;;) {
678 t = *pt;
679 if (!t)
680 break;
681 if (t == ts) {
682 *pt = t->next;
683 break;
684 }
685 pt = &t->next;
686 }
687 }
689 /* modify the current timer so that it will be fired when current_time
690 >= expire_time. The corresponding callback will be called. */
691 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
692 {
693 QEMUTimer **pt, *t;
695 qemu_del_timer(ts);
697 /* add the timer in the sorted list */
698 /* NOTE: this code must be signal safe because
699 qemu_timer_expired() can be called from a signal. */
700 pt = &active_timers[ts->clock->type];
701 for(;;) {
702 t = *pt;
703 if (!t)
704 break;
705 if (t->expire_time > expire_time)
706 break;
707 pt = &t->next;
708 }
709 ts->expire_time = expire_time;
710 ts->next = *pt;
711 *pt = ts;
712 }
714 int qemu_timer_pending(QEMUTimer *ts)
715 {
716 QEMUTimer *t;
717 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
718 if (t == ts)
719 return 1;
720 }
721 return 0;
722 }
724 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
725 {
726 if (!timer_head)
727 return 0;
728 return (timer_head->expire_time <= current_time);
729 }
731 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
732 {
733 QEMUTimer *ts;
735 for(;;) {
736 ts = *ptimer_head;
737 if (!ts || ts->expire_time > current_time)
738 break;
739 /* remove timer from the list before calling the callback */
740 *ptimer_head = ts->next;
741 ts->next = NULL;
743 /* run the callback (the timer list can be modified) */
744 ts->cb(ts->opaque);
745 }
746 }
748 int64_t qemu_get_clock(QEMUClock *clock)
749 {
750 switch(clock->type) {
751 case QEMU_TIMER_REALTIME:
752 #ifdef _WIN32
753 return GetTickCount();
754 #else
755 {
756 struct tms tp;
758 /* Note that using gettimeofday() is not a good solution
759 for timers because its value change when the date is
760 modified. */
761 if (timer_freq == 100) {
762 return times(&tp) * 10;
763 } else {
764 return ((int64_t)times(&tp) * 1000) / timer_freq;
765 }
766 }
767 #endif
768 default:
769 case QEMU_TIMER_VIRTUAL:
770 return cpu_get_ticks();
771 }
772 }
774 /* save a timer */
775 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
776 {
777 uint64_t expire_time;
779 if (qemu_timer_pending(ts)) {
780 expire_time = ts->expire_time;
781 } else {
782 expire_time = -1;
783 }
784 qemu_put_be64(f, expire_time);
785 }
787 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
788 {
789 uint64_t expire_time;
791 expire_time = qemu_get_be64(f);
792 if (expire_time != -1) {
793 qemu_mod_timer(ts, expire_time);
794 } else {
795 qemu_del_timer(ts);
796 }
797 }
799 static void init_timers(void)
800 {
801 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
802 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
804 #ifdef _WIN32
805 {
806 int count=0;
807 timerID = timeSetEvent(10, // interval (ms)
808 0, // resolution
809 host_alarm_handler, // function
810 (DWORD)&count, // user parameter
811 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
812 if( !timerID ) {
813 fprintf(logfile, "failed timer alarm");
814 exit(1);
815 }
816 }
817 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
818 #else
819 {
820 /* get times() syscall frequency */
821 timer_freq = sysconf(_SC_CLK_TCK);
823 #ifndef TARGET_HVM
824 /* timer signal */
825 sigfillset(&act.sa_mask);
826 act.sa_flags = 0;
827 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
828 act.sa_flags |= SA_ONSTACK;
829 #endif
830 act.sa_handler = host_alarm_handler;
831 sigaction(SIGALRM, &act, NULL);
833 itv.it_interval.tv_sec = 0;
834 itv.it_interval.tv_usec = 1000;
835 itv.it_value.tv_sec = 0;
836 itv.it_value.tv_usec = 10 * 1000;
837 setitimer(ITIMER_REAL, &itv, NULL);
838 /* we probe the tick duration of the kernel to inform the user if
839 the emulated kernel requested a too high timer frequency */
840 getitimer(ITIMER_REAL, &itv);
842 #if defined(__linux__)
843 if (itv.it_interval.tv_usec > 1000) {
844 /* try to use /dev/rtc to have a faster timer */
845 if (start_rtc_timer() < 0)
846 goto use_itimer;
847 /* disable itimer */
848 itv.it_interval.tv_sec = 0;
849 itv.it_interval.tv_usec = 0;
850 itv.it_value.tv_sec = 0;
851 itv.it_value.tv_usec = 0;
852 setitimer(ITIMER_REAL, &itv, NULL);
854 /* use the RTC */
855 sigaction(SIGIO, &act, NULL);
856 fcntl(rtc_fd, F_SETFL, O_ASYNC);
857 fcntl(rtc_fd, F_SETOWN, getpid());
858 } else
859 #endif /* defined(__linux__) */
860 {
861 use_itimer:
862 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
863 PIT_FREQ) / 1000000;
864 }
865 #endif /* TARGET_HVM */
866 }
867 #endif
868 }
870 void quit_timers(void)
871 {
872 #ifdef _WIN32
873 timeKillEvent(timerID);
874 #endif
875 }
877 /***********************************************************/
878 /* character device */
880 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
881 {
882 return s->chr_write(s, buf, len);
883 }
885 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
886 {
887 char buf[4096];
888 va_list ap;
889 va_start(ap, fmt);
890 vsnprintf(buf, sizeof(buf), fmt, ap);
891 qemu_chr_write(s, buf, strlen(buf));
892 va_end(ap);
893 }
895 void qemu_chr_send_event(CharDriverState *s, int event)
896 {
897 if (s->chr_send_event)
898 s->chr_send_event(s, event);
899 }
901 void qemu_chr_add_read_handler(CharDriverState *s,
902 IOCanRWHandler *fd_can_read,
903 IOReadHandler *fd_read, void *opaque)
904 {
905 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
906 }
908 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
909 {
910 s->chr_event = chr_event;
911 }
913 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
914 {
915 return len;
916 }
918 static void null_chr_add_read_handler(CharDriverState *chr,
919 IOCanRWHandler *fd_can_read,
920 IOReadHandler *fd_read, void *opaque)
921 {
922 }
924 CharDriverState *qemu_chr_open_null(void)
925 {
926 CharDriverState *chr;
928 chr = qemu_mallocz(sizeof(CharDriverState));
929 if (!chr)
930 return NULL;
931 chr->chr_write = null_chr_write;
932 chr->chr_add_read_handler = null_chr_add_read_handler;
933 return chr;
934 }
936 #ifndef _WIN32
938 typedef struct {
939 int fd_in, fd_out;
940 /* for nographic stdio only */
941 IOCanRWHandler *fd_can_read;
942 IOReadHandler *fd_read;
943 void *fd_opaque;
944 } FDCharDriver;
946 #define STDIO_MAX_CLIENTS 2
948 static int stdio_nb_clients;
949 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
951 static int unix_write(int fd, const uint8_t *buf, int len1)
952 {
953 int ret,sel_ret,len;
954 int max_fd;
955 fd_set writefds;
956 struct timeval timeout;
958 max_fd = fd;
960 len = len1;
961 while (len > 0) {
962 FD_ZERO(&writefds);
963 FD_SET(fd, &writefds);
964 timeout.tv_sec = 0;
965 timeout.tv_usec = 0;
966 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
967 if (sel_ret <= 0) {
968 /* Timeout or select error */
969 return -1;
970 } else {
971 ret = write(fd, buf, len);
972 if (ret < 0) {
973 if (errno != EINTR && errno != EAGAIN)
974 return -1;
975 } else if (ret == 0) {
976 break;
977 } else {
978 buf += ret;
979 len -= ret;
980 }
981 }
982 }
983 return len1 - len;
984 }
986 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
987 {
988 FDCharDriver *s = chr->opaque;
989 return unix_write(s->fd_out, buf, len);
990 }
992 static void fd_chr_add_read_handler(CharDriverState *chr,
993 IOCanRWHandler *fd_can_read,
994 IOReadHandler *fd_read, void *opaque)
995 {
996 FDCharDriver *s = chr->opaque;
998 if (nographic && s->fd_in == 0) {
999 s->fd_can_read = fd_can_read;
1000 s->fd_read = fd_read;
1001 s->fd_opaque = opaque;
1002 } else {
1003 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1007 /* open a character device to a unix fd */
1008 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1010 CharDriverState *chr;
1011 FDCharDriver *s;
1013 chr = qemu_mallocz(sizeof(CharDriverState));
1014 if (!chr)
1015 return NULL;
1016 s = qemu_mallocz(sizeof(FDCharDriver));
1017 if (!s) {
1018 free(chr);
1019 return NULL;
1021 s->fd_in = fd_in;
1022 s->fd_out = fd_out;
1023 chr->opaque = s;
1024 chr->chr_write = fd_chr_write;
1025 chr->chr_add_read_handler = fd_chr_add_read_handler;
1026 return chr;
1029 /* for STDIO, we handle the case where several clients use it
1030 (nographic mode) */
1032 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1034 static int term_got_escape, client_index;
1036 void term_print_help(void)
1038 printf("\n"
1039 "C-a h print this help\n"
1040 "C-a x exit emulator\n"
1041 "C-a s save disk data back to file (if -snapshot)\n"
1042 "C-a b send break (magic sysrq)\n"
1043 "C-a c switch between console and monitor\n"
1044 "C-a C-a send C-a\n"
1045 );
1048 /* called when a char is received */
1049 static void stdio_received_byte(int ch)
1051 if (term_got_escape) {
1052 term_got_escape = 0;
1053 switch(ch) {
1054 case 'h':
1055 term_print_help();
1056 break;
1057 case 'x':
1058 exit(0);
1059 break;
1060 case 's':
1062 int i;
1063 for (i = 0; i < MAX_DISKS; i++) {
1064 if (bs_table[i])
1065 bdrv_commit(bs_table[i]);
1068 break;
1069 case 'b':
1070 if (client_index < stdio_nb_clients) {
1071 CharDriverState *chr;
1072 FDCharDriver *s;
1074 chr = stdio_clients[client_index];
1075 s = chr->opaque;
1076 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1078 break;
1079 case 'c':
1080 client_index++;
1081 if (client_index >= stdio_nb_clients)
1082 client_index = 0;
1083 if (client_index == 0) {
1084 /* send a new line in the monitor to get the prompt */
1085 ch = '\r';
1086 goto send_char;
1088 break;
1089 case TERM_ESCAPE:
1090 goto send_char;
1092 } else if (ch == TERM_ESCAPE) {
1093 term_got_escape = 1;
1094 } else {
1095 send_char:
1096 if (client_index < stdio_nb_clients) {
1097 uint8_t buf[1];
1098 CharDriverState *chr;
1099 FDCharDriver *s;
1101 chr = stdio_clients[client_index];
1102 s = chr->opaque;
1103 buf[0] = ch;
1104 /* XXX: should queue the char if the device is not
1105 ready */
1106 if (s->fd_can_read(s->fd_opaque) > 0)
1107 s->fd_read(s->fd_opaque, buf, 1);
1112 static int stdio_can_read(void *opaque)
1114 /* XXX: not strictly correct */
1115 return 1;
1118 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1120 int i;
1121 for(i = 0; i < size; i++)
1122 stdio_received_byte(buf[i]);
1125 /* init terminal so that we can grab keys */
1126 static struct termios oldtty;
1127 static int old_fd0_flags;
1129 static void term_exit(void)
1131 tcsetattr (0, TCSANOW, &oldtty);
1132 fcntl(0, F_SETFL, old_fd0_flags);
1135 static void term_init(void)
1137 struct termios tty;
1139 tcgetattr (0, &tty);
1140 oldtty = tty;
1141 old_fd0_flags = fcntl(0, F_GETFL);
1143 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1144 |INLCR|IGNCR|ICRNL|IXON);
1145 tty.c_oflag |= OPOST;
1146 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1147 /* if graphical mode, we allow Ctrl-C handling */
1148 if (nographic)
1149 tty.c_lflag &= ~ISIG;
1150 tty.c_cflag &= ~(CSIZE|PARENB);
1151 tty.c_cflag |= CS8;
1152 tty.c_cc[VMIN] = 1;
1153 tty.c_cc[VTIME] = 0;
1155 tcsetattr (0, TCSANOW, &tty);
1157 atexit(term_exit);
1159 fcntl(0, F_SETFL, O_NONBLOCK);
1162 CharDriverState *qemu_chr_open_stdio(void)
1164 CharDriverState *chr;
1166 if (nographic) {
1167 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1168 return NULL;
1169 chr = qemu_chr_open_fd(0, 1);
1170 if (stdio_nb_clients == 0)
1171 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1172 client_index = stdio_nb_clients;
1173 } else {
1174 if (stdio_nb_clients != 0)
1175 return NULL;
1176 chr = qemu_chr_open_fd(0, 1);
1178 stdio_clients[stdio_nb_clients++] = chr;
1179 if (stdio_nb_clients == 1) {
1180 /* set the terminal in raw mode */
1181 term_init();
1183 return chr;
1186 int store_console_dev(int domid, char *pts)
1188 int xc_handle;
1189 struct xs_handle *xs;
1190 char *path;
1192 xs = xs_daemon_open();
1193 if (xs == NULL) {
1194 fprintf(logfile, "Could not contact XenStore\n");
1195 return -1;
1198 xc_handle = xc_interface_open();
1199 if (xc_handle == -1) {
1200 fprintf(logfile, "xc_interface_open() error\n");
1201 return -1;
1204 path = xs_get_domain_path(xs, domid);
1205 if (path == NULL) {
1206 fprintf(logfile, "xs_get_domain_path() error\n");
1207 return -1;
1209 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1210 if (path == NULL) {
1211 fprintf(logfile, "realloc error\n");
1212 return -1;
1214 strcat(path, "/console/tty");
1215 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1216 fprintf(logfile, "xs_write for console fail");
1217 return -1;
1220 free(path);
1221 xs_daemon_close(xs);
1222 close(xc_handle);
1224 return 0;
1227 #if defined(__linux__)
1228 CharDriverState *qemu_chr_open_pty(void)
1230 int master_fd, slave_fd;
1231 struct termios term;
1233 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0)
1234 return NULL;
1236 /* Set raw attributes on the pty. */
1237 cfmakeraw(&term);
1238 tcsetattr(slave_fd, TCSAFLUSH, &term);
1240 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1241 store_console_dev(domid, ptsname(master_fd));
1243 return qemu_chr_open_fd(master_fd, master_fd);
1245 #else
1246 CharDriverState *qemu_chr_open_pty(void)
1248 return NULL;
1250 #endif
1252 #endif /* !defined(_WIN32) */
1254 CharDriverState *qemu_chr_open(const char *filename)
1256 if (!strcmp(filename, "vc")) {
1257 return text_console_init(&display_state);
1258 } else if (!strcmp(filename, "null")) {
1259 return qemu_chr_open_null();
1260 } else
1261 #ifndef _WIN32
1262 if (!strcmp(filename, "pty")) {
1263 return qemu_chr_open_pty();
1264 } else if (!strcmp(filename, "stdio")) {
1265 return qemu_chr_open_stdio();
1266 } else
1267 #endif
1269 return NULL;
1273 /***********************************************************/
1274 /* Linux network device redirectors */
1276 void hex_dump(FILE *f, const uint8_t *buf, int size)
1278 int len, i, j, c;
1280 for(i=0;i<size;i+=16) {
1281 len = size - i;
1282 if (len > 16)
1283 len = 16;
1284 fprintf(f, "%08x ", i);
1285 for(j=0;j<16;j++) {
1286 if (j < len)
1287 fprintf(f, " %02x", buf[i+j]);
1288 else
1289 fprintf(f, " ");
1291 fprintf(f, " ");
1292 for(j=0;j<len;j++) {
1293 c = buf[i+j];
1294 if (c < ' ' || c > '~')
1295 c = '.';
1296 fprintf(f, "%c", c);
1298 fprintf(f, "\n");
1302 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1304 nd->send_packet(nd, buf, size);
1307 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1308 IOReadHandler *fd_read, void *opaque)
1310 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1313 /* dummy network adapter */
1315 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1319 static void dummy_add_read_packet(NetDriverState *nd,
1320 IOCanRWHandler *fd_can_read,
1321 IOReadHandler *fd_read, void *opaque)
1325 static int net_dummy_init(NetDriverState *nd)
1327 nd->send_packet = dummy_send_packet;
1328 nd->add_read_packet = dummy_add_read_packet;
1329 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1330 return 0;
1333 #if defined(CONFIG_SLIRP)
1335 /* slirp network adapter */
1337 static void *slirp_fd_opaque;
1338 static IOCanRWHandler *slirp_fd_can_read;
1339 static IOReadHandler *slirp_fd_read;
1340 static int slirp_inited;
1342 int slirp_can_output(void)
1344 return slirp_fd_can_read(slirp_fd_opaque);
1347 void slirp_output(const uint8_t *pkt, int pkt_len)
1349 #if 0
1350 printf("output:\n");
1351 hex_dump(stdout, pkt, pkt_len);
1352 #endif
1353 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1356 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1358 #if 0
1359 printf("input:\n");
1360 hex_dump(stdout, buf, size);
1361 #endif
1362 slirp_input(buf, size);
1365 static void slirp_add_read_packet(NetDriverState *nd,
1366 IOCanRWHandler *fd_can_read,
1367 IOReadHandler *fd_read, void *opaque)
1369 slirp_fd_opaque = opaque;
1370 slirp_fd_can_read = fd_can_read;
1371 slirp_fd_read = fd_read;
1374 static int net_slirp_init(NetDriverState *nd)
1376 if (!slirp_inited) {
1377 slirp_inited = 1;
1378 slirp_init();
1380 nd->send_packet = slirp_send_packet;
1381 nd->add_read_packet = slirp_add_read_packet;
1382 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1383 return 0;
1386 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1388 const char *p, *p1;
1389 int len;
1390 p = *pp;
1391 p1 = strchr(p, sep);
1392 if (!p1)
1393 return -1;
1394 len = p1 - p;
1395 p1++;
1396 if (buf_size > 0) {
1397 if (len > buf_size - 1)
1398 len = buf_size - 1;
1399 memcpy(buf, p, len);
1400 buf[len] = '\0';
1402 *pp = p1;
1403 return 0;
1406 static void net_slirp_redir(const char *redir_str)
1408 int is_udp;
1409 char buf[256], *r;
1410 const char *p;
1411 struct in_addr guest_addr;
1412 int host_port, guest_port;
1414 if (!slirp_inited) {
1415 slirp_inited = 1;
1416 slirp_init();
1419 p = redir_str;
1420 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1421 goto fail;
1422 if (!strcmp(buf, "tcp")) {
1423 is_udp = 0;
1424 } else if (!strcmp(buf, "udp")) {
1425 is_udp = 1;
1426 } else {
1427 goto fail;
1430 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1431 goto fail;
1432 host_port = strtol(buf, &r, 0);
1433 if (r == buf)
1434 goto fail;
1436 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1437 goto fail;
1438 if (buf[0] == '\0') {
1439 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1441 if (!inet_aton(buf, &guest_addr))
1442 goto fail;
1444 guest_port = strtol(p, &r, 0);
1445 if (r == p)
1446 goto fail;
1448 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1449 fprintf(stderr, "qemu: could not set up redirection\n");
1450 exit(1);
1452 return;
1453 fail:
1454 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1455 exit(1);
1458 #ifndef _WIN32
1460 char smb_dir[1024];
1462 static void smb_exit(void)
1464 DIR *d;
1465 struct dirent *de;
1466 char filename[1024];
1468 /* erase all the files in the directory */
1469 d = opendir(smb_dir);
1470 for(;;) {
1471 de = readdir(d);
1472 if (!de)
1473 break;
1474 if (strcmp(de->d_name, ".") != 0 &&
1475 strcmp(de->d_name, "..") != 0) {
1476 snprintf(filename, sizeof(filename), "%s/%s",
1477 smb_dir, de->d_name);
1478 unlink(filename);
1481 closedir(d);
1482 rmdir(smb_dir);
1485 /* automatic user mode samba server configuration */
1486 void net_slirp_smb(const char *exported_dir)
1488 char smb_conf[1024];
1489 char smb_cmdline[1024];
1490 FILE *f;
1492 if (!slirp_inited) {
1493 slirp_inited = 1;
1494 slirp_init();
1497 /* XXX: better tmp dir construction */
1498 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1499 if (mkdir(smb_dir, 0700) < 0) {
1500 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1501 exit(1);
1503 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1505 f = fopen(smb_conf, "w");
1506 if (!f) {
1507 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1508 exit(1);
1510 fprintf(f,
1511 "[global]\n"
1512 "pid directory=%s\n"
1513 "lock directory=%s\n"
1514 "log file=%s/log.smbd\n"
1515 "smb passwd file=%s/smbpasswd\n"
1516 "security = share\n"
1517 "[qemu]\n"
1518 "path=%s\n"
1519 "read only=no\n"
1520 "guest ok=yes\n",
1521 smb_dir,
1522 smb_dir,
1523 smb_dir,
1524 smb_dir,
1525 exported_dir
1526 );
1527 fclose(f);
1528 atexit(smb_exit);
1530 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1531 smb_conf);
1533 slirp_add_exec(0, smb_cmdline, 4, 139);
1536 #endif /* !defined(_WIN32) */
1538 #endif /* CONFIG_SLIRP */
1540 #if !defined(_WIN32)
1541 #ifdef _BSD
1542 static int tun_open(char *ifname, int ifname_size)
1544 int fd;
1545 char *dev;
1546 struct stat s;
1548 fd = open("/dev/tap", O_RDWR);
1549 if (fd < 0) {
1550 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1551 return -1;
1554 fstat(fd, &s);
1555 dev = devname(s.st_rdev, S_IFCHR);
1556 pstrcpy(ifname, ifname_size, dev);
1558 fcntl(fd, F_SETFL, O_NONBLOCK);
1559 return fd;
1561 #else
1562 static int tun_open(char *ifname, int ifname_size)
1564 struct ifreq ifr;
1565 int fd, ret;
1567 fd = open("/dev/net/tun", O_RDWR);
1568 if (fd < 0) {
1569 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1570 return -1;
1572 memset(&ifr, 0, sizeof(ifr));
1573 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1574 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1575 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1576 if (ret != 0) {
1577 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1578 close(fd);
1579 return -1;
1581 fprintf(logfile, "Connected to host network interface: %s\n", ifr.ifr_name);
1582 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1583 fcntl(fd, F_SETFL, O_NONBLOCK);
1584 return fd;
1586 #endif
1588 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1590 write(nd->fd, buf, size);
1593 static void tun_add_read_packet(NetDriverState *nd,
1594 IOCanRWHandler *fd_can_read,
1595 IOReadHandler *fd_read, void *opaque)
1597 qemu_add_fd_event_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1600 static int net_tun_init(NetDriverState *nd)
1602 int pid, status;
1603 char *args[4];
1604 char **parg;
1605 extern int highest_fds;
1607 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1608 if (nd->fd < 0)
1609 return -1;
1611 if ( nd->fd > highest_fds ) highest_fds = nd->fd;
1612 /* try to launch network init script */
1613 pid = fork();
1614 if (pid >= 0) {
1615 if (pid == 0) {
1616 parg = args;
1617 *parg++ = network_script;
1618 *parg++ = nd->ifname;
1619 *parg++ = bridge;
1620 *parg++ = NULL;
1621 execv(network_script, args);
1622 exit(1);
1624 while (waitpid(pid, &status, 0) != pid);
1625 if (!WIFEXITED(status) ||
1626 WEXITSTATUS(status) != 0) {
1627 fprintf(stderr, "%s: could not launch network script\n",
1628 network_script);
1631 nd->send_packet = tun_send_packet;
1632 nd->add_read_packet = tun_add_read_packet;
1633 return 0;
1636 static int net_fd_init(NetDriverState *nd, int fd)
1638 nd->fd = fd;
1639 nd->send_packet = tun_send_packet;
1640 nd->add_read_packet = tun_add_read_packet;
1641 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1642 return 0;
1645 #endif /* !_WIN32 */
1647 /***********************************************************/
1648 /* dumb display */
1650 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1654 static void dumb_resize(DisplayState *ds, int w, int h)
1658 static void dumb_refresh(DisplayState *ds)
1660 vga_update_display();
1663 void dumb_display_init(DisplayState *ds)
1665 ds->data = NULL;
1666 ds->linesize = 0;
1667 ds->depth = 0;
1668 ds->dpy_update = dumb_update;
1669 ds->dpy_resize = dumb_resize;
1670 ds->dpy_refresh = dumb_refresh;
1673 #if !defined(CONFIG_SOFTMMU)
1674 /***********************************************************/
1675 /* cpu signal handler */
1676 static void host_segv_handler(int host_signum, siginfo_t *info,
1677 void *puc)
1679 abort();
1681 #endif
1683 /***********************************************************/
1684 /* I/O handling */
1686 #define MAX_IO_HANDLERS 64
1688 typedef struct IOHandlerRecord {
1689 int fd;
1690 IOCanRWHandler *fd_can_read;
1691 IOReadHandler *fd_read;
1692 void *opaque;
1693 /* temporary data */
1694 struct pollfd *ufd;
1695 int max_size;
1696 struct IOHandlerRecord *next;
1697 } IOHandlerRecord;
1699 static IOHandlerRecord *first_io_handler;
1700 static IOHandlerRecord *first_eventio_handler;
1702 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1703 IOReadHandler *fd_read, void *opaque)
1705 IOHandlerRecord *ioh;
1707 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1708 if (!ioh)
1709 return -1;
1710 ioh->fd = fd;
1711 ioh->fd_can_read = fd_can_read;
1712 ioh->fd_read = fd_read;
1713 ioh->opaque = opaque;
1714 ioh->next = first_io_handler;
1715 first_io_handler = ioh;
1716 return 0;
1719 int qemu_add_fd_event_read_handler(int fd, IOCanRWHandler *fd_can_read,
1720 IOReadHandler *fd_read, void *opaque)
1722 IOHandlerRecord *ioh;
1724 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1725 if (!ioh)
1726 return -1;
1727 ioh->fd = fd;
1728 ioh->fd_can_read = fd_can_read;
1729 ioh->fd_read = fd_read;
1730 ioh->opaque = opaque;
1731 ioh->next = first_eventio_handler;
1732 first_eventio_handler = ioh;
1733 return 0;
1736 void qemu_del_fd_read_handler(int fd)
1738 IOHandlerRecord **pioh, *ioh;
1740 pioh = &first_io_handler;
1741 for(;;) {
1742 ioh = *pioh;
1743 if (ioh == NULL)
1744 break;
1745 if (ioh->fd == fd) {
1746 *pioh = ioh->next;
1747 break;
1749 pioh = &ioh->next;
1753 /***********************************************************/
1754 /* savevm/loadvm support */
1756 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1758 fwrite(buf, 1, size, f);
1761 void qemu_put_byte(QEMUFile *f, int v)
1763 fputc(v, f);
1766 void qemu_put_be16(QEMUFile *f, unsigned int v)
1768 qemu_put_byte(f, v >> 8);
1769 qemu_put_byte(f, v);
1772 void qemu_put_be32(QEMUFile *f, unsigned int v)
1774 qemu_put_byte(f, v >> 24);
1775 qemu_put_byte(f, v >> 16);
1776 qemu_put_byte(f, v >> 8);
1777 qemu_put_byte(f, v);
1780 void qemu_put_be64(QEMUFile *f, uint64_t v)
1782 qemu_put_be32(f, v >> 32);
1783 qemu_put_be32(f, v);
1786 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1788 return fread(buf, 1, size, f);
1791 int qemu_get_byte(QEMUFile *f)
1793 int v;
1794 v = fgetc(f);
1795 if (v == EOF)
1796 return 0;
1797 else
1798 return v;
1801 unsigned int qemu_get_be16(QEMUFile *f)
1803 unsigned int v;
1804 v = qemu_get_byte(f) << 8;
1805 v |= qemu_get_byte(f);
1806 return v;
1809 unsigned int qemu_get_be32(QEMUFile *f)
1811 unsigned int v;
1812 v = qemu_get_byte(f) << 24;
1813 v |= qemu_get_byte(f) << 16;
1814 v |= qemu_get_byte(f) << 8;
1815 v |= qemu_get_byte(f);
1816 return v;
1819 uint64_t qemu_get_be64(QEMUFile *f)
1821 uint64_t v;
1822 v = (uint64_t)qemu_get_be32(f) << 32;
1823 v |= qemu_get_be32(f);
1824 return v;
1827 int64_t qemu_ftell(QEMUFile *f)
1829 return ftell(f);
1832 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1834 if (fseek(f, pos, whence) < 0)
1835 return -1;
1836 return ftell(f);
1839 typedef struct SaveStateEntry {
1840 char idstr[256];
1841 int instance_id;
1842 int version_id;
1843 SaveStateHandler *save_state;
1844 LoadStateHandler *load_state;
1845 void *opaque;
1846 struct SaveStateEntry *next;
1847 } SaveStateEntry;
1849 static SaveStateEntry *first_se;
1851 int register_savevm(const char *idstr,
1852 int instance_id,
1853 int version_id,
1854 SaveStateHandler *save_state,
1855 LoadStateHandler *load_state,
1856 void *opaque)
1858 SaveStateEntry *se, **pse;
1860 se = qemu_malloc(sizeof(SaveStateEntry));
1861 if (!se)
1862 return -1;
1863 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1864 se->instance_id = instance_id;
1865 se->version_id = version_id;
1866 se->save_state = save_state;
1867 se->load_state = load_state;
1868 se->opaque = opaque;
1869 se->next = NULL;
1871 /* add at the end of list */
1872 pse = &first_se;
1873 while (*pse != NULL)
1874 pse = &(*pse)->next;
1875 *pse = se;
1876 return 0;
1879 #define QEMU_VM_FILE_MAGIC 0x5145564d
1880 #define QEMU_VM_FILE_VERSION 0x00000001
1882 int qemu_savevm(const char *filename)
1884 SaveStateEntry *se;
1885 QEMUFile *f;
1886 int len, len_pos, cur_pos, saved_vm_running, ret;
1888 saved_vm_running = vm_running;
1889 vm_stop(0);
1891 f = fopen(filename, "wb");
1892 if (!f) {
1893 ret = -1;
1894 goto the_end;
1897 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1898 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1900 for(se = first_se; se != NULL; se = se->next) {
1901 /* ID string */
1902 len = strlen(se->idstr);
1903 qemu_put_byte(f, len);
1904 qemu_put_buffer(f, se->idstr, len);
1906 qemu_put_be32(f, se->instance_id);
1907 qemu_put_be32(f, se->version_id);
1909 /* record size: filled later */
1910 len_pos = ftell(f);
1911 qemu_put_be32(f, 0);
1913 se->save_state(f, se->opaque);
1915 /* fill record size */
1916 cur_pos = ftell(f);
1917 len = ftell(f) - len_pos - 4;
1918 fseek(f, len_pos, SEEK_SET);
1919 qemu_put_be32(f, len);
1920 fseek(f, cur_pos, SEEK_SET);
1923 fclose(f);
1924 ret = 0;
1925 the_end:
1926 if (saved_vm_running)
1927 vm_start();
1928 return ret;
1931 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1933 SaveStateEntry *se;
1935 for(se = first_se; se != NULL; se = se->next) {
1936 if (!strcmp(se->idstr, idstr) &&
1937 instance_id == se->instance_id)
1938 return se;
1940 return NULL;
1943 int qemu_loadvm(const char *filename)
1945 SaveStateEntry *se;
1946 QEMUFile *f;
1947 int len, cur_pos, ret, instance_id, record_len, version_id;
1948 int saved_vm_running;
1949 unsigned int v;
1950 char idstr[256];
1952 saved_vm_running = vm_running;
1953 vm_stop(0);
1955 f = fopen(filename, "rb");
1956 if (!f) {
1957 ret = -1;
1958 goto the_end;
1961 v = qemu_get_be32(f);
1962 if (v != QEMU_VM_FILE_MAGIC)
1963 goto fail;
1964 v = qemu_get_be32(f);
1965 if (v != QEMU_VM_FILE_VERSION) {
1966 fail:
1967 fclose(f);
1968 ret = -1;
1969 goto the_end;
1971 for(;;) {
1972 #if defined (DO_TB_FLUSH)
1973 tb_flush(global_env);
1974 #endif
1975 len = qemu_get_byte(f);
1976 if (feof(f))
1977 break;
1978 qemu_get_buffer(f, idstr, len);
1979 idstr[len] = '\0';
1980 instance_id = qemu_get_be32(f);
1981 version_id = qemu_get_be32(f);
1982 record_len = qemu_get_be32(f);
1983 #if 0
1984 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1985 idstr, instance_id, version_id, record_len);
1986 #endif
1987 cur_pos = ftell(f);
1988 se = find_se(idstr, instance_id);
1989 if (!se) {
1990 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1991 instance_id, idstr);
1992 } else {
1993 ret = se->load_state(f, se->opaque, version_id);
1994 if (ret < 0) {
1995 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1996 instance_id, idstr);
1999 /* always seek to exact end of record */
2000 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2002 fclose(f);
2003 ret = 0;
2004 the_end:
2005 if (saved_vm_running)
2006 vm_start();
2007 return ret;
2010 /***********************************************************/
2011 /* main execution loop */
2013 void gui_update(void *opaque)
2015 display_state.dpy_refresh(&display_state);
2016 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2018 void polling_handler(void *opaque)
2020 #ifndef _WIN32
2021 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2022 IOHandlerRecord *ioh, *ioh_next;
2023 uint8_t buf[4096];
2024 int n, max_size;
2025 #endif
2026 int timeout = 0;
2027 int ret;
2029 #ifdef _WIN32
2030 if (timeout > 0)
2031 Sleep(timeout);
2032 #else
2033 /* poll any events */
2034 /* XXX: separate device handlers from system ones */
2035 pf = ufds;
2036 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2037 if (!ioh->fd_can_read) {
2038 max_size = 0;
2039 pf->fd = ioh->fd;
2040 pf->events = POLLIN;
2041 ioh->ufd = pf;
2042 pf++;
2043 } else {
2044 max_size = ioh->fd_can_read(ioh->opaque);
2045 if (max_size > 0) {
2046 if (max_size > sizeof(buf))
2047 max_size = sizeof(buf);
2048 pf->fd = ioh->fd;
2049 pf->events = POLLIN;
2050 ioh->ufd = pf;
2051 pf++;
2052 } else {
2053 ioh->ufd = NULL;
2056 ioh->max_size = max_size;
2059 ret = poll(ufds, pf - ufds, timeout);
2060 if (ret > 0) {
2061 /* XXX: better handling of removal */
2062 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2063 ioh_next = ioh->next;
2064 pf = ioh->ufd;
2065 if (pf) {
2066 if (pf->revents & POLLIN) {
2067 if (ioh->max_size == 0) {
2068 /* just a read event */
2069 ioh->fd_read(ioh->opaque, NULL, 0);
2070 } else {
2071 n = read(ioh->fd, buf, ioh->max_size);
2072 if (n >= 0) {
2073 ioh->fd_read(ioh->opaque, buf, n);
2074 } else if (errno != EAGAIN) {
2075 ioh->fd_read(ioh->opaque, NULL, -errno);
2082 #endif /* !defined(_WIN32) */
2084 qemu_mod_timer(polling_timer, POLLING_INTERVAL + qemu_get_clock(rt_clock));
2088 /* XXX: support several handlers */
2089 VMStopHandler *vm_stop_cb;
2090 VMStopHandler *vm_stop_opaque;
2092 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2094 vm_stop_cb = cb;
2095 vm_stop_opaque = opaque;
2096 return 0;
2099 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2101 vm_stop_cb = NULL;
2104 void vm_start(void)
2106 if (!vm_running) {
2107 cpu_enable_ticks();
2108 vm_running = 1;
2112 void vm_stop(int reason)
2114 if (vm_running) {
2115 cpu_disable_ticks();
2116 vm_running = 0;
2117 if (reason != 0) {
2118 if (vm_stop_cb) {
2119 vm_stop_cb(vm_stop_opaque, reason);
2125 /* reset/shutdown handler */
2127 typedef struct QEMUResetEntry {
2128 QEMUResetHandler *func;
2129 void *opaque;
2130 struct QEMUResetEntry *next;
2131 } QEMUResetEntry;
2133 static QEMUResetEntry *first_reset_entry;
2134 int reset_requested;
2135 int shutdown_requested;
2137 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2139 QEMUResetEntry **pre, *re;
2141 pre = &first_reset_entry;
2142 while (*pre != NULL)
2143 pre = &(*pre)->next;
2144 re = qemu_mallocz(sizeof(QEMUResetEntry));
2145 re->func = func;
2146 re->opaque = opaque;
2147 re->next = NULL;
2148 *pre = re;
2151 void qemu_system_reset(void)
2153 QEMUResetEntry *re;
2155 /* reset all devices */
2156 for(re = first_reset_entry; re != NULL; re = re->next) {
2157 re->func(re->opaque);
2161 void qemu_system_reset_request(void)
2163 reset_requested = 1;
2164 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2167 void qemu_system_shutdown_request(void)
2169 shutdown_requested = 1;
2170 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2173 void main_loop_wait(int timeout)
2175 if (vm_running) {
2176 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2177 qemu_get_clock(vm_clock));
2178 /* run dma transfers, if any */
2179 DMA_run();
2182 /* real time timers */
2183 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2184 qemu_get_clock(rt_clock));
2187 void help(void)
2189 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2190 "usage: %s [options] [disk_image]\n"
2191 "\n"
2192 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2193 "\n"
2194 "Standard options:\n"
2195 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2196 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2197 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2198 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2199 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2200 "-snapshot write to temporary files instead of disk image files\n"
2201 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2202 "-nographic disable graphical output and redirect serial I/Os to console\n"
2203 "-vcpus set CPU number of guest platform\n"
2204 #ifdef CONFIG_VNC
2205 "-vnc port use vnc instead of sdl\n"
2206 "-vncport port use a different port\n"
2207 "-vncconnect host:port do a reverse connect\n"
2208 #ifdef CONFIG_SDL
2209 "-vnc-and-sdl use vnc and sdl simultaneously\n"
2210 #endif
2211 #endif
2212 "-k <language> use keyboard layout (for example \"fr\" for french)\n"
2213 "-enable-audio enable audio support\n"
2214 "-localtime set the real time clock to local time [default=utc]\n"
2215 "-full-screen start in full screen\n"
2216 #ifdef TARGET_PPC
2217 "-prep Simulate a PREP system (default is PowerMAC)\n"
2218 "-g WxH[xDEPTH] Set the initial VGA graphic mode\n"
2219 #endif
2220 "-nic-ne2000 simulate an Realtek ne2k PCI ethernet adaptor\n"
2221 "\n"
2222 "Network options:\n"
2223 "-nics n simulate 'n' network cards [default=1]\n"
2224 "-macaddr addr set the mac address of the first interface\n"
2225 "-bridge br set the bridge interface for nic\n"
2226 "-n script set tap/tun network init script [default=%s]\n"
2227 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2228 #ifdef CONFIG_SLIRP
2229 "-user-net use user mode network stack [default if no tap/tun script]\n"
2230 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2231 #ifndef _WIN32
2232 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2233 #endif
2234 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2235 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2236 #endif
2237 "-dummy-net use dummy network stack\n"
2238 "\n"
2239 "Linux boot specific:\n"
2240 "-kernel bzImage use 'bzImage' as kernel image\n"
2241 "-append cmdline use 'cmdline' as kernel command line\n"
2242 "-initrd file use 'file' as initial ram disk\n"
2243 "\n"
2244 "Debug/Expert options:\n"
2245 "-monitor dev redirect the monitor to char device 'dev'\n"
2246 "-serial dev redirect the serial port to char device 'dev'\n"
2247 "-S freeze CPU at startup (use 'c' to start execution)\n"
2248 "-s wait gdb connection to port %d\n"
2249 "-p port ioreq port for xen\n"
2250 "-d domain domain that we're serving\n"
2251 "-domain-name domain name that we're serving\n"
2252 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
2253 "-L path set the directory for the BIOS and VGA BIOS\n"
2254 "-timeoffset time offset (in seconds) from local time (Xen)\n"
2255 #ifdef USE_CODE_COPY
2256 "-no-code-copy disable code copy acceleration\n"
2257 #endif
2258 #ifdef TARGET_I386
2259 "-isa simulate an ISA-only system (default is PCI system)\n"
2260 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2261 " (default is CL-GD5446 PCI VGA)\n"
2262 "-vgaacc [0|1] 1 to accelerate CL-GD5446 speed, default is 1\n"
2263 "-no-repeatkey disable key repeat feature for SDL keyboard simulation"
2264 #endif
2265 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2266 "\n"
2267 "During emulation, the following keys are useful:\n"
2268 "ctrl-alt-f toggle full screen\n"
2269 "ctrl-alt-n switch to virtual console 'n'\n"
2270 "ctrl-alt toggle mouse and keyboard grab\n"
2271 "\n"
2272 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2274 #ifdef CONFIG_SOFTMMU
2275 "qemu",
2276 #else
2277 "qemu-fast",
2278 #endif
2279 DEFAULT_RAM_SIZE,
2280 DEFAULT_NETWORK_SCRIPT,
2281 DEFAULT_GDBSTUB_PORT);
2282 #ifndef CONFIG_SOFTMMU
2283 printf("\n"
2284 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2285 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2286 "PC emulation.\n");
2287 #endif
2288 exit(1);
2291 #define HAS_ARG 0x0001
2293 enum {
2294 QEMU_OPTION_h,
2296 QEMU_OPTION_fda,
2297 QEMU_OPTION_fdb,
2298 QEMU_OPTION_hda,
2299 QEMU_OPTION_hdb,
2300 QEMU_OPTION_hdc,
2301 QEMU_OPTION_hdd,
2302 QEMU_OPTION_cdrom,
2303 QEMU_OPTION_boot,
2304 QEMU_OPTION_snapshot,
2305 QEMU_OPTION_m,
2306 QEMU_OPTION_nographic,
2307 #ifdef CONFIG_VNC
2308 QEMU_OPTION_vnc,
2309 QEMU_OPTION_vncport,
2310 QEMU_OPTION_vncconnect,
2311 #ifdef CONFIG_SDL
2312 QEMU_OPTION_vnc_and_sdl,
2313 #endif
2314 #endif
2315 QEMU_OPTION_enable_audio,
2317 QEMU_OPTION_nics,
2318 QEMU_OPTION_macaddr,
2319 QEMU_OPTION_bridge,
2320 QEMU_OPTION_n,
2321 QEMU_OPTION_tun_fd,
2322 QEMU_OPTION_user_net,
2323 QEMU_OPTION_tftp,
2324 QEMU_OPTION_smb,
2325 QEMU_OPTION_redir,
2326 QEMU_OPTION_dummy_net,
2328 QEMU_OPTION_kernel,
2329 QEMU_OPTION_append,
2330 QEMU_OPTION_initrd,
2332 QEMU_OPTION_S,
2333 QEMU_OPTION_s,
2334 QEMU_OPTION_d,
2335 QEMU_OPTION_l,
2336 QEMU_OPTION_hdachs,
2337 QEMU_OPTION_L,
2338 QEMU_OPTION_no_code_copy,
2339 QEMU_OPTION_vcpus,
2340 QEMU_OPTION_pci,
2341 QEMU_OPTION_nic_ne2000,
2342 QEMU_OPTION_isa,
2343 QEMU_OPTION_prep,
2344 QEMU_OPTION_k,
2345 QEMU_OPTION_localtime,
2346 QEMU_OPTION_cirrusvga,
2347 QEMU_OPTION_g,
2348 QEMU_OPTION_std_vga,
2349 QEMU_OPTION_monitor,
2350 QEMU_OPTION_domainname,
2351 QEMU_OPTION_serial,
2352 QEMU_OPTION_timeoffset,
2353 QEMU_OPTION_loadvm,
2354 QEMU_OPTION_full_screen,
2355 QEMU_OPTION_vgaacc,
2356 QEMU_OPTION_repeatkey,
2357 };
2359 typedef struct QEMUOption {
2360 const char *name;
2361 int flags;
2362 int index;
2363 } QEMUOption;
2365 const QEMUOption qemu_options[] = {
2366 { "h", 0, QEMU_OPTION_h },
2368 { "fda", HAS_ARG, QEMU_OPTION_fda },
2369 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2370 { "hda", HAS_ARG, QEMU_OPTION_hda },
2371 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2372 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2373 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2374 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2375 { "boot", HAS_ARG, QEMU_OPTION_boot },
2376 { "snapshot", 0, QEMU_OPTION_snapshot },
2377 { "m", HAS_ARG, QEMU_OPTION_m },
2378 { "nographic", 0, QEMU_OPTION_nographic },
2379 #ifdef CONFIG_VNC
2380 { "vnc", 0, QEMU_OPTION_vnc },
2381 { "vncport", HAS_ARG, QEMU_OPTION_vncport },
2382 { "vncconnect", HAS_ARG, QEMU_OPTION_vncconnect },
2383 #ifdef CONFIG_SDL
2384 { "vnc-and-sdl", 0, QEMU_OPTION_vnc_and_sdl },
2385 #endif
2386 #endif
2387 { "k", HAS_ARG, QEMU_OPTION_k },
2388 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2390 { "nics", HAS_ARG, QEMU_OPTION_nics},
2391 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2392 { "bridge", HAS_ARG, QEMU_OPTION_bridge},
2393 { "n", HAS_ARG, QEMU_OPTION_n },
2394 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2395 #ifdef CONFIG_SLIRP
2396 { "user-net", 0, QEMU_OPTION_user_net },
2397 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2398 #ifndef _WIN32
2399 { "smb", HAS_ARG, QEMU_OPTION_smb },
2400 #endif
2401 { "redir", HAS_ARG, QEMU_OPTION_redir },
2402 #endif
2403 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2405 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2406 { "append", HAS_ARG, QEMU_OPTION_append },
2407 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2409 { "S", 0, QEMU_OPTION_S },
2410 { "s", 0, QEMU_OPTION_s },
2411 { "d", HAS_ARG, QEMU_OPTION_d },
2412 { "l", HAS_ARG, QEMU_OPTION_l },
2413 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2414 { "L", HAS_ARG, QEMU_OPTION_L },
2415 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2416 { "vcpus", 1, QEMU_OPTION_vcpus },
2417 #ifdef TARGET_PPC
2418 { "prep", 0, QEMU_OPTION_prep },
2419 { "g", 1, QEMU_OPTION_g },
2420 #endif
2421 { "localtime", 0, QEMU_OPTION_localtime },
2422 { "isa", 0, QEMU_OPTION_isa },
2423 { "std-vga", 0, QEMU_OPTION_std_vga },
2424 { "monitor", 1, QEMU_OPTION_monitor },
2425 { "domain-name", 1, QEMU_OPTION_domainname },
2426 { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
2427 { "serial", 1, QEMU_OPTION_serial },
2428 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2429 { "full-screen", 0, QEMU_OPTION_full_screen },
2431 /* temporary options */
2432 { "pci", 0, QEMU_OPTION_pci },
2433 { "nic-ne2000", 0, QEMU_OPTION_nic_ne2000 },
2434 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2435 { "vgaacc", HAS_ARG, QEMU_OPTION_vgaacc },
2436 { "no-repeatkey", 0, QEMU_OPTION_repeatkey },
2437 { NULL },
2438 };
2440 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2442 /* this stack is only used during signal handling */
2443 #define SIGNAL_STACK_SIZE 32768
2445 static uint8_t *signal_stack;
2447 #endif
2449 #define NET_IF_TUN 0
2450 #define NET_IF_USER 1
2451 #define NET_IF_DUMMY 2
2453 #include <xg_private.h>
2455 /* FIXME Flush the shadow page */
2456 int unset_mm_mapping(int xc_handle,
2457 uint32_t domid,
2458 unsigned long nr_pages,
2459 unsigned int address_bits,
2460 unsigned long *extent_start)
2462 int err = 0;
2463 xc_dominfo_t info;
2465 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
2466 nr_pages, 0, extent_start);
2468 if ( err )
2469 fprintf(stderr, "Failed to decrease physmap\n");
2471 xc_domain_getinfo(xc_handle, domid, 1, &info);
2473 if ( (info.nr_pages - nr_pages) <= 0 )
2475 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
2476 err = -1;
2479 if ( xc_domain_setmaxmem(xc_handle, domid,
2480 (info.nr_pages - nr_pages) * PAGE_SIZE/1024) != 0)
2482 fprintf(logfile, "set maxmem returned error %d\n", errno);
2483 err = -1;
2486 return err;
2489 int set_mm_mapping(int xc_handle,
2490 uint32_t domid,
2491 unsigned long nr_pages,
2492 unsigned int address_bits,
2493 unsigned long *extent_start)
2495 xc_dominfo_t info;
2496 int err = 0;
2498 xc_domain_getinfo(xc_handle, domid, 1, &info);
2500 if ( xc_domain_setmaxmem(xc_handle, domid,
2501 (info.nr_pages + nr_pages) * PAGE_SIZE/1024) != 0)
2503 fprintf(logfile, "set maxmem returned error %d\n", errno);
2504 return -1;
2507 err = xc_domain_memory_populate_physmap(xc_handle, domid,
2508 nr_pages, 0,
2509 address_bits, extent_start);
2511 if ( err )
2513 fprintf(stderr, "Failed to populate physmap\n");
2514 return -1;
2517 err = xc_domain_translate_gpfn_list(xc_handle, domid,
2518 nr_pages,
2519 extent_start, extent_start);
2521 if ( err )
2523 fprintf(stderr, "Failed to translate gpfn list\n");
2524 return -1;
2527 #if 0 /* Generates lots of log file output - turn on for debugging */
2528 for (i = 0; i < nr_pages; i++)
2529 fprintf(stderr, "set_map result i %x result %lx\n", i, extent_start[i]);
2530 #endif
2532 return 0;
2535 int main(int argc, char **argv)
2537 #ifdef CONFIG_GDBSTUB
2538 int use_gdbstub, gdbstub_port;
2539 #endif
2540 int i, has_cdrom;
2541 int snapshot, linux_boot;
2542 CPUState *env;
2543 const char *initrd_filename;
2544 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2545 const char *kernel_filename, *kernel_cmdline;
2546 DisplayState *ds = &display_state;
2547 int cyls, heads, secs;
2548 int start_emulation = 1;
2549 uint8_t macaddr[6];
2550 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2551 int optind;
2552 const char *r, *optarg;
2553 CharDriverState *monitor_hd;
2554 char monitor_device[128];
2555 char serial_devices[MAX_SERIAL_PORTS][128];
2556 int serial_device_index;
2557 char qemu_dm_logfilename[64];
2558 const char *loadvm = NULL;
2559 unsigned long nr_pages, *page_array;
2560 extern void *shared_page;
2562 #if !defined(CONFIG_SOFTMMU)
2563 /* we never want that malloc() uses mmap() */
2564 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2565 #endif
2566 initrd_filename = NULL;
2567 for(i = 0; i < MAX_FD; i++)
2568 fd_filename[i] = NULL;
2569 for(i = 0; i < MAX_DISKS; i++)
2570 hd_filename[i] = NULL;
2571 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2572 vga_ram_size = VGA_RAM_SIZE;
2573 bios_size = BIOS_SIZE;
2574 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2575 #ifdef CONFIG_GDBSTUB
2576 use_gdbstub = 0;
2577 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2578 #endif
2579 snapshot = 0;
2580 nographic = 0;
2581 usevnc = 0;
2582 vncport=0;
2583 vncconnect=NULL;
2584 kernel_filename = NULL;
2585 kernel_cmdline = "";
2586 has_cdrom = 1;
2587 cyls = heads = secs = 0;
2588 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2590 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2591 pstrcpy(serial_devices[1], sizeof(serial_devices[1]), "null");
2592 for(i = 2; i < MAX_SERIAL_PORTS; i++)
2593 serial_devices[i][0] = '\0';
2594 serial_device_index = 0;
2596 nb_tun_fds = 0;
2597 net_if_type = -1;
2598 nb_nics = 1;
2599 /* default mac address of the first network interface */
2600 macaddr[0] = 0x52;
2601 macaddr[1] = 0x54;
2602 macaddr[2] = 0x00;
2603 macaddr[3] = 0x12;
2604 macaddr[4] = 0x34;
2605 macaddr[5] = 0x56;
2607 /* init debug */
2608 sprintf(qemu_dm_logfilename, "/var/log/qemu-dm.%d.log", getpid());
2609 cpu_set_log_filename(qemu_dm_logfilename);
2610 cpu_set_log(0);
2612 optind = 1;
2613 for(;;) {
2614 if (optind >= argc)
2615 break;
2616 r = argv[optind];
2617 if (r[0] != '-') {
2618 hd_filename[0] = argv[optind++];
2619 } else {
2620 const QEMUOption *popt;
2622 optind++;
2623 popt = qemu_options;
2624 for(;;) {
2625 if (!popt->name) {
2626 fprintf(stderr, "%s: invalid option -- '%s'\n",
2627 argv[0], r);
2628 exit(1);
2630 if (!strcmp(popt->name, r + 1))
2631 break;
2632 popt++;
2634 if (popt->flags & HAS_ARG) {
2635 if (optind >= argc) {
2636 fprintf(stderr, "%s: option '%s' requires an argument\n",
2637 argv[0], r);
2638 exit(1);
2640 optarg = argv[optind++];
2641 } else {
2642 optarg = NULL;
2645 switch(popt->index) {
2646 case QEMU_OPTION_initrd:
2647 initrd_filename = optarg;
2648 break;
2649 case QEMU_OPTION_hda:
2650 hd_filename[0] = optarg;
2651 break;
2652 case QEMU_OPTION_hdb:
2653 hd_filename[1] = optarg;
2654 break;
2655 case QEMU_OPTION_snapshot:
2656 snapshot = 1;
2657 break;
2658 case QEMU_OPTION_hdachs:
2660 const char *p;
2661 p = optarg;
2662 cyls = strtol(p, (char **)&p, 0);
2663 if (*p != ',')
2664 goto chs_fail;
2665 p++;
2666 heads = strtol(p, (char **)&p, 0);
2667 if (*p != ',')
2668 goto chs_fail;
2669 p++;
2670 secs = strtol(p, (char **)&p, 0);
2671 if (*p != '\0') {
2672 chs_fail:
2673 cyls = 0;
2676 break;
2677 case QEMU_OPTION_nographic:
2678 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2679 if(!strcmp(serial_devices[0], "vc"))
2680 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
2681 "stdio");
2682 nographic = 1;
2683 break;
2684 #ifdef CONFIG_VNC
2685 case QEMU_OPTION_vnc:
2686 usevnc = 1;
2687 break;
2688 case QEMU_OPTION_vncport:
2690 const char *p;
2691 p = optarg;
2692 vncport= strtol(optarg, (char **)&p, 0);
2694 break;
2695 case QEMU_OPTION_vncconnect:
2696 vncconnect = optarg;
2697 break;
2698 #ifdef CONFIG_SDL
2699 case QEMU_OPTION_vnc_and_sdl:
2700 usevnc = 2;
2701 break;
2702 #endif
2703 #endif
2704 case QEMU_OPTION_kernel:
2705 kernel_filename = optarg;
2706 break;
2707 case QEMU_OPTION_append:
2708 kernel_cmdline = optarg;
2709 break;
2710 case QEMU_OPTION_tun_fd:
2712 const char *p;
2713 int fd;
2714 net_if_type = NET_IF_TUN;
2715 if ( nb_tun_fds < MAX_NICS ) {
2716 fd = strtol(optarg, (char **)&p, 0);
2717 if (*p != '\0') {
2718 fprintf(stderr,
2719 "qemu: invalid fd for network interface %d\n",
2720 nb_tun_fds);
2721 exit(1);
2723 tun_fds[nb_tun_fds++] = fd;
2726 break;
2727 case QEMU_OPTION_hdc:
2728 hd_filename[2] = optarg;
2729 has_cdrom = 0;
2730 break;
2731 case QEMU_OPTION_hdd:
2732 hd_filename[3] = optarg;
2733 break;
2734 case QEMU_OPTION_cdrom:
2735 hd_filename[2] = optarg;
2736 has_cdrom = 1;
2737 break;
2738 case QEMU_OPTION_boot:
2739 boot_device = optarg[0];
2740 if ( boot_device != 'a' &&
2741 boot_device != 'c' &&
2742 boot_device != 'd' ) {
2743 fprintf(stderr, "qemu: invalid boot device '%c'\n",
2744 boot_device);
2745 exit(1);
2747 break;
2748 case QEMU_OPTION_fda:
2749 fd_filename[0] = optarg;
2750 break;
2751 case QEMU_OPTION_fdb:
2752 fd_filename[1] = optarg;
2753 break;
2754 case QEMU_OPTION_nics:
2755 nb_nics = atoi(optarg);
2756 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2757 fprintf(stderr,
2758 "qemu: invalid number of network interfaces\n");
2759 exit(1);
2761 break;
2762 case QEMU_OPTION_bridge:
2763 pstrcpy(bridge, sizeof(bridge), optarg);
2764 break;
2765 case QEMU_OPTION_macaddr:
2767 const char *p;
2768 int i;
2770 p = optarg;
2771 for (i = 0; i < 6; i++) {
2772 macaddr[i] = strtol(p, (char **)&p, 16);
2773 if (i == 5) {
2774 if (*p != '\0')
2775 goto macaddr_error;
2776 } else {
2777 if (*p != ':') {
2778 macaddr_error:
2779 fprintf(stderr, "qemu: invalid syntax "
2780 "for ethernet address\n");
2781 exit(1);
2783 p++;
2787 break;
2788 #ifdef CONFIG_SLIRP
2789 case QEMU_OPTION_tftp:
2790 tftp_prefix = optarg;
2791 break;
2792 #ifndef _WIN32
2793 case QEMU_OPTION_smb:
2794 net_slirp_smb(optarg);
2795 break;
2796 #endif
2797 case QEMU_OPTION_user_net:
2798 net_if_type = NET_IF_USER;
2799 break;
2800 case QEMU_OPTION_redir:
2801 net_slirp_redir(optarg);
2802 break;
2803 #endif
2804 case QEMU_OPTION_dummy_net:
2805 net_if_type = NET_IF_DUMMY;
2806 break;
2807 case QEMU_OPTION_enable_audio:
2808 audio_enabled = 1;
2809 break;
2810 case QEMU_OPTION_h:
2811 help();
2812 break;
2813 case QEMU_OPTION_m:
2814 ram_size = atol(optarg) * 1024 * 1024;
2815 if (ram_size <= 0)
2816 help();
2817 break;
2818 case QEMU_OPTION_d:
2820 domid = atoi(optarg);
2821 fprintf(logfile, "domid: %d\n", domid);
2823 break;
2824 case QEMU_OPTION_l:
2826 int mask;
2827 mask = cpu_str_to_log_mask(optarg);
2828 fprintf(logfile, "mask: %x\n", mask);
2829 cpu_set_log(mask);
2831 break;
2832 case QEMU_OPTION_n:
2833 pstrcpy(network_script, sizeof(network_script), optarg);
2834 break;
2835 #ifdef CONFIG_GDBSTUB
2836 case QEMU_OPTION_s:
2837 use_gdbstub = 1;
2838 break;
2839 #endif
2840 case QEMU_OPTION_L:
2841 bios_dir = optarg;
2842 break;
2843 case QEMU_OPTION_S:
2844 start_emulation = 0;
2845 break;
2846 case QEMU_OPTION_vcpus:
2847 vcpus = atoi(optarg);
2848 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
2849 break;
2850 case QEMU_OPTION_pci:
2851 pci_enabled = 1;
2852 break;
2853 case QEMU_OPTION_nic_ne2000:
2854 nic_ne2000 = 1;
2855 break;
2856 case QEMU_OPTION_isa:
2857 pci_enabled = 0;
2858 break;
2859 case QEMU_OPTION_prep:
2860 prep_enabled = 1;
2861 break;
2862 case QEMU_OPTION_k:
2863 keyboard_layout = optarg;
2864 break;
2865 case QEMU_OPTION_localtime:
2866 rtc_utc = 0;
2867 break;
2868 case QEMU_OPTION_cirrusvga:
2869 cirrus_vga_enabled = 1;
2870 break;
2871 case QEMU_OPTION_vgaacc:
2873 const char *p;
2874 p = optarg;
2875 vga_accelerate = strtol(p, (char **)&p, 0);
2876 if (*p != '\0') {
2877 fprintf(stderr, "qemu: invalid vgaacc option\n");
2878 exit(1);
2881 break;
2882 case QEMU_OPTION_repeatkey:
2883 repeat_key = 0;
2884 break;
2885 case QEMU_OPTION_std_vga:
2886 cirrus_vga_enabled = 0;
2887 break;
2888 case QEMU_OPTION_g:
2890 const char *p;
2891 int w, h, depth;
2892 p = optarg;
2893 w = strtol(p, (char **)&p, 10);
2894 if (w <= 0) {
2895 graphic_error:
2896 fprintf(stderr, "qemu: invalid resolution or depth\n");
2897 exit(1);
2899 if (*p != 'x')
2900 goto graphic_error;
2901 p++;
2902 h = strtol(p, (char **)&p, 10);
2903 if (h <= 0)
2904 goto graphic_error;
2905 if (*p == 'x') {
2906 p++;
2907 depth = strtol(p, (char **)&p, 10);
2908 if (depth != 8 && depth != 15 && depth != 16 &&
2909 depth != 24 && depth != 32)
2910 goto graphic_error;
2911 } else if (*p == '\0') {
2912 depth = graphic_depth;
2913 } else {
2914 goto graphic_error;
2917 graphic_width = w;
2918 graphic_height = h;
2919 graphic_depth = depth;
2921 break;
2922 case QEMU_OPTION_monitor:
2923 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
2924 break;
2925 case QEMU_OPTION_serial:
2926 if (serial_device_index >= MAX_SERIAL_PORTS) {
2927 fprintf(stderr, "qemu: too many serial ports\n");
2928 exit(1);
2930 pstrcpy(serial_devices[serial_device_index],
2931 sizeof(serial_devices[0]), optarg);
2932 serial_device_index++;
2933 break;
2934 case QEMU_OPTION_loadvm:
2935 loadvm = optarg;
2936 break;
2937 case QEMU_OPTION_full_screen:
2938 full_screen = 1;
2939 break;
2940 case QEMU_OPTION_domainname:
2941 strncat(domain_name, optarg, sizeof(domain_name) - 20);
2942 break;
2943 case QEMU_OPTION_timeoffset:
2944 timeoffset = strtol(optarg, NULL, 0);
2945 break;
2951 linux_boot = (kernel_filename != NULL);
2953 if ( !linux_boot && hd_filename[0] == '\0' &&
2954 hd_filename[2] == '\0' && fd_filename[0] == '\0' )
2955 help();
2957 /* boot to cd by default if no hard disk */
2958 if (hd_filename[0] == '\0' && boot_device == 'c') {
2959 if (fd_filename[0] != '\0')
2960 boot_device = 'a';
2961 else
2962 boot_device = 'd';
2965 #if !defined(CONFIG_SOFTMMU)
2966 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2968 static uint8_t stdout_buf[4096];
2969 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2971 #else
2972 setvbuf(stdout, NULL, _IOLBF, 0);
2973 #endif
2975 /* init host network redirectors */
2976 if (net_if_type == -1) {
2977 net_if_type = NET_IF_TUN;
2978 #if defined(CONFIG_SLIRP)
2979 if (access(network_script, R_OK) < 0) {
2980 net_if_type = NET_IF_USER;
2982 #endif
2985 for(i = 0; i < nb_nics; i++) {
2986 NetDriverState *nd = &nd_table[i];
2987 nd->index = i;
2988 /* init virtual mac address */
2989 nd->macaddr[0] = macaddr[0];
2990 nd->macaddr[1] = macaddr[1];
2991 nd->macaddr[2] = macaddr[2];
2992 nd->macaddr[3] = macaddr[3];
2993 nd->macaddr[4] = macaddr[4];
2994 nd->macaddr[5] = macaddr[5] + i;
2995 switch(net_if_type) {
2996 #if defined(CONFIG_SLIRP)
2997 case NET_IF_USER:
2998 net_slirp_init(nd);
2999 break;
3000 #endif
3001 #if !defined(_WIN32)
3002 case NET_IF_TUN:
3003 if (i < nb_tun_fds) {
3004 net_fd_init(nd, tun_fds[i]);
3005 } else {
3006 if (net_tun_init(nd) < 0)
3007 net_dummy_init(nd);
3009 break;
3010 #endif
3011 case NET_IF_DUMMY:
3012 default:
3013 net_dummy_init(nd);
3014 break;
3018 /* init the memory */
3019 phys_ram_size = ram_size + vga_ram_size + bios_size;
3021 nr_pages = ram_size/PAGE_SIZE;
3023 xc_handle = xc_interface_open();
3025 if ( (page_array = (unsigned long *)
3026 malloc(nr_pages * sizeof(unsigned long))) == NULL)
3028 fprintf(logfile, "malloc returned error %d\n", errno);
3029 exit(-1);
3032 #if defined(__i386__) || defined(__x86_64__)
3033 if ( xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages )
3035 fprintf(logfile, "xc_get_pfn_list returned error %d\n", errno);
3036 exit(-1);
3038 if ( (phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3039 PROT_READ|PROT_WRITE,
3040 page_array,
3041 nr_pages - 1)) == 0 )
3043 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
3044 exit(-1);
3047 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3048 PROT_READ|PROT_WRITE,
3049 page_array[nr_pages - 1]);
3051 #elif defined(__ia64__)
3052 if ( xc_ia64_get_pfn_list(xc_handle, domid, page_array, 0, nr_pages)
3053 != nr_pages)
3055 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
3056 exit(-1);
3059 if ( (phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3060 PROT_READ|PROT_WRITE,
3061 page_array,
3062 nr_pages)) == 0 )
3064 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
3065 exit(-1);
3068 if ( xc_ia64_get_pfn_list(xc_handle, domid,
3069 page_array,
3070 nr_pages + (GFW_SIZE >> PAGE_SHIFT), 1) != 1 )
3072 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
3073 exit(-1);
3076 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3077 PROT_READ|PROT_WRITE,
3078 page_array[0]);
3079 #endif
3081 fprintf(logfile, "shared page at pfn:%lx, mfn: %lx\n", (nr_pages-1),
3082 (page_array[nr_pages - 1]));
3084 /* we always create the cdrom drive, even if no disk is there */
3085 bdrv_init();
3086 if (has_cdrom) {
3087 int fd;
3088 if ( (fd = open(hd_filename[2], O_RDONLY | O_BINARY)) < 0) {
3089 hd_filename[2]=NULL;
3090 bs_table[2]=NULL;
3091 fprintf(logfile, "Could not open CD %s.\n", hd_filename[i]);
3093 else {
3094 close(fd);
3095 bs_table[2] = bdrv_new("cdrom");
3096 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3100 /* open the virtual block devices */
3101 for(i = 0; i < MAX_DISKS; i++) {
3102 if (hd_filename[i]) {
3103 if (!bs_table[i]) {
3104 char buf[64];
3105 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3106 bs_table[i] = bdrv_new(buf);
3108 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3109 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3110 hd_filename[i]);
3111 exit(1);
3113 if (i == 0 && cyls != 0)
3114 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3118 /* we always create at least one floppy disk */
3119 fd_table[0] = bdrv_new("fda");
3120 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3122 for(i = 0; i < MAX_FD; i++) {
3123 if (fd_filename[i]) {
3124 if (!fd_table[i]) {
3125 char buf[64];
3126 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3127 fd_table[i] = bdrv_new(buf);
3128 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3130 if (fd_filename[i] != '\0') {
3131 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3132 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3133 fd_filename[i]);
3134 exit(1);
3140 /* init CPU state */
3141 env = cpu_init();
3142 global_env = env;
3143 cpu_single_env = env;
3145 init_ioports();
3146 cpu_calibrate_ticks();
3148 /* terminal init */
3149 if (nographic) {
3150 dumb_display_init(ds);
3151 } else {
3152 if (usevnc) {
3153 #ifdef CONFIG_VNC
3154 vnc_display_init(ds, (usevnc==2), vncport, vncconnect);
3155 #else
3156 fprintf(logfile, "qemu not configured with vnc support\n");
3157 #endif
3158 } else {
3159 #ifdef CONFIG_SDL
3160 sdl_display_init(ds, full_screen);
3161 #else
3162 dumb_display_init(ds);
3163 #endif
3167 vga_console = graphic_console_init(ds);
3169 monitor_hd = qemu_chr_open(monitor_device);
3170 if (!monitor_hd) {
3171 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3172 exit(1);
3174 monitor_init(monitor_hd, !nographic);
3176 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3177 if (serial_devices[i][0] != '\0') {
3178 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3179 if (!serial_hds[i]) {
3180 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3181 serial_devices[i]);
3182 exit(1);
3184 if (!strcmp(serial_devices[i], "vc"))
3185 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3189 /* setup cpu signal handlers for MMU / self modifying code handling */
3190 #if !defined(CONFIG_SOFTMMU)
3192 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3194 stack_t stk;
3195 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3196 stk.ss_sp = signal_stack;
3197 stk.ss_size = SIGNAL_STACK_SIZE;
3198 stk.ss_flags = 0;
3200 if (sigaltstack(&stk, NULL) < 0) {
3201 fprintf(logfile, "sigaltstack returned error %d\n", errno);
3202 exit(1);
3205 #endif
3207 struct sigaction act;
3209 sigfillset(&act.sa_mask);
3210 act.sa_flags = SA_SIGINFO;
3211 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3212 act.sa_flags |= SA_ONSTACK;
3213 #endif
3214 act.sa_sigaction = host_segv_handler;
3215 sigaction(SIGSEGV, &act, NULL);
3216 sigaction(SIGBUS, &act, NULL);
3217 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3218 sigaction(SIGFPE, &act, NULL);
3219 #endif
3221 #endif
3223 #ifndef _WIN32
3225 struct sigaction act;
3226 sigfillset(&act.sa_mask);
3227 act.sa_flags = 0;
3228 act.sa_handler = SIG_IGN;
3229 sigaction(SIGPIPE, &act, NULL);
3231 #endif
3232 init_timers();
3234 #if defined(TARGET_I386)
3235 pc_init(ram_size, vga_ram_size, boot_device,
3236 ds, fd_filename, snapshot,
3237 kernel_filename, kernel_cmdline, initrd_filename, timeoffset);
3238 #elif defined(TARGET_PPC)
3239 ppc_init(ram_size, vga_ram_size, boot_device,
3240 ds, fd_filename, snapshot,
3241 kernel_filename, kernel_cmdline, initrd_filename);
3242 #elif defined(TARGET_SPARC)
3243 sun4m_init(ram_size, vga_ram_size, boot_device,
3244 ds, fd_filename, snapshot,
3245 kernel_filename, kernel_cmdline, initrd_filename);
3246 #endif
3248 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3249 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3251 polling_timer = qemu_new_timer(rt_clock, polling_handler, NULL);
3252 qemu_mod_timer(polling_timer, qemu_get_clock(rt_clock));
3254 #ifdef CONFIG_GDBSTUB
3255 if (use_gdbstub) {
3256 if (gdbserver_start(gdbstub_port) < 0) {
3257 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3258 gdbstub_port);
3259 exit(1);
3260 } else {
3261 fprintf(logfile, "Waiting gdb connection on port %d\n", gdbstub_port);
3263 } else
3264 #endif
3265 if (loadvm)
3266 qemu_loadvm(loadvm);
3269 /* XXX: simplify init */
3270 if (start_emulation) {
3271 vm_start();
3274 main_loop();
3275 quit_timers();
3276 return 0;
3279 extern fd_set wakeup_rfds;
3280 void tun_receive_handler(fd_set *rfds)
3282 IOHandlerRecord *ioh;
3283 static uint8_t buf[4096];
3284 int n, max_size;
3286 for (ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3287 if ( FD_ISSET(ioh->fd, rfds) ) {
3288 max_size = ioh->fd_can_read(ioh->opaque);
3289 if (max_size > 0) {
3290 if (max_size > sizeof(buf))
3291 max_size = sizeof(buf);
3292 n = read(ioh->fd, buf, max_size);
3293 if (n >= 0) {
3294 ioh->fd_read(ioh->opaque, buf, n);
3299 update_select_wakeup_events();
3302 void update_select_wakeup_events(void)
3304 IOHandlerRecord *ioh;
3305 int max_size;
3307 for(ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3308 FD_CLR(ioh->fd, &wakeup_rfds);
3309 if (ioh->fd_can_read) {
3310 max_size = ioh->fd_can_read(ioh->opaque);
3311 if (max_size > 0) {
3312 FD_SET(ioh->fd, &wakeup_rfds);