direct-io.hg

view tools/ioemu/vl.c @ 10939:5980fb28b050

[qemu] Free page_array when it's no longer used.
Seems no special reason for keeping page_array, free it
to avoid memroy leak in Qemu.

Signed-off-by : Zhang xiantao<xiantao.zhang@intel.com>
author chris@kneesaa.uk.xensource.com
date Fri Aug 04 10:56:53 2006 +0100 (2006-08-04)
parents a0b3cf802d99
children 08a11694b109
line source
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 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"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #else
51 #ifndef __sun__
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 #include <linux/ppdev.h>
58 #endif
59 #endif
60 #endif
62 #if defined(CONFIG_SLIRP)
63 #include "libslirp.h"
64 #endif
66 #ifdef _WIN32
67 #include <malloc.h>
68 #include <sys/timeb.h>
69 #include <windows.h>
70 #define getopt_long_only getopt_long
71 #define memalign(align, size) malloc(size)
72 #endif
74 #include "qemu_socket.h"
76 #ifdef CONFIG_SDL
77 #ifdef __APPLE__
78 #include <SDL/SDL.h>
79 #endif
80 #endif /* CONFIG_SDL */
82 #ifdef CONFIG_COCOA
83 #undef main
84 #define main qemu_main
85 #endif /* CONFIG_COCOA */
87 #include "disas.h"
89 #include "exec-all.h"
91 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
92 #define DEFAULT_BRIDGE "xenbr0"
94 //#define DEBUG_UNUSED_IOPORT
95 //#define DEBUG_IOPORT
97 #if !defined(CONFIG_SOFTMMU)
98 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
99 #else
100 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
101 #endif
103 #ifdef TARGET_PPC
104 #define DEFAULT_RAM_SIZE 144
105 #else
106 #define DEFAULT_RAM_SIZE 128
107 #endif
108 /* in ms */
109 #define GUI_REFRESH_INTERVAL 30
111 /* XXX: use a two level table to limit memory usage */
112 #define MAX_IOPORTS 65536
114 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
115 char phys_ram_file[1024];
116 void *ioport_opaque[MAX_IOPORTS];
117 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
118 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
119 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
120 int vga_ram_size;
121 int bios_size;
122 static DisplayState display_state;
123 int nographic;
124 int vncviewer;
125 const char* keyboard_layout = NULL;
126 int64_t ticks_per_sec;
127 int boot_device = 'c';
128 uint64_t ram_size;
129 int pit_min_timer_count = 0;
130 int nb_nics;
131 NICInfo nd_table[MAX_NICS];
132 QEMUTimer *gui_timer;
133 int vm_running;
134 int rtc_utc = 1;
135 int cirrus_vga_enabled = 1;
136 #ifdef TARGET_SPARC
137 int graphic_width = 1024;
138 int graphic_height = 768;
139 #else
140 int graphic_width = 800;
141 int graphic_height = 600;
142 #endif
143 int graphic_depth = 15;
144 int full_screen = 0;
145 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
146 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
147 #ifdef TARGET_I386
148 int win2k_install_hack = 0;
149 #endif
150 int usb_enabled = 0;
151 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
152 USBDevice *vm_usb_hub;
153 static VLANState *first_vlan;
154 int smp_cpus = 1;
155 int vnc_display = -1;
156 #if defined(TARGET_SPARC)
157 #define MAX_CPUS 16
158 #elif defined(TARGET_I386)
159 #define MAX_CPUS 255
160 #else
161 #define MAX_CPUS 1
162 #endif
164 extern int vcpus;
166 int xc_handle;
168 time_t timeoffset = 0;
170 int acpi_enabled = 0;
172 char domain_name[1024] = { 'H','V', 'M', 'X', 'E', 'N', '-'};
173 extern int domid;
175 /***********************************************************/
176 /* x86 ISA bus support */
178 target_phys_addr_t isa_mem_base = 0;
179 PicState2 *isa_pic;
181 uint32_t default_ioport_readb(void *opaque, uint32_t address)
182 {
183 #ifdef DEBUG_UNUSED_IOPORT
184 fprintf(stderr, "inb: port=0x%04x\n", address);
185 #endif
186 return 0xff;
187 }
189 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
190 {
191 #ifdef DEBUG_UNUSED_IOPORT
192 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
193 #endif
194 }
196 /* default is to make two byte accesses */
197 uint32_t default_ioport_readw(void *opaque, uint32_t address)
198 {
199 uint32_t data;
200 data = ioport_read_table[0][address](ioport_opaque[address], address);
201 address = (address + 1) & (MAX_IOPORTS - 1);
202 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
203 return data;
204 }
206 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
207 {
208 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
209 address = (address + 1) & (MAX_IOPORTS - 1);
210 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
211 }
213 uint32_t default_ioport_readl(void *opaque, uint32_t address)
214 {
215 #ifdef DEBUG_UNUSED_IOPORT
216 fprintf(stderr, "inl: port=0x%04x\n", address);
217 #endif
218 return 0xffffffff;
219 }
221 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
222 {
223 #ifdef DEBUG_UNUSED_IOPORT
224 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
225 #endif
226 }
228 void init_ioports(void)
229 {
230 int i;
232 for(i = 0; i < MAX_IOPORTS; i++) {
233 ioport_read_table[0][i] = default_ioport_readb;
234 ioport_write_table[0][i] = default_ioport_writeb;
235 ioport_read_table[1][i] = default_ioport_readw;
236 ioport_write_table[1][i] = default_ioport_writew;
237 ioport_read_table[2][i] = default_ioport_readl;
238 ioport_write_table[2][i] = default_ioport_writel;
239 }
240 }
242 /* size is the word size in byte */
243 int register_ioport_read(int start, int length, int size,
244 IOPortReadFunc *func, void *opaque)
245 {
246 int i, bsize;
248 if (size == 1) {
249 bsize = 0;
250 } else if (size == 2) {
251 bsize = 1;
252 } else if (size == 4) {
253 bsize = 2;
254 } else {
255 hw_error("register_ioport_read: invalid size");
256 return -1;
257 }
258 for(i = start; i < start + length; i += size) {
259 ioport_read_table[bsize][i] = func;
260 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
261 hw_error("register_ioport_read: invalid opaque");
262 ioport_opaque[i] = opaque;
263 }
264 return 0;
265 }
267 /* size is the word size in byte */
268 int register_ioport_write(int start, int length, int size,
269 IOPortWriteFunc *func, void *opaque)
270 {
271 int i, bsize;
273 if (size == 1) {
274 bsize = 0;
275 } else if (size == 2) {
276 bsize = 1;
277 } else if (size == 4) {
278 bsize = 2;
279 } else {
280 hw_error("register_ioport_write: invalid size");
281 return -1;
282 }
283 for(i = start; i < start + length; i += size) {
284 ioport_write_table[bsize][i] = func;
285 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
286 hw_error("register_ioport_read: invalid opaque");
287 ioport_opaque[i] = opaque;
288 }
289 return 0;
290 }
292 void isa_unassign_ioport(int start, int length)
293 {
294 int i;
296 for(i = start; i < start + length; i++) {
297 ioport_read_table[0][i] = default_ioport_readb;
298 ioport_read_table[1][i] = default_ioport_readw;
299 ioport_read_table[2][i] = default_ioport_readl;
301 ioport_write_table[0][i] = default_ioport_writeb;
302 ioport_write_table[1][i] = default_ioport_writew;
303 ioport_write_table[2][i] = default_ioport_writel;
304 }
305 }
307 /***********************************************************/
309 void pstrcpy(char *buf, int buf_size, const char *str)
310 {
311 int c;
312 char *q = buf;
314 if (buf_size <= 0)
315 return;
317 for(;;) {
318 c = *str++;
319 if (c == 0 || q >= buf + buf_size - 1)
320 break;
321 *q++ = c;
322 }
323 *q = '\0';
324 }
326 /* strcat and truncate. */
327 char *pstrcat(char *buf, int buf_size, const char *s)
328 {
329 int len;
330 len = strlen(buf);
331 if (len < buf_size)
332 pstrcpy(buf + len, buf_size - len, s);
333 return buf;
334 }
336 int strstart(const char *str, const char *val, const char **ptr)
337 {
338 const char *p, *q;
339 p = str;
340 q = val;
341 while (*q != '\0') {
342 if (*p != *q)
343 return 0;
344 p++;
345 q++;
346 }
347 if (ptr)
348 *ptr = p;
349 return 1;
350 }
352 void cpu_outb(CPUState *env, int addr, int val)
353 {
354 #ifdef DEBUG_IOPORT
355 if (loglevel & CPU_LOG_IOPORT)
356 fprintf(logfile, "outb: %04x %02x\n", addr, val);
357 #endif
358 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
359 #ifdef USE_KQEMU
360 if (env)
361 env->last_io_time = cpu_get_time_fast();
362 #endif
363 }
365 void cpu_outw(CPUState *env, int addr, int val)
366 {
367 #ifdef DEBUG_IOPORT
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "outw: %04x %04x\n", addr, val);
370 #endif
371 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
372 #ifdef USE_KQEMU
373 if (env)
374 env->last_io_time = cpu_get_time_fast();
375 #endif
376 }
378 void cpu_outl(CPUState *env, int addr, int val)
379 {
380 #ifdef DEBUG_IOPORT
381 if (loglevel & CPU_LOG_IOPORT)
382 fprintf(logfile, "outl: %04x %08x\n", addr, val);
383 #endif
384 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
385 #ifdef USE_KQEMU
386 if (env)
387 env->last_io_time = cpu_get_time_fast();
388 #endif
389 }
391 int cpu_inb(CPUState *env, int addr)
392 {
393 int val;
394 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
395 #ifdef DEBUG_IOPORT
396 if (loglevel & CPU_LOG_IOPORT)
397 fprintf(logfile, "inb : %04x %02x\n", addr, val);
398 #endif
399 #ifdef USE_KQEMU
400 if (env)
401 env->last_io_time = cpu_get_time_fast();
402 #endif
403 return val;
404 }
406 int cpu_inw(CPUState *env, int addr)
407 {
408 int val;
409 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
410 #ifdef DEBUG_IOPORT
411 if (loglevel & CPU_LOG_IOPORT)
412 fprintf(logfile, "inw : %04x %04x\n", addr, val);
413 #endif
414 #ifdef USE_KQEMU
415 if (env)
416 env->last_io_time = cpu_get_time_fast();
417 #endif
418 return val;
419 }
421 int cpu_inl(CPUState *env, int addr)
422 {
423 int val;
424 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
425 #ifdef DEBUG_IOPORT
426 if (loglevel & CPU_LOG_IOPORT)
427 fprintf(logfile, "inl : %04x %08x\n", addr, val);
428 #endif
429 #ifdef USE_KQEMU
430 if (env)
431 env->last_io_time = cpu_get_time_fast();
432 #endif
433 return val;
434 }
436 /***********************************************************/
437 void hw_error(const char *fmt, ...)
438 {
439 va_list ap;
440 #ifndef CONFIG_DM
441 CPUState *env;
442 #endif /* !CONFIG_DM */
444 va_start(ap, fmt);
445 fprintf(stderr, "qemu: hardware error: ");
446 vfprintf(stderr, fmt, ap);
447 fprintf(stderr, "\n");
448 #ifndef CONFIG_DM
449 for(env = first_cpu; env != NULL; env = env->next_cpu) {
450 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
451 #ifdef TARGET_I386
452 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
453 #else
454 cpu_dump_state(env, stderr, fprintf, 0);
455 #endif
456 }
457 #endif /* !CONFIG_DM */
458 va_end(ap);
459 abort();
460 }
462 /***********************************************************/
463 /* keyboard/mouse */
465 static QEMUPutKBDEvent *qemu_put_kbd_event;
466 static void *qemu_put_kbd_event_opaque;
467 static QEMUPutMouseEvent *qemu_put_mouse_event;
468 static void *qemu_put_mouse_event_opaque;
469 static int qemu_put_mouse_event_absolute;
471 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
472 {
473 qemu_put_kbd_event_opaque = opaque;
474 qemu_put_kbd_event = func;
475 }
477 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
478 {
479 qemu_put_mouse_event_opaque = opaque;
480 qemu_put_mouse_event = func;
481 qemu_put_mouse_event_absolute = absolute;
482 }
484 void kbd_put_keycode(int keycode)
485 {
486 if (qemu_put_kbd_event) {
487 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
488 }
489 }
491 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
492 {
493 if (qemu_put_mouse_event) {
494 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
495 dx, dy, dz, buttons_state);
496 }
497 }
499 int kbd_mouse_is_absolute(void)
500 {
501 return qemu_put_mouse_event_absolute;
502 }
504 /***********************************************************/
505 /* timers */
507 #if defined(__powerpc__)
509 static inline uint32_t get_tbl(void)
510 {
511 uint32_t tbl;
512 asm volatile("mftb %0" : "=r" (tbl));
513 return tbl;
514 }
516 static inline uint32_t get_tbu(void)
517 {
518 uint32_t tbl;
519 asm volatile("mftbu %0" : "=r" (tbl));
520 return tbl;
521 }
523 int64_t cpu_get_real_ticks(void)
524 {
525 uint32_t l, h, h1;
526 /* NOTE: we test if wrapping has occurred */
527 do {
528 h = get_tbu();
529 l = get_tbl();
530 h1 = get_tbu();
531 } while (h != h1);
532 return ((int64_t)h << 32) | l;
533 }
535 #elif defined(__i386__)
537 int64_t cpu_get_real_ticks(void)
538 {
539 #ifdef _WIN32
540 LARGE_INTEGER ti;
541 QueryPerformanceCounter(&ti);
542 return ti.QuadPart;
543 #else
544 int64_t val;
545 asm volatile ("rdtsc" : "=A" (val));
546 return val;
547 #endif
548 }
550 #elif defined(__x86_64__)
552 int64_t cpu_get_real_ticks(void)
553 {
554 uint32_t low,high;
555 int64_t val;
556 asm volatile("rdtsc" : "=a" (low), "=d" (high));
557 val = high;
558 val <<= 32;
559 val |= low;
560 return val;
561 }
563 #elif defined(__ia64)
565 int64_t cpu_get_real_ticks(void)
566 {
567 int64_t val;
568 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
569 return val;
570 }
572 #elif defined(__s390__)
574 int64_t cpu_get_real_ticks(void)
575 {
576 int64_t val;
577 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
578 return val;
579 }
581 #else
582 #error unsupported CPU
583 #endif
585 static int64_t cpu_ticks_prev;
586 static int64_t cpu_ticks_offset;
587 static int cpu_ticks_enabled;
589 static inline int64_t cpu_get_ticks(void)
590 {
591 if (!cpu_ticks_enabled) {
592 return cpu_ticks_offset;
593 } else {
594 int64_t ticks;
595 ticks = cpu_get_real_ticks();
596 if (cpu_ticks_prev > ticks) {
597 /* Note: non increasing ticks may happen if the host uses
598 software suspend */
599 cpu_ticks_offset += cpu_ticks_prev - ticks;
600 }
601 cpu_ticks_prev = ticks;
602 return ticks + cpu_ticks_offset;
603 }
604 }
606 /* enable cpu_get_ticks() */
607 void cpu_enable_ticks(void)
608 {
609 if (!cpu_ticks_enabled) {
610 cpu_ticks_offset -= cpu_get_real_ticks();
611 cpu_ticks_enabled = 1;
612 }
613 }
615 /* disable cpu_get_ticks() : the clock is stopped. You must not call
616 cpu_get_ticks() after that. */
617 void cpu_disable_ticks(void)
618 {
619 if (cpu_ticks_enabled) {
620 cpu_ticks_offset = cpu_get_ticks();
621 cpu_ticks_enabled = 0;
622 }
623 }
625 #ifdef _WIN32
626 void cpu_calibrate_ticks(void)
627 {
628 LARGE_INTEGER freq;
629 int ret;
631 ret = QueryPerformanceFrequency(&freq);
632 if (ret == 0) {
633 fprintf(stderr, "Could not calibrate ticks\n");
634 exit(1);
635 }
636 ticks_per_sec = freq.QuadPart;
637 }
639 #else
640 static int64_t get_clock(void)
641 {
642 struct timeval tv;
643 gettimeofday(&tv, NULL);
644 return tv.tv_sec * 1000000LL + tv.tv_usec;
645 }
647 void cpu_calibrate_ticks(void)
648 {
649 int64_t usec, ticks;
651 usec = get_clock();
652 ticks = cpu_get_real_ticks();
653 usleep(50 * 1000);
654 usec = get_clock() - usec;
655 ticks = cpu_get_real_ticks() - ticks;
656 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
657 }
658 #endif /* !_WIN32 */
660 /* compute with 96 bit intermediate result: (a*b)/c */
661 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
662 {
663 union {
664 uint64_t ll;
665 struct {
666 #ifdef WORDS_BIGENDIAN
667 uint32_t high, low;
668 #else
669 uint32_t low, high;
670 #endif
671 } l;
672 } u, res;
673 uint64_t rl, rh;
675 u.ll = a;
676 rl = (uint64_t)u.l.low * (uint64_t)b;
677 rh = (uint64_t)u.l.high * (uint64_t)b;
678 rh += (rl >> 32);
679 res.l.high = rh / c;
680 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
681 return res.ll;
682 }
684 #define QEMU_TIMER_REALTIME 0
685 #define QEMU_TIMER_VIRTUAL 1
687 struct QEMUClock {
688 int type;
689 /* XXX: add frequency */
690 };
692 struct QEMUTimer {
693 QEMUClock *clock;
694 int64_t expire_time;
695 QEMUTimerCB *cb;
696 void *opaque;
697 struct QEMUTimer *next;
698 };
700 QEMUClock *rt_clock;
701 QEMUClock *vm_clock;
703 static QEMUTimer *active_timers[2];
704 #ifdef _WIN32
705 static MMRESULT timerID;
706 static HANDLE host_alarm = NULL;
707 static unsigned int period = 1;
708 #else
709 /* frequency of the times() clock tick */
710 static int timer_freq;
711 #endif
713 QEMUClock *qemu_new_clock(int type)
714 {
715 QEMUClock *clock;
716 clock = qemu_mallocz(sizeof(QEMUClock));
717 if (!clock)
718 return NULL;
719 clock->type = type;
720 return clock;
721 }
723 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
724 {
725 QEMUTimer *ts;
727 ts = qemu_mallocz(sizeof(QEMUTimer));
728 ts->clock = clock;
729 ts->cb = cb;
730 ts->opaque = opaque;
731 return ts;
732 }
734 void qemu_free_timer(QEMUTimer *ts)
735 {
736 qemu_free(ts);
737 }
739 /* stop a timer, but do not dealloc it */
740 void qemu_del_timer(QEMUTimer *ts)
741 {
742 QEMUTimer **pt, *t;
744 /* NOTE: this code must be signal safe because
745 qemu_timer_expired() can be called from a signal. */
746 pt = &active_timers[ts->clock->type];
747 for(;;) {
748 t = *pt;
749 if (!t)
750 break;
751 if (t == ts) {
752 *pt = t->next;
753 break;
754 }
755 pt = &t->next;
756 }
757 }
759 /* modify the current timer so that it will be fired when current_time
760 >= expire_time. The corresponding callback will be called. */
761 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
762 {
763 QEMUTimer **pt, *t;
765 qemu_del_timer(ts);
767 /* add the timer in the sorted list */
768 /* NOTE: this code must be signal safe because
769 qemu_timer_expired() can be called from a signal. */
770 pt = &active_timers[ts->clock->type];
771 for(;;) {
772 t = *pt;
773 if (!t)
774 break;
775 if (t->expire_time > expire_time)
776 break;
777 pt = &t->next;
778 }
779 ts->expire_time = expire_time;
780 ts->next = *pt;
781 *pt = ts;
782 }
784 int qemu_timer_pending(QEMUTimer *ts)
785 {
786 QEMUTimer *t;
787 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
788 if (t == ts)
789 return 1;
790 }
791 return 0;
792 }
794 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
795 {
796 if (!timer_head)
797 return 0;
798 return (timer_head->expire_time <= current_time);
799 }
801 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
802 {
803 QEMUTimer *ts;
805 for(;;) {
806 ts = *ptimer_head;
807 if (!ts || ts->expire_time > current_time)
808 break;
809 /* remove timer from the list before calling the callback */
810 *ptimer_head = ts->next;
811 ts->next = NULL;
813 /* run the callback (the timer list can be modified) */
814 ts->cb(ts->opaque);
815 }
816 }
818 int64_t qemu_get_clock(QEMUClock *clock)
819 {
820 switch(clock->type) {
821 case QEMU_TIMER_REALTIME:
822 #ifdef _WIN32
823 return GetTickCount();
824 #else
825 {
826 struct tms tp;
828 /* Note that using gettimeofday() is not a good solution
829 for timers because its value change when the date is
830 modified. */
831 if (timer_freq == 100) {
832 return times(&tp) * 10;
833 } else {
834 return ((int64_t)times(&tp) * 1000) / timer_freq;
835 }
836 }
837 #endif
838 default:
839 case QEMU_TIMER_VIRTUAL:
840 return cpu_get_ticks();
841 }
842 }
844 /* save a timer */
845 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
846 {
847 uint64_t expire_time;
849 if (qemu_timer_pending(ts)) {
850 expire_time = ts->expire_time;
851 } else {
852 expire_time = -1;
853 }
854 qemu_put_be64(f, expire_time);
855 }
857 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
858 {
859 uint64_t expire_time;
861 expire_time = qemu_get_be64(f);
862 if (expire_time != -1) {
863 qemu_mod_timer(ts, expire_time);
864 } else {
865 qemu_del_timer(ts);
866 }
867 }
869 #ifdef CONFIG_DM
870 static void timer_save(QEMUFile *f, void *opaque)
871 {
872 }
874 static int timer_load(QEMUFile *f, void *opaque, int version_id)
875 {
876 return 0;
877 }
878 #else /* !CONFIG_DM */
879 static void timer_save(QEMUFile *f, void *opaque)
880 {
881 if (cpu_ticks_enabled) {
882 hw_error("cannot save state if virtual timers are running");
883 }
884 qemu_put_be64s(f, &cpu_ticks_offset);
885 qemu_put_be64s(f, &ticks_per_sec);
886 }
888 static int timer_load(QEMUFile *f, void *opaque, int version_id)
889 {
890 if (version_id != 1)
891 return -EINVAL;
892 if (cpu_ticks_enabled) {
893 return -EINVAL;
894 }
895 qemu_get_be64s(f, &cpu_ticks_offset);
896 qemu_get_be64s(f, &ticks_per_sec);
897 return 0;
898 }
900 #ifdef _WIN32
901 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
902 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
903 #else
904 static void host_alarm_handler(int host_signum)
905 #endif
906 {
907 #if 0
908 #define DISP_FREQ 1000
909 {
910 static int64_t delta_min = INT64_MAX;
911 static int64_t delta_max, delta_cum, last_clock, delta, ti;
912 static int count;
913 ti = qemu_get_clock(vm_clock);
914 if (last_clock != 0) {
915 delta = ti - last_clock;
916 if (delta < delta_min)
917 delta_min = delta;
918 if (delta > delta_max)
919 delta_max = delta;
920 delta_cum += delta;
921 if (++count == DISP_FREQ) {
922 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
923 muldiv64(delta_min, 1000000, ticks_per_sec),
924 muldiv64(delta_max, 1000000, ticks_per_sec),
925 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
926 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
927 count = 0;
928 delta_min = INT64_MAX;
929 delta_max = 0;
930 delta_cum = 0;
931 }
932 }
933 last_clock = ti;
934 }
935 #endif
936 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
937 qemu_get_clock(vm_clock)) ||
938 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
939 qemu_get_clock(rt_clock))) {
940 #ifdef _WIN32
941 SetEvent(host_alarm);
942 #endif
943 CPUState *env = cpu_single_env;
944 if (env) {
945 /* stop the currently executing cpu because a timer occured */
946 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
947 #ifdef USE_KQEMU
948 if (env->kqemu_enabled) {
949 kqemu_cpu_interrupt(env);
950 }
951 #endif
952 }
953 }
954 }
956 #ifndef _WIN32
958 #if defined(__linux__)
960 #define RTC_FREQ 1024
962 static int rtc_fd;
964 static int start_rtc_timer(void)
965 {
966 rtc_fd = open("/dev/rtc", O_RDONLY);
967 if (rtc_fd < 0)
968 return -1;
969 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
970 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
971 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
972 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
973 goto fail;
974 }
975 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
976 fail:
977 close(rtc_fd);
978 return -1;
979 }
980 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
981 return 0;
982 }
984 #else
986 static int start_rtc_timer(void)
987 {
988 return -1;
989 }
991 #endif /* !defined(__linux__) */
993 #endif /* !defined(_WIN32) */
995 #endif /* !CONFIG_DM */
997 static void init_timers(void)
998 {
999 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1000 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1002 #ifdef _WIN32
1004 int count=0;
1005 TIMECAPS tc;
1007 ZeroMemory(&tc, sizeof(TIMECAPS));
1008 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1009 if (period < tc.wPeriodMin)
1010 period = tc.wPeriodMin;
1011 timeBeginPeriod(period);
1012 timerID = timeSetEvent(1, // interval (ms)
1013 period, // resolution
1014 host_alarm_handler, // function
1015 (DWORD)&count, // user parameter
1016 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1017 if( !timerID ) {
1018 perror("failed timer alarm");
1019 exit(1);
1021 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1022 if (!host_alarm) {
1023 perror("failed CreateEvent");
1024 exit(1);
1026 ResetEvent(host_alarm);
1028 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1029 #else
1031 #ifndef CONFIG_DM
1032 struct sigaction act;
1033 struct itimerval itv;
1034 #endif
1036 /* get times() syscall frequency */
1037 timer_freq = sysconf(_SC_CLK_TCK);
1039 #ifndef CONFIG_DM
1040 /* timer signal */
1041 sigfillset(&act.sa_mask);
1042 act.sa_flags = 0;
1043 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1044 act.sa_flags |= SA_ONSTACK;
1045 #endif
1046 act.sa_handler = host_alarm_handler;
1047 sigaction(SIGALRM, &act, NULL);
1049 itv.it_interval.tv_sec = 0;
1050 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1051 itv.it_value.tv_sec = 0;
1052 itv.it_value.tv_usec = 10 * 1000;
1053 setitimer(ITIMER_REAL, &itv, NULL);
1054 /* we probe the tick duration of the kernel to inform the user if
1055 the emulated kernel requested a too high timer frequency */
1056 getitimer(ITIMER_REAL, &itv);
1058 #if defined(__linux__)
1059 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1060 have timers with 1 ms resolution. The correct solution will
1061 be to use the POSIX real time timers available in recent
1062 2.6 kernels */
1063 if (itv.it_interval.tv_usec > 1000 || 1) {
1064 /* try to use /dev/rtc to have a faster timer */
1065 if (start_rtc_timer() < 0)
1066 goto use_itimer;
1067 /* disable itimer */
1068 itv.it_interval.tv_sec = 0;
1069 itv.it_interval.tv_usec = 0;
1070 itv.it_value.tv_sec = 0;
1071 itv.it_value.tv_usec = 0;
1072 setitimer(ITIMER_REAL, &itv, NULL);
1074 /* use the RTC */
1075 sigaction(SIGIO, &act, NULL);
1076 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1077 fcntl(rtc_fd, F_SETOWN, getpid());
1078 } else
1079 #endif /* defined(__linux__) */
1081 use_itimer:
1082 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1083 PIT_FREQ) / 1000000;
1085 #endif /* CONFIG_DM */
1087 #endif
1090 void quit_timers(void)
1092 #ifdef _WIN32
1093 timeKillEvent(timerID);
1094 timeEndPeriod(period);
1095 if (host_alarm) {
1096 CloseHandle(host_alarm);
1097 host_alarm = NULL;
1099 #endif
1102 /***********************************************************/
1103 /* character device */
1105 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1107 return s->chr_write(s, buf, len);
1110 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1112 if (!s->chr_ioctl)
1113 return -ENOTSUP;
1114 return s->chr_ioctl(s, cmd, arg);
1117 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1119 char buf[4096];
1120 va_list ap;
1121 va_start(ap, fmt);
1122 vsnprintf(buf, sizeof(buf), fmt, ap);
1123 qemu_chr_write(s, buf, strlen(buf));
1124 va_end(ap);
1127 void qemu_chr_send_event(CharDriverState *s, int event)
1129 if (s->chr_send_event)
1130 s->chr_send_event(s, event);
1133 void qemu_chr_add_read_handler(CharDriverState *s,
1134 IOCanRWHandler *fd_can_read,
1135 IOReadHandler *fd_read, void *opaque)
1137 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1140 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1142 s->chr_event = chr_event;
1145 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1147 return len;
1150 static void null_chr_add_read_handler(CharDriverState *chr,
1151 IOCanRWHandler *fd_can_read,
1152 IOReadHandler *fd_read, void *opaque)
1156 CharDriverState *qemu_chr_open_null(void)
1158 CharDriverState *chr;
1160 chr = qemu_mallocz(sizeof(CharDriverState));
1161 if (!chr)
1162 return NULL;
1163 chr->chr_write = null_chr_write;
1164 chr->chr_add_read_handler = null_chr_add_read_handler;
1165 return chr;
1168 #ifdef _WIN32
1170 static void socket_cleanup(void)
1172 WSACleanup();
1175 static int socket_init(void)
1177 WSADATA Data;
1178 int ret, err;
1180 ret = WSAStartup(MAKEWORD(2,2), &Data);
1181 if (ret != 0) {
1182 err = WSAGetLastError();
1183 fprintf(stderr, "WSAStartup: %d\n", err);
1184 return -1;
1186 atexit(socket_cleanup);
1187 return 0;
1190 static int send_all(int fd, const uint8_t *buf, int len1)
1192 int ret, len;
1194 len = len1;
1195 while (len > 0) {
1196 ret = send(fd, buf, len, 0);
1197 if (ret < 0) {
1198 int errno;
1199 errno = WSAGetLastError();
1200 if (errno != WSAEWOULDBLOCK) {
1201 return -1;
1203 } else if (ret == 0) {
1204 break;
1205 } else {
1206 buf += ret;
1207 len -= ret;
1210 return len1 - len;
1213 void socket_set_nonblock(int fd)
1215 unsigned long opt = 1;
1216 ioctlsocket(fd, FIONBIO, &opt);
1219 #else
1221 static int unix_write(int fd, const uint8_t *buf, int len1)
1223 int ret, sel_ret, len;
1224 int max_fd;
1225 fd_set writefds;
1226 struct timeval timeout;
1228 max_fd = fd;
1230 len = len1;
1231 while (len > 0) {
1232 FD_ZERO(&writefds);
1233 FD_SET(fd, &writefds);
1234 timeout.tv_sec = 0;
1235 timeout.tv_usec = 0;
1236 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1237 if (sel_ret <= 0) {
1238 /* Timeout or select error */
1239 return -1;
1240 } else {
1241 ret = write(fd, buf, len);
1242 if (ret < 0) {
1243 if (errno != EINTR && errno != EAGAIN)
1244 return -1;
1245 } else if (ret == 0) {
1246 break;
1247 } else {
1248 buf += ret;
1249 len -= ret;
1253 return len1 - len;
1256 static inline int send_all(int fd, const uint8_t *buf, int len1)
1258 return unix_write(fd, buf, len1);
1261 void socket_set_nonblock(int fd)
1263 fcntl(fd, F_SETFL, O_NONBLOCK);
1265 #endif /* !_WIN32 */
1267 #ifndef _WIN32
1269 typedef struct {
1270 int fd_in, fd_out;
1271 IOCanRWHandler *fd_can_read;
1272 IOReadHandler *fd_read;
1273 void *fd_opaque;
1274 int max_size;
1275 } FDCharDriver;
1277 #define STDIO_MAX_CLIENTS 2
1279 static int stdio_nb_clients;
1280 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1282 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1284 FDCharDriver *s = chr->opaque;
1285 return unix_write(s->fd_out, buf, len);
1288 static int fd_chr_read_poll(void *opaque)
1290 CharDriverState *chr = opaque;
1291 FDCharDriver *s = chr->opaque;
1293 s->max_size = s->fd_can_read(s->fd_opaque);
1294 return s->max_size;
1297 static void fd_chr_read(void *opaque)
1299 CharDriverState *chr = opaque;
1300 FDCharDriver *s = chr->opaque;
1301 int size, len;
1302 uint8_t buf[1024];
1304 len = sizeof(buf);
1305 if (len > s->max_size)
1306 len = s->max_size;
1307 if (len == 0)
1308 return;
1309 size = read(s->fd_in, buf, len);
1310 if (size > 0) {
1311 s->fd_read(s->fd_opaque, buf, size);
1315 static void fd_chr_add_read_handler(CharDriverState *chr,
1316 IOCanRWHandler *fd_can_read,
1317 IOReadHandler *fd_read, void *opaque)
1319 FDCharDriver *s = chr->opaque;
1321 if (s->fd_in >= 0) {
1322 s->fd_can_read = fd_can_read;
1323 s->fd_read = fd_read;
1324 s->fd_opaque = opaque;
1325 if (nographic && s->fd_in == 0) {
1326 } else {
1327 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1328 fd_chr_read, NULL, chr);
1333 /* open a character device to a unix fd */
1334 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1336 CharDriverState *chr;
1337 FDCharDriver *s;
1339 chr = qemu_mallocz(sizeof(CharDriverState));
1340 if (!chr)
1341 return NULL;
1342 s = qemu_mallocz(sizeof(FDCharDriver));
1343 if (!s) {
1344 free(chr);
1345 return NULL;
1347 s->fd_in = fd_in;
1348 s->fd_out = fd_out;
1349 chr->opaque = s;
1350 chr->chr_write = fd_chr_write;
1351 chr->chr_add_read_handler = fd_chr_add_read_handler;
1352 return chr;
1355 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1357 int fd_out;
1359 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1360 if (fd_out < 0)
1361 return NULL;
1362 return qemu_chr_open_fd(-1, fd_out);
1365 CharDriverState *qemu_chr_open_pipe(const char *filename)
1367 int fd;
1369 fd = open(filename, O_RDWR | O_BINARY);
1370 if (fd < 0)
1371 return NULL;
1372 return qemu_chr_open_fd(fd, fd);
1376 /* for STDIO, we handle the case where several clients use it
1377 (nographic mode) */
1379 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1381 #define TERM_FIFO_MAX_SIZE 1
1383 static int term_got_escape, client_index;
1384 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1385 int term_fifo_size;
1387 void term_print_help(void)
1389 printf("\n"
1390 "C-a h print this help\n"
1391 "C-a x exit emulator\n"
1392 "C-a s save disk data back to file (if -snapshot)\n"
1393 "C-a b send break (magic sysrq)\n"
1394 "C-a c switch between console and monitor\n"
1395 "C-a C-a send C-a\n"
1396 );
1399 /* called when a char is received */
1400 static void stdio_received_byte(int ch)
1402 if (term_got_escape) {
1403 term_got_escape = 0;
1404 switch(ch) {
1405 case 'h':
1406 term_print_help();
1407 break;
1408 case 'x':
1409 exit(0);
1410 break;
1411 case 's':
1413 int i;
1414 for (i = 0; i < MAX_DISKS; i++) {
1415 if (bs_table[i])
1416 bdrv_commit(bs_table[i]);
1419 break;
1420 case 'b':
1421 if (client_index < stdio_nb_clients) {
1422 CharDriverState *chr;
1423 FDCharDriver *s;
1425 chr = stdio_clients[client_index];
1426 s = chr->opaque;
1427 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1429 break;
1430 case 'c':
1431 client_index++;
1432 if (client_index >= stdio_nb_clients)
1433 client_index = 0;
1434 if (client_index == 0) {
1435 /* send a new line in the monitor to get the prompt */
1436 ch = '\r';
1437 goto send_char;
1439 break;
1440 case TERM_ESCAPE:
1441 goto send_char;
1443 } else if (ch == TERM_ESCAPE) {
1444 term_got_escape = 1;
1445 } else {
1446 send_char:
1447 if (client_index < stdio_nb_clients) {
1448 uint8_t buf[1];
1449 CharDriverState *chr;
1450 FDCharDriver *s;
1452 chr = stdio_clients[client_index];
1453 s = chr->opaque;
1454 if (s->fd_can_read(s->fd_opaque) > 0) {
1455 buf[0] = ch;
1456 s->fd_read(s->fd_opaque, buf, 1);
1457 } else if (term_fifo_size == 0) {
1458 term_fifo[term_fifo_size++] = ch;
1464 static int stdio_read_poll(void *opaque)
1466 CharDriverState *chr;
1467 FDCharDriver *s;
1469 if (client_index < stdio_nb_clients) {
1470 chr = stdio_clients[client_index];
1471 s = chr->opaque;
1472 /* try to flush the queue if needed */
1473 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1474 s->fd_read(s->fd_opaque, term_fifo, 1);
1475 term_fifo_size = 0;
1477 /* see if we can absorb more chars */
1478 if (term_fifo_size == 0)
1479 return 1;
1480 else
1481 return 0;
1482 } else {
1483 return 1;
1487 static void stdio_read(void *opaque)
1489 int size;
1490 uint8_t buf[1];
1492 size = read(0, buf, 1);
1493 if (size > 0)
1494 stdio_received_byte(buf[0]);
1497 /* init terminal so that we can grab keys */
1498 static struct termios oldtty;
1499 static int old_fd0_flags;
1501 static void term_exit(void)
1503 tcsetattr (0, TCSANOW, &oldtty);
1504 fcntl(0, F_SETFL, old_fd0_flags);
1507 static void term_init(void)
1509 struct termios tty;
1511 tcgetattr (0, &tty);
1512 oldtty = tty;
1513 old_fd0_flags = fcntl(0, F_GETFL);
1515 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1516 |INLCR|IGNCR|ICRNL|IXON);
1517 tty.c_oflag |= OPOST;
1518 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1519 /* if graphical mode, we allow Ctrl-C handling */
1520 if (nographic)
1521 tty.c_lflag &= ~ISIG;
1522 tty.c_cflag &= ~(CSIZE|PARENB);
1523 tty.c_cflag |= CS8;
1524 tty.c_cc[VMIN] = 1;
1525 tty.c_cc[VTIME] = 0;
1527 tcsetattr (0, TCSANOW, &tty);
1529 atexit(term_exit);
1531 fcntl(0, F_SETFL, O_NONBLOCK);
1534 CharDriverState *qemu_chr_open_stdio(void)
1536 CharDriverState *chr;
1538 if (nographic) {
1539 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1540 return NULL;
1541 chr = qemu_chr_open_fd(0, 1);
1542 if (stdio_nb_clients == 0)
1543 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1544 client_index = stdio_nb_clients;
1545 } else {
1546 if (stdio_nb_clients != 0)
1547 return NULL;
1548 chr = qemu_chr_open_fd(0, 1);
1550 stdio_clients[stdio_nb_clients++] = chr;
1551 if (stdio_nb_clients == 1) {
1552 /* set the terminal in raw mode */
1553 term_init();
1555 return chr;
1558 int store_console_dev(int domid, char *pts)
1560 int xc_handle;
1561 struct xs_handle *xs;
1562 char *path;
1564 xs = xs_daemon_open();
1565 if (xs == NULL) {
1566 fprintf(logfile, "Could not contact XenStore\n");
1567 return -1;
1570 xc_handle = xc_interface_open();
1571 if (xc_handle == -1) {
1572 fprintf(logfile, "xc_interface_open() error\n");
1573 return -1;
1576 path = xs_get_domain_path(xs, domid);
1577 if (path == NULL) {
1578 fprintf(logfile, "xs_get_domain_path() error\n");
1579 return -1;
1581 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1582 if (path == NULL) {
1583 fprintf(logfile, "realloc error\n");
1584 return -1;
1586 strcat(path, "/console/tty");
1587 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1588 fprintf(logfile, "xs_write for console fail");
1589 return -1;
1592 free(path);
1593 xs_daemon_close(xs);
1594 close(xc_handle);
1596 return 0;
1599 #if defined(__linux__)
1600 CharDriverState *qemu_chr_open_pty(void)
1602 struct termios tty;
1603 int master_fd, slave_fd;
1605 /* Not satisfying */
1606 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1607 return NULL;
1610 /* Set raw attributes on the pty. */
1611 cfmakeraw(&tty);
1612 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1614 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1615 store_console_dev(domid, ptsname(master_fd));
1617 return qemu_chr_open_fd(master_fd, master_fd);
1620 static void tty_serial_init(int fd, int speed,
1621 int parity, int data_bits, int stop_bits)
1623 struct termios tty;
1624 speed_t spd;
1626 #if 0
1627 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1628 speed, parity, data_bits, stop_bits);
1629 #endif
1630 tcgetattr (fd, &tty);
1632 switch(speed) {
1633 case 50:
1634 spd = B50;
1635 break;
1636 case 75:
1637 spd = B75;
1638 break;
1639 case 300:
1640 spd = B300;
1641 break;
1642 case 600:
1643 spd = B600;
1644 break;
1645 case 1200:
1646 spd = B1200;
1647 break;
1648 case 2400:
1649 spd = B2400;
1650 break;
1651 case 4800:
1652 spd = B4800;
1653 break;
1654 case 9600:
1655 spd = B9600;
1656 break;
1657 case 19200:
1658 spd = B19200;
1659 break;
1660 case 38400:
1661 spd = B38400;
1662 break;
1663 case 57600:
1664 spd = B57600;
1665 break;
1666 default:
1667 case 115200:
1668 spd = B115200;
1669 break;
1672 cfsetispeed(&tty, spd);
1673 cfsetospeed(&tty, spd);
1675 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1676 |INLCR|IGNCR|ICRNL|IXON);
1677 tty.c_oflag |= OPOST;
1678 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1679 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1680 switch(data_bits) {
1681 default:
1682 case 8:
1683 tty.c_cflag |= CS8;
1684 break;
1685 case 7:
1686 tty.c_cflag |= CS7;
1687 break;
1688 case 6:
1689 tty.c_cflag |= CS6;
1690 break;
1691 case 5:
1692 tty.c_cflag |= CS5;
1693 break;
1695 switch(parity) {
1696 default:
1697 case 'N':
1698 break;
1699 case 'E':
1700 tty.c_cflag |= PARENB;
1701 break;
1702 case 'O':
1703 tty.c_cflag |= PARENB | PARODD;
1704 break;
1707 tcsetattr (fd, TCSANOW, &tty);
1710 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1712 FDCharDriver *s = chr->opaque;
1714 switch(cmd) {
1715 case CHR_IOCTL_SERIAL_SET_PARAMS:
1717 QEMUSerialSetParams *ssp = arg;
1718 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1719 ssp->data_bits, ssp->stop_bits);
1721 break;
1722 case CHR_IOCTL_SERIAL_SET_BREAK:
1724 int enable = *(int *)arg;
1725 if (enable)
1726 tcsendbreak(s->fd_in, 1);
1728 break;
1729 default:
1730 return -ENOTSUP;
1732 return 0;
1735 CharDriverState *qemu_chr_open_tty(const char *filename)
1737 CharDriverState *chr;
1738 int fd;
1740 fd = open(filename, O_RDWR | O_NONBLOCK);
1741 if (fd < 0)
1742 return NULL;
1743 fcntl(fd, F_SETFL, O_NONBLOCK);
1744 tty_serial_init(fd, 115200, 'N', 8, 1);
1745 chr = qemu_chr_open_fd(fd, fd);
1746 if (!chr)
1747 return NULL;
1748 chr->chr_ioctl = tty_serial_ioctl;
1749 return chr;
1752 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1754 int fd = (int)chr->opaque;
1755 uint8_t b;
1757 switch(cmd) {
1758 case CHR_IOCTL_PP_READ_DATA:
1759 if (ioctl(fd, PPRDATA, &b) < 0)
1760 return -ENOTSUP;
1761 *(uint8_t *)arg = b;
1762 break;
1763 case CHR_IOCTL_PP_WRITE_DATA:
1764 b = *(uint8_t *)arg;
1765 if (ioctl(fd, PPWDATA, &b) < 0)
1766 return -ENOTSUP;
1767 break;
1768 case CHR_IOCTL_PP_READ_CONTROL:
1769 if (ioctl(fd, PPRCONTROL, &b) < 0)
1770 return -ENOTSUP;
1771 *(uint8_t *)arg = b;
1772 break;
1773 case CHR_IOCTL_PP_WRITE_CONTROL:
1774 b = *(uint8_t *)arg;
1775 if (ioctl(fd, PPWCONTROL, &b) < 0)
1776 return -ENOTSUP;
1777 break;
1778 case CHR_IOCTL_PP_READ_STATUS:
1779 if (ioctl(fd, PPRSTATUS, &b) < 0)
1780 return -ENOTSUP;
1781 *(uint8_t *)arg = b;
1782 break;
1783 default:
1784 return -ENOTSUP;
1786 return 0;
1789 CharDriverState *qemu_chr_open_pp(const char *filename)
1791 CharDriverState *chr;
1792 int fd;
1794 fd = open(filename, O_RDWR);
1795 if (fd < 0)
1796 return NULL;
1798 if (ioctl(fd, PPCLAIM) < 0) {
1799 close(fd);
1800 return NULL;
1803 chr = qemu_mallocz(sizeof(CharDriverState));
1804 if (!chr) {
1805 close(fd);
1806 return NULL;
1808 chr->opaque = (void *)fd;
1809 chr->chr_write = null_chr_write;
1810 chr->chr_add_read_handler = null_chr_add_read_handler;
1811 chr->chr_ioctl = pp_ioctl;
1812 return chr;
1815 #else
1816 CharDriverState *qemu_chr_open_pty(void)
1818 return NULL;
1820 #endif
1822 #endif /* !defined(_WIN32) */
1824 #ifdef _WIN32
1825 typedef struct {
1826 IOCanRWHandler *fd_can_read;
1827 IOReadHandler *fd_read;
1828 void *win_opaque;
1829 int max_size;
1830 HANDLE hcom, hrecv, hsend;
1831 OVERLAPPED orecv, osend;
1832 BOOL fpipe;
1833 DWORD len;
1834 } WinCharState;
1836 #define NSENDBUF 2048
1837 #define NRECVBUF 2048
1838 #define MAXCONNECT 1
1839 #define NTIMEOUT 5000
1841 static int win_chr_poll(void *opaque);
1842 static int win_chr_pipe_poll(void *opaque);
1844 static void win_chr_close2(WinCharState *s)
1846 if (s->hsend) {
1847 CloseHandle(s->hsend);
1848 s->hsend = NULL;
1850 if (s->hrecv) {
1851 CloseHandle(s->hrecv);
1852 s->hrecv = NULL;
1854 if (s->hcom) {
1855 CloseHandle(s->hcom);
1856 s->hcom = NULL;
1858 if (s->fpipe)
1859 qemu_del_polling_cb(win_chr_pipe_poll, s);
1860 else
1861 qemu_del_polling_cb(win_chr_poll, s);
1864 static void win_chr_close(CharDriverState *chr)
1866 WinCharState *s = chr->opaque;
1867 win_chr_close2(s);
1870 static int win_chr_init(WinCharState *s, const char *filename)
1872 COMMCONFIG comcfg;
1873 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1874 COMSTAT comstat;
1875 DWORD size;
1876 DWORD err;
1878 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1879 if (!s->hsend) {
1880 fprintf(stderr, "Failed CreateEvent\n");
1881 goto fail;
1883 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1884 if (!s->hrecv) {
1885 fprintf(stderr, "Failed CreateEvent\n");
1886 goto fail;
1889 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1890 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1891 if (s->hcom == INVALID_HANDLE_VALUE) {
1892 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1893 s->hcom = NULL;
1894 goto fail;
1897 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1898 fprintf(stderr, "Failed SetupComm\n");
1899 goto fail;
1902 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1903 size = sizeof(COMMCONFIG);
1904 GetDefaultCommConfig(filename, &comcfg, &size);
1905 comcfg.dcb.DCBlength = sizeof(DCB);
1906 CommConfigDialog(filename, NULL, &comcfg);
1908 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1909 fprintf(stderr, "Failed SetCommState\n");
1910 goto fail;
1913 if (!SetCommMask(s->hcom, EV_ERR)) {
1914 fprintf(stderr, "Failed SetCommMask\n");
1915 goto fail;
1918 cto.ReadIntervalTimeout = MAXDWORD;
1919 if (!SetCommTimeouts(s->hcom, &cto)) {
1920 fprintf(stderr, "Failed SetCommTimeouts\n");
1921 goto fail;
1924 if (!ClearCommError(s->hcom, &err, &comstat)) {
1925 fprintf(stderr, "Failed ClearCommError\n");
1926 goto fail;
1928 qemu_add_polling_cb(win_chr_poll, s);
1929 return 0;
1931 fail:
1932 win_chr_close2(s);
1933 return -1;
1936 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1938 WinCharState *s = chr->opaque;
1939 DWORD len, ret, size, err;
1941 len = len1;
1942 ZeroMemory(&s->osend, sizeof(s->osend));
1943 s->osend.hEvent = s->hsend;
1944 while (len > 0) {
1945 if (s->hsend)
1946 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1947 else
1948 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1949 if (!ret) {
1950 err = GetLastError();
1951 if (err == ERROR_IO_PENDING) {
1952 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1953 if (ret) {
1954 buf += size;
1955 len -= size;
1956 } else {
1957 break;
1959 } else {
1960 break;
1962 } else {
1963 buf += size;
1964 len -= size;
1967 return len1 - len;
1970 static int win_chr_read_poll(WinCharState *s)
1972 s->max_size = s->fd_can_read(s->win_opaque);
1973 return s->max_size;
1976 static void win_chr_readfile(WinCharState *s)
1978 int ret, err;
1979 uint8_t buf[1024];
1980 DWORD size;
1982 ZeroMemory(&s->orecv, sizeof(s->orecv));
1983 s->orecv.hEvent = s->hrecv;
1984 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1985 if (!ret) {
1986 err = GetLastError();
1987 if (err == ERROR_IO_PENDING) {
1988 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1992 if (size > 0) {
1993 s->fd_read(s->win_opaque, buf, size);
1997 static void win_chr_read(WinCharState *s)
1999 if (s->len > s->max_size)
2000 s->len = s->max_size;
2001 if (s->len == 0)
2002 return;
2004 win_chr_readfile(s);
2007 static int win_chr_poll(void *opaque)
2009 WinCharState *s = opaque;
2010 COMSTAT status;
2011 DWORD comerr;
2013 ClearCommError(s->hcom, &comerr, &status);
2014 if (status.cbInQue > 0) {
2015 s->len = status.cbInQue;
2016 win_chr_read_poll(s);
2017 win_chr_read(s);
2018 return 1;
2020 return 0;
2023 static void win_chr_add_read_handler(CharDriverState *chr,
2024 IOCanRWHandler *fd_can_read,
2025 IOReadHandler *fd_read, void *opaque)
2027 WinCharState *s = chr->opaque;
2029 s->fd_can_read = fd_can_read;
2030 s->fd_read = fd_read;
2031 s->win_opaque = opaque;
2034 CharDriverState *qemu_chr_open_win(const char *filename)
2036 CharDriverState *chr;
2037 WinCharState *s;
2039 chr = qemu_mallocz(sizeof(CharDriverState));
2040 if (!chr)
2041 return NULL;
2042 s = qemu_mallocz(sizeof(WinCharState));
2043 if (!s) {
2044 free(chr);
2045 return NULL;
2047 chr->opaque = s;
2048 chr->chr_write = win_chr_write;
2049 chr->chr_add_read_handler = win_chr_add_read_handler;
2050 chr->chr_close = win_chr_close;
2052 if (win_chr_init(s, filename) < 0) {
2053 free(s);
2054 free(chr);
2055 return NULL;
2057 return chr;
2060 static int win_chr_pipe_poll(void *opaque)
2062 WinCharState *s = opaque;
2063 DWORD size;
2065 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2066 if (size > 0) {
2067 s->len = size;
2068 win_chr_read_poll(s);
2069 win_chr_read(s);
2070 return 1;
2072 return 0;
2075 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2077 OVERLAPPED ov;
2078 int ret;
2079 DWORD size;
2080 char openname[256];
2082 s->fpipe = TRUE;
2084 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2085 if (!s->hsend) {
2086 fprintf(stderr, "Failed CreateEvent\n");
2087 goto fail;
2089 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2090 if (!s->hrecv) {
2091 fprintf(stderr, "Failed CreateEvent\n");
2092 goto fail;
2095 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2096 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2097 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2098 PIPE_WAIT,
2099 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2100 if (s->hcom == INVALID_HANDLE_VALUE) {
2101 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2102 s->hcom = NULL;
2103 goto fail;
2106 ZeroMemory(&ov, sizeof(ov));
2107 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2108 ret = ConnectNamedPipe(s->hcom, &ov);
2109 if (ret) {
2110 fprintf(stderr, "Failed ConnectNamedPipe\n");
2111 goto fail;
2114 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2115 if (!ret) {
2116 fprintf(stderr, "Failed GetOverlappedResult\n");
2117 if (ov.hEvent) {
2118 CloseHandle(ov.hEvent);
2119 ov.hEvent = NULL;
2121 goto fail;
2124 if (ov.hEvent) {
2125 CloseHandle(ov.hEvent);
2126 ov.hEvent = NULL;
2128 qemu_add_polling_cb(win_chr_pipe_poll, s);
2129 return 0;
2131 fail:
2132 win_chr_close2(s);
2133 return -1;
2137 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2139 CharDriverState *chr;
2140 WinCharState *s;
2142 chr = qemu_mallocz(sizeof(CharDriverState));
2143 if (!chr)
2144 return NULL;
2145 s = qemu_mallocz(sizeof(WinCharState));
2146 if (!s) {
2147 free(chr);
2148 return NULL;
2150 chr->opaque = s;
2151 chr->chr_write = win_chr_write;
2152 chr->chr_add_read_handler = win_chr_add_read_handler;
2153 chr->chr_close = win_chr_close;
2155 if (win_chr_pipe_init(s, filename) < 0) {
2156 free(s);
2157 free(chr);
2158 return NULL;
2160 return chr;
2163 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2165 CharDriverState *chr;
2166 WinCharState *s;
2168 chr = qemu_mallocz(sizeof(CharDriverState));
2169 if (!chr)
2170 return NULL;
2171 s = qemu_mallocz(sizeof(WinCharState));
2172 if (!s) {
2173 free(chr);
2174 return NULL;
2176 s->hcom = fd_out;
2177 chr->opaque = s;
2178 chr->chr_write = win_chr_write;
2179 chr->chr_add_read_handler = win_chr_add_read_handler;
2180 return chr;
2183 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2185 HANDLE fd_out;
2187 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2188 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2189 if (fd_out == INVALID_HANDLE_VALUE)
2190 return NULL;
2192 return qemu_chr_open_win_file(fd_out);
2194 #endif
2196 CharDriverState *qemu_chr_open(const char *filename)
2198 const char *p;
2200 if (!strcmp(filename, "vc")) {
2201 return text_console_init(&display_state);
2202 } else if (!strcmp(filename, "null")) {
2203 return qemu_chr_open_null();
2204 } else
2205 #ifndef _WIN32
2206 if (strstart(filename, "file:", &p)) {
2207 return qemu_chr_open_file_out(p);
2208 } else if (strstart(filename, "pipe:", &p)) {
2209 return qemu_chr_open_pipe(p);
2210 } else if (!strcmp(filename, "pty")) {
2211 return qemu_chr_open_pty();
2212 } else if (!strcmp(filename, "stdio")) {
2213 return qemu_chr_open_stdio();
2214 } else
2215 #endif
2216 #if defined(__linux__)
2217 if (strstart(filename, "/dev/parport", NULL)) {
2218 return qemu_chr_open_pp(filename);
2219 } else
2220 if (strstart(filename, "/dev/", NULL)) {
2221 return qemu_chr_open_tty(filename);
2222 } else
2223 #endif
2224 #ifdef _WIN32
2225 if (strstart(filename, "COM", NULL)) {
2226 return qemu_chr_open_win(filename);
2227 } else
2228 if (strstart(filename, "pipe:", &p)) {
2229 return qemu_chr_open_win_pipe(p);
2230 } else
2231 if (strstart(filename, "file:", &p)) {
2232 return qemu_chr_open_win_file_out(p);
2234 #endif
2236 return NULL;
2240 void qemu_chr_close(CharDriverState *chr)
2242 if (chr->chr_close)
2243 chr->chr_close(chr);
2246 /***********************************************************/
2247 /* network device redirectors */
2249 void hex_dump(FILE *f, const uint8_t *buf, int size)
2251 int len, i, j, c;
2253 for(i=0;i<size;i+=16) {
2254 len = size - i;
2255 if (len > 16)
2256 len = 16;
2257 fprintf(f, "%08x ", i);
2258 for(j=0;j<16;j++) {
2259 if (j < len)
2260 fprintf(f, " %02x", buf[i+j]);
2261 else
2262 fprintf(f, " ");
2264 fprintf(f, " ");
2265 for(j=0;j<len;j++) {
2266 c = buf[i+j];
2267 if (c < ' ' || c > '~')
2268 c = '.';
2269 fprintf(f, "%c", c);
2271 fprintf(f, "\n");
2275 static int parse_macaddr(uint8_t *macaddr, const char *p)
2277 int i;
2278 for(i = 0; i < 6; i++) {
2279 macaddr[i] = strtol(p, (char **)&p, 16);
2280 if (i == 5) {
2281 if (*p != '\0')
2282 return -1;
2283 } else {
2284 if (*p != ':')
2285 return -1;
2286 p++;
2289 return 0;
2292 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2294 const char *p, *p1;
2295 int len;
2296 p = *pp;
2297 p1 = strchr(p, sep);
2298 if (!p1)
2299 return -1;
2300 len = p1 - p;
2301 p1++;
2302 if (buf_size > 0) {
2303 if (len > buf_size - 1)
2304 len = buf_size - 1;
2305 memcpy(buf, p, len);
2306 buf[len] = '\0';
2308 *pp = p1;
2309 return 0;
2312 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2314 char buf[512];
2315 struct hostent *he;
2316 const char *p, *r;
2317 int port;
2319 p = str;
2320 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2321 return -1;
2322 saddr->sin_family = AF_INET;
2323 if (buf[0] == '\0') {
2324 saddr->sin_addr.s_addr = 0;
2325 } else {
2326 if (isdigit(buf[0])) {
2327 if (!inet_aton(buf, &saddr->sin_addr))
2328 return -1;
2329 } else {
2330 if ((he = gethostbyname(buf)) == NULL)
2331 return - 1;
2332 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2335 port = strtol(p, (char **)&r, 0);
2336 if (r == p)
2337 return -1;
2338 saddr->sin_port = htons(port);
2339 return 0;
2342 /* find or alloc a new VLAN */
2343 VLANState *qemu_find_vlan(int id)
2345 VLANState **pvlan, *vlan;
2346 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2347 if (vlan->id == id)
2348 return vlan;
2350 vlan = qemu_mallocz(sizeof(VLANState));
2351 if (!vlan)
2352 return NULL;
2353 vlan->id = id;
2354 vlan->next = NULL;
2355 pvlan = &first_vlan;
2356 while (*pvlan != NULL)
2357 pvlan = &(*pvlan)->next;
2358 *pvlan = vlan;
2359 return vlan;
2362 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2363 IOReadHandler *fd_read,
2364 IOCanRWHandler *fd_can_read,
2365 void *opaque)
2367 VLANClientState *vc, **pvc;
2368 vc = qemu_mallocz(sizeof(VLANClientState));
2369 if (!vc)
2370 return NULL;
2371 vc->fd_read = fd_read;
2372 vc->fd_can_read = fd_can_read;
2373 vc->opaque = opaque;
2374 vc->vlan = vlan;
2376 vc->next = NULL;
2377 pvc = &vlan->first_client;
2378 while (*pvc != NULL)
2379 pvc = &(*pvc)->next;
2380 *pvc = vc;
2381 return vc;
2384 int qemu_can_send_packet(VLANClientState *vc1)
2386 VLANState *vlan = vc1->vlan;
2387 VLANClientState *vc;
2389 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2390 if (vc != vc1) {
2391 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2392 return 0;
2395 return 1;
2398 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2400 VLANState *vlan = vc1->vlan;
2401 VLANClientState *vc;
2403 #if 0
2404 printf("vlan %d send:\n", vlan->id);
2405 hex_dump(stdout, buf, size);
2406 #endif
2407 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2408 if (vc != vc1) {
2409 vc->fd_read(vc->opaque, buf, size);
2414 #if defined(CONFIG_SLIRP)
2416 /* slirp network adapter */
2418 static int slirp_inited;
2419 static VLANClientState *slirp_vc;
2421 int slirp_can_output(void)
2423 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2426 void slirp_output(const uint8_t *pkt, int pkt_len)
2428 #if 0
2429 printf("slirp output:\n");
2430 hex_dump(stdout, pkt, pkt_len);
2431 #endif
2432 if (!slirp_vc)
2433 return;
2434 qemu_send_packet(slirp_vc, pkt, pkt_len);
2437 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2439 #if 0
2440 printf("slirp input:\n");
2441 hex_dump(stdout, buf, size);
2442 #endif
2443 slirp_input(buf, size);
2446 static int net_slirp_init(VLANState *vlan)
2448 if (!slirp_inited) {
2449 slirp_inited = 1;
2450 slirp_init();
2452 slirp_vc = qemu_new_vlan_client(vlan,
2453 slirp_receive, NULL, NULL);
2454 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2455 return 0;
2458 static void net_slirp_redir(const char *redir_str)
2460 int is_udp;
2461 char buf[256], *r;
2462 const char *p;
2463 struct in_addr guest_addr;
2464 int host_port, guest_port;
2466 if (!slirp_inited) {
2467 slirp_inited = 1;
2468 slirp_init();
2471 p = redir_str;
2472 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2473 goto fail;
2474 if (!strcmp(buf, "tcp")) {
2475 is_udp = 0;
2476 } else if (!strcmp(buf, "udp")) {
2477 is_udp = 1;
2478 } else {
2479 goto fail;
2482 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2483 goto fail;
2484 host_port = strtol(buf, &r, 0);
2485 if (r == buf)
2486 goto fail;
2488 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2489 goto fail;
2490 if (buf[0] == '\0') {
2491 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2493 if (!inet_aton(buf, &guest_addr))
2494 goto fail;
2496 guest_port = strtol(p, &r, 0);
2497 if (r == p)
2498 goto fail;
2500 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2501 fprintf(stderr, "qemu: could not set up redirection\n");
2502 exit(1);
2504 return;
2505 fail:
2506 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2507 exit(1);
2510 #ifndef _WIN32
2512 char smb_dir[1024];
2514 static void smb_exit(void)
2516 DIR *d;
2517 struct dirent *de;
2518 char filename[1024];
2520 /* erase all the files in the directory */
2521 d = opendir(smb_dir);
2522 for(;;) {
2523 de = readdir(d);
2524 if (!de)
2525 break;
2526 if (strcmp(de->d_name, ".") != 0 &&
2527 strcmp(de->d_name, "..") != 0) {
2528 snprintf(filename, sizeof(filename), "%s/%s",
2529 smb_dir, de->d_name);
2530 unlink(filename);
2533 closedir(d);
2534 rmdir(smb_dir);
2537 /* automatic user mode samba server configuration */
2538 void net_slirp_smb(const char *exported_dir)
2540 char smb_conf[1024];
2541 char smb_cmdline[1024];
2542 FILE *f;
2544 if (!slirp_inited) {
2545 slirp_inited = 1;
2546 slirp_init();
2549 /* XXX: better tmp dir construction */
2550 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2551 if (mkdir(smb_dir, 0700) < 0) {
2552 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2553 exit(1);
2555 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2557 f = fopen(smb_conf, "w");
2558 if (!f) {
2559 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2560 exit(1);
2562 fprintf(f,
2563 "[global]\n"
2564 "private dir=%s\n"
2565 "smb ports=0\n"
2566 "socket address=127.0.0.1\n"
2567 "pid directory=%s\n"
2568 "lock directory=%s\n"
2569 "log file=%s/log.smbd\n"
2570 "smb passwd file=%s/smbpasswd\n"
2571 "security = share\n"
2572 "[qemu]\n"
2573 "path=%s\n"
2574 "read only=no\n"
2575 "guest ok=yes\n",
2576 smb_dir,
2577 smb_dir,
2578 smb_dir,
2579 smb_dir,
2580 smb_dir,
2581 exported_dir
2582 );
2583 fclose(f);
2584 atexit(smb_exit);
2586 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2587 smb_conf);
2589 slirp_add_exec(0, smb_cmdline, 4, 139);
2592 #endif /* !defined(_WIN32) */
2594 #endif /* CONFIG_SLIRP */
2596 #if !defined(_WIN32)
2598 typedef struct TAPState {
2599 VLANClientState *vc;
2600 int fd;
2601 } TAPState;
2603 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2605 TAPState *s = opaque;
2606 int ret;
2607 for(;;) {
2608 ret = write(s->fd, buf, size);
2609 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2610 } else {
2611 break;
2616 static void tap_send(void *opaque)
2618 TAPState *s = opaque;
2619 uint8_t buf[4096];
2620 int size;
2622 size = read(s->fd, buf, sizeof(buf));
2623 if (size > 0) {
2624 qemu_send_packet(s->vc, buf, size);
2628 /* fd support */
2630 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2632 TAPState *s;
2634 s = qemu_mallocz(sizeof(TAPState));
2635 if (!s)
2636 return NULL;
2637 s->fd = fd;
2638 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2639 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2640 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2641 return s;
2644 #ifdef _BSD
2645 static int tap_open(char *ifname, int ifname_size)
2647 int fd;
2648 char *dev;
2649 struct stat s;
2651 fd = open("/dev/tap", O_RDWR);
2652 if (fd < 0) {
2653 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2654 return -1;
2657 fstat(fd, &s);
2658 dev = devname(s.st_rdev, S_IFCHR);
2659 pstrcpy(ifname, ifname_size, dev);
2661 fcntl(fd, F_SETFL, O_NONBLOCK);
2662 return fd;
2664 #elif defined(__sun__)
2665 static int tap_open(char *ifname, int ifname_size)
2667 fprintf(stderr, "warning: tap_open not yet implemented\n");
2668 return -1;
2670 #else
2671 static int tap_open(char *ifname, int ifname_size)
2673 struct ifreq ifr;
2674 int fd, ret;
2676 fd = open("/dev/net/tun", O_RDWR);
2677 if (fd < 0) {
2678 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2679 return -1;
2681 memset(&ifr, 0, sizeof(ifr));
2682 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2683 if (ifname[0] != '\0')
2684 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2685 else
2686 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2687 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2688 if (ret != 0) {
2689 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2690 close(fd);
2691 return -1;
2693 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2694 fcntl(fd, F_SETFL, O_NONBLOCK);
2695 return fd;
2697 #endif
2699 static int net_tap_init(VLANState *vlan, const char *ifname1,
2700 const char *setup_script, const char *bridge)
2702 TAPState *s;
2703 int pid, status, fd;
2704 char *args[4];
2705 char **parg;
2706 char ifname[128];
2708 if (ifname1 != NULL)
2709 pstrcpy(ifname, sizeof(ifname), ifname1);
2710 else
2711 ifname[0] = '\0';
2712 fd = tap_open(ifname, sizeof(ifname));
2713 if (fd < 0)
2714 return -1;
2716 if (!setup_script)
2717 setup_script = "";
2718 if (setup_script[0] != '\0') {
2719 /* try to launch network init script */
2720 pid = fork();
2721 if (pid >= 0) {
2722 if (pid == 0) {
2723 parg = args;
2724 *parg++ = (char *)setup_script;
2725 *parg++ = ifname;
2726 *parg++ = (char *)bridge;
2727 *parg++ = NULL;
2728 execv(setup_script, args);
2729 _exit(1);
2731 while (waitpid(pid, &status, 0) != pid);
2732 if (!WIFEXITED(status) ||
2733 WEXITSTATUS(status) != 0) {
2734 fprintf(stderr, "%s: could not launch network script\n",
2735 setup_script);
2736 return -1;
2740 s = net_tap_fd_init(vlan, fd);
2741 if (!s)
2742 return -1;
2743 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2744 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2745 return 0;
2748 #endif /* !_WIN32 */
2750 /* network connection */
2751 typedef struct NetSocketState {
2752 VLANClientState *vc;
2753 int fd;
2754 int state; /* 0 = getting length, 1 = getting data */
2755 int index;
2756 int packet_len;
2757 uint8_t buf[4096];
2758 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2759 } NetSocketState;
2761 typedef struct NetSocketListenState {
2762 VLANState *vlan;
2763 int fd;
2764 } NetSocketListenState;
2766 /* XXX: we consider we can send the whole packet without blocking */
2767 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2769 NetSocketState *s = opaque;
2770 uint32_t len;
2771 len = htonl(size);
2773 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2774 send_all(s->fd, buf, size);
2777 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2779 NetSocketState *s = opaque;
2780 sendto(s->fd, buf, size, 0,
2781 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2784 static void net_socket_send(void *opaque)
2786 NetSocketState *s = opaque;
2787 int l, size, err;
2788 uint8_t buf1[4096];
2789 const uint8_t *buf;
2791 size = recv(s->fd, buf1, sizeof(buf1), 0);
2792 if (size < 0) {
2793 err = socket_error();
2794 if (err != EWOULDBLOCK)
2795 goto eoc;
2796 } else if (size == 0) {
2797 /* end of connection */
2798 eoc:
2799 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2800 closesocket(s->fd);
2801 return;
2803 buf = buf1;
2804 while (size > 0) {
2805 /* reassemble a packet from the network */
2806 switch(s->state) {
2807 case 0:
2808 l = 4 - s->index;
2809 if (l > size)
2810 l = size;
2811 memcpy(s->buf + s->index, buf, l);
2812 buf += l;
2813 size -= l;
2814 s->index += l;
2815 if (s->index == 4) {
2816 /* got length */
2817 s->packet_len = ntohl(*(uint32_t *)s->buf);
2818 s->index = 0;
2819 s->state = 1;
2821 break;
2822 case 1:
2823 l = s->packet_len - s->index;
2824 if (l > size)
2825 l = size;
2826 memcpy(s->buf + s->index, buf, l);
2827 s->index += l;
2828 buf += l;
2829 size -= l;
2830 if (s->index >= s->packet_len) {
2831 qemu_send_packet(s->vc, s->buf, s->packet_len);
2832 s->index = 0;
2833 s->state = 0;
2835 break;
2840 static void net_socket_send_dgram(void *opaque)
2842 NetSocketState *s = opaque;
2843 int size;
2845 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2846 if (size < 0)
2847 return;
2848 if (size == 0) {
2849 /* end of connection */
2850 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2851 return;
2853 qemu_send_packet(s->vc, s->buf, size);
2856 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2858 struct ip_mreq imr;
2859 int fd;
2860 int val, ret;
2861 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2862 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2863 inet_ntoa(mcastaddr->sin_addr),
2864 (int)ntohl(mcastaddr->sin_addr.s_addr));
2865 return -1;
2868 fd = socket(PF_INET, SOCK_DGRAM, 0);
2869 if (fd < 0) {
2870 perror("socket(PF_INET, SOCK_DGRAM)");
2871 return -1;
2874 val = 1;
2875 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2876 (const char *)&val, sizeof(val));
2877 if (ret < 0) {
2878 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2879 goto fail;
2882 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2883 if (ret < 0) {
2884 perror("bind");
2885 goto fail;
2888 /* Add host to multicast group */
2889 imr.imr_multiaddr = mcastaddr->sin_addr;
2890 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2892 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2893 (const char *)&imr, sizeof(struct ip_mreq));
2894 if (ret < 0) {
2895 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2896 goto fail;
2899 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2900 val = 1;
2901 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2902 (const char *)&val, sizeof(val));
2903 if (ret < 0) {
2904 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2905 goto fail;
2908 socket_set_nonblock(fd);
2909 return fd;
2910 fail:
2911 if (fd>=0) close(fd);
2912 return -1;
2915 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2916 int is_connected)
2918 struct sockaddr_in saddr;
2919 int newfd;
2920 socklen_t saddr_len;
2921 NetSocketState *s;
2923 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2924 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2925 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2926 */
2928 if (is_connected) {
2929 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2930 /* must be bound */
2931 if (saddr.sin_addr.s_addr==0) {
2932 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2933 fd);
2934 return NULL;
2936 /* clone dgram socket */
2937 newfd = net_socket_mcast_create(&saddr);
2938 if (newfd < 0) {
2939 /* error already reported by net_socket_mcast_create() */
2940 close(fd);
2941 return NULL;
2943 /* clone newfd to fd, close newfd */
2944 dup2(newfd, fd);
2945 close(newfd);
2947 } else {
2948 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2949 fd, strerror(errno));
2950 return NULL;
2954 s = qemu_mallocz(sizeof(NetSocketState));
2955 if (!s)
2956 return NULL;
2957 s->fd = fd;
2959 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2960 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2962 /* mcast: save bound address as dst */
2963 if (is_connected) s->dgram_dst=saddr;
2965 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2966 "socket: fd=%d (%s mcast=%s:%d)",
2967 fd, is_connected? "cloned" : "",
2968 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2969 return s;
2972 static void net_socket_connect(void *opaque)
2974 NetSocketState *s = opaque;
2975 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2978 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2979 int is_connected)
2981 NetSocketState *s;
2982 s = qemu_mallocz(sizeof(NetSocketState));
2983 if (!s)
2984 return NULL;
2985 s->fd = fd;
2986 s->vc = qemu_new_vlan_client(vlan,
2987 net_socket_receive, NULL, s);
2988 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2989 "socket: fd=%d", fd);
2990 if (is_connected) {
2991 net_socket_connect(s);
2992 } else {
2993 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2995 return s;
2998 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2999 int is_connected)
3001 int so_type=-1, optlen=sizeof(so_type);
3003 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3004 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3005 return NULL;
3007 switch(so_type) {
3008 case SOCK_DGRAM:
3009 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3010 case SOCK_STREAM:
3011 return net_socket_fd_init_stream(vlan, fd, is_connected);
3012 default:
3013 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3014 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3015 return net_socket_fd_init_stream(vlan, fd, is_connected);
3017 return NULL;
3020 static void net_socket_accept(void *opaque)
3022 NetSocketListenState *s = opaque;
3023 NetSocketState *s1;
3024 struct sockaddr_in saddr;
3025 socklen_t len;
3026 int fd;
3028 for(;;) {
3029 len = sizeof(saddr);
3030 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3031 if (fd < 0 && errno != EINTR) {
3032 return;
3033 } else if (fd >= 0) {
3034 break;
3037 s1 = net_socket_fd_init(s->vlan, fd, 1);
3038 if (!s1) {
3039 close(fd);
3040 } else {
3041 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3042 "socket: connection from %s:%d",
3043 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3047 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3049 NetSocketListenState *s;
3050 int fd, val, ret;
3051 struct sockaddr_in saddr;
3053 if (parse_host_port(&saddr, host_str) < 0)
3054 return -1;
3056 s = qemu_mallocz(sizeof(NetSocketListenState));
3057 if (!s)
3058 return -1;
3060 fd = socket(PF_INET, SOCK_STREAM, 0);
3061 if (fd < 0) {
3062 perror("socket");
3063 return -1;
3065 socket_set_nonblock(fd);
3067 /* allow fast reuse */
3068 val = 1;
3069 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3071 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3072 if (ret < 0) {
3073 perror("bind");
3074 return -1;
3076 ret = listen(fd, 0);
3077 if (ret < 0) {
3078 perror("listen");
3079 return -1;
3081 s->vlan = vlan;
3082 s->fd = fd;
3083 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3084 return 0;
3087 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3089 NetSocketState *s;
3090 int fd, connected, ret, err;
3091 struct sockaddr_in saddr;
3093 if (parse_host_port(&saddr, host_str) < 0)
3094 return -1;
3096 fd = socket(PF_INET, SOCK_STREAM, 0);
3097 if (fd < 0) {
3098 perror("socket");
3099 return -1;
3101 socket_set_nonblock(fd);
3103 connected = 0;
3104 for(;;) {
3105 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3106 if (ret < 0) {
3107 err = socket_error();
3108 if (err == EINTR || err == EWOULDBLOCK) {
3109 } else if (err == EINPROGRESS) {
3110 break;
3111 } else {
3112 perror("connect");
3113 closesocket(fd);
3114 return -1;
3116 } else {
3117 connected = 1;
3118 break;
3121 s = net_socket_fd_init(vlan, fd, connected);
3122 if (!s)
3123 return -1;
3124 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3125 "socket: connect to %s:%d",
3126 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3127 return 0;
3130 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3132 NetSocketState *s;
3133 int fd;
3134 struct sockaddr_in saddr;
3136 if (parse_host_port(&saddr, host_str) < 0)
3137 return -1;
3140 fd = net_socket_mcast_create(&saddr);
3141 if (fd < 0)
3142 return -1;
3144 s = net_socket_fd_init(vlan, fd, 0);
3145 if (!s)
3146 return -1;
3148 s->dgram_dst = saddr;
3150 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3151 "socket: mcast=%s:%d",
3152 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3153 return 0;
3157 static int get_param_value(char *buf, int buf_size,
3158 const char *tag, const char *str)
3160 const char *p;
3161 char *q;
3162 char option[128];
3164 p = str;
3165 for(;;) {
3166 q = option;
3167 while (*p != '\0' && *p != '=') {
3168 if ((q - option) < sizeof(option) - 1)
3169 *q++ = *p;
3170 p++;
3172 *q = '\0';
3173 if (*p != '=')
3174 break;
3175 p++;
3176 if (!strcmp(tag, option)) {
3177 q = buf;
3178 while (*p != '\0' && *p != ',') {
3179 if ((q - buf) < buf_size - 1)
3180 *q++ = *p;
3181 p++;
3183 *q = '\0';
3184 return q - buf;
3185 } else {
3186 while (*p != '\0' && *p != ',') {
3187 p++;
3190 if (*p != ',')
3191 break;
3192 p++;
3194 return 0;
3197 int net_client_init(const char *str)
3199 const char *p;
3200 char *q;
3201 char device[64];
3202 char buf[1024];
3203 int vlan_id, ret;
3204 VLANState *vlan;
3206 p = str;
3207 q = device;
3208 while (*p != '\0' && *p != ',') {
3209 if ((q - device) < sizeof(device) - 1)
3210 *q++ = *p;
3211 p++;
3213 *q = '\0';
3214 if (*p == ',')
3215 p++;
3216 vlan_id = 0;
3217 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3218 vlan_id = strtol(buf, NULL, 0);
3220 vlan = qemu_find_vlan(vlan_id);
3221 if (!vlan) {
3222 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3223 return -1;
3225 if (!strcmp(device, "nic")) {
3226 NICInfo *nd;
3227 uint8_t *macaddr;
3229 if (nb_nics >= MAX_NICS) {
3230 fprintf(stderr, "Too Many NICs\n");
3231 return -1;
3233 nd = &nd_table[nb_nics];
3234 macaddr = nd->macaddr;
3235 macaddr[0] = 0x52;
3236 macaddr[1] = 0x54;
3237 macaddr[2] = 0x00;
3238 macaddr[3] = 0x12;
3239 macaddr[4] = 0x34;
3240 macaddr[5] = 0x56 + nb_nics;
3242 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3243 if (parse_macaddr(macaddr, buf) < 0) {
3244 fprintf(stderr, "invalid syntax for ethernet address\n");
3245 return -1;
3248 if (get_param_value(buf, sizeof(buf), "model", p)) {
3249 nd->model = strdup(buf);
3251 nd->vlan = vlan;
3252 nb_nics++;
3253 ret = 0;
3254 } else
3255 if (!strcmp(device, "none")) {
3256 /* does nothing. It is needed to signal that no network cards
3257 are wanted */
3258 ret = 0;
3259 } else
3260 #ifdef CONFIG_SLIRP
3261 if (!strcmp(device, "user")) {
3262 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3263 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3265 ret = net_slirp_init(vlan);
3266 } else
3267 #endif
3268 #ifdef _WIN32
3269 if (!strcmp(device, "tap")) {
3270 char ifname[64];
3271 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3272 fprintf(stderr, "tap: no interface name\n");
3273 return -1;
3275 ret = tap_win32_init(vlan, ifname);
3276 } else
3277 #else
3278 if (!strcmp(device, "tap")) {
3279 char ifname[64];
3280 char setup_script[1024];
3281 char bridge[16];
3282 int fd;
3283 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3284 fd = strtol(buf, NULL, 0);
3285 ret = -1;
3286 if (net_tap_fd_init(vlan, fd))
3287 ret = 0;
3288 } else {
3289 ifname[0] = '\0';
3290 get_param_value(ifname, sizeof(ifname), "ifname", p);
3291 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3292 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3294 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
3295 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
3297 ret = net_tap_init(vlan, ifname, setup_script, bridge);
3299 } else
3300 #endif
3301 if (!strcmp(device, "socket")) {
3302 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3303 int fd;
3304 fd = strtol(buf, NULL, 0);
3305 ret = -1;
3306 if (net_socket_fd_init(vlan, fd, 1))
3307 ret = 0;
3308 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3309 ret = net_socket_listen_init(vlan, buf);
3310 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3311 ret = net_socket_connect_init(vlan, buf);
3312 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3313 ret = net_socket_mcast_init(vlan, buf);
3314 } else {
3315 fprintf(stderr, "Unknown socket options: %s\n", p);
3316 return -1;
3318 } else
3320 fprintf(stderr, "Unknown network device: %s\n", device);
3321 return -1;
3323 if (ret < 0) {
3324 fprintf(stderr, "Could not initialize device '%s'\n", device);
3327 return ret;
3330 void do_info_network(void)
3332 VLANState *vlan;
3333 VLANClientState *vc;
3335 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3336 term_printf("VLAN %d devices:\n", vlan->id);
3337 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3338 term_printf(" %s\n", vc->info_str);
3342 /***********************************************************/
3343 /* USB devices */
3345 static int usb_device_add(const char *devname)
3347 const char *p;
3348 USBDevice *dev;
3349 int i;
3351 if (!vm_usb_hub)
3352 return -1;
3353 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3354 if (!vm_usb_ports[i]->dev)
3355 break;
3357 if (i == MAX_VM_USB_PORTS)
3358 return -1;
3360 if (strstart(devname, "host:", &p)) {
3361 dev = usb_host_device_open(p);
3362 if (!dev)
3363 return -1;
3364 } else if (!strcmp(devname, "mouse")) {
3365 dev = usb_mouse_init();
3366 if (!dev)
3367 return -1;
3368 } else if (!strcmp(devname, "tablet")) {
3369 dev = usb_tablet_init();
3370 if (!dev)
3371 return -1;
3372 } else {
3373 return -1;
3375 usb_attach(vm_usb_ports[i], dev);
3376 return 0;
3379 static int usb_device_del(const char *devname)
3381 USBDevice *dev;
3382 int bus_num, addr, i;
3383 const char *p;
3385 if (!vm_usb_hub)
3386 return -1;
3388 p = strchr(devname, '.');
3389 if (!p)
3390 return -1;
3391 bus_num = strtoul(devname, NULL, 0);
3392 addr = strtoul(p + 1, NULL, 0);
3393 if (bus_num != 0)
3394 return -1;
3395 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3396 dev = vm_usb_ports[i]->dev;
3397 if (dev && dev->addr == addr)
3398 break;
3400 if (i == MAX_VM_USB_PORTS)
3401 return -1;
3402 usb_attach(vm_usb_ports[i], NULL);
3403 return 0;
3406 void do_usb_add(const char *devname)
3408 int ret;
3409 ret = usb_device_add(devname);
3410 if (ret < 0)
3411 term_printf("Could not add USB device '%s'\n", devname);
3414 void do_usb_del(const char *devname)
3416 int ret;
3417 ret = usb_device_del(devname);
3418 if (ret < 0)
3419 term_printf("Could not remove USB device '%s'\n", devname);
3422 void usb_info(void)
3424 USBDevice *dev;
3425 int i;
3426 const char *speed_str;
3428 if (!vm_usb_hub) {
3429 term_printf("USB support not enabled\n");
3430 return;
3433 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3434 dev = vm_usb_ports[i]->dev;
3435 if (dev) {
3436 term_printf("Hub port %d:\n", i);
3437 switch(dev->speed) {
3438 case USB_SPEED_LOW:
3439 speed_str = "1.5";
3440 break;
3441 case USB_SPEED_FULL:
3442 speed_str = "12";
3443 break;
3444 case USB_SPEED_HIGH:
3445 speed_str = "480";
3446 break;
3447 default:
3448 speed_str = "?";
3449 break;
3451 term_printf(" Device %d.%d, speed %s Mb/s\n",
3452 0, dev->addr, speed_str);
3457 /***********************************************************/
3458 /* pid file */
3460 static char *pid_filename;
3462 /* Remove PID file. Called on normal exit */
3464 static void remove_pidfile(void)
3466 unlink (pid_filename);
3469 static void create_pidfile(const char *filename)
3471 struct stat pidstat;
3472 FILE *f;
3474 /* Try to write our PID to the named file */
3475 if (stat(filename, &pidstat) < 0) {
3476 if (errno == ENOENT) {
3477 if ((f = fopen (filename, "w")) == NULL) {
3478 perror("Opening pidfile");
3479 exit(1);
3481 fprintf(f, "%d\n", getpid());
3482 fclose(f);
3483 pid_filename = qemu_strdup(filename);
3484 if (!pid_filename) {
3485 fprintf(stderr, "Could not save PID filename");
3486 exit(1);
3488 atexit(remove_pidfile);
3490 } else {
3491 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3492 filename);
3493 exit(1);
3497 /***********************************************************/
3498 /* dumb display */
3500 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3504 static void dumb_resize(DisplayState *ds, int w, int h)
3508 static void dumb_refresh(DisplayState *ds)
3510 vga_hw_update();
3513 void dumb_display_init(DisplayState *ds)
3515 ds->data = NULL;
3516 ds->linesize = 0;
3517 ds->depth = 0;
3518 ds->dpy_update = dumb_update;
3519 ds->dpy_resize = dumb_resize;
3520 ds->dpy_refresh = dumb_refresh;
3523 #if !defined(CONFIG_SOFTMMU)
3524 /***********************************************************/
3525 /* cpu signal handler */
3526 static void host_segv_handler(int host_signum, siginfo_t *info,
3527 void *puc)
3529 if (cpu_signal_handler(host_signum, info, puc))
3530 return;
3531 if (stdio_nb_clients > 0)
3532 term_exit();
3533 abort();
3535 #endif
3537 /***********************************************************/
3538 /* I/O handling */
3540 #define MAX_IO_HANDLERS 64
3542 typedef struct IOHandlerRecord {
3543 int fd;
3544 IOCanRWHandler *fd_read_poll;
3545 IOHandler *fd_read;
3546 IOHandler *fd_write;
3547 void *opaque;
3548 /* temporary data */
3549 struct pollfd *ufd;
3550 struct IOHandlerRecord *next;
3551 } IOHandlerRecord;
3553 static IOHandlerRecord *first_io_handler;
3555 /* XXX: fd_read_poll should be suppressed, but an API change is
3556 necessary in the character devices to suppress fd_can_read(). */
3557 int qemu_set_fd_handler2(int fd,
3558 IOCanRWHandler *fd_read_poll,
3559 IOHandler *fd_read,
3560 IOHandler *fd_write,
3561 void *opaque)
3563 IOHandlerRecord **pioh, *ioh;
3565 if (!fd_read && !fd_write) {
3566 pioh = &first_io_handler;
3567 for(;;) {
3568 ioh = *pioh;
3569 if (ioh == NULL)
3570 break;
3571 if (ioh->fd == fd) {
3572 *pioh = ioh->next;
3573 qemu_free(ioh);
3574 break;
3576 pioh = &ioh->next;
3578 } else {
3579 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3580 if (ioh->fd == fd)
3581 goto found;
3583 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3584 if (!ioh)
3585 return -1;
3586 ioh->next = first_io_handler;
3587 first_io_handler = ioh;
3588 found:
3589 ioh->fd = fd;
3590 ioh->fd_read_poll = fd_read_poll;
3591 ioh->fd_read = fd_read;
3592 ioh->fd_write = fd_write;
3593 ioh->opaque = opaque;
3595 return 0;
3598 int qemu_set_fd_handler(int fd,
3599 IOHandler *fd_read,
3600 IOHandler *fd_write,
3601 void *opaque)
3603 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3606 /***********************************************************/
3607 /* Polling handling */
3609 typedef struct PollingEntry {
3610 PollingFunc *func;
3611 void *opaque;
3612 struct PollingEntry *next;
3613 } PollingEntry;
3615 static PollingEntry *first_polling_entry;
3617 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3619 PollingEntry **ppe, *pe;
3620 pe = qemu_mallocz(sizeof(PollingEntry));
3621 if (!pe)
3622 return -1;
3623 pe->func = func;
3624 pe->opaque = opaque;
3625 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3626 *ppe = pe;
3627 return 0;
3630 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3632 PollingEntry **ppe, *pe;
3633 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3634 pe = *ppe;
3635 if (pe->func == func && pe->opaque == opaque) {
3636 *ppe = pe->next;
3637 qemu_free(pe);
3638 break;
3643 /***********************************************************/
3644 /* savevm/loadvm support */
3646 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3648 fwrite(buf, 1, size, f);
3651 void qemu_put_byte(QEMUFile *f, int v)
3653 fputc(v, f);
3656 void qemu_put_be16(QEMUFile *f, unsigned int v)
3658 qemu_put_byte(f, v >> 8);
3659 qemu_put_byte(f, v);
3662 void qemu_put_be32(QEMUFile *f, unsigned int v)
3664 qemu_put_byte(f, v >> 24);
3665 qemu_put_byte(f, v >> 16);
3666 qemu_put_byte(f, v >> 8);
3667 qemu_put_byte(f, v);
3670 void qemu_put_be64(QEMUFile *f, uint64_t v)
3672 qemu_put_be32(f, v >> 32);
3673 qemu_put_be32(f, v);
3676 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3678 return fread(buf, 1, size, f);
3681 int qemu_get_byte(QEMUFile *f)
3683 int v;
3684 v = fgetc(f);
3685 if (v == EOF)
3686 return 0;
3687 else
3688 return v;
3691 unsigned int qemu_get_be16(QEMUFile *f)
3693 unsigned int v;
3694 v = qemu_get_byte(f) << 8;
3695 v |= qemu_get_byte(f);
3696 return v;
3699 unsigned int qemu_get_be32(QEMUFile *f)
3701 unsigned int v;
3702 v = qemu_get_byte(f) << 24;
3703 v |= qemu_get_byte(f) << 16;
3704 v |= qemu_get_byte(f) << 8;
3705 v |= qemu_get_byte(f);
3706 return v;
3709 uint64_t qemu_get_be64(QEMUFile *f)
3711 uint64_t v;
3712 v = (uint64_t)qemu_get_be32(f) << 32;
3713 v |= qemu_get_be32(f);
3714 return v;
3717 int64_t qemu_ftell(QEMUFile *f)
3719 return ftell(f);
3722 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3724 if (fseek(f, pos, whence) < 0)
3725 return -1;
3726 return ftell(f);
3729 typedef struct SaveStateEntry {
3730 char idstr[256];
3731 int instance_id;
3732 int version_id;
3733 SaveStateHandler *save_state;
3734 LoadStateHandler *load_state;
3735 void *opaque;
3736 struct SaveStateEntry *next;
3737 } SaveStateEntry;
3739 static SaveStateEntry *first_se;
3741 int register_savevm(const char *idstr,
3742 int instance_id,
3743 int version_id,
3744 SaveStateHandler *save_state,
3745 LoadStateHandler *load_state,
3746 void *opaque)
3748 SaveStateEntry *se, **pse;
3750 se = qemu_malloc(sizeof(SaveStateEntry));
3751 if (!se)
3752 return -1;
3753 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3754 se->instance_id = instance_id;
3755 se->version_id = version_id;
3756 se->save_state = save_state;
3757 se->load_state = load_state;
3758 se->opaque = opaque;
3759 se->next = NULL;
3761 /* add at the end of list */
3762 pse = &first_se;
3763 while (*pse != NULL)
3764 pse = &(*pse)->next;
3765 *pse = se;
3766 return 0;
3769 #define QEMU_VM_FILE_MAGIC 0x5145564d
3770 #define QEMU_VM_FILE_VERSION 0x00000001
3772 int qemu_savevm(const char *filename)
3774 SaveStateEntry *se;
3775 QEMUFile *f;
3776 int len, len_pos, cur_pos, saved_vm_running, ret;
3778 saved_vm_running = vm_running;
3779 vm_stop(0);
3781 f = fopen(filename, "wb");
3782 if (!f) {
3783 ret = -1;
3784 goto the_end;
3787 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3788 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3790 for(se = first_se; se != NULL; se = se->next) {
3791 /* ID string */
3792 len = strlen(se->idstr);
3793 qemu_put_byte(f, len);
3794 qemu_put_buffer(f, se->idstr, len);
3796 qemu_put_be32(f, se->instance_id);
3797 qemu_put_be32(f, se->version_id);
3799 /* record size: filled later */
3800 len_pos = ftell(f);
3801 qemu_put_be32(f, 0);
3803 se->save_state(f, se->opaque);
3805 /* fill record size */
3806 cur_pos = ftell(f);
3807 len = ftell(f) - len_pos - 4;
3808 fseek(f, len_pos, SEEK_SET);
3809 qemu_put_be32(f, len);
3810 fseek(f, cur_pos, SEEK_SET);
3813 fclose(f);
3814 ret = 0;
3815 the_end:
3816 if (saved_vm_running)
3817 vm_start();
3818 return ret;
3821 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3823 SaveStateEntry *se;
3825 for(se = first_se; se != NULL; se = se->next) {
3826 if (!strcmp(se->idstr, idstr) &&
3827 instance_id == se->instance_id)
3828 return se;
3830 return NULL;
3833 int qemu_loadvm(const char *filename)
3835 SaveStateEntry *se;
3836 QEMUFile *f;
3837 int len, cur_pos, ret, instance_id, record_len, version_id;
3838 int saved_vm_running;
3839 unsigned int v;
3840 char idstr[256];
3842 saved_vm_running = vm_running;
3843 vm_stop(0);
3845 f = fopen(filename, "rb");
3846 if (!f) {
3847 ret = -1;
3848 goto the_end;
3851 v = qemu_get_be32(f);
3852 if (v != QEMU_VM_FILE_MAGIC)
3853 goto fail;
3854 v = qemu_get_be32(f);
3855 if (v != QEMU_VM_FILE_VERSION) {
3856 fail:
3857 fclose(f);
3858 ret = -1;
3859 goto the_end;
3861 for(;;) {
3862 len = qemu_get_byte(f);
3863 if (feof(f))
3864 break;
3865 qemu_get_buffer(f, idstr, len);
3866 idstr[len] = '\0';
3867 instance_id = qemu_get_be32(f);
3868 version_id = qemu_get_be32(f);
3869 record_len = qemu_get_be32(f);
3870 #if 0
3871 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3872 idstr, instance_id, version_id, record_len);
3873 #endif
3874 cur_pos = ftell(f);
3875 se = find_se(idstr, instance_id);
3876 if (!se) {
3877 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3878 instance_id, idstr);
3879 } else {
3880 ret = se->load_state(f, se->opaque, version_id);
3881 if (ret < 0) {
3882 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3883 instance_id, idstr);
3886 /* always seek to exact end of record */
3887 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3889 fclose(f);
3890 ret = 0;
3891 the_end:
3892 if (saved_vm_running)
3893 vm_start();
3894 return ret;
3897 #ifndef CONFIG_DM
3898 /***********************************************************/
3899 /* cpu save/restore */
3901 #if defined(TARGET_I386)
3903 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3905 qemu_put_be32(f, dt->selector);
3906 qemu_put_betl(f, dt->base);
3907 qemu_put_be32(f, dt->limit);
3908 qemu_put_be32(f, dt->flags);
3911 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3913 dt->selector = qemu_get_be32(f);
3914 dt->base = qemu_get_betl(f);
3915 dt->limit = qemu_get_be32(f);
3916 dt->flags = qemu_get_be32(f);
3919 void cpu_save(QEMUFile *f, void *opaque)
3921 CPUState *env = opaque;
3922 uint16_t fptag, fpus, fpuc, fpregs_format;
3923 uint32_t hflags;
3924 int i;
3926 for(i = 0; i < CPU_NB_REGS; i++)
3927 qemu_put_betls(f, &env->regs[i]);
3928 qemu_put_betls(f, &env->eip);
3929 qemu_put_betls(f, &env->eflags);
3930 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3931 qemu_put_be32s(f, &hflags);
3933 /* FPU */
3934 fpuc = env->fpuc;
3935 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3936 fptag = 0;
3937 for(i = 0; i < 8; i++) {
3938 fptag |= ((!env->fptags[i]) << i);
3941 qemu_put_be16s(f, &fpuc);
3942 qemu_put_be16s(f, &fpus);
3943 qemu_put_be16s(f, &fptag);
3945 #ifdef USE_X86LDOUBLE
3946 fpregs_format = 0;
3947 #else
3948 fpregs_format = 1;
3949 #endif
3950 qemu_put_be16s(f, &fpregs_format);
3952 for(i = 0; i < 8; i++) {
3953 #ifdef USE_X86LDOUBLE
3955 uint64_t mant;
3956 uint16_t exp;
3957 /* we save the real CPU data (in case of MMX usage only 'mant'
3958 contains the MMX register */
3959 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3960 qemu_put_be64(f, mant);
3961 qemu_put_be16(f, exp);
3963 #else
3964 /* if we use doubles for float emulation, we save the doubles to
3965 avoid losing information in case of MMX usage. It can give
3966 problems if the image is restored on a CPU where long
3967 doubles are used instead. */
3968 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3969 #endif
3972 for(i = 0; i < 6; i++)
3973 cpu_put_seg(f, &env->segs[i]);
3974 cpu_put_seg(f, &env->ldt);
3975 cpu_put_seg(f, &env->tr);
3976 cpu_put_seg(f, &env->gdt);
3977 cpu_put_seg(f, &env->idt);
3979 qemu_put_be32s(f, &env->sysenter_cs);
3980 qemu_put_be32s(f, &env->sysenter_esp);
3981 qemu_put_be32s(f, &env->sysenter_eip);
3983 qemu_put_betls(f, &env->cr[0]);
3984 qemu_put_betls(f, &env->cr[2]);
3985 qemu_put_betls(f, &env->cr[3]);
3986 qemu_put_betls(f, &env->cr[4]);
3988 for(i = 0; i < 8; i++)
3989 qemu_put_betls(f, &env->dr[i]);
3991 /* MMU */
3992 qemu_put_be32s(f, &env->a20_mask);
3994 /* XMM */
3995 qemu_put_be32s(f, &env->mxcsr);
3996 for(i = 0; i < CPU_NB_REGS; i++) {
3997 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3998 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4001 #ifdef TARGET_X86_64
4002 qemu_put_be64s(f, &env->efer);
4003 qemu_put_be64s(f, &env->star);
4004 qemu_put_be64s(f, &env->lstar);
4005 qemu_put_be64s(f, &env->cstar);
4006 qemu_put_be64s(f, &env->fmask);
4007 qemu_put_be64s(f, &env->kernelgsbase);
4008 #endif
4011 #ifdef USE_X86LDOUBLE
4012 /* XXX: add that in a FPU generic layer */
4013 union x86_longdouble {
4014 uint64_t mant;
4015 uint16_t exp;
4016 };
4018 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4019 #define EXPBIAS1 1023
4020 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4021 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4023 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4025 int e;
4026 /* mantissa */
4027 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4028 /* exponent + sign */
4029 e = EXPD1(temp) - EXPBIAS1 + 16383;
4030 e |= SIGND1(temp) >> 16;
4031 p->exp = e;
4033 #endif
4035 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4037 CPUState *env = opaque;
4038 int i, guess_mmx;
4039 uint32_t hflags;
4040 uint16_t fpus, fpuc, fptag, fpregs_format;
4042 if (version_id != 3)
4043 return -EINVAL;
4044 for(i = 0; i < CPU_NB_REGS; i++)
4045 qemu_get_betls(f, &env->regs[i]);
4046 qemu_get_betls(f, &env->eip);
4047 qemu_get_betls(f, &env->eflags);
4048 qemu_get_be32s(f, &hflags);
4050 qemu_get_be16s(f, &fpuc);
4051 qemu_get_be16s(f, &fpus);
4052 qemu_get_be16s(f, &fptag);
4053 qemu_get_be16s(f, &fpregs_format);
4055 /* NOTE: we cannot always restore the FPU state if the image come
4056 from a host with a different 'USE_X86LDOUBLE' define. We guess
4057 if we are in an MMX state to restore correctly in that case. */
4058 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4059 for(i = 0; i < 8; i++) {
4060 uint64_t mant;
4061 uint16_t exp;
4063 switch(fpregs_format) {
4064 case 0:
4065 mant = qemu_get_be64(f);
4066 exp = qemu_get_be16(f);
4067 #ifdef USE_X86LDOUBLE
4068 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4069 #else
4070 /* difficult case */
4071 if (guess_mmx)
4072 env->fpregs[i].mmx.MMX_Q(0) = mant;
4073 else
4074 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4075 #endif
4076 break;
4077 case 1:
4078 mant = qemu_get_be64(f);
4079 #ifdef USE_X86LDOUBLE
4081 union x86_longdouble *p;
4082 /* difficult case */
4083 p = (void *)&env->fpregs[i];
4084 if (guess_mmx) {
4085 p->mant = mant;
4086 p->exp = 0xffff;
4087 } else {
4088 fp64_to_fp80(p, mant);
4091 #else
4092 env->fpregs[i].mmx.MMX_Q(0) = mant;
4093 #endif
4094 break;
4095 default:
4096 return -EINVAL;
4100 env->fpuc = fpuc;
4101 /* XXX: restore FPU round state */
4102 env->fpstt = (fpus >> 11) & 7;
4103 env->fpus = fpus & ~0x3800;
4104 fptag ^= 0xff;
4105 for(i = 0; i < 8; i++) {
4106 env->fptags[i] = (fptag >> i) & 1;
4109 for(i = 0; i < 6; i++)
4110 cpu_get_seg(f, &env->segs[i]);
4111 cpu_get_seg(f, &env->ldt);
4112 cpu_get_seg(f, &env->tr);
4113 cpu_get_seg(f, &env->gdt);
4114 cpu_get_seg(f, &env->idt);
4116 qemu_get_be32s(f, &env->sysenter_cs);
4117 qemu_get_be32s(f, &env->sysenter_esp);
4118 qemu_get_be32s(f, &env->sysenter_eip);
4120 qemu_get_betls(f, &env->cr[0]);
4121 qemu_get_betls(f, &env->cr[2]);
4122 qemu_get_betls(f, &env->cr[3]);
4123 qemu_get_betls(f, &env->cr[4]);
4125 for(i = 0; i < 8; i++)
4126 qemu_get_betls(f, &env->dr[i]);
4128 /* MMU */
4129 qemu_get_be32s(f, &env->a20_mask);
4131 qemu_get_be32s(f, &env->mxcsr);
4132 for(i = 0; i < CPU_NB_REGS; i++) {
4133 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4134 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4137 #ifdef TARGET_X86_64
4138 qemu_get_be64s(f, &env->efer);
4139 qemu_get_be64s(f, &env->star);
4140 qemu_get_be64s(f, &env->lstar);
4141 qemu_get_be64s(f, &env->cstar);
4142 qemu_get_be64s(f, &env->fmask);
4143 qemu_get_be64s(f, &env->kernelgsbase);
4144 #endif
4146 /* XXX: compute hflags from scratch, except for CPL and IIF */
4147 env->hflags = hflags;
4148 tlb_flush(env, 1);
4149 return 0;
4152 #elif defined(TARGET_PPC)
4153 void cpu_save(QEMUFile *f, void *opaque)
4157 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4159 return 0;
4162 #elif defined(TARGET_MIPS)
4163 void cpu_save(QEMUFile *f, void *opaque)
4167 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4169 return 0;
4172 #elif defined(TARGET_SPARC)
4173 void cpu_save(QEMUFile *f, void *opaque)
4175 CPUState *env = opaque;
4176 int i;
4177 uint32_t tmp;
4179 for(i = 0; i < 8; i++)
4180 qemu_put_betls(f, &env->gregs[i]);
4181 for(i = 0; i < NWINDOWS * 16; i++)
4182 qemu_put_betls(f, &env->regbase[i]);
4184 /* FPU */
4185 for(i = 0; i < TARGET_FPREGS; i++) {
4186 union {
4187 TARGET_FPREG_T f;
4188 target_ulong i;
4189 } u;
4190 u.f = env->fpr[i];
4191 qemu_put_betl(f, u.i);
4194 qemu_put_betls(f, &env->pc);
4195 qemu_put_betls(f, &env->npc);
4196 qemu_put_betls(f, &env->y);
4197 tmp = GET_PSR(env);
4198 qemu_put_be32(f, tmp);
4199 qemu_put_betls(f, &env->fsr);
4200 qemu_put_betls(f, &env->tbr);
4201 #ifndef TARGET_SPARC64
4202 qemu_put_be32s(f, &env->wim);
4203 /* MMU */
4204 for(i = 0; i < 16; i++)
4205 qemu_put_be32s(f, &env->mmuregs[i]);
4206 #endif
4209 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4211 CPUState *env = opaque;
4212 int i;
4213 uint32_t tmp;
4215 for(i = 0; i < 8; i++)
4216 qemu_get_betls(f, &env->gregs[i]);
4217 for(i = 0; i < NWINDOWS * 16; i++)
4218 qemu_get_betls(f, &env->regbase[i]);
4220 /* FPU */
4221 for(i = 0; i < TARGET_FPREGS; i++) {
4222 union {
4223 TARGET_FPREG_T f;
4224 target_ulong i;
4225 } u;
4226 u.i = qemu_get_betl(f);
4227 env->fpr[i] = u.f;
4230 qemu_get_betls(f, &env->pc);
4231 qemu_get_betls(f, &env->npc);
4232 qemu_get_betls(f, &env->y);
4233 tmp = qemu_get_be32(f);
4234 env->cwp = 0; /* needed to ensure that the wrapping registers are
4235 correctly updated */
4236 PUT_PSR(env, tmp);
4237 qemu_get_betls(f, &env->fsr);
4238 qemu_get_betls(f, &env->tbr);
4239 #ifndef TARGET_SPARC64
4240 qemu_get_be32s(f, &env->wim);
4241 /* MMU */
4242 for(i = 0; i < 16; i++)
4243 qemu_get_be32s(f, &env->mmuregs[i]);
4244 #endif
4245 tlb_flush(env, 1);
4246 return 0;
4249 #elif defined(TARGET_ARM)
4251 /* ??? Need to implement these. */
4252 void cpu_save(QEMUFile *f, void *opaque)
4256 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4258 return 0;
4261 #else
4263 #warning No CPU save/restore functions
4265 #endif
4267 /***********************************************************/
4268 /* ram save/restore */
4270 /* we just avoid storing empty pages */
4271 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4273 int i, v;
4275 v = buf[0];
4276 for(i = 1; i < len; i++) {
4277 if (buf[i] != v)
4278 goto normal_save;
4280 qemu_put_byte(f, 1);
4281 qemu_put_byte(f, v);
4282 return;
4283 normal_save:
4284 qemu_put_byte(f, 0);
4285 qemu_put_buffer(f, buf, len);
4288 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4290 int v;
4292 v = qemu_get_byte(f);
4293 switch(v) {
4294 case 0:
4295 if (qemu_get_buffer(f, buf, len) != len)
4296 return -EIO;
4297 break;
4298 case 1:
4299 v = qemu_get_byte(f);
4300 memset(buf, v, len);
4301 break;
4302 default:
4303 return -EINVAL;
4305 return 0;
4308 static void ram_save(QEMUFile *f, void *opaque)
4310 int i;
4311 qemu_put_be32(f, phys_ram_size);
4312 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4313 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4317 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4319 int i, ret;
4321 if (version_id != 1)
4322 return -EINVAL;
4323 if (qemu_get_be32(f) != phys_ram_size)
4324 return -EINVAL;
4325 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4326 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4327 if (ret)
4328 return ret;
4330 return 0;
4332 #else /* CONFIG_DM */
4333 void cpu_save(QEMUFile *f, void *opaque)
4337 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4339 return 0;
4342 static void ram_save(QEMUFile *f, void *opaque)
4346 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4348 return 0;
4350 #endif /* CONFIG_DM */
4352 /***********************************************************/
4353 /* machine registration */
4355 QEMUMachine *first_machine = NULL;
4357 int qemu_register_machine(QEMUMachine *m)
4359 QEMUMachine **pm;
4360 pm = &first_machine;
4361 while (*pm != NULL)
4362 pm = &(*pm)->next;
4363 m->next = NULL;
4364 *pm = m;
4365 return 0;
4368 QEMUMachine *find_machine(const char *name)
4370 QEMUMachine *m;
4372 for(m = first_machine; m != NULL; m = m->next) {
4373 if (!strcmp(m->name, name))
4374 return m;
4376 return NULL;
4379 /***********************************************************/
4380 /* main execution loop */
4382 void gui_update(void *opaque)
4384 display_state.dpy_refresh(&display_state);
4385 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4388 struct vm_change_state_entry {
4389 VMChangeStateHandler *cb;
4390 void *opaque;
4391 LIST_ENTRY (vm_change_state_entry) entries;
4392 };
4394 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4396 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4397 void *opaque)
4399 VMChangeStateEntry *e;
4401 e = qemu_mallocz(sizeof (*e));
4402 if (!e)
4403 return NULL;
4405 e->cb = cb;
4406 e->opaque = opaque;
4407 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4408 return e;
4411 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4413 LIST_REMOVE (e, entries);
4414 qemu_free (e);
4417 static void vm_state_notify(int running)
4419 VMChangeStateEntry *e;
4421 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4422 e->cb(e->opaque, running);
4426 /* XXX: support several handlers */
4427 static VMStopHandler *vm_stop_cb;
4428 static void *vm_stop_opaque;
4430 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4432 vm_stop_cb = cb;
4433 vm_stop_opaque = opaque;
4434 return 0;
4437 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4439 vm_stop_cb = NULL;
4442 void vm_start(void)
4444 if (!vm_running) {
4445 cpu_enable_ticks();
4446 vm_running = 1;
4447 vm_state_notify(1);
4451 void vm_stop(int reason)
4453 if (vm_running) {
4454 cpu_disable_ticks();
4455 vm_running = 0;
4456 if (reason != 0) {
4457 if (vm_stop_cb) {
4458 vm_stop_cb(vm_stop_opaque, reason);
4461 vm_state_notify(0);
4465 /* reset/shutdown handler */
4467 typedef struct QEMUResetEntry {
4468 QEMUResetHandler *func;
4469 void *opaque;
4470 struct QEMUResetEntry *next;
4471 } QEMUResetEntry;
4473 static QEMUResetEntry *first_reset_entry;
4474 int reset_requested;
4475 int shutdown_requested;
4476 static int powerdown_requested;
4478 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4480 QEMUResetEntry **pre, *re;
4482 pre = &first_reset_entry;
4483 while (*pre != NULL)
4484 pre = &(*pre)->next;
4485 re = qemu_mallocz(sizeof(QEMUResetEntry));
4486 re->func = func;
4487 re->opaque = opaque;
4488 re->next = NULL;
4489 *pre = re;
4492 void qemu_system_reset(void)
4494 QEMUResetEntry *re;
4496 /* reset all devices */
4497 for(re = first_reset_entry; re != NULL; re = re->next) {
4498 re->func(re->opaque);
4502 void qemu_system_reset_request(void)
4504 reset_requested = 1;
4505 if (cpu_single_env)
4506 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4509 void qemu_system_shutdown_request(void)
4511 shutdown_requested = 1;
4512 if (cpu_single_env)
4513 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4516 void qemu_system_powerdown_request(void)
4518 powerdown_requested = 1;
4519 if (cpu_single_env)
4520 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4523 void main_loop_wait(int timeout)
4525 IOHandlerRecord *ioh, *ioh_next;
4526 fd_set rfds, wfds, xfds;
4527 int ret, nfds;
4528 struct timeval tv;
4529 PollingEntry *pe;
4532 /* XXX: need to suppress polling by better using win32 events */
4533 ret = 0;
4534 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4535 ret |= pe->func(pe->opaque);
4537 #ifdef _WIN32
4538 if (ret == 0 && timeout > 0) {
4539 int err;
4540 HANDLE hEvents[1];
4542 hEvents[0] = host_alarm;
4543 ret = WaitForMultipleObjects(1, hEvents, FALSE, timeout);
4544 switch(ret) {
4545 case WAIT_OBJECT_0 + 0:
4546 break;
4547 case WAIT_TIMEOUT:
4548 break;
4549 default:
4550 err = GetLastError();
4551 fprintf(stderr, "Wait error %d %d\n", ret, err);
4552 break;
4555 #endif
4556 /* poll any events */
4557 /* XXX: separate device handlers from system ones */
4558 nfds = -1;
4559 FD_ZERO(&rfds);
4560 FD_ZERO(&wfds);
4561 FD_ZERO(&xfds);
4562 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4563 if (ioh->fd_read &&
4564 (!ioh->fd_read_poll ||
4565 ioh->fd_read_poll(ioh->opaque) != 0)) {
4566 FD_SET(ioh->fd, &rfds);
4567 if (ioh->fd > nfds)
4568 nfds = ioh->fd;
4570 if (ioh->fd_write) {
4571 FD_SET(ioh->fd, &wfds);
4572 if (ioh->fd > nfds)
4573 nfds = ioh->fd;
4577 tv.tv_sec = 0;
4578 #ifdef _WIN32
4579 tv.tv_usec = 0;
4580 #else
4581 tv.tv_usec = timeout * 1000;
4582 #endif
4583 #if defined(CONFIG_SLIRP)
4584 if (slirp_inited) {
4585 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4587 #endif
4588 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4589 if (ret > 0) {
4590 /* XXX: better handling of removal */
4591 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4592 ioh_next = ioh->next;
4593 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4594 ioh->fd_read(ioh->opaque);
4596 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4597 ioh->fd_write(ioh->opaque);
4601 #if defined(CONFIG_SLIRP)
4602 if (slirp_inited) {
4603 if (ret < 0) {
4604 FD_ZERO(&rfds);
4605 FD_ZERO(&wfds);
4606 FD_ZERO(&xfds);
4608 slirp_select_poll(&rfds, &wfds, &xfds);
4610 #endif
4611 #ifdef _WIN32
4612 tap_win32_poll();
4613 #endif
4615 if (vm_running) {
4616 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4617 qemu_get_clock(vm_clock));
4618 /* run dma transfers, if any */
4619 DMA_run();
4622 /* real time timers */
4623 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4624 qemu_get_clock(rt_clock));
4627 #ifndef CONFIG_DM
4628 static CPUState *cur_cpu;
4630 int main_loop(void)
4632 int ret, timeout;
4633 #ifdef CONFIG_PROFILER
4634 int64_t ti;
4635 #endif
4636 CPUState *env;
4638 cur_cpu = first_cpu;
4639 for(;;) {
4640 if (vm_running) {
4642 env = cur_cpu;
4643 for(;;) {
4644 /* get next cpu */
4645 env = env->next_cpu;
4646 if (!env)
4647 env = first_cpu;
4648 #ifdef CONFIG_PROFILER
4649 ti = profile_getclock();
4650 #endif
4651 ret = cpu_exec(env);
4652 #ifdef CONFIG_PROFILER
4653 qemu_time += profile_getclock() - ti;
4654 #endif
4655 if (ret != EXCP_HALTED)
4656 break;
4657 /* all CPUs are halted ? */
4658 if (env == cur_cpu) {
4659 ret = EXCP_HLT;
4660 break;
4663 cur_cpu = env;
4665 if (shutdown_requested) {
4666 ret = EXCP_INTERRUPT;
4667 break;
4669 if (reset_requested) {
4670 reset_requested = 0;
4671 qemu_system_reset();
4672 ret = EXCP_INTERRUPT;
4674 if (powerdown_requested) {
4675 powerdown_requested = 0;
4676 qemu_system_powerdown();
4677 ret = EXCP_INTERRUPT;
4679 if (ret == EXCP_DEBUG) {
4680 vm_stop(EXCP_DEBUG);
4682 /* if hlt instruction, we wait until the next IRQ */
4683 /* XXX: use timeout computed from timers */
4684 if (ret == EXCP_HLT)
4685 timeout = 10;
4686 else
4687 timeout = 0;
4688 } else {
4689 timeout = 10;
4691 #ifdef CONFIG_PROFILER
4692 ti = profile_getclock();
4693 #endif
4694 main_loop_wait(timeout);
4695 #ifdef CONFIG_PROFILER
4696 dev_time += profile_getclock() - ti;
4697 #endif
4699 cpu_disable_ticks();
4700 return ret;
4702 #endif /* !CONFIG_DM */
4704 void help(void)
4706 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4707 "usage: %s [options] [disk_image]\n"
4708 "\n"
4709 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4710 "\n"
4711 "Standard options:\n"
4712 "-M machine select emulated machine (-M ? for list)\n"
4713 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4714 #ifndef CONFIG_DM
4715 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4716 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4717 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4718 #endif /* !CONFIG_DM */
4719 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4720 "-snapshot write to temporary files instead of disk image files\n"
4721 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4722 "-smp n set the number of CPUs to 'n' [default=1]\n"
4723 "-nographic disable graphical output and redirect serial I/Os to console\n"
4724 "-vcpus set CPU number of guest platform\n"
4725 #ifndef _WIN32
4726 "-k language use keyboard layout (for example \"fr\" for French)\n"
4727 #endif
4728 #ifdef HAS_AUDIO
4729 "-audio-help print list of audio drivers and their options\n"
4730 "-soundhw c1,... enable audio support\n"
4731 " and only specified sound cards (comma separated list)\n"
4732 " use -soundhw ? to get the list of supported cards\n"
4733 " use -soundhw all to enable all of them\n"
4734 #endif
4735 "-localtime set the real time clock to local time [default=utc]\n"
4736 "-full-screen start in full screen\n"
4737 #ifdef TARGET_I386
4738 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4739 #endif
4740 "-usb enable the USB driver (will be the default soon)\n"
4741 "-usbdevice name add the host or guest USB device 'name'\n"
4742 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4743 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4744 #endif
4745 "\n"
4746 "Network options:\n"
4747 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4748 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4749 #ifdef CONFIG_SLIRP
4750 "-net user[,vlan=n][,hostname=host]\n"
4751 " connect the user mode network stack to VLAN 'n' and send\n"
4752 " hostname 'host' to DHCP clients\n"
4753 #endif
4754 #ifdef _WIN32
4755 "-net tap[,vlan=n],ifname=name\n"
4756 " connect the host TAP network interface to VLAN 'n'\n"
4757 #else
4758 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
4759 " connect the host TAP network interface to VLAN 'n' and use\n"
4760 " the network script 'file' (default=%s);\n"
4761 " use 'fd=h' to connect to an already opened TAP interface\n"
4762 #endif
4763 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4764 " connect the vlan 'n' to another VLAN using a socket connection\n"
4765 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4766 " connect the vlan 'n' to multicast maddr and port\n"
4767 "-net none use it alone to have zero network devices; if no -net option\n"
4768 " is provided, the default is '-net nic -net user'\n"
4769 "\n"
4770 #ifdef CONFIG_SLIRP
4771 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4772 #ifndef _WIN32
4773 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4774 #endif
4775 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4776 " redirect TCP or UDP connections from host to guest [-net user]\n"
4777 #endif
4778 "\n"
4779 "Linux boot specific:\n"
4780 "-kernel bzImage use 'bzImage' as kernel image\n"
4781 "-append cmdline use 'cmdline' as kernel command line\n"
4782 "-initrd file use 'file' as initial ram disk\n"
4783 "\n"
4784 "Debug/Expert options:\n"
4785 "-monitor dev redirect the monitor to char device 'dev'\n"
4786 "-serial dev redirect the serial port to char device 'dev'\n"
4787 "-parallel dev redirect the parallel port to char device 'dev'\n"
4788 "-pidfile file Write PID to 'file'\n"
4789 "-S freeze CPU at startup (use 'c' to start execution)\n"
4790 "-s wait gdb connection to port %d\n"
4791 "-p port change gdb connection port\n"
4792 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
4793 "-d domain domain that we're serving\n"
4794 "-domain-name domain name that we're serving\n"
4795 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4796 " translation (t=none or lba) (usually qemu can guess them)\n"
4797 "-L path set the directory for the BIOS and VGA BIOS\n"
4798 #ifdef USE_KQEMU
4799 "-no-kqemu disable KQEMU kernel module usage\n"
4800 #endif
4801 #ifdef USE_CODE_COPY
4802 "-no-code-copy disable code copy acceleration\n"
4803 #endif
4804 #ifdef TARGET_I386
4805 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4806 " (default is CL-GD5446 PCI VGA)\n"
4807 #endif
4808 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4809 "-vnc display start a VNC server on display\n"
4810 "-vncviewer start a vncviewer process for this domain\n"
4811 "-timeoffset time offset (in seconds) from local time\n"
4812 "-acpi disable or enable ACPI of HVM domain \n"
4813 "\n"
4814 "During emulation, the following keys are useful:\n"
4815 "ctrl-alt-f toggle full screen\n"
4816 "ctrl-alt-n switch to virtual console 'n'\n"
4817 "ctrl-alt toggle mouse and keyboard grab\n"
4818 "\n"
4819 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4821 #ifdef CONFIG_SOFTMMU
4822 "qemu",
4823 #else
4824 "qemu-fast",
4825 #endif
4826 DEFAULT_RAM_SIZE,
4827 #ifndef _WIN32
4828 DEFAULT_NETWORK_SCRIPT,
4829 #endif
4830 DEFAULT_GDBSTUB_PORT,
4831 "/tmp/qemu.log");
4832 #ifndef CONFIG_SOFTMMU
4833 printf("\n"
4834 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4835 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4836 "PC emulation.\n");
4837 #endif
4838 exit(1);
4841 #define HAS_ARG 0x0001
4843 enum {
4844 QEMU_OPTION_h,
4846 QEMU_OPTION_M,
4847 QEMU_OPTION_fda,
4848 QEMU_OPTION_fdb,
4849 #ifndef CONFIG_DM
4850 QEMU_OPTION_hda,
4851 QEMU_OPTION_hdb,
4852 QEMU_OPTION_hdc,
4853 QEMU_OPTION_hdd,
4854 QEMU_OPTION_cdrom,
4855 #endif /* !CONFIG_DM */
4856 QEMU_OPTION_boot,
4857 QEMU_OPTION_snapshot,
4858 QEMU_OPTION_m,
4859 QEMU_OPTION_nographic,
4860 #ifdef HAS_AUDIO
4861 QEMU_OPTION_audio_help,
4862 QEMU_OPTION_soundhw,
4863 #endif
4865 QEMU_OPTION_net,
4866 QEMU_OPTION_tftp,
4867 QEMU_OPTION_smb,
4868 QEMU_OPTION_redir,
4870 QEMU_OPTION_kernel,
4871 QEMU_OPTION_append,
4872 QEMU_OPTION_initrd,
4874 QEMU_OPTION_S,
4875 QEMU_OPTION_s,
4876 QEMU_OPTION_p,
4877 QEMU_OPTION_l,
4878 QEMU_OPTION_hdachs,
4879 QEMU_OPTION_L,
4880 #ifdef USE_CODE_COPY
4881 QEMU_OPTION_no_code_copy,
4882 #endif
4883 QEMU_OPTION_k,
4884 QEMU_OPTION_localtime,
4885 QEMU_OPTION_cirrusvga,
4886 QEMU_OPTION_g,
4887 QEMU_OPTION_std_vga,
4888 QEMU_OPTION_monitor,
4889 QEMU_OPTION_domainname,
4890 QEMU_OPTION_serial,
4891 QEMU_OPTION_parallel,
4892 QEMU_OPTION_loadvm,
4893 QEMU_OPTION_full_screen,
4894 QEMU_OPTION_pidfile,
4895 QEMU_OPTION_no_kqemu,
4896 QEMU_OPTION_kernel_kqemu,
4897 QEMU_OPTION_win2k_hack,
4898 QEMU_OPTION_usb,
4899 QEMU_OPTION_usbdevice,
4900 QEMU_OPTION_smp,
4901 QEMU_OPTION_vnc,
4902 QEMU_OPTION_vncviewer,
4904 QEMU_OPTION_d,
4905 QEMU_OPTION_vcpus,
4906 QEMU_OPTION_timeoffset,
4907 QEMU_OPTION_acpi,
4908 };
4910 typedef struct QEMUOption {
4911 const char *name;
4912 int flags;
4913 int index;
4914 } QEMUOption;
4916 const QEMUOption qemu_options[] = {
4917 { "h", 0, QEMU_OPTION_h },
4919 { "M", HAS_ARG, QEMU_OPTION_M },
4920 { "fda", HAS_ARG, QEMU_OPTION_fda },
4921 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4922 #ifndef CONFIG_DM
4923 { "hda", HAS_ARG, QEMU_OPTION_hda },
4924 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4925 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4926 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4927 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4928 #endif /* !CONFIG_DM */
4929 { "boot", HAS_ARG, QEMU_OPTION_boot },
4930 { "snapshot", 0, QEMU_OPTION_snapshot },
4931 { "m", HAS_ARG, QEMU_OPTION_m },
4932 { "nographic", 0, QEMU_OPTION_nographic },
4933 { "k", HAS_ARG, QEMU_OPTION_k },
4934 #ifdef HAS_AUDIO
4935 { "audio-help", 0, QEMU_OPTION_audio_help },
4936 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4937 #endif
4939 { "net", HAS_ARG, QEMU_OPTION_net},
4940 #ifdef CONFIG_SLIRP
4941 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4942 #ifndef _WIN32
4943 { "smb", HAS_ARG, QEMU_OPTION_smb },
4944 #endif
4945 { "redir", HAS_ARG, QEMU_OPTION_redir },
4946 #endif
4948 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4949 { "append", HAS_ARG, QEMU_OPTION_append },
4950 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4952 { "S", 0, QEMU_OPTION_S },
4953 { "s", 0, QEMU_OPTION_s },
4954 { "p", HAS_ARG, QEMU_OPTION_p },
4955 { "l", HAS_ARG, QEMU_OPTION_l },
4956 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4957 { "L", HAS_ARG, QEMU_OPTION_L },
4958 #ifdef USE_CODE_COPY
4959 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4960 #endif
4961 #ifdef USE_KQEMU
4962 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4963 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4964 #endif
4965 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4966 { "g", 1, QEMU_OPTION_g },
4967 #endif
4968 { "localtime", 0, QEMU_OPTION_localtime },
4969 { "std-vga", 0, QEMU_OPTION_std_vga },
4970 { "monitor", 1, QEMU_OPTION_monitor },
4971 { "domain-name", 1, QEMU_OPTION_domainname },
4972 { "serial", 1, QEMU_OPTION_serial },
4973 { "parallel", 1, QEMU_OPTION_parallel },
4974 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4975 { "full-screen", 0, QEMU_OPTION_full_screen },
4976 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4977 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4978 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4979 { "smp", HAS_ARG, QEMU_OPTION_smp },
4980 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4981 { "vncviewer", 0, QEMU_OPTION_vncviewer },
4983 /* temporary options */
4984 { "usb", 0, QEMU_OPTION_usb },
4985 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4987 { "d", HAS_ARG, QEMU_OPTION_d },
4988 { "vcpus", 1, QEMU_OPTION_vcpus },
4989 { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
4990 { "acpi", 0, QEMU_OPTION_acpi },
4991 { NULL },
4992 };
4994 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4996 /* this stack is only used during signal handling */
4997 #define SIGNAL_STACK_SIZE 32768
4999 static uint8_t *signal_stack;
5001 #endif
5003 /* password input */
5005 static BlockDriverState *get_bdrv(int index)
5007 BlockDriverState *bs;
5009 if (index < 4) {
5010 bs = bs_table[index];
5011 } else if (index < 6) {
5012 bs = fd_table[index - 4];
5013 } else {
5014 bs = NULL;
5016 return bs;
5019 static void read_passwords(void)
5021 BlockDriverState *bs;
5022 int i, j;
5023 char password[256];
5025 for(i = 0; i < 6; i++) {
5026 bs = get_bdrv(i);
5027 if (bs && bdrv_is_encrypted(bs)) {
5028 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5029 for(j = 0; j < 3; j++) {
5030 monitor_readline("Password: ",
5031 1, password, sizeof(password));
5032 if (bdrv_set_key(bs, password) == 0)
5033 break;
5034 term_printf("invalid password\n");
5040 /* XXX: currently we cannot use simultaneously different CPUs */
5041 void register_machines(void)
5043 #if defined(TARGET_I386)
5044 qemu_register_machine(&pc_machine);
5045 qemu_register_machine(&isapc_machine);
5046 #elif defined(TARGET_PPC)
5047 qemu_register_machine(&heathrow_machine);
5048 qemu_register_machine(&core99_machine);
5049 qemu_register_machine(&prep_machine);
5050 #elif defined(TARGET_MIPS)
5051 qemu_register_machine(&mips_machine);
5052 #elif defined(TARGET_SPARC)
5053 #ifdef TARGET_SPARC64
5054 qemu_register_machine(&sun4u_machine);
5055 #else
5056 qemu_register_machine(&sun4m_machine);
5057 #endif
5058 #elif defined(TARGET_ARM)
5059 qemu_register_machine(&integratorcp926_machine);
5060 qemu_register_machine(&integratorcp1026_machine);
5061 qemu_register_machine(&versatilepb_machine);
5062 qemu_register_machine(&versatileab_machine);
5063 #elif defined(TARGET_SH4)
5064 qemu_register_machine(&shix_machine);
5065 #else
5066 #error unsupported CPU
5067 #endif
5070 #ifdef HAS_AUDIO
5071 struct soundhw soundhw[] = {
5072 #ifndef CONFIG_DM
5073 #ifdef TARGET_I386
5075 "pcspk",
5076 "PC speaker",
5077 0,
5078 1,
5079 { .init_isa = pcspk_audio_init }
5080 },
5081 #endif
5082 #endif /* !CONFIG_DM */
5084 "sb16",
5085 "Creative Sound Blaster 16",
5086 0,
5087 1,
5088 { .init_isa = SB16_init }
5089 },
5091 #ifdef CONFIG_ADLIB
5093 "adlib",
5094 #ifdef HAS_YMF262
5095 "Yamaha YMF262 (OPL3)",
5096 #else
5097 "Yamaha YM3812 (OPL2)",
5098 #endif
5099 0,
5100 1,
5101 { .init_isa = Adlib_init }
5102 },
5103 #endif
5105 #ifdef CONFIG_GUS
5107 "gus",
5108 "Gravis Ultrasound GF1",
5109 0,
5110 1,
5111 { .init_isa = GUS_init }
5112 },
5113 #endif
5116 "es1370",
5117 "ENSONIQ AudioPCI ES1370",
5118 0,
5119 0,
5120 { .init_pci = es1370_init }
5121 },
5123 { NULL, NULL, 0, 0, { NULL } }
5124 };
5126 static void select_soundhw (const char *optarg)
5128 struct soundhw *c;
5130 if (*optarg == '?') {
5131 show_valid_cards:
5133 printf ("Valid sound card names (comma separated):\n");
5134 for (c = soundhw; c->name; ++c) {
5135 printf ("%-11s %s\n", c->name, c->descr);
5137 printf ("\n-soundhw all will enable all of the above\n");
5138 exit (*optarg != '?');
5140 else {
5141 size_t l;
5142 const char *p;
5143 char *e;
5144 int bad_card = 0;
5146 if (!strcmp (optarg, "all")) {
5147 for (c = soundhw; c->name; ++c) {
5148 c->enabled = 1;
5150 return;
5153 p = optarg;
5154 while (*p) {
5155 e = strchr (p, ',');
5156 l = !e ? strlen (p) : (size_t) (e - p);
5158 for (c = soundhw; c->name; ++c) {
5159 if (!strncmp (c->name, p, l)) {
5160 c->enabled = 1;
5161 break;
5165 if (!c->name) {
5166 if (l > 80) {
5167 fprintf (stderr,
5168 "Unknown sound card name (too big to show)\n");
5170 else {
5171 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5172 (int) l, p);
5174 bad_card = 1;
5176 p += l + (e != NULL);
5179 if (bad_card)
5180 goto show_valid_cards;
5183 #endif
5185 #define MAX_NET_CLIENTS 32
5187 #include <xg_private.h>
5189 /* FIXME Flush the shadow page */
5190 int unset_mm_mapping(int xc_handle, uint32_t domid,
5191 unsigned long nr_pages, unsigned int address_bits,
5192 xen_pfn_t *extent_start)
5194 int err = 0;
5195 xc_dominfo_t info;
5197 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
5198 nr_pages, 0, extent_start);
5199 if (err)
5200 fprintf(stderr, "Failed to decrease physmap\n");
5202 xc_domain_getinfo(xc_handle, domid, 1, &info);
5204 if ((info.nr_pages - nr_pages) <= 0) {
5205 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
5206 err = -1;
5209 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
5210 PAGE_SIZE/1024) != 0) {
5211 fprintf(logfile, "set maxmem returned error %d\n", errno);
5212 err = -1;
5215 return err;
5218 int set_mm_mapping(int xc_handle, uint32_t domid,
5219 unsigned long nr_pages, unsigned int address_bits,
5220 xen_pfn_t *extent_start)
5222 #if 0
5223 int i;
5224 #endif
5225 xc_dominfo_t info;
5226 int err = 0;
5228 xc_domain_getinfo(xc_handle, domid, 1, &info);
5230 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
5231 nr_pages * PAGE_SIZE/1024) != 0) {
5232 fprintf(logfile, "set maxmem returned error %d\n", errno);
5233 return -1;
5236 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
5237 address_bits, extent_start);
5238 if (err) {
5239 fprintf(stderr, "Failed to populate physmap\n");
5240 return -1;
5243 err = xc_domain_translate_gpfn_list(xc_handle, domid, nr_pages,
5244 extent_start, extent_start);
5245 if (err) {
5246 fprintf(stderr, "Failed to translate gpfn list\n");
5247 return -1;
5250 #if 0 /* Generates lots of log file output - turn on for debugging */
5251 for (i = 0; i < nr_pages; i++)
5252 fprintf(stderr, "set_map result i %x result %lx\n", i,
5253 extent_start[i]);
5254 #endif
5256 return 0;
5259 int main(int argc, char **argv)
5261 #ifdef CONFIG_GDBSTUB
5262 int use_gdbstub, gdbstub_port;
5263 #endif
5264 int i;
5265 #ifndef CONFIG_DM
5266 int cdrom_index;
5267 #endif /* !CONFIG_DM */
5268 int snapshot, linux_boot;
5269 const char *initrd_filename;
5270 #ifndef CONFIG_DM
5271 const char *hd_filename[MAX_DISKS];
5272 #endif /* !CONFIG_DM */
5273 const char *fd_filename[MAX_FD];
5274 const char *kernel_filename, *kernel_cmdline;
5275 DisplayState *ds = &display_state;
5276 int cyls, heads, secs, translation;
5277 int start_emulation = 1;
5278 char net_clients[MAX_NET_CLIENTS][256];
5279 int nb_net_clients;
5280 int optind;
5281 const char *r, *optarg;
5282 CharDriverState *monitor_hd;
5283 char monitor_device[128];
5284 char serial_devices[MAX_SERIAL_PORTS][128];
5285 int serial_device_index;
5286 char parallel_devices[MAX_PARALLEL_PORTS][128];
5287 int parallel_device_index;
5288 const char *loadvm = NULL;
5289 QEMUMachine *machine;
5290 char usb_devices[MAX_VM_USB_PORTS][128];
5291 int usb_devices_index;
5292 unsigned long nr_pages;
5293 xen_pfn_t *page_array;
5294 extern void *shared_page;
5296 char qemu_dm_logfilename[64];
5298 LIST_INIT (&vm_change_state_head);
5299 #if !defined(CONFIG_SOFTMMU)
5300 /* we never want that malloc() uses mmap() */
5301 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5302 #endif
5303 register_machines();
5304 machine = first_machine;
5305 initrd_filename = NULL;
5306 for(i = 0; i < MAX_FD; i++)
5307 fd_filename[i] = NULL;
5308 #ifndef CONFIG_DM
5309 for(i = 0; i < MAX_DISKS; i++)
5310 hd_filename[i] = NULL;
5311 #endif /* !CONFIG_DM */
5312 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5313 vga_ram_size = VGA_RAM_SIZE;
5314 bios_size = BIOS_SIZE;
5315 #ifdef CONFIG_GDBSTUB
5316 use_gdbstub = 0;
5317 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5318 #endif
5319 snapshot = 0;
5320 nographic = 0;
5321 vncviewer = 0;
5322 kernel_filename = NULL;
5323 kernel_cmdline = "";
5324 #ifndef CONFIG_DM
5325 #ifdef TARGET_PPC
5326 cdrom_index = 1;
5327 #else
5328 cdrom_index = 2;
5329 #endif
5330 #endif /* !CONFIG_DM */
5331 cyls = heads = secs = 0;
5332 translation = BIOS_ATA_TRANSLATION_AUTO;
5333 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5335 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5336 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5337 serial_devices[i][0] = '\0';
5338 serial_device_index = 0;
5340 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5341 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5342 parallel_devices[i][0] = '\0';
5343 parallel_device_index = 0;
5345 usb_devices_index = 0;
5347 nb_net_clients = 0;
5349 nb_nics = 0;
5350 /* default mac address of the first network interface */
5352 /* init debug */
5353 sprintf(qemu_dm_logfilename, "/var/log/qemu-dm.%d.log", getpid());
5354 cpu_set_log_filename(qemu_dm_logfilename);
5355 cpu_set_log(0);
5357 optind = 1;
5358 for(;;) {
5359 if (optind >= argc)
5360 break;
5361 r = argv[optind];
5362 if (r[0] != '-') {
5363 #ifndef CONFIG_DM
5364 hd_filename[0] = argv[optind++];
5365 #else
5366 help();
5367 #endif /* !CONFIG_DM */
5368 } else {
5369 const QEMUOption *popt;
5371 optind++;
5372 popt = qemu_options;
5373 for(;;) {
5374 if (!popt->name) {
5375 fprintf(stderr, "%s: invalid option -- '%s'\n",
5376 argv[0], r);
5377 exit(1);
5379 if (!strcmp(popt->name, r + 1))
5380 break;
5381 popt++;
5383 if (popt->flags & HAS_ARG) {
5384 if (optind >= argc) {
5385 fprintf(stderr, "%s: option '%s' requires an argument\n",
5386 argv[0], r);
5387 exit(1);
5389 optarg = argv[optind++];
5390 } else {
5391 optarg = NULL;
5394 switch(popt->index) {
5395 case QEMU_OPTION_M:
5396 machine = find_machine(optarg);
5397 if (!machine) {
5398 QEMUMachine *m;
5399 printf("Supported machines are:\n");
5400 for(m = first_machine; m != NULL; m = m->next) {
5401 printf("%-10s %s%s\n",
5402 m->name, m->desc,
5403 m == first_machine ? " (default)" : "");
5405 exit(1);
5407 break;
5408 case QEMU_OPTION_initrd:
5409 initrd_filename = optarg;
5410 break;
5411 #ifndef CONFIG_DM
5412 case QEMU_OPTION_hda:
5413 case QEMU_OPTION_hdb:
5414 case QEMU_OPTION_hdc:
5415 case QEMU_OPTION_hdd:
5417 int hd_index;
5418 hd_index = popt->index - QEMU_OPTION_hda;
5419 hd_filename[hd_index] = optarg;
5420 if (hd_index == cdrom_index)
5421 cdrom_index = -1;
5423 break;
5424 #endif /* !CONFIG_DM */
5425 case QEMU_OPTION_snapshot:
5426 snapshot = 1;
5427 break;
5428 case QEMU_OPTION_hdachs:
5430 const char *p;
5431 p = optarg;
5432 cyls = strtol(p, (char **)&p, 0);
5433 if (cyls < 1 || cyls > 16383)
5434 goto chs_fail;
5435 if (*p != ',')
5436 goto chs_fail;
5437 p++;
5438 heads = strtol(p, (char **)&p, 0);
5439 if (heads < 1 || heads > 16)
5440 goto chs_fail;
5441 if (*p != ',')
5442 goto chs_fail;
5443 p++;
5444 secs = strtol(p, (char **)&p, 0);
5445 if (secs < 1 || secs > 63)
5446 goto chs_fail;
5447 if (*p == ',') {
5448 p++;
5449 if (!strcmp(p, "none"))
5450 translation = BIOS_ATA_TRANSLATION_NONE;
5451 else if (!strcmp(p, "lba"))
5452 translation = BIOS_ATA_TRANSLATION_LBA;
5453 else if (!strcmp(p, "auto"))
5454 translation = BIOS_ATA_TRANSLATION_AUTO;
5455 else
5456 goto chs_fail;
5457 } else if (*p != '\0') {
5458 chs_fail:
5459 fprintf(stderr, "qemu: invalid physical CHS format\n");
5460 exit(1);
5463 break;
5464 case QEMU_OPTION_nographic:
5465 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5466 if(!strcmp(serial_devices[0], "vc"))
5467 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
5468 "stdio");
5469 nographic = 1;
5470 break;
5471 case QEMU_OPTION_kernel:
5472 kernel_filename = optarg;
5473 break;
5474 case QEMU_OPTION_append:
5475 kernel_cmdline = optarg;
5476 break;
5477 #ifndef CONFIG_DM
5478 case QEMU_OPTION_cdrom:
5479 if (cdrom_index >= 0) {
5480 hd_filename[cdrom_index] = optarg;
5482 break;
5483 #endif /* !CONFIG_DM */
5484 case QEMU_OPTION_boot:
5485 boot_device = optarg[0];
5486 if (boot_device != 'a' &&
5487 #ifdef TARGET_SPARC
5488 // Network boot
5489 boot_device != 'n' &&
5490 #endif
5491 boot_device != 'c' && boot_device != 'd') {
5492 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5493 exit(1);
5495 break;
5496 case QEMU_OPTION_fda:
5497 fd_filename[0] = optarg;
5498 break;
5499 case QEMU_OPTION_fdb:
5500 fd_filename[1] = optarg;
5501 break;
5502 #ifdef USE_CODE_COPY
5503 case QEMU_OPTION_no_code_copy:
5504 code_copy_enabled = 0;
5505 break;
5506 #endif
5507 case QEMU_OPTION_net:
5508 if (nb_net_clients >= MAX_NET_CLIENTS) {
5509 fprintf(stderr, "qemu: too many network clients\n");
5510 exit(1);
5512 pstrcpy(net_clients[nb_net_clients],
5513 sizeof(net_clients[0]),
5514 optarg);
5515 nb_net_clients++;
5516 break;
5517 #ifdef CONFIG_SLIRP
5518 case QEMU_OPTION_tftp:
5519 tftp_prefix = optarg;
5520 break;
5521 #ifndef _WIN32
5522 case QEMU_OPTION_smb:
5523 net_slirp_smb(optarg);
5524 break;
5525 #endif
5526 case QEMU_OPTION_redir:
5527 net_slirp_redir(optarg);
5528 break;
5529 #endif
5530 #ifdef HAS_AUDIO
5531 case QEMU_OPTION_audio_help:
5532 AUD_help ();
5533 exit (0);
5534 break;
5535 case QEMU_OPTION_soundhw:
5536 select_soundhw (optarg);
5537 break;
5538 #endif
5539 case QEMU_OPTION_h:
5540 help();
5541 break;
5542 case QEMU_OPTION_m:
5543 ram_size = atol(optarg) * 1024 * 1024;
5544 if (ram_size <= 0)
5545 help();
5546 #ifndef CONFIG_DM
5547 if (ram_size > PHYS_RAM_MAX_SIZE) {
5548 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5549 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5550 exit(1);
5552 #endif /* !CONFIG_DM */
5553 break;
5554 case QEMU_OPTION_l:
5556 int mask;
5557 CPULogItem *item;
5559 mask = cpu_str_to_log_mask(optarg);
5560 if (!mask) {
5561 printf("Log items (comma separated):\n");
5562 for(item = cpu_log_items; item->mask != 0; item++) {
5563 printf("%-10s %s\n", item->name, item->help);
5565 exit(1);
5567 cpu_set_log(mask);
5569 break;
5570 #ifdef CONFIG_GDBSTUB
5571 case QEMU_OPTION_s:
5572 use_gdbstub = 1;
5573 break;
5574 case QEMU_OPTION_p:
5575 gdbstub_port = atoi(optarg);
5576 break;
5577 #endif
5578 case QEMU_OPTION_L:
5579 bios_dir = optarg;
5580 break;
5581 case QEMU_OPTION_S:
5582 start_emulation = 0;
5583 break;
5584 case QEMU_OPTION_k:
5585 keyboard_layout = optarg;
5586 break;
5587 case QEMU_OPTION_localtime:
5588 rtc_utc = 0;
5589 break;
5590 case QEMU_OPTION_cirrusvga:
5591 cirrus_vga_enabled = 1;
5592 break;
5593 case QEMU_OPTION_std_vga:
5594 cirrus_vga_enabled = 0;
5595 break;
5596 case QEMU_OPTION_g:
5598 const char *p;
5599 int w, h, depth;
5600 p = optarg;
5601 w = strtol(p, (char **)&p, 10);
5602 if (w <= 0) {
5603 graphic_error:
5604 fprintf(stderr, "qemu: invalid resolution or depth\n");
5605 exit(1);
5607 if (*p != 'x')
5608 goto graphic_error;
5609 p++;
5610 h = strtol(p, (char **)&p, 10);
5611 if (h <= 0)
5612 goto graphic_error;
5613 if (*p == 'x') {
5614 p++;
5615 depth = strtol(p, (char **)&p, 10);
5616 if (depth != 8 && depth != 15 && depth != 16 &&
5617 depth != 24 && depth != 32)
5618 goto graphic_error;
5619 } else if (*p == '\0') {
5620 depth = graphic_depth;
5621 } else {
5622 goto graphic_error;
5625 graphic_width = w;
5626 graphic_height = h;
5627 graphic_depth = depth;
5629 break;
5630 case QEMU_OPTION_monitor:
5631 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5632 break;
5633 case QEMU_OPTION_serial:
5634 if (serial_device_index >= MAX_SERIAL_PORTS) {
5635 fprintf(stderr, "qemu: too many serial ports\n");
5636 exit(1);
5638 pstrcpy(serial_devices[serial_device_index],
5639 sizeof(serial_devices[0]), optarg);
5640 serial_device_index++;
5641 break;
5642 case QEMU_OPTION_parallel:
5643 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5644 fprintf(stderr, "qemu: too many parallel ports\n");
5645 exit(1);
5647 pstrcpy(parallel_devices[parallel_device_index],
5648 sizeof(parallel_devices[0]), optarg);
5649 parallel_device_index++;
5650 break;
5651 case QEMU_OPTION_loadvm:
5652 loadvm = optarg;
5653 break;
5654 case QEMU_OPTION_full_screen:
5655 full_screen = 1;
5656 break;
5657 case QEMU_OPTION_pidfile:
5658 create_pidfile(optarg);
5659 break;
5660 #ifdef TARGET_I386
5661 case QEMU_OPTION_win2k_hack:
5662 win2k_install_hack = 1;
5663 break;
5664 #endif
5665 #ifdef USE_KQEMU
5666 case QEMU_OPTION_no_kqemu:
5667 kqemu_allowed = 0;
5668 break;
5669 case QEMU_OPTION_kernel_kqemu:
5670 kqemu_allowed = 2;
5671 break;
5672 #endif
5673 case QEMU_OPTION_usb:
5674 usb_enabled = 1;
5675 break;
5676 case QEMU_OPTION_usbdevice:
5677 usb_enabled = 1;
5678 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5679 fprintf(stderr, "Too many USB devices\n");
5680 exit(1);
5682 pstrcpy(usb_devices[usb_devices_index],
5683 sizeof(usb_devices[usb_devices_index]),
5684 optarg);
5685 usb_devices_index++;
5686 break;
5687 case QEMU_OPTION_smp:
5688 smp_cpus = atoi(optarg);
5689 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5690 fprintf(stderr, "Invalid number of CPUs\n");
5691 exit(1);
5693 break;
5694 case QEMU_OPTION_vnc:
5695 vnc_display = atoi(optarg);
5696 if (vnc_display < 0) {
5697 fprintf(stderr, "Invalid VNC display\n");
5698 exit(1);
5700 break;
5701 case QEMU_OPTION_vncviewer:
5702 vncviewer++;
5703 break;
5704 case QEMU_OPTION_domainname:
5705 strncat(domain_name, optarg, sizeof(domain_name) - 20);
5706 break;
5707 case QEMU_OPTION_d:
5708 domid = atoi(optarg);
5709 fprintf(logfile, "domid: %d\n", domid);
5710 break;
5711 case QEMU_OPTION_vcpus:
5712 vcpus = atoi(optarg);
5713 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
5714 break;
5715 case QEMU_OPTION_timeoffset:
5716 timeoffset = strtol(optarg, NULL, 0);
5717 break;
5718 case QEMU_OPTION_acpi:
5719 acpi_enabled = 1;
5720 break;
5725 #ifdef CONFIG_DM
5726 bdrv_init();
5727 xenstore_parse_domain_config(domid);
5728 #endif /* CONFIG_DM */
5730 #ifdef USE_KQEMU
5731 if (smp_cpus > 1)
5732 kqemu_allowed = 0;
5733 #endif
5734 linux_boot = (kernel_filename != NULL);
5736 #ifndef CONFIG_DM
5737 if (!linux_boot &&
5738 hd_filename[0] == '\0' &&
5739 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5740 fd_filename[0] == '\0')
5741 help();
5743 /* boot to cd by default if no hard disk */
5744 if (hd_filename[0] == '\0' && boot_device == 'c') {
5745 if (fd_filename[0] != '\0')
5746 boot_device = 'a';
5747 else
5748 boot_device = 'd';
5750 #endif /* !CONFIG_DM */
5752 #if !defined(CONFIG_SOFTMMU)
5753 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5755 static uint8_t stdout_buf[4096];
5756 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5758 #else
5759 setvbuf(stdout, NULL, _IOLBF, 0);
5760 #endif
5762 #ifdef _WIN32
5763 socket_init();
5764 #endif
5766 #ifndef CONFIG_DM
5767 /* init network clients */
5768 if (nb_net_clients == 0) {
5769 /* if no clients, we use a default config */
5770 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5771 "nic");
5772 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5773 "user");
5774 nb_net_clients = 2;
5776 #endif /* !CONFIG_DM */
5778 for(i = 0;i < nb_net_clients; i++) {
5779 if (net_client_init(net_clients[i]) < 0)
5780 exit(1);
5783 /* init the memory */
5784 phys_ram_size = ram_size + vga_ram_size + bios_size;
5786 #if defined (__ia64__)
5787 if (ram_size > MMIO_START)
5788 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
5789 #endif
5791 #ifdef CONFIG_DM
5793 nr_pages = ram_size/PAGE_SIZE;
5794 xc_handle = xc_interface_open();
5796 page_array = (xen_pfn_t *)malloc(nr_pages * sizeof(xen_pfn_t));
5797 if (page_array == NULL) {
5798 fprintf(logfile, "malloc returned error %d\n", errno);
5799 exit(-1);
5802 #if defined(__i386__) || defined(__x86_64__)
5803 if (xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages) {
5804 fprintf(logfile, "xc_get_pfn_list returned error %d\n", errno);
5805 exit(-1);
5808 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
5809 PROT_READ|PROT_WRITE, page_array,
5810 nr_pages - 1);
5811 if (phys_ram_base == 0) {
5812 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
5813 exit(-1);
5816 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
5817 PROT_READ|PROT_WRITE,
5818 page_array[nr_pages - 1]);
5820 fprintf(logfile, "shared page at pfn:%lx, mfn: %"PRIx64"\n", nr_pages - 1,
5821 (uint64_t)(page_array[nr_pages - 1]));
5823 free(page_array);
5825 #elif defined(__ia64__)
5827 if (xc_ia64_get_pfn_list(xc_handle, domid, page_array,
5828 IO_PAGE_START >> PAGE_SHIFT, 1) != 1) {
5829 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
5830 exit(-1);
5833 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
5834 PROT_READ|PROT_WRITE,
5835 page_array[0]);
5837 fprintf(logfile, "shared page at pfn:%lx, mfn: %016lx\n",
5838 IO_PAGE_START >> PAGE_SHIFT, page_array[0]);
5840 if (xc_ia64_get_pfn_list(xc_handle, domid,
5841 page_array, 0, nr_pages) != nr_pages) {
5842 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
5843 exit(-1);
5846 if (ram_size > MMIO_START) {
5847 for (i = 0 ; i < MEM_G >> PAGE_SHIFT; i++)
5848 page_array[MMIO_START >> PAGE_SHIFT + i] =
5849 page_array[IO_PAGE_START >> PAGE_SHIFT + 1];
5852 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
5853 PROT_READ|PROT_WRITE,
5854 page_array, nr_pages);
5855 if (phys_ram_base == 0) {
5856 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
5857 exit(-1);
5859 #endif
5860 #else /* !CONFIG_DM */
5862 #ifdef CONFIG_SOFTMMU
5863 phys_ram_base = qemu_vmalloc(phys_ram_size);
5864 if (!phys_ram_base) {
5865 fprintf(stderr, "Could not allocate physical memory\n");
5866 exit(1);
5868 #else
5869 /* as we must map the same page at several addresses, we must use
5870 a fd */
5872 const char *tmpdir;
5874 tmpdir = getenv("QEMU_TMPDIR");
5875 if (!tmpdir)
5876 tmpdir = "/tmp";
5877 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5878 if (mkstemp(phys_ram_file) < 0) {
5879 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5880 phys_ram_file);
5881 exit(1);
5883 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5884 if (phys_ram_fd < 0) {
5885 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5886 phys_ram_file);
5887 exit(1);
5889 ftruncate(phys_ram_fd, phys_ram_size);
5890 unlink(phys_ram_file);
5891 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5892 phys_ram_size,
5893 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5894 phys_ram_fd, 0);
5895 if (phys_ram_base == MAP_FAILED) {
5896 fprintf(stderr, "Could not map physical memory\n");
5897 exit(1);
5900 #endif
5902 #endif /* !CONFIG_DM */
5904 #ifndef CONFIG_DM
5905 /* we always create the cdrom drive, even if no disk is there */
5906 bdrv_init();
5907 if (cdrom_index >= 0) {
5908 bs_table[cdrom_index] = bdrv_new("cdrom");
5909 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5912 /* open the virtual block devices */
5913 for(i = 0; i < MAX_DISKS; i++) {
5914 if (hd_filename[i]) {
5915 if (!bs_table[i]) {
5916 char buf[64];
5917 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5918 bs_table[i] = bdrv_new(buf);
5920 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5921 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5922 hd_filename[i]);
5923 exit(1);
5925 if (i == 0 && cyls != 0) {
5926 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5927 bdrv_set_translation_hint(bs_table[i], translation);
5931 #endif /* !CONFIG_DM */
5933 /* we always create at least one floppy disk */
5934 fd_table[0] = bdrv_new("fda");
5935 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5937 for(i = 0; i < MAX_FD; i++) {
5938 if (fd_filename[i]) {
5939 if (!fd_table[i]) {
5940 char buf[64];
5941 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5942 fd_table[i] = bdrv_new(buf);
5943 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5945 if (fd_filename[i] != '\0') {
5946 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5947 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5948 fd_filename[i]);
5949 exit(1);
5955 /* init USB devices */
5956 if (usb_enabled) {
5957 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5958 for(i = 0; i < usb_devices_index; i++) {
5959 if (usb_device_add(usb_devices[i]) < 0) {
5960 fprintf(stderr, "Warning: could not add USB device %s\n",
5961 usb_devices[i]);
5966 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5967 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5969 init_ioports();
5970 cpu_calibrate_ticks();
5972 /* terminal init */
5973 if (nographic) {
5974 dumb_display_init(ds);
5975 } else if (vnc_display != -1) {
5976 vnc_display_init(ds, vnc_display);
5977 if (vncviewer)
5978 vnc_start_viewer(vnc_display);
5979 xenstore_write_vncport(vnc_display);
5980 } else {
5981 #if defined(CONFIG_SDL)
5982 sdl_display_init(ds, full_screen);
5983 #elif defined(CONFIG_COCOA)
5984 cocoa_display_init(ds, full_screen);
5985 #else
5986 dumb_display_init(ds);
5987 #endif
5990 monitor_hd = qemu_chr_open(monitor_device);
5991 if (!monitor_hd) {
5992 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5993 exit(1);
5995 monitor_init(monitor_hd, !nographic);
5997 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5998 if (serial_devices[i][0] != '\0') {
5999 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6000 if (!serial_hds[i]) {
6001 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6002 serial_devices[i]);
6003 exit(1);
6005 if (!strcmp(serial_devices[i], "vc"))
6006 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
6010 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6011 if (parallel_devices[i][0] != '\0') {
6012 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6013 if (!parallel_hds[i]) {
6014 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6015 parallel_devices[i]);
6016 exit(1);
6018 if (!strcmp(parallel_devices[i], "vc"))
6019 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
6023 /* setup cpu signal handlers for MMU / self modifying code handling */
6024 #if !defined(CONFIG_SOFTMMU)
6026 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6028 stack_t stk;
6029 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
6030 stk.ss_sp = signal_stack;
6031 stk.ss_size = SIGNAL_STACK_SIZE;
6032 stk.ss_flags = 0;
6034 if (sigaltstack(&stk, NULL) < 0) {
6035 fprintf(logfile, "sigaltstack returned error %d\n", errno);
6036 exit(1);
6039 #endif
6041 struct sigaction act;
6043 sigfillset(&act.sa_mask);
6044 act.sa_flags = SA_SIGINFO;
6045 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6046 act.sa_flags |= SA_ONSTACK;
6047 #endif
6048 act.sa_sigaction = host_segv_handler;
6049 sigaction(SIGSEGV, &act, NULL);
6050 sigaction(SIGBUS, &act, NULL);
6051 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6052 sigaction(SIGFPE, &act, NULL);
6053 #endif
6055 #endif
6057 #ifndef _WIN32
6059 struct sigaction act;
6060 sigfillset(&act.sa_mask);
6061 act.sa_flags = 0;
6062 act.sa_handler = SIG_IGN;
6063 sigaction(SIGPIPE, &act, NULL);
6065 #endif
6066 init_timers();
6068 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
6070 machine->init(ram_size, vga_ram_size, boot_device,
6071 ds, fd_filename, snapshot,
6072 kernel_filename, kernel_cmdline, initrd_filename,
6073 timeoffset);
6075 if (vnc_display == -1) {
6076 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6077 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6080 #ifdef CONFIG_GDBSTUB
6081 if (use_gdbstub) {
6082 if (gdbserver_start(gdbstub_port) < 0) {
6083 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6084 gdbstub_port);
6085 exit(1);
6086 } else {
6087 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6089 } else
6090 #endif
6091 if (loadvm)
6092 qemu_loadvm(loadvm);
6095 /* XXX: simplify init */
6096 read_passwords();
6097 if (start_emulation) {
6098 vm_start();
6101 main_loop();
6102 quit_timers();
6103 return 0;