ia64/xen-unstable

view tools/ioemu/vl.c @ 9739:41823e46d6ac

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