ia64/xen-unstable

view tools/ioemu/vl.c @ 10803:42aa63188a88

IA64-specific code for new Qemu
Due to some ia64 patches aren't checked into xen-unstable.hg.
I reversed related logic.

Signed-off-by: Zhang xiantao <xiantao.zhang@intel.com>
Signed-off-by: Christian Limpach <Christian.Limpach@xensource.com>
author chris@kneesaa.uk.xensource.com
date Wed Jul 26 13:41:10 2006 +0100 (2006-07-26)
parents ecb8ff1fcf1f
children 21918b22746e f3d6a5281617
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 char domain_name[1024] = { 'H','V', 'M', 'X', 'E', 'N', '-'};
171 extern int domid;
173 /***********************************************************/
174 /* x86 ISA bus support */
176 target_phys_addr_t isa_mem_base = 0;
177 PicState2 *isa_pic;
179 uint32_t default_ioport_readb(void *opaque, uint32_t address)
180 {
181 #ifdef DEBUG_UNUSED_IOPORT
182 fprintf(stderr, "inb: port=0x%04x\n", address);
183 #endif
184 return 0xff;
185 }
187 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
188 {
189 #ifdef DEBUG_UNUSED_IOPORT
190 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
191 #endif
192 }
194 /* default is to make two byte accesses */
195 uint32_t default_ioport_readw(void *opaque, uint32_t address)
196 {
197 uint32_t data;
198 data = ioport_read_table[0][address](ioport_opaque[address], address);
199 address = (address + 1) & (MAX_IOPORTS - 1);
200 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
201 return data;
202 }
204 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
205 {
206 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
207 address = (address + 1) & (MAX_IOPORTS - 1);
208 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
209 }
211 uint32_t default_ioport_readl(void *opaque, uint32_t address)
212 {
213 #ifdef DEBUG_UNUSED_IOPORT
214 fprintf(stderr, "inl: port=0x%04x\n", address);
215 #endif
216 return 0xffffffff;
217 }
219 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
220 {
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
223 #endif
224 }
226 void init_ioports(void)
227 {
228 int i;
230 for(i = 0; i < MAX_IOPORTS; i++) {
231 ioport_read_table[0][i] = default_ioport_readb;
232 ioport_write_table[0][i] = default_ioport_writeb;
233 ioport_read_table[1][i] = default_ioport_readw;
234 ioport_write_table[1][i] = default_ioport_writew;
235 ioport_read_table[2][i] = default_ioport_readl;
236 ioport_write_table[2][i] = default_ioport_writel;
237 }
238 }
240 /* size is the word size in byte */
241 int register_ioport_read(int start, int length, int size,
242 IOPortReadFunc *func, void *opaque)
243 {
244 int i, bsize;
246 if (size == 1) {
247 bsize = 0;
248 } else if (size == 2) {
249 bsize = 1;
250 } else if (size == 4) {
251 bsize = 2;
252 } else {
253 hw_error("register_ioport_read: invalid size");
254 return -1;
255 }
256 for(i = start; i < start + length; i += size) {
257 ioport_read_table[bsize][i] = func;
258 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
259 hw_error("register_ioport_read: invalid opaque");
260 ioport_opaque[i] = opaque;
261 }
262 return 0;
263 }
265 /* size is the word size in byte */
266 int register_ioport_write(int start, int length, int size,
267 IOPortWriteFunc *func, void *opaque)
268 {
269 int i, bsize;
271 if (size == 1) {
272 bsize = 0;
273 } else if (size == 2) {
274 bsize = 1;
275 } else if (size == 4) {
276 bsize = 2;
277 } else {
278 hw_error("register_ioport_write: invalid size");
279 return -1;
280 }
281 for(i = start; i < start + length; i += size) {
282 ioport_write_table[bsize][i] = func;
283 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
284 hw_error("register_ioport_read: invalid opaque");
285 ioport_opaque[i] = opaque;
286 }
287 return 0;
288 }
290 void isa_unassign_ioport(int start, int length)
291 {
292 int i;
294 for(i = start; i < start + length; i++) {
295 ioport_read_table[0][i] = default_ioport_readb;
296 ioport_read_table[1][i] = default_ioport_readw;
297 ioport_read_table[2][i] = default_ioport_readl;
299 ioport_write_table[0][i] = default_ioport_writeb;
300 ioport_write_table[1][i] = default_ioport_writew;
301 ioport_write_table[2][i] = default_ioport_writel;
302 }
303 }
305 /***********************************************************/
307 void pstrcpy(char *buf, int buf_size, const char *str)
308 {
309 int c;
310 char *q = buf;
312 if (buf_size <= 0)
313 return;
315 for(;;) {
316 c = *str++;
317 if (c == 0 || q >= buf + buf_size - 1)
318 break;
319 *q++ = c;
320 }
321 *q = '\0';
322 }
324 /* strcat and truncate. */
325 char *pstrcat(char *buf, int buf_size, const char *s)
326 {
327 int len;
328 len = strlen(buf);
329 if (len < buf_size)
330 pstrcpy(buf + len, buf_size - len, s);
331 return buf;
332 }
334 int strstart(const char *str, const char *val, const char **ptr)
335 {
336 const char *p, *q;
337 p = str;
338 q = val;
339 while (*q != '\0') {
340 if (*p != *q)
341 return 0;
342 p++;
343 q++;
344 }
345 if (ptr)
346 *ptr = p;
347 return 1;
348 }
350 void cpu_outb(CPUState *env, int addr, int val)
351 {
352 #ifdef DEBUG_IOPORT
353 if (loglevel & CPU_LOG_IOPORT)
354 fprintf(logfile, "outb: %04x %02x\n", addr, val);
355 #endif
356 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
357 #ifdef USE_KQEMU
358 if (env)
359 env->last_io_time = cpu_get_time_fast();
360 #endif
361 }
363 void cpu_outw(CPUState *env, int addr, int val)
364 {
365 #ifdef DEBUG_IOPORT
366 if (loglevel & CPU_LOG_IOPORT)
367 fprintf(logfile, "outw: %04x %04x\n", addr, val);
368 #endif
369 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
370 #ifdef USE_KQEMU
371 if (env)
372 env->last_io_time = cpu_get_time_fast();
373 #endif
374 }
376 void cpu_outl(CPUState *env, int addr, int val)
377 {
378 #ifdef DEBUG_IOPORT
379 if (loglevel & CPU_LOG_IOPORT)
380 fprintf(logfile, "outl: %04x %08x\n", addr, val);
381 #endif
382 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
383 #ifdef USE_KQEMU
384 if (env)
385 env->last_io_time = cpu_get_time_fast();
386 #endif
387 }
389 int cpu_inb(CPUState *env, int addr)
390 {
391 int val;
392 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "inb : %04x %02x\n", addr, val);
396 #endif
397 #ifdef USE_KQEMU
398 if (env)
399 env->last_io_time = cpu_get_time_fast();
400 #endif
401 return val;
402 }
404 int cpu_inw(CPUState *env, int addr)
405 {
406 int val;
407 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
408 #ifdef DEBUG_IOPORT
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "inw : %04x %04x\n", addr, val);
411 #endif
412 #ifdef USE_KQEMU
413 if (env)
414 env->last_io_time = cpu_get_time_fast();
415 #endif
416 return val;
417 }
419 int cpu_inl(CPUState *env, int addr)
420 {
421 int val;
422 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inl : %04x %08x\n", addr, val);
426 #endif
427 #ifdef USE_KQEMU
428 if (env)
429 env->last_io_time = cpu_get_time_fast();
430 #endif
431 return val;
432 }
434 /***********************************************************/
435 void hw_error(const char *fmt, ...)
436 {
437 va_list ap;
438 #ifndef CONFIG_DM
439 CPUState *env;
440 #endif /* !CONFIG_DM */
442 va_start(ap, fmt);
443 fprintf(stderr, "qemu: hardware error: ");
444 vfprintf(stderr, fmt, ap);
445 fprintf(stderr, "\n");
446 #ifndef CONFIG_DM
447 for(env = first_cpu; env != NULL; env = env->next_cpu) {
448 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
449 #ifdef TARGET_I386
450 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
451 #else
452 cpu_dump_state(env, stderr, fprintf, 0);
453 #endif
454 }
455 #endif /* !CONFIG_DM */
456 va_end(ap);
457 abort();
458 }
460 /***********************************************************/
461 /* keyboard/mouse */
463 static QEMUPutKBDEvent *qemu_put_kbd_event;
464 static void *qemu_put_kbd_event_opaque;
465 static QEMUPutMouseEvent *qemu_put_mouse_event;
466 static void *qemu_put_mouse_event_opaque;
467 static int qemu_put_mouse_event_absolute;
469 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
470 {
471 qemu_put_kbd_event_opaque = opaque;
472 qemu_put_kbd_event = func;
473 }
475 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
476 {
477 qemu_put_mouse_event_opaque = opaque;
478 qemu_put_mouse_event = func;
479 qemu_put_mouse_event_absolute = absolute;
480 }
482 void kbd_put_keycode(int keycode)
483 {
484 if (qemu_put_kbd_event) {
485 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
486 }
487 }
489 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
490 {
491 if (qemu_put_mouse_event) {
492 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
493 dx, dy, dz, buttons_state);
494 }
495 }
497 int kbd_mouse_is_absolute(void)
498 {
499 return qemu_put_mouse_event_absolute;
500 }
502 /***********************************************************/
503 /* timers */
505 #if defined(__powerpc__)
507 static inline uint32_t get_tbl(void)
508 {
509 uint32_t tbl;
510 asm volatile("mftb %0" : "=r" (tbl));
511 return tbl;
512 }
514 static inline uint32_t get_tbu(void)
515 {
516 uint32_t tbl;
517 asm volatile("mftbu %0" : "=r" (tbl));
518 return tbl;
519 }
521 int64_t cpu_get_real_ticks(void)
522 {
523 uint32_t l, h, h1;
524 /* NOTE: we test if wrapping has occurred */
525 do {
526 h = get_tbu();
527 l = get_tbl();
528 h1 = get_tbu();
529 } while (h != h1);
530 return ((int64_t)h << 32) | l;
531 }
533 #elif defined(__i386__)
535 int64_t cpu_get_real_ticks(void)
536 {
537 #ifdef _WIN32
538 LARGE_INTEGER ti;
539 QueryPerformanceCounter(&ti);
540 return ti.QuadPart;
541 #else
542 int64_t val;
543 asm volatile ("rdtsc" : "=A" (val));
544 return val;
545 #endif
546 }
548 #elif defined(__x86_64__)
550 int64_t cpu_get_real_ticks(void)
551 {
552 uint32_t low,high;
553 int64_t val;
554 asm volatile("rdtsc" : "=a" (low), "=d" (high));
555 val = high;
556 val <<= 32;
557 val |= low;
558 return val;
559 }
561 #elif defined(__ia64)
563 int64_t cpu_get_real_ticks(void)
564 {
565 int64_t val;
566 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
567 return val;
568 }
570 #elif defined(__s390__)
572 int64_t cpu_get_real_ticks(void)
573 {
574 int64_t val;
575 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
576 return val;
577 }
579 #else
580 #error unsupported CPU
581 #endif
583 static int64_t cpu_ticks_prev;
584 static int64_t cpu_ticks_offset;
585 static int cpu_ticks_enabled;
587 static inline int64_t cpu_get_ticks(void)
588 {
589 if (!cpu_ticks_enabled) {
590 return cpu_ticks_offset;
591 } else {
592 int64_t ticks;
593 ticks = cpu_get_real_ticks();
594 if (cpu_ticks_prev > ticks) {
595 /* Note: non increasing ticks may happen if the host uses
596 software suspend */
597 cpu_ticks_offset += cpu_ticks_prev - ticks;
598 }
599 cpu_ticks_prev = ticks;
600 return ticks + cpu_ticks_offset;
601 }
602 }
604 /* enable cpu_get_ticks() */
605 void cpu_enable_ticks(void)
606 {
607 if (!cpu_ticks_enabled) {
608 cpu_ticks_offset -= cpu_get_real_ticks();
609 cpu_ticks_enabled = 1;
610 }
611 }
613 /* disable cpu_get_ticks() : the clock is stopped. You must not call
614 cpu_get_ticks() after that. */
615 void cpu_disable_ticks(void)
616 {
617 if (cpu_ticks_enabled) {
618 cpu_ticks_offset = cpu_get_ticks();
619 cpu_ticks_enabled = 0;
620 }
621 }
623 #ifdef _WIN32
624 void cpu_calibrate_ticks(void)
625 {
626 LARGE_INTEGER freq;
627 int ret;
629 ret = QueryPerformanceFrequency(&freq);
630 if (ret == 0) {
631 fprintf(stderr, "Could not calibrate ticks\n");
632 exit(1);
633 }
634 ticks_per_sec = freq.QuadPart;
635 }
637 #else
638 static int64_t get_clock(void)
639 {
640 struct timeval tv;
641 gettimeofday(&tv, NULL);
642 return tv.tv_sec * 1000000LL + tv.tv_usec;
643 }
645 void cpu_calibrate_ticks(void)
646 {
647 int64_t usec, ticks;
649 usec = get_clock();
650 ticks = cpu_get_real_ticks();
651 usleep(50 * 1000);
652 usec = get_clock() - usec;
653 ticks = cpu_get_real_ticks() - ticks;
654 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
655 }
656 #endif /* !_WIN32 */
658 /* compute with 96 bit intermediate result: (a*b)/c */
659 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
660 {
661 union {
662 uint64_t ll;
663 struct {
664 #ifdef WORDS_BIGENDIAN
665 uint32_t high, low;
666 #else
667 uint32_t low, high;
668 #endif
669 } l;
670 } u, res;
671 uint64_t rl, rh;
673 u.ll = a;
674 rl = (uint64_t)u.l.low * (uint64_t)b;
675 rh = (uint64_t)u.l.high * (uint64_t)b;
676 rh += (rl >> 32);
677 res.l.high = rh / c;
678 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
679 return res.ll;
680 }
682 #define QEMU_TIMER_REALTIME 0
683 #define QEMU_TIMER_VIRTUAL 1
685 struct QEMUClock {
686 int type;
687 /* XXX: add frequency */
688 };
690 struct QEMUTimer {
691 QEMUClock *clock;
692 int64_t expire_time;
693 QEMUTimerCB *cb;
694 void *opaque;
695 struct QEMUTimer *next;
696 };
698 QEMUClock *rt_clock;
699 QEMUClock *vm_clock;
701 static QEMUTimer *active_timers[2];
702 #ifdef _WIN32
703 static MMRESULT timerID;
704 static HANDLE host_alarm = NULL;
705 static unsigned int period = 1;
706 #else
707 /* frequency of the times() clock tick */
708 static int timer_freq;
709 #endif
711 QEMUClock *qemu_new_clock(int type)
712 {
713 QEMUClock *clock;
714 clock = qemu_mallocz(sizeof(QEMUClock));
715 if (!clock)
716 return NULL;
717 clock->type = type;
718 return clock;
719 }
721 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
722 {
723 QEMUTimer *ts;
725 ts = qemu_mallocz(sizeof(QEMUTimer));
726 ts->clock = clock;
727 ts->cb = cb;
728 ts->opaque = opaque;
729 return ts;
730 }
732 void qemu_free_timer(QEMUTimer *ts)
733 {
734 qemu_free(ts);
735 }
737 /* stop a timer, but do not dealloc it */
738 void qemu_del_timer(QEMUTimer *ts)
739 {
740 QEMUTimer **pt, *t;
742 /* NOTE: this code must be signal safe because
743 qemu_timer_expired() can be called from a signal. */
744 pt = &active_timers[ts->clock->type];
745 for(;;) {
746 t = *pt;
747 if (!t)
748 break;
749 if (t == ts) {
750 *pt = t->next;
751 break;
752 }
753 pt = &t->next;
754 }
755 }
757 /* modify the current timer so that it will be fired when current_time
758 >= expire_time. The corresponding callback will be called. */
759 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
760 {
761 QEMUTimer **pt, *t;
763 qemu_del_timer(ts);
765 /* add the timer in the sorted list */
766 /* NOTE: this code must be signal safe because
767 qemu_timer_expired() can be called from a signal. */
768 pt = &active_timers[ts->clock->type];
769 for(;;) {
770 t = *pt;
771 if (!t)
772 break;
773 if (t->expire_time > expire_time)
774 break;
775 pt = &t->next;
776 }
777 ts->expire_time = expire_time;
778 ts->next = *pt;
779 *pt = ts;
780 }
782 int qemu_timer_pending(QEMUTimer *ts)
783 {
784 QEMUTimer *t;
785 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
786 if (t == ts)
787 return 1;
788 }
789 return 0;
790 }
792 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
793 {
794 if (!timer_head)
795 return 0;
796 return (timer_head->expire_time <= current_time);
797 }
799 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
800 {
801 QEMUTimer *ts;
803 for(;;) {
804 ts = *ptimer_head;
805 if (!ts || ts->expire_time > current_time)
806 break;
807 /* remove timer from the list before calling the callback */
808 *ptimer_head = ts->next;
809 ts->next = NULL;
811 /* run the callback (the timer list can be modified) */
812 ts->cb(ts->opaque);
813 }
814 }
816 int64_t qemu_get_clock(QEMUClock *clock)
817 {
818 switch(clock->type) {
819 case QEMU_TIMER_REALTIME:
820 #ifdef _WIN32
821 return GetTickCount();
822 #else
823 {
824 struct tms tp;
826 /* Note that using gettimeofday() is not a good solution
827 for timers because its value change when the date is
828 modified. */
829 if (timer_freq == 100) {
830 return times(&tp) * 10;
831 } else {
832 return ((int64_t)times(&tp) * 1000) / timer_freq;
833 }
834 }
835 #endif
836 default:
837 case QEMU_TIMER_VIRTUAL:
838 return cpu_get_ticks();
839 }
840 }
842 /* save a timer */
843 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
844 {
845 uint64_t expire_time;
847 if (qemu_timer_pending(ts)) {
848 expire_time = ts->expire_time;
849 } else {
850 expire_time = -1;
851 }
852 qemu_put_be64(f, expire_time);
853 }
855 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
856 {
857 uint64_t expire_time;
859 expire_time = qemu_get_be64(f);
860 if (expire_time != -1) {
861 qemu_mod_timer(ts, expire_time);
862 } else {
863 qemu_del_timer(ts);
864 }
865 }
867 #ifdef CONFIG_DM
868 static void timer_save(QEMUFile *f, void *opaque)
869 {
870 }
872 static int timer_load(QEMUFile *f, void *opaque, int version_id)
873 {
874 return 0;
875 }
876 #else /* !CONFIG_DM */
877 static void timer_save(QEMUFile *f, void *opaque)
878 {
879 if (cpu_ticks_enabled) {
880 hw_error("cannot save state if virtual timers are running");
881 }
882 qemu_put_be64s(f, &cpu_ticks_offset);
883 qemu_put_be64s(f, &ticks_per_sec);
884 }
886 static int timer_load(QEMUFile *f, void *opaque, int version_id)
887 {
888 if (version_id != 1)
889 return -EINVAL;
890 if (cpu_ticks_enabled) {
891 return -EINVAL;
892 }
893 qemu_get_be64s(f, &cpu_ticks_offset);
894 qemu_get_be64s(f, &ticks_per_sec);
895 return 0;
896 }
898 #ifdef _WIN32
899 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
900 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
901 #else
902 static void host_alarm_handler(int host_signum)
903 #endif
904 {
905 #if 0
906 #define DISP_FREQ 1000
907 {
908 static int64_t delta_min = INT64_MAX;
909 static int64_t delta_max, delta_cum, last_clock, delta, ti;
910 static int count;
911 ti = qemu_get_clock(vm_clock);
912 if (last_clock != 0) {
913 delta = ti - last_clock;
914 if (delta < delta_min)
915 delta_min = delta;
916 if (delta > delta_max)
917 delta_max = delta;
918 delta_cum += delta;
919 if (++count == DISP_FREQ) {
920 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
921 muldiv64(delta_min, 1000000, ticks_per_sec),
922 muldiv64(delta_max, 1000000, ticks_per_sec),
923 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
924 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
925 count = 0;
926 delta_min = INT64_MAX;
927 delta_max = 0;
928 delta_cum = 0;
929 }
930 }
931 last_clock = ti;
932 }
933 #endif
934 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
935 qemu_get_clock(vm_clock)) ||
936 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
937 qemu_get_clock(rt_clock))) {
938 #ifdef _WIN32
939 SetEvent(host_alarm);
940 #endif
941 CPUState *env = cpu_single_env;
942 if (env) {
943 /* stop the currently executing cpu because a timer occured */
944 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
945 #ifdef USE_KQEMU
946 if (env->kqemu_enabled) {
947 kqemu_cpu_interrupt(env);
948 }
949 #endif
950 }
951 }
952 }
954 #ifndef _WIN32
956 #if defined(__linux__)
958 #define RTC_FREQ 1024
960 static int rtc_fd;
962 static int start_rtc_timer(void)
963 {
964 rtc_fd = open("/dev/rtc", O_RDONLY);
965 if (rtc_fd < 0)
966 return -1;
967 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
968 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
969 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
970 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
971 goto fail;
972 }
973 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
974 fail:
975 close(rtc_fd);
976 return -1;
977 }
978 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
979 return 0;
980 }
982 #else
984 static int start_rtc_timer(void)
985 {
986 return -1;
987 }
989 #endif /* !defined(__linux__) */
991 #endif /* !defined(_WIN32) */
993 #endif /* !CONFIG_DM */
995 static void init_timers(void)
996 {
997 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
998 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1000 #ifdef _WIN32
1002 int count=0;
1003 TIMECAPS tc;
1005 ZeroMemory(&tc, sizeof(TIMECAPS));
1006 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1007 if (period < tc.wPeriodMin)
1008 period = tc.wPeriodMin;
1009 timeBeginPeriod(period);
1010 timerID = timeSetEvent(1, // interval (ms)
1011 period, // resolution
1012 host_alarm_handler, // function
1013 (DWORD)&count, // user parameter
1014 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1015 if( !timerID ) {
1016 perror("failed timer alarm");
1017 exit(1);
1019 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1020 if (!host_alarm) {
1021 perror("failed CreateEvent");
1022 exit(1);
1024 ResetEvent(host_alarm);
1026 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1027 #else
1029 #ifndef CONFIG_DM
1030 struct sigaction act;
1031 struct itimerval itv;
1032 #endif
1034 /* get times() syscall frequency */
1035 timer_freq = sysconf(_SC_CLK_TCK);
1037 #ifndef CONFIG_DM
1038 /* timer signal */
1039 sigfillset(&act.sa_mask);
1040 act.sa_flags = 0;
1041 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1042 act.sa_flags |= SA_ONSTACK;
1043 #endif
1044 act.sa_handler = host_alarm_handler;
1045 sigaction(SIGALRM, &act, NULL);
1047 itv.it_interval.tv_sec = 0;
1048 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1049 itv.it_value.tv_sec = 0;
1050 itv.it_value.tv_usec = 10 * 1000;
1051 setitimer(ITIMER_REAL, &itv, NULL);
1052 /* we probe the tick duration of the kernel to inform the user if
1053 the emulated kernel requested a too high timer frequency */
1054 getitimer(ITIMER_REAL, &itv);
1056 #if defined(__linux__)
1057 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1058 have timers with 1 ms resolution. The correct solution will
1059 be to use the POSIX real time timers available in recent
1060 2.6 kernels */
1061 if (itv.it_interval.tv_usec > 1000 || 1) {
1062 /* try to use /dev/rtc to have a faster timer */
1063 if (start_rtc_timer() < 0)
1064 goto use_itimer;
1065 /* disable itimer */
1066 itv.it_interval.tv_sec = 0;
1067 itv.it_interval.tv_usec = 0;
1068 itv.it_value.tv_sec = 0;
1069 itv.it_value.tv_usec = 0;
1070 setitimer(ITIMER_REAL, &itv, NULL);
1072 /* use the RTC */
1073 sigaction(SIGIO, &act, NULL);
1074 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1075 fcntl(rtc_fd, F_SETOWN, getpid());
1076 } else
1077 #endif /* defined(__linux__) */
1079 use_itimer:
1080 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1081 PIT_FREQ) / 1000000;
1083 #endif /* CONFIG_DM */
1085 #endif
1088 void quit_timers(void)
1090 #ifdef _WIN32
1091 timeKillEvent(timerID);
1092 timeEndPeriod(period);
1093 if (host_alarm) {
1094 CloseHandle(host_alarm);
1095 host_alarm = NULL;
1097 #endif
1100 /***********************************************************/
1101 /* character device */
1103 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1105 return s->chr_write(s, buf, len);
1108 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1110 if (!s->chr_ioctl)
1111 return -ENOTSUP;
1112 return s->chr_ioctl(s, cmd, arg);
1115 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1117 char buf[4096];
1118 va_list ap;
1119 va_start(ap, fmt);
1120 vsnprintf(buf, sizeof(buf), fmt, ap);
1121 qemu_chr_write(s, buf, strlen(buf));
1122 va_end(ap);
1125 void qemu_chr_send_event(CharDriverState *s, int event)
1127 if (s->chr_send_event)
1128 s->chr_send_event(s, event);
1131 void qemu_chr_add_read_handler(CharDriverState *s,
1132 IOCanRWHandler *fd_can_read,
1133 IOReadHandler *fd_read, void *opaque)
1135 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1138 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1140 s->chr_event = chr_event;
1143 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1145 return len;
1148 static void null_chr_add_read_handler(CharDriverState *chr,
1149 IOCanRWHandler *fd_can_read,
1150 IOReadHandler *fd_read, void *opaque)
1154 CharDriverState *qemu_chr_open_null(void)
1156 CharDriverState *chr;
1158 chr = qemu_mallocz(sizeof(CharDriverState));
1159 if (!chr)
1160 return NULL;
1161 chr->chr_write = null_chr_write;
1162 chr->chr_add_read_handler = null_chr_add_read_handler;
1163 return chr;
1166 #ifdef _WIN32
1168 static void socket_cleanup(void)
1170 WSACleanup();
1173 static int socket_init(void)
1175 WSADATA Data;
1176 int ret, err;
1178 ret = WSAStartup(MAKEWORD(2,2), &Data);
1179 if (ret != 0) {
1180 err = WSAGetLastError();
1181 fprintf(stderr, "WSAStartup: %d\n", err);
1182 return -1;
1184 atexit(socket_cleanup);
1185 return 0;
1188 static int send_all(int fd, const uint8_t *buf, int len1)
1190 int ret, len;
1192 len = len1;
1193 while (len > 0) {
1194 ret = send(fd, buf, len, 0);
1195 if (ret < 0) {
1196 int errno;
1197 errno = WSAGetLastError();
1198 if (errno != WSAEWOULDBLOCK) {
1199 return -1;
1201 } else if (ret == 0) {
1202 break;
1203 } else {
1204 buf += ret;
1205 len -= ret;
1208 return len1 - len;
1211 void socket_set_nonblock(int fd)
1213 unsigned long opt = 1;
1214 ioctlsocket(fd, FIONBIO, &opt);
1217 #else
1219 static int unix_write(int fd, const uint8_t *buf, int len1)
1221 int ret, sel_ret, len;
1222 int max_fd;
1223 fd_set writefds;
1224 struct timeval timeout;
1226 max_fd = fd;
1228 len = len1;
1229 while (len > 0) {
1230 FD_ZERO(&writefds);
1231 FD_SET(fd, &writefds);
1232 timeout.tv_sec = 0;
1233 timeout.tv_usec = 0;
1234 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1235 if (sel_ret <= 0) {
1236 /* Timeout or select error */
1237 return -1;
1238 } else {
1239 ret = write(fd, buf, len);
1240 if (ret < 0) {
1241 if (errno != EINTR && errno != EAGAIN)
1242 return -1;
1243 } else if (ret == 0) {
1244 break;
1245 } else {
1246 buf += ret;
1247 len -= ret;
1251 return len1 - len;
1254 static inline int send_all(int fd, const uint8_t *buf, int len1)
1256 return unix_write(fd, buf, len1);
1259 void socket_set_nonblock(int fd)
1261 fcntl(fd, F_SETFL, O_NONBLOCK);
1263 #endif /* !_WIN32 */
1265 #ifndef _WIN32
1267 typedef struct {
1268 int fd_in, fd_out;
1269 IOCanRWHandler *fd_can_read;
1270 IOReadHandler *fd_read;
1271 void *fd_opaque;
1272 int max_size;
1273 } FDCharDriver;
1275 #define STDIO_MAX_CLIENTS 2
1277 static int stdio_nb_clients;
1278 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1280 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1282 FDCharDriver *s = chr->opaque;
1283 return unix_write(s->fd_out, buf, len);
1286 static int fd_chr_read_poll(void *opaque)
1288 CharDriverState *chr = opaque;
1289 FDCharDriver *s = chr->opaque;
1291 s->max_size = s->fd_can_read(s->fd_opaque);
1292 return s->max_size;
1295 static void fd_chr_read(void *opaque)
1297 CharDriverState *chr = opaque;
1298 FDCharDriver *s = chr->opaque;
1299 int size, len;
1300 uint8_t buf[1024];
1302 len = sizeof(buf);
1303 if (len > s->max_size)
1304 len = s->max_size;
1305 if (len == 0)
1306 return;
1307 size = read(s->fd_in, buf, len);
1308 if (size > 0) {
1309 s->fd_read(s->fd_opaque, buf, size);
1313 static void fd_chr_add_read_handler(CharDriverState *chr,
1314 IOCanRWHandler *fd_can_read,
1315 IOReadHandler *fd_read, void *opaque)
1317 FDCharDriver *s = chr->opaque;
1319 if (s->fd_in >= 0) {
1320 s->fd_can_read = fd_can_read;
1321 s->fd_read = fd_read;
1322 s->fd_opaque = opaque;
1323 if (nographic && s->fd_in == 0) {
1324 } else {
1325 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1326 fd_chr_read, NULL, chr);
1331 /* open a character device to a unix fd */
1332 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1334 CharDriverState *chr;
1335 FDCharDriver *s;
1337 chr = qemu_mallocz(sizeof(CharDriverState));
1338 if (!chr)
1339 return NULL;
1340 s = qemu_mallocz(sizeof(FDCharDriver));
1341 if (!s) {
1342 free(chr);
1343 return NULL;
1345 s->fd_in = fd_in;
1346 s->fd_out = fd_out;
1347 chr->opaque = s;
1348 chr->chr_write = fd_chr_write;
1349 chr->chr_add_read_handler = fd_chr_add_read_handler;
1350 return chr;
1353 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1355 int fd_out;
1357 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1358 if (fd_out < 0)
1359 return NULL;
1360 return qemu_chr_open_fd(-1, fd_out);
1363 CharDriverState *qemu_chr_open_pipe(const char *filename)
1365 int fd;
1367 fd = open(filename, O_RDWR | O_BINARY);
1368 if (fd < 0)
1369 return NULL;
1370 return qemu_chr_open_fd(fd, fd);
1374 /* for STDIO, we handle the case where several clients use it
1375 (nographic mode) */
1377 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1379 #define TERM_FIFO_MAX_SIZE 1
1381 static int term_got_escape, client_index;
1382 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1383 int term_fifo_size;
1385 void term_print_help(void)
1387 printf("\n"
1388 "C-a h print this help\n"
1389 "C-a x exit emulator\n"
1390 "C-a s save disk data back to file (if -snapshot)\n"
1391 "C-a b send break (magic sysrq)\n"
1392 "C-a c switch between console and monitor\n"
1393 "C-a C-a send C-a\n"
1394 );
1397 /* called when a char is received */
1398 static void stdio_received_byte(int ch)
1400 if (term_got_escape) {
1401 term_got_escape = 0;
1402 switch(ch) {
1403 case 'h':
1404 term_print_help();
1405 break;
1406 case 'x':
1407 exit(0);
1408 break;
1409 case 's':
1411 int i;
1412 for (i = 0; i < MAX_DISKS; i++) {
1413 if (bs_table[i])
1414 bdrv_commit(bs_table[i]);
1417 break;
1418 case 'b':
1419 if (client_index < stdio_nb_clients) {
1420 CharDriverState *chr;
1421 FDCharDriver *s;
1423 chr = stdio_clients[client_index];
1424 s = chr->opaque;
1425 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1427 break;
1428 case 'c':
1429 client_index++;
1430 if (client_index >= stdio_nb_clients)
1431 client_index = 0;
1432 if (client_index == 0) {
1433 /* send a new line in the monitor to get the prompt */
1434 ch = '\r';
1435 goto send_char;
1437 break;
1438 case TERM_ESCAPE:
1439 goto send_char;
1441 } else if (ch == TERM_ESCAPE) {
1442 term_got_escape = 1;
1443 } else {
1444 send_char:
1445 if (client_index < stdio_nb_clients) {
1446 uint8_t buf[1];
1447 CharDriverState *chr;
1448 FDCharDriver *s;
1450 chr = stdio_clients[client_index];
1451 s = chr->opaque;
1452 if (s->fd_can_read(s->fd_opaque) > 0) {
1453 buf[0] = ch;
1454 s->fd_read(s->fd_opaque, buf, 1);
1455 } else if (term_fifo_size == 0) {
1456 term_fifo[term_fifo_size++] = ch;
1462 static int stdio_read_poll(void *opaque)
1464 CharDriverState *chr;
1465 FDCharDriver *s;
1467 if (client_index < stdio_nb_clients) {
1468 chr = stdio_clients[client_index];
1469 s = chr->opaque;
1470 /* try to flush the queue if needed */
1471 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1472 s->fd_read(s->fd_opaque, term_fifo, 1);
1473 term_fifo_size = 0;
1475 /* see if we can absorb more chars */
1476 if (term_fifo_size == 0)
1477 return 1;
1478 else
1479 return 0;
1480 } else {
1481 return 1;
1485 static void stdio_read(void *opaque)
1487 int size;
1488 uint8_t buf[1];
1490 size = read(0, buf, 1);
1491 if (size > 0)
1492 stdio_received_byte(buf[0]);
1495 /* init terminal so that we can grab keys */
1496 static struct termios oldtty;
1497 static int old_fd0_flags;
1499 static void term_exit(void)
1501 tcsetattr (0, TCSANOW, &oldtty);
1502 fcntl(0, F_SETFL, old_fd0_flags);
1505 static void term_init(void)
1507 struct termios tty;
1509 tcgetattr (0, &tty);
1510 oldtty = tty;
1511 old_fd0_flags = fcntl(0, F_GETFL);
1513 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1514 |INLCR|IGNCR|ICRNL|IXON);
1515 tty.c_oflag |= OPOST;
1516 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1517 /* if graphical mode, we allow Ctrl-C handling */
1518 if (nographic)
1519 tty.c_lflag &= ~ISIG;
1520 tty.c_cflag &= ~(CSIZE|PARENB);
1521 tty.c_cflag |= CS8;
1522 tty.c_cc[VMIN] = 1;
1523 tty.c_cc[VTIME] = 0;
1525 tcsetattr (0, TCSANOW, &tty);
1527 atexit(term_exit);
1529 fcntl(0, F_SETFL, O_NONBLOCK);
1532 CharDriverState *qemu_chr_open_stdio(void)
1534 CharDriverState *chr;
1536 if (nographic) {
1537 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1538 return NULL;
1539 chr = qemu_chr_open_fd(0, 1);
1540 if (stdio_nb_clients == 0)
1541 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1542 client_index = stdio_nb_clients;
1543 } else {
1544 if (stdio_nb_clients != 0)
1545 return NULL;
1546 chr = qemu_chr_open_fd(0, 1);
1548 stdio_clients[stdio_nb_clients++] = chr;
1549 if (stdio_nb_clients == 1) {
1550 /* set the terminal in raw mode */
1551 term_init();
1553 return chr;
1556 int store_console_dev(int domid, char *pts)
1558 int xc_handle;
1559 struct xs_handle *xs;
1560 char *path;
1562 xs = xs_daemon_open();
1563 if (xs == NULL) {
1564 fprintf(logfile, "Could not contact XenStore\n");
1565 return -1;
1568 xc_handle = xc_interface_open();
1569 if (xc_handle == -1) {
1570 fprintf(logfile, "xc_interface_open() error\n");
1571 return -1;
1574 path = xs_get_domain_path(xs, domid);
1575 if (path == NULL) {
1576 fprintf(logfile, "xs_get_domain_path() error\n");
1577 return -1;
1579 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1580 if (path == NULL) {
1581 fprintf(logfile, "realloc error\n");
1582 return -1;
1584 strcat(path, "/console/tty");
1585 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1586 fprintf(logfile, "xs_write for console fail");
1587 return -1;
1590 free(path);
1591 xs_daemon_close(xs);
1592 close(xc_handle);
1594 return 0;
1597 #if defined(__linux__)
1598 CharDriverState *qemu_chr_open_pty(void)
1600 struct termios tty;
1601 int master_fd, slave_fd;
1603 /* Not satisfying */
1604 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1605 return NULL;
1608 /* Set raw attributes on the pty. */
1609 cfmakeraw(&tty);
1610 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1612 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1613 store_console_dev(domid, ptsname(master_fd));
1615 return qemu_chr_open_fd(master_fd, master_fd);
1618 static void tty_serial_init(int fd, int speed,
1619 int parity, int data_bits, int stop_bits)
1621 struct termios tty;
1622 speed_t spd;
1624 #if 0
1625 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1626 speed, parity, data_bits, stop_bits);
1627 #endif
1628 tcgetattr (fd, &tty);
1630 switch(speed) {
1631 case 50:
1632 spd = B50;
1633 break;
1634 case 75:
1635 spd = B75;
1636 break;
1637 case 300:
1638 spd = B300;
1639 break;
1640 case 600:
1641 spd = B600;
1642 break;
1643 case 1200:
1644 spd = B1200;
1645 break;
1646 case 2400:
1647 spd = B2400;
1648 break;
1649 case 4800:
1650 spd = B4800;
1651 break;
1652 case 9600:
1653 spd = B9600;
1654 break;
1655 case 19200:
1656 spd = B19200;
1657 break;
1658 case 38400:
1659 spd = B38400;
1660 break;
1661 case 57600:
1662 spd = B57600;
1663 break;
1664 default:
1665 case 115200:
1666 spd = B115200;
1667 break;
1670 cfsetispeed(&tty, spd);
1671 cfsetospeed(&tty, spd);
1673 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1674 |INLCR|IGNCR|ICRNL|IXON);
1675 tty.c_oflag |= OPOST;
1676 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1677 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1678 switch(data_bits) {
1679 default:
1680 case 8:
1681 tty.c_cflag |= CS8;
1682 break;
1683 case 7:
1684 tty.c_cflag |= CS7;
1685 break;
1686 case 6:
1687 tty.c_cflag |= CS6;
1688 break;
1689 case 5:
1690 tty.c_cflag |= CS5;
1691 break;
1693 switch(parity) {
1694 default:
1695 case 'N':
1696 break;
1697 case 'E':
1698 tty.c_cflag |= PARENB;
1699 break;
1700 case 'O':
1701 tty.c_cflag |= PARENB | PARODD;
1702 break;
1705 tcsetattr (fd, TCSANOW, &tty);
1708 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1710 FDCharDriver *s = chr->opaque;
1712 switch(cmd) {
1713 case CHR_IOCTL_SERIAL_SET_PARAMS:
1715 QEMUSerialSetParams *ssp = arg;
1716 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1717 ssp->data_bits, ssp->stop_bits);
1719 break;
1720 case CHR_IOCTL_SERIAL_SET_BREAK:
1722 int enable = *(int *)arg;
1723 if (enable)
1724 tcsendbreak(s->fd_in, 1);
1726 break;
1727 default:
1728 return -ENOTSUP;
1730 return 0;
1733 CharDriverState *qemu_chr_open_tty(const char *filename)
1735 CharDriverState *chr;
1736 int fd;
1738 fd = open(filename, O_RDWR | O_NONBLOCK);
1739 if (fd < 0)
1740 return NULL;
1741 fcntl(fd, F_SETFL, O_NONBLOCK);
1742 tty_serial_init(fd, 115200, 'N', 8, 1);
1743 chr = qemu_chr_open_fd(fd, fd);
1744 if (!chr)
1745 return NULL;
1746 chr->chr_ioctl = tty_serial_ioctl;
1747 return chr;
1750 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1752 int fd = (int)chr->opaque;
1753 uint8_t b;
1755 switch(cmd) {
1756 case CHR_IOCTL_PP_READ_DATA:
1757 if (ioctl(fd, PPRDATA, &b) < 0)
1758 return -ENOTSUP;
1759 *(uint8_t *)arg = b;
1760 break;
1761 case CHR_IOCTL_PP_WRITE_DATA:
1762 b = *(uint8_t *)arg;
1763 if (ioctl(fd, PPWDATA, &b) < 0)
1764 return -ENOTSUP;
1765 break;
1766 case CHR_IOCTL_PP_READ_CONTROL:
1767 if (ioctl(fd, PPRCONTROL, &b) < 0)
1768 return -ENOTSUP;
1769 *(uint8_t *)arg = b;
1770 break;
1771 case CHR_IOCTL_PP_WRITE_CONTROL:
1772 b = *(uint8_t *)arg;
1773 if (ioctl(fd, PPWCONTROL, &b) < 0)
1774 return -ENOTSUP;
1775 break;
1776 case CHR_IOCTL_PP_READ_STATUS:
1777 if (ioctl(fd, PPRSTATUS, &b) < 0)
1778 return -ENOTSUP;
1779 *(uint8_t *)arg = b;
1780 break;
1781 default:
1782 return -ENOTSUP;
1784 return 0;
1787 CharDriverState *qemu_chr_open_pp(const char *filename)
1789 CharDriverState *chr;
1790 int fd;
1792 fd = open(filename, O_RDWR);
1793 if (fd < 0)
1794 return NULL;
1796 if (ioctl(fd, PPCLAIM) < 0) {
1797 close(fd);
1798 return NULL;
1801 chr = qemu_mallocz(sizeof(CharDriverState));
1802 if (!chr) {
1803 close(fd);
1804 return NULL;
1806 chr->opaque = (void *)fd;
1807 chr->chr_write = null_chr_write;
1808 chr->chr_add_read_handler = null_chr_add_read_handler;
1809 chr->chr_ioctl = pp_ioctl;
1810 return chr;
1813 #else
1814 CharDriverState *qemu_chr_open_pty(void)
1816 return NULL;
1818 #endif
1820 #endif /* !defined(_WIN32) */
1822 #ifdef _WIN32
1823 typedef struct {
1824 IOCanRWHandler *fd_can_read;
1825 IOReadHandler *fd_read;
1826 void *win_opaque;
1827 int max_size;
1828 HANDLE hcom, hrecv, hsend;
1829 OVERLAPPED orecv, osend;
1830 BOOL fpipe;
1831 DWORD len;
1832 } WinCharState;
1834 #define NSENDBUF 2048
1835 #define NRECVBUF 2048
1836 #define MAXCONNECT 1
1837 #define NTIMEOUT 5000
1839 static int win_chr_poll(void *opaque);
1840 static int win_chr_pipe_poll(void *opaque);
1842 static void win_chr_close2(WinCharState *s)
1844 if (s->hsend) {
1845 CloseHandle(s->hsend);
1846 s->hsend = NULL;
1848 if (s->hrecv) {
1849 CloseHandle(s->hrecv);
1850 s->hrecv = NULL;
1852 if (s->hcom) {
1853 CloseHandle(s->hcom);
1854 s->hcom = NULL;
1856 if (s->fpipe)
1857 qemu_del_polling_cb(win_chr_pipe_poll, s);
1858 else
1859 qemu_del_polling_cb(win_chr_poll, s);
1862 static void win_chr_close(CharDriverState *chr)
1864 WinCharState *s = chr->opaque;
1865 win_chr_close2(s);
1868 static int win_chr_init(WinCharState *s, const char *filename)
1870 COMMCONFIG comcfg;
1871 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1872 COMSTAT comstat;
1873 DWORD size;
1874 DWORD err;
1876 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1877 if (!s->hsend) {
1878 fprintf(stderr, "Failed CreateEvent\n");
1879 goto fail;
1881 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1882 if (!s->hrecv) {
1883 fprintf(stderr, "Failed CreateEvent\n");
1884 goto fail;
1887 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1888 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1889 if (s->hcom == INVALID_HANDLE_VALUE) {
1890 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1891 s->hcom = NULL;
1892 goto fail;
1895 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1896 fprintf(stderr, "Failed SetupComm\n");
1897 goto fail;
1900 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1901 size = sizeof(COMMCONFIG);
1902 GetDefaultCommConfig(filename, &comcfg, &size);
1903 comcfg.dcb.DCBlength = sizeof(DCB);
1904 CommConfigDialog(filename, NULL, &comcfg);
1906 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1907 fprintf(stderr, "Failed SetCommState\n");
1908 goto fail;
1911 if (!SetCommMask(s->hcom, EV_ERR)) {
1912 fprintf(stderr, "Failed SetCommMask\n");
1913 goto fail;
1916 cto.ReadIntervalTimeout = MAXDWORD;
1917 if (!SetCommTimeouts(s->hcom, &cto)) {
1918 fprintf(stderr, "Failed SetCommTimeouts\n");
1919 goto fail;
1922 if (!ClearCommError(s->hcom, &err, &comstat)) {
1923 fprintf(stderr, "Failed ClearCommError\n");
1924 goto fail;
1926 qemu_add_polling_cb(win_chr_poll, s);
1927 return 0;
1929 fail:
1930 win_chr_close2(s);
1931 return -1;
1934 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1936 WinCharState *s = chr->opaque;
1937 DWORD len, ret, size, err;
1939 len = len1;
1940 ZeroMemory(&s->osend, sizeof(s->osend));
1941 s->osend.hEvent = s->hsend;
1942 while (len > 0) {
1943 if (s->hsend)
1944 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1945 else
1946 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1947 if (!ret) {
1948 err = GetLastError();
1949 if (err == ERROR_IO_PENDING) {
1950 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1951 if (ret) {
1952 buf += size;
1953 len -= size;
1954 } else {
1955 break;
1957 } else {
1958 break;
1960 } else {
1961 buf += size;
1962 len -= size;
1965 return len1 - len;
1968 static int win_chr_read_poll(WinCharState *s)
1970 s->max_size = s->fd_can_read(s->win_opaque);
1971 return s->max_size;
1974 static void win_chr_readfile(WinCharState *s)
1976 int ret, err;
1977 uint8_t buf[1024];
1978 DWORD size;
1980 ZeroMemory(&s->orecv, sizeof(s->orecv));
1981 s->orecv.hEvent = s->hrecv;
1982 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1983 if (!ret) {
1984 err = GetLastError();
1985 if (err == ERROR_IO_PENDING) {
1986 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1990 if (size > 0) {
1991 s->fd_read(s->win_opaque, buf, size);
1995 static void win_chr_read(WinCharState *s)
1997 if (s->len > s->max_size)
1998 s->len = s->max_size;
1999 if (s->len == 0)
2000 return;
2002 win_chr_readfile(s);
2005 static int win_chr_poll(void *opaque)
2007 WinCharState *s = opaque;
2008 COMSTAT status;
2009 DWORD comerr;
2011 ClearCommError(s->hcom, &comerr, &status);
2012 if (status.cbInQue > 0) {
2013 s->len = status.cbInQue;
2014 win_chr_read_poll(s);
2015 win_chr_read(s);
2016 return 1;
2018 return 0;
2021 static void win_chr_add_read_handler(CharDriverState *chr,
2022 IOCanRWHandler *fd_can_read,
2023 IOReadHandler *fd_read, void *opaque)
2025 WinCharState *s = chr->opaque;
2027 s->fd_can_read = fd_can_read;
2028 s->fd_read = fd_read;
2029 s->win_opaque = opaque;
2032 CharDriverState *qemu_chr_open_win(const char *filename)
2034 CharDriverState *chr;
2035 WinCharState *s;
2037 chr = qemu_mallocz(sizeof(CharDriverState));
2038 if (!chr)
2039 return NULL;
2040 s = qemu_mallocz(sizeof(WinCharState));
2041 if (!s) {
2042 free(chr);
2043 return NULL;
2045 chr->opaque = s;
2046 chr->chr_write = win_chr_write;
2047 chr->chr_add_read_handler = win_chr_add_read_handler;
2048 chr->chr_close = win_chr_close;
2050 if (win_chr_init(s, filename) < 0) {
2051 free(s);
2052 free(chr);
2053 return NULL;
2055 return chr;
2058 static int win_chr_pipe_poll(void *opaque)
2060 WinCharState *s = opaque;
2061 DWORD size;
2063 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2064 if (size > 0) {
2065 s->len = size;
2066 win_chr_read_poll(s);
2067 win_chr_read(s);
2068 return 1;
2070 return 0;
2073 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2075 OVERLAPPED ov;
2076 int ret;
2077 DWORD size;
2078 char openname[256];
2080 s->fpipe = TRUE;
2082 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2083 if (!s->hsend) {
2084 fprintf(stderr, "Failed CreateEvent\n");
2085 goto fail;
2087 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2088 if (!s->hrecv) {
2089 fprintf(stderr, "Failed CreateEvent\n");
2090 goto fail;
2093 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2094 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2095 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2096 PIPE_WAIT,
2097 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2098 if (s->hcom == INVALID_HANDLE_VALUE) {
2099 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2100 s->hcom = NULL;
2101 goto fail;
2104 ZeroMemory(&ov, sizeof(ov));
2105 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2106 ret = ConnectNamedPipe(s->hcom, &ov);
2107 if (ret) {
2108 fprintf(stderr, "Failed ConnectNamedPipe\n");
2109 goto fail;
2112 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2113 if (!ret) {
2114 fprintf(stderr, "Failed GetOverlappedResult\n");
2115 if (ov.hEvent) {
2116 CloseHandle(ov.hEvent);
2117 ov.hEvent = NULL;
2119 goto fail;
2122 if (ov.hEvent) {
2123 CloseHandle(ov.hEvent);
2124 ov.hEvent = NULL;
2126 qemu_add_polling_cb(win_chr_pipe_poll, s);
2127 return 0;
2129 fail:
2130 win_chr_close2(s);
2131 return -1;
2135 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2137 CharDriverState *chr;
2138 WinCharState *s;
2140 chr = qemu_mallocz(sizeof(CharDriverState));
2141 if (!chr)
2142 return NULL;
2143 s = qemu_mallocz(sizeof(WinCharState));
2144 if (!s) {
2145 free(chr);
2146 return NULL;
2148 chr->opaque = s;
2149 chr->chr_write = win_chr_write;
2150 chr->chr_add_read_handler = win_chr_add_read_handler;
2151 chr->chr_close = win_chr_close;
2153 if (win_chr_pipe_init(s, filename) < 0) {
2154 free(s);
2155 free(chr);
2156 return NULL;
2158 return chr;
2161 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2163 CharDriverState *chr;
2164 WinCharState *s;
2166 chr = qemu_mallocz(sizeof(CharDriverState));
2167 if (!chr)
2168 return NULL;
2169 s = qemu_mallocz(sizeof(WinCharState));
2170 if (!s) {
2171 free(chr);
2172 return NULL;
2174 s->hcom = fd_out;
2175 chr->opaque = s;
2176 chr->chr_write = win_chr_write;
2177 chr->chr_add_read_handler = win_chr_add_read_handler;
2178 return chr;
2181 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2183 HANDLE fd_out;
2185 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2186 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2187 if (fd_out == INVALID_HANDLE_VALUE)
2188 return NULL;
2190 return qemu_chr_open_win_file(fd_out);
2192 #endif
2194 CharDriverState *qemu_chr_open(const char *filename)
2196 const char *p;
2198 if (!strcmp(filename, "vc")) {
2199 return text_console_init(&display_state);
2200 } else if (!strcmp(filename, "null")) {
2201 return qemu_chr_open_null();
2202 } else
2203 #ifndef _WIN32
2204 if (strstart(filename, "file:", &p)) {
2205 return qemu_chr_open_file_out(p);
2206 } else if (strstart(filename, "pipe:", &p)) {
2207 return qemu_chr_open_pipe(p);
2208 } else if (!strcmp(filename, "pty")) {
2209 return qemu_chr_open_pty();
2210 } else if (!strcmp(filename, "stdio")) {
2211 return qemu_chr_open_stdio();
2212 } else
2213 #endif
2214 #if defined(__linux__)
2215 if (strstart(filename, "/dev/parport", NULL)) {
2216 return qemu_chr_open_pp(filename);
2217 } else
2218 if (strstart(filename, "/dev/", NULL)) {
2219 return qemu_chr_open_tty(filename);
2220 } else
2221 #endif
2222 #ifdef _WIN32
2223 if (strstart(filename, "COM", NULL)) {
2224 return qemu_chr_open_win(filename);
2225 } else
2226 if (strstart(filename, "pipe:", &p)) {
2227 return qemu_chr_open_win_pipe(p);
2228 } else
2229 if (strstart(filename, "file:", &p)) {
2230 return qemu_chr_open_win_file_out(p);
2232 #endif
2234 return NULL;
2238 void qemu_chr_close(CharDriverState *chr)
2240 if (chr->chr_close)
2241 chr->chr_close(chr);
2244 /***********************************************************/
2245 /* network device redirectors */
2247 void hex_dump(FILE *f, const uint8_t *buf, int size)
2249 int len, i, j, c;
2251 for(i=0;i<size;i+=16) {
2252 len = size - i;
2253 if (len > 16)
2254 len = 16;
2255 fprintf(f, "%08x ", i);
2256 for(j=0;j<16;j++) {
2257 if (j < len)
2258 fprintf(f, " %02x", buf[i+j]);
2259 else
2260 fprintf(f, " ");
2262 fprintf(f, " ");
2263 for(j=0;j<len;j++) {
2264 c = buf[i+j];
2265 if (c < ' ' || c > '~')
2266 c = '.';
2267 fprintf(f, "%c", c);
2269 fprintf(f, "\n");
2273 static int parse_macaddr(uint8_t *macaddr, const char *p)
2275 int i;
2276 for(i = 0; i < 6; i++) {
2277 macaddr[i] = strtol(p, (char **)&p, 16);
2278 if (i == 5) {
2279 if (*p != '\0')
2280 return -1;
2281 } else {
2282 if (*p != ':')
2283 return -1;
2284 p++;
2287 return 0;
2290 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2292 const char *p, *p1;
2293 int len;
2294 p = *pp;
2295 p1 = strchr(p, sep);
2296 if (!p1)
2297 return -1;
2298 len = p1 - p;
2299 p1++;
2300 if (buf_size > 0) {
2301 if (len > buf_size - 1)
2302 len = buf_size - 1;
2303 memcpy(buf, p, len);
2304 buf[len] = '\0';
2306 *pp = p1;
2307 return 0;
2310 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2312 char buf[512];
2313 struct hostent *he;
2314 const char *p, *r;
2315 int port;
2317 p = str;
2318 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2319 return -1;
2320 saddr->sin_family = AF_INET;
2321 if (buf[0] == '\0') {
2322 saddr->sin_addr.s_addr = 0;
2323 } else {
2324 if (isdigit(buf[0])) {
2325 if (!inet_aton(buf, &saddr->sin_addr))
2326 return -1;
2327 } else {
2328 if ((he = gethostbyname(buf)) == NULL)
2329 return - 1;
2330 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2333 port = strtol(p, (char **)&r, 0);
2334 if (r == p)
2335 return -1;
2336 saddr->sin_port = htons(port);
2337 return 0;
2340 /* find or alloc a new VLAN */
2341 VLANState *qemu_find_vlan(int id)
2343 VLANState **pvlan, *vlan;
2344 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2345 if (vlan->id == id)
2346 return vlan;
2348 vlan = qemu_mallocz(sizeof(VLANState));
2349 if (!vlan)
2350 return NULL;
2351 vlan->id = id;
2352 vlan->next = NULL;
2353 pvlan = &first_vlan;
2354 while (*pvlan != NULL)
2355 pvlan = &(*pvlan)->next;
2356 *pvlan = vlan;
2357 return vlan;
2360 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2361 IOReadHandler *fd_read,
2362 IOCanRWHandler *fd_can_read,
2363 void *opaque)
2365 VLANClientState *vc, **pvc;
2366 vc = qemu_mallocz(sizeof(VLANClientState));
2367 if (!vc)
2368 return NULL;
2369 vc->fd_read = fd_read;
2370 vc->fd_can_read = fd_can_read;
2371 vc->opaque = opaque;
2372 vc->vlan = vlan;
2374 vc->next = NULL;
2375 pvc = &vlan->first_client;
2376 while (*pvc != NULL)
2377 pvc = &(*pvc)->next;
2378 *pvc = vc;
2379 return vc;
2382 int qemu_can_send_packet(VLANClientState *vc1)
2384 VLANState *vlan = vc1->vlan;
2385 VLANClientState *vc;
2387 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2388 if (vc != vc1) {
2389 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2390 return 0;
2393 return 1;
2396 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2398 VLANState *vlan = vc1->vlan;
2399 VLANClientState *vc;
2401 #if 0
2402 printf("vlan %d send:\n", vlan->id);
2403 hex_dump(stdout, buf, size);
2404 #endif
2405 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2406 if (vc != vc1) {
2407 vc->fd_read(vc->opaque, buf, size);
2412 #if defined(CONFIG_SLIRP)
2414 /* slirp network adapter */
2416 static int slirp_inited;
2417 static VLANClientState *slirp_vc;
2419 int slirp_can_output(void)
2421 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2424 void slirp_output(const uint8_t *pkt, int pkt_len)
2426 #if 0
2427 printf("slirp output:\n");
2428 hex_dump(stdout, pkt, pkt_len);
2429 #endif
2430 if (!slirp_vc)
2431 return;
2432 qemu_send_packet(slirp_vc, pkt, pkt_len);
2435 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2437 #if 0
2438 printf("slirp input:\n");
2439 hex_dump(stdout, buf, size);
2440 #endif
2441 slirp_input(buf, size);
2444 static int net_slirp_init(VLANState *vlan)
2446 if (!slirp_inited) {
2447 slirp_inited = 1;
2448 slirp_init();
2450 slirp_vc = qemu_new_vlan_client(vlan,
2451 slirp_receive, NULL, NULL);
2452 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2453 return 0;
2456 static void net_slirp_redir(const char *redir_str)
2458 int is_udp;
2459 char buf[256], *r;
2460 const char *p;
2461 struct in_addr guest_addr;
2462 int host_port, guest_port;
2464 if (!slirp_inited) {
2465 slirp_inited = 1;
2466 slirp_init();
2469 p = redir_str;
2470 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2471 goto fail;
2472 if (!strcmp(buf, "tcp")) {
2473 is_udp = 0;
2474 } else if (!strcmp(buf, "udp")) {
2475 is_udp = 1;
2476 } else {
2477 goto fail;
2480 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2481 goto fail;
2482 host_port = strtol(buf, &r, 0);
2483 if (r == buf)
2484 goto fail;
2486 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2487 goto fail;
2488 if (buf[0] == '\0') {
2489 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2491 if (!inet_aton(buf, &guest_addr))
2492 goto fail;
2494 guest_port = strtol(p, &r, 0);
2495 if (r == p)
2496 goto fail;
2498 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2499 fprintf(stderr, "qemu: could not set up redirection\n");
2500 exit(1);
2502 return;
2503 fail:
2504 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2505 exit(1);
2508 #ifndef _WIN32
2510 char smb_dir[1024];
2512 static void smb_exit(void)
2514 DIR *d;
2515 struct dirent *de;
2516 char filename[1024];
2518 /* erase all the files in the directory */
2519 d = opendir(smb_dir);
2520 for(;;) {
2521 de = readdir(d);
2522 if (!de)
2523 break;
2524 if (strcmp(de->d_name, ".") != 0 &&
2525 strcmp(de->d_name, "..") != 0) {
2526 snprintf(filename, sizeof(filename), "%s/%s",
2527 smb_dir, de->d_name);
2528 unlink(filename);
2531 closedir(d);
2532 rmdir(smb_dir);
2535 /* automatic user mode samba server configuration */
2536 void net_slirp_smb(const char *exported_dir)
2538 char smb_conf[1024];
2539 char smb_cmdline[1024];
2540 FILE *f;
2542 if (!slirp_inited) {
2543 slirp_inited = 1;
2544 slirp_init();
2547 /* XXX: better tmp dir construction */
2548 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2549 if (mkdir(smb_dir, 0700) < 0) {
2550 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2551 exit(1);
2553 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2555 f = fopen(smb_conf, "w");
2556 if (!f) {
2557 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2558 exit(1);
2560 fprintf(f,
2561 "[global]\n"
2562 "private dir=%s\n"
2563 "smb ports=0\n"
2564 "socket address=127.0.0.1\n"
2565 "pid directory=%s\n"
2566 "lock directory=%s\n"
2567 "log file=%s/log.smbd\n"
2568 "smb passwd file=%s/smbpasswd\n"
2569 "security = share\n"
2570 "[qemu]\n"
2571 "path=%s\n"
2572 "read only=no\n"
2573 "guest ok=yes\n",
2574 smb_dir,
2575 smb_dir,
2576 smb_dir,
2577 smb_dir,
2578 smb_dir,
2579 exported_dir
2580 );
2581 fclose(f);
2582 atexit(smb_exit);
2584 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2585 smb_conf);
2587 slirp_add_exec(0, smb_cmdline, 4, 139);
2590 #endif /* !defined(_WIN32) */
2592 #endif /* CONFIG_SLIRP */
2594 #if !defined(_WIN32)
2596 typedef struct TAPState {
2597 VLANClientState *vc;
2598 int fd;
2599 } TAPState;
2601 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2603 TAPState *s = opaque;
2604 int ret;
2605 for(;;) {
2606 ret = write(s->fd, buf, size);
2607 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2608 } else {
2609 break;
2614 static void tap_send(void *opaque)
2616 TAPState *s = opaque;
2617 uint8_t buf[4096];
2618 int size;
2620 size = read(s->fd, buf, sizeof(buf));
2621 if (size > 0) {
2622 qemu_send_packet(s->vc, buf, size);
2626 /* fd support */
2628 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2630 TAPState *s;
2632 s = qemu_mallocz(sizeof(TAPState));
2633 if (!s)
2634 return NULL;
2635 s->fd = fd;
2636 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2637 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2638 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2639 return s;
2642 #ifdef _BSD
2643 static int tap_open(char *ifname, int ifname_size)
2645 int fd;
2646 char *dev;
2647 struct stat s;
2649 fd = open("/dev/tap", O_RDWR);
2650 if (fd < 0) {
2651 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2652 return -1;
2655 fstat(fd, &s);
2656 dev = devname(s.st_rdev, S_IFCHR);
2657 pstrcpy(ifname, ifname_size, dev);
2659 fcntl(fd, F_SETFL, O_NONBLOCK);
2660 return fd;
2662 #elif defined(__sun__)
2663 static int tap_open(char *ifname, int ifname_size)
2665 fprintf(stderr, "warning: tap_open not yet implemented\n");
2666 return -1;
2668 #else
2669 static int tap_open(char *ifname, int ifname_size)
2671 struct ifreq ifr;
2672 int fd, ret;
2674 fd = open("/dev/net/tun", O_RDWR);
2675 if (fd < 0) {
2676 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2677 return -1;
2679 memset(&ifr, 0, sizeof(ifr));
2680 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2681 if (ifname[0] != '\0')
2682 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2683 else
2684 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2685 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2686 if (ret != 0) {
2687 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2688 close(fd);
2689 return -1;
2691 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2692 fcntl(fd, F_SETFL, O_NONBLOCK);
2693 return fd;
2695 #endif
2697 static int net_tap_init(VLANState *vlan, const char *ifname1,
2698 const char *setup_script, const char *bridge)
2700 TAPState *s;
2701 int pid, status, fd;
2702 char *args[4];
2703 char **parg;
2704 char ifname[128];
2706 if (ifname1 != NULL)
2707 pstrcpy(ifname, sizeof(ifname), ifname1);
2708 else
2709 ifname[0] = '\0';
2710 fd = tap_open(ifname, sizeof(ifname));
2711 if (fd < 0)
2712 return -1;
2714 if (!setup_script)
2715 setup_script = "";
2716 if (setup_script[0] != '\0') {
2717 /* try to launch network init script */
2718 pid = fork();
2719 if (pid >= 0) {
2720 if (pid == 0) {
2721 parg = args;
2722 *parg++ = (char *)setup_script;
2723 *parg++ = ifname;
2724 *parg++ = (char *)bridge;
2725 *parg++ = NULL;
2726 execv(setup_script, args);
2727 _exit(1);
2729 while (waitpid(pid, &status, 0) != pid);
2730 if (!WIFEXITED(status) ||
2731 WEXITSTATUS(status) != 0) {
2732 fprintf(stderr, "%s: could not launch network script\n",
2733 setup_script);
2734 return -1;
2738 s = net_tap_fd_init(vlan, fd);
2739 if (!s)
2740 return -1;
2741 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2742 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2743 return 0;
2746 #endif /* !_WIN32 */
2748 /* network connection */
2749 typedef struct NetSocketState {
2750 VLANClientState *vc;
2751 int fd;
2752 int state; /* 0 = getting length, 1 = getting data */
2753 int index;
2754 int packet_len;
2755 uint8_t buf[4096];
2756 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2757 } NetSocketState;
2759 typedef struct NetSocketListenState {
2760 VLANState *vlan;
2761 int fd;
2762 } NetSocketListenState;
2764 /* XXX: we consider we can send the whole packet without blocking */
2765 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2767 NetSocketState *s = opaque;
2768 uint32_t len;
2769 len = htonl(size);
2771 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2772 send_all(s->fd, buf, size);
2775 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2777 NetSocketState *s = opaque;
2778 sendto(s->fd, buf, size, 0,
2779 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2782 static void net_socket_send(void *opaque)
2784 NetSocketState *s = opaque;
2785 int l, size, err;
2786 uint8_t buf1[4096];
2787 const uint8_t *buf;
2789 size = recv(s->fd, buf1, sizeof(buf1), 0);
2790 if (size < 0) {
2791 err = socket_error();
2792 if (err != EWOULDBLOCK)
2793 goto eoc;
2794 } else if (size == 0) {
2795 /* end of connection */
2796 eoc:
2797 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2798 closesocket(s->fd);
2799 return;
2801 buf = buf1;
2802 while (size > 0) {
2803 /* reassemble a packet from the network */
2804 switch(s->state) {
2805 case 0:
2806 l = 4 - s->index;
2807 if (l > size)
2808 l = size;
2809 memcpy(s->buf + s->index, buf, l);
2810 buf += l;
2811 size -= l;
2812 s->index += l;
2813 if (s->index == 4) {
2814 /* got length */
2815 s->packet_len = ntohl(*(uint32_t *)s->buf);
2816 s->index = 0;
2817 s->state = 1;
2819 break;
2820 case 1:
2821 l = s->packet_len - s->index;
2822 if (l > size)
2823 l = size;
2824 memcpy(s->buf + s->index, buf, l);
2825 s->index += l;
2826 buf += l;
2827 size -= l;
2828 if (s->index >= s->packet_len) {
2829 qemu_send_packet(s->vc, s->buf, s->packet_len);
2830 s->index = 0;
2831 s->state = 0;
2833 break;
2838 static void net_socket_send_dgram(void *opaque)
2840 NetSocketState *s = opaque;
2841 int size;
2843 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2844 if (size < 0)
2845 return;
2846 if (size == 0) {
2847 /* end of connection */
2848 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2849 return;
2851 qemu_send_packet(s->vc, s->buf, size);
2854 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2856 struct ip_mreq imr;
2857 int fd;
2858 int val, ret;
2859 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2860 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2861 inet_ntoa(mcastaddr->sin_addr),
2862 (int)ntohl(mcastaddr->sin_addr.s_addr));
2863 return -1;
2866 fd = socket(PF_INET, SOCK_DGRAM, 0);
2867 if (fd < 0) {
2868 perror("socket(PF_INET, SOCK_DGRAM)");
2869 return -1;
2872 val = 1;
2873 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2874 (const char *)&val, sizeof(val));
2875 if (ret < 0) {
2876 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2877 goto fail;
2880 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2881 if (ret < 0) {
2882 perror("bind");
2883 goto fail;
2886 /* Add host to multicast group */
2887 imr.imr_multiaddr = mcastaddr->sin_addr;
2888 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2890 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2891 (const char *)&imr, sizeof(struct ip_mreq));
2892 if (ret < 0) {
2893 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2894 goto fail;
2897 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2898 val = 1;
2899 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2900 (const char *)&val, sizeof(val));
2901 if (ret < 0) {
2902 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2903 goto fail;
2906 socket_set_nonblock(fd);
2907 return fd;
2908 fail:
2909 if (fd>=0) close(fd);
2910 return -1;
2913 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2914 int is_connected)
2916 struct sockaddr_in saddr;
2917 int newfd;
2918 socklen_t saddr_len;
2919 NetSocketState *s;
2921 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2922 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2923 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2924 */
2926 if (is_connected) {
2927 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2928 /* must be bound */
2929 if (saddr.sin_addr.s_addr==0) {
2930 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2931 fd);
2932 return NULL;
2934 /* clone dgram socket */
2935 newfd = net_socket_mcast_create(&saddr);
2936 if (newfd < 0) {
2937 /* error already reported by net_socket_mcast_create() */
2938 close(fd);
2939 return NULL;
2941 /* clone newfd to fd, close newfd */
2942 dup2(newfd, fd);
2943 close(newfd);
2945 } else {
2946 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2947 fd, strerror(errno));
2948 return NULL;
2952 s = qemu_mallocz(sizeof(NetSocketState));
2953 if (!s)
2954 return NULL;
2955 s->fd = fd;
2957 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2958 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2960 /* mcast: save bound address as dst */
2961 if (is_connected) s->dgram_dst=saddr;
2963 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2964 "socket: fd=%d (%s mcast=%s:%d)",
2965 fd, is_connected? "cloned" : "",
2966 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2967 return s;
2970 static void net_socket_connect(void *opaque)
2972 NetSocketState *s = opaque;
2973 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2976 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2977 int is_connected)
2979 NetSocketState *s;
2980 s = qemu_mallocz(sizeof(NetSocketState));
2981 if (!s)
2982 return NULL;
2983 s->fd = fd;
2984 s->vc = qemu_new_vlan_client(vlan,
2985 net_socket_receive, NULL, s);
2986 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2987 "socket: fd=%d", fd);
2988 if (is_connected) {
2989 net_socket_connect(s);
2990 } else {
2991 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2993 return s;
2996 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2997 int is_connected)
2999 int so_type=-1, optlen=sizeof(so_type);
3001 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3002 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3003 return NULL;
3005 switch(so_type) {
3006 case SOCK_DGRAM:
3007 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3008 case SOCK_STREAM:
3009 return net_socket_fd_init_stream(vlan, fd, is_connected);
3010 default:
3011 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3012 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3013 return net_socket_fd_init_stream(vlan, fd, is_connected);
3015 return NULL;
3018 static void net_socket_accept(void *opaque)
3020 NetSocketListenState *s = opaque;
3021 NetSocketState *s1;
3022 struct sockaddr_in saddr;
3023 socklen_t len;
3024 int fd;
3026 for(;;) {
3027 len = sizeof(saddr);
3028 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3029 if (fd < 0 && errno != EINTR) {
3030 return;
3031 } else if (fd >= 0) {
3032 break;
3035 s1 = net_socket_fd_init(s->vlan, fd, 1);
3036 if (!s1) {
3037 close(fd);
3038 } else {
3039 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3040 "socket: connection from %s:%d",
3041 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3045 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3047 NetSocketListenState *s;
3048 int fd, val, ret;
3049 struct sockaddr_in saddr;
3051 if (parse_host_port(&saddr, host_str) < 0)
3052 return -1;
3054 s = qemu_mallocz(sizeof(NetSocketListenState));
3055 if (!s)
3056 return -1;
3058 fd = socket(PF_INET, SOCK_STREAM, 0);
3059 if (fd < 0) {
3060 perror("socket");
3061 return -1;
3063 socket_set_nonblock(fd);
3065 /* allow fast reuse */
3066 val = 1;
3067 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3069 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3070 if (ret < 0) {
3071 perror("bind");
3072 return -1;
3074 ret = listen(fd, 0);
3075 if (ret < 0) {
3076 perror("listen");
3077 return -1;
3079 s->vlan = vlan;
3080 s->fd = fd;
3081 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3082 return 0;
3085 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3087 NetSocketState *s;
3088 int fd, connected, ret, err;
3089 struct sockaddr_in saddr;
3091 if (parse_host_port(&saddr, host_str) < 0)
3092 return -1;
3094 fd = socket(PF_INET, SOCK_STREAM, 0);
3095 if (fd < 0) {
3096 perror("socket");
3097 return -1;
3099 socket_set_nonblock(fd);
3101 connected = 0;
3102 for(;;) {
3103 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3104 if (ret < 0) {
3105 err = socket_error();
3106 if (err == EINTR || err == EWOULDBLOCK) {
3107 } else if (err == EINPROGRESS) {
3108 break;
3109 } else {
3110 perror("connect");
3111 closesocket(fd);
3112 return -1;
3114 } else {
3115 connected = 1;
3116 break;
3119 s = net_socket_fd_init(vlan, fd, connected);
3120 if (!s)
3121 return -1;
3122 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3123 "socket: connect to %s:%d",
3124 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3125 return 0;
3128 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3130 NetSocketState *s;
3131 int fd;
3132 struct sockaddr_in saddr;
3134 if (parse_host_port(&saddr, host_str) < 0)
3135 return -1;
3138 fd = net_socket_mcast_create(&saddr);
3139 if (fd < 0)
3140 return -1;
3142 s = net_socket_fd_init(vlan, fd, 0);
3143 if (!s)
3144 return -1;
3146 s->dgram_dst = saddr;
3148 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3149 "socket: mcast=%s:%d",
3150 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3151 return 0;
3155 static int get_param_value(char *buf, int buf_size,
3156 const char *tag, const char *str)
3158 const char *p;
3159 char *q;
3160 char option[128];
3162 p = str;
3163 for(;;) {
3164 q = option;
3165 while (*p != '\0' && *p != '=') {
3166 if ((q - option) < sizeof(option) - 1)
3167 *q++ = *p;
3168 p++;
3170 *q = '\0';
3171 if (*p != '=')
3172 break;
3173 p++;
3174 if (!strcmp(tag, option)) {
3175 q = buf;
3176 while (*p != '\0' && *p != ',') {
3177 if ((q - buf) < buf_size - 1)
3178 *q++ = *p;
3179 p++;
3181 *q = '\0';
3182 return q - buf;
3183 } else {
3184 while (*p != '\0' && *p != ',') {
3185 p++;
3188 if (*p != ',')
3189 break;
3190 p++;
3192 return 0;
3195 int net_client_init(const char *str)
3197 const char *p;
3198 char *q;
3199 char device[64];
3200 char buf[1024];
3201 int vlan_id, ret;
3202 VLANState *vlan;
3204 p = str;
3205 q = device;
3206 while (*p != '\0' && *p != ',') {
3207 if ((q - device) < sizeof(device) - 1)
3208 *q++ = *p;
3209 p++;
3211 *q = '\0';
3212 if (*p == ',')
3213 p++;
3214 vlan_id = 0;
3215 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3216 vlan_id = strtol(buf, NULL, 0);
3218 vlan = qemu_find_vlan(vlan_id);
3219 if (!vlan) {
3220 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3221 return -1;
3223 if (!strcmp(device, "nic")) {
3224 NICInfo *nd;
3225 uint8_t *macaddr;
3227 if (nb_nics >= MAX_NICS) {
3228 fprintf(stderr, "Too Many NICs\n");
3229 return -1;
3231 nd = &nd_table[nb_nics];
3232 macaddr = nd->macaddr;
3233 macaddr[0] = 0x52;
3234 macaddr[1] = 0x54;
3235 macaddr[2] = 0x00;
3236 macaddr[3] = 0x12;
3237 macaddr[4] = 0x34;
3238 macaddr[5] = 0x56 + nb_nics;
3240 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3241 if (parse_macaddr(macaddr, buf) < 0) {
3242 fprintf(stderr, "invalid syntax for ethernet address\n");
3243 return -1;
3246 if (get_param_value(buf, sizeof(buf), "model", p)) {
3247 nd->model = strdup(buf);
3249 nd->vlan = vlan;
3250 nb_nics++;
3251 ret = 0;
3252 } else
3253 if (!strcmp(device, "none")) {
3254 /* does nothing. It is needed to signal that no network cards
3255 are wanted */
3256 ret = 0;
3257 } else
3258 #ifdef CONFIG_SLIRP
3259 if (!strcmp(device, "user")) {
3260 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3261 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3263 ret = net_slirp_init(vlan);
3264 } else
3265 #endif
3266 #ifdef _WIN32
3267 if (!strcmp(device, "tap")) {
3268 char ifname[64];
3269 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3270 fprintf(stderr, "tap: no interface name\n");
3271 return -1;
3273 ret = tap_win32_init(vlan, ifname);
3274 } else
3275 #else
3276 if (!strcmp(device, "tap")) {
3277 char ifname[64];
3278 char setup_script[1024];
3279 char bridge[16];
3280 int fd;
3281 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3282 fd = strtol(buf, NULL, 0);
3283 ret = -1;
3284 if (net_tap_fd_init(vlan, fd))
3285 ret = 0;
3286 } else {
3287 get_param_value(ifname, sizeof(ifname), "ifname", p);
3288 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3289 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3291 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
3292 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
3294 ret = net_tap_init(vlan, ifname, setup_script, bridge);
3296 } else
3297 #endif
3298 if (!strcmp(device, "socket")) {
3299 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3300 int fd;
3301 fd = strtol(buf, NULL, 0);
3302 ret = -1;
3303 if (net_socket_fd_init(vlan, fd, 1))
3304 ret = 0;
3305 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3306 ret = net_socket_listen_init(vlan, buf);
3307 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3308 ret = net_socket_connect_init(vlan, buf);
3309 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3310 ret = net_socket_mcast_init(vlan, buf);
3311 } else {
3312 fprintf(stderr, "Unknown socket options: %s\n", p);
3313 return -1;
3315 } else
3317 fprintf(stderr, "Unknown network device: %s\n", device);
3318 return -1;
3320 if (ret < 0) {
3321 fprintf(stderr, "Could not initialize device '%s'\n", device);
3324 return ret;
3327 void do_info_network(void)
3329 VLANState *vlan;
3330 VLANClientState *vc;
3332 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3333 term_printf("VLAN %d devices:\n", vlan->id);
3334 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3335 term_printf(" %s\n", vc->info_str);
3339 /***********************************************************/
3340 /* USB devices */
3342 static int usb_device_add(const char *devname)
3344 const char *p;
3345 USBDevice *dev;
3346 int i;
3348 if (!vm_usb_hub)
3349 return -1;
3350 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3351 if (!vm_usb_ports[i]->dev)
3352 break;
3354 if (i == MAX_VM_USB_PORTS)
3355 return -1;
3357 if (strstart(devname, "host:", &p)) {
3358 dev = usb_host_device_open(p);
3359 if (!dev)
3360 return -1;
3361 } else if (!strcmp(devname, "mouse")) {
3362 dev = usb_mouse_init();
3363 if (!dev)
3364 return -1;
3365 } else if (!strcmp(devname, "tablet")) {
3366 dev = usb_tablet_init();
3367 if (!dev)
3368 return -1;
3369 } else {
3370 return -1;
3372 usb_attach(vm_usb_ports[i], dev);
3373 return 0;
3376 static int usb_device_del(const char *devname)
3378 USBDevice *dev;
3379 int bus_num, addr, i;
3380 const char *p;
3382 if (!vm_usb_hub)
3383 return -1;
3385 p = strchr(devname, '.');
3386 if (!p)
3387 return -1;
3388 bus_num = strtoul(devname, NULL, 0);
3389 addr = strtoul(p + 1, NULL, 0);
3390 if (bus_num != 0)
3391 return -1;
3392 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3393 dev = vm_usb_ports[i]->dev;
3394 if (dev && dev->addr == addr)
3395 break;
3397 if (i == MAX_VM_USB_PORTS)
3398 return -1;
3399 usb_attach(vm_usb_ports[i], NULL);
3400 return 0;
3403 void do_usb_add(const char *devname)
3405 int ret;
3406 ret = usb_device_add(devname);
3407 if (ret < 0)
3408 term_printf("Could not add USB device '%s'\n", devname);
3411 void do_usb_del(const char *devname)
3413 int ret;
3414 ret = usb_device_del(devname);
3415 if (ret < 0)
3416 term_printf("Could not remove USB device '%s'\n", devname);
3419 void usb_info(void)
3421 USBDevice *dev;
3422 int i;
3423 const char *speed_str;
3425 if (!vm_usb_hub) {
3426 term_printf("USB support not enabled\n");
3427 return;
3430 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3431 dev = vm_usb_ports[i]->dev;
3432 if (dev) {
3433 term_printf("Hub port %d:\n", i);
3434 switch(dev->speed) {
3435 case USB_SPEED_LOW:
3436 speed_str = "1.5";
3437 break;
3438 case USB_SPEED_FULL:
3439 speed_str = "12";
3440 break;
3441 case USB_SPEED_HIGH:
3442 speed_str = "480";
3443 break;
3444 default:
3445 speed_str = "?";
3446 break;
3448 term_printf(" Device %d.%d, speed %s Mb/s\n",
3449 0, dev->addr, speed_str);
3454 /***********************************************************/
3455 /* pid file */
3457 static char *pid_filename;
3459 /* Remove PID file. Called on normal exit */
3461 static void remove_pidfile(void)
3463 unlink (pid_filename);
3466 static void create_pidfile(const char *filename)
3468 struct stat pidstat;
3469 FILE *f;
3471 /* Try to write our PID to the named file */
3472 if (stat(filename, &pidstat) < 0) {
3473 if (errno == ENOENT) {
3474 if ((f = fopen (filename, "w")) == NULL) {
3475 perror("Opening pidfile");
3476 exit(1);
3478 fprintf(f, "%d\n", getpid());
3479 fclose(f);
3480 pid_filename = qemu_strdup(filename);
3481 if (!pid_filename) {
3482 fprintf(stderr, "Could not save PID filename");
3483 exit(1);
3485 atexit(remove_pidfile);
3487 } else {
3488 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3489 filename);
3490 exit(1);
3494 /***********************************************************/
3495 /* dumb display */
3497 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3501 static void dumb_resize(DisplayState *ds, int w, int h)
3505 static void dumb_refresh(DisplayState *ds)
3507 vga_hw_update();
3510 void dumb_display_init(DisplayState *ds)
3512 ds->data = NULL;
3513 ds->linesize = 0;
3514 ds->depth = 0;
3515 ds->dpy_update = dumb_update;
3516 ds->dpy_resize = dumb_resize;
3517 ds->dpy_refresh = dumb_refresh;
3520 #if !defined(CONFIG_SOFTMMU)
3521 /***********************************************************/
3522 /* cpu signal handler */
3523 static void host_segv_handler(int host_signum, siginfo_t *info,
3524 void *puc)
3526 if (cpu_signal_handler(host_signum, info, puc))
3527 return;
3528 if (stdio_nb_clients > 0)
3529 term_exit();
3530 abort();
3532 #endif
3534 /***********************************************************/
3535 /* I/O handling */
3537 #define MAX_IO_HANDLERS 64
3539 typedef struct IOHandlerRecord {
3540 int fd;
3541 IOCanRWHandler *fd_read_poll;
3542 IOHandler *fd_read;
3543 IOHandler *fd_write;
3544 void *opaque;
3545 /* temporary data */
3546 struct pollfd *ufd;
3547 struct IOHandlerRecord *next;
3548 } IOHandlerRecord;
3550 static IOHandlerRecord *first_io_handler;
3552 /* XXX: fd_read_poll should be suppressed, but an API change is
3553 necessary in the character devices to suppress fd_can_read(). */
3554 int qemu_set_fd_handler2(int fd,
3555 IOCanRWHandler *fd_read_poll,
3556 IOHandler *fd_read,
3557 IOHandler *fd_write,
3558 void *opaque)
3560 IOHandlerRecord **pioh, *ioh;
3562 if (!fd_read && !fd_write) {
3563 pioh = &first_io_handler;
3564 for(;;) {
3565 ioh = *pioh;
3566 if (ioh == NULL)
3567 break;
3568 if (ioh->fd == fd) {
3569 *pioh = ioh->next;
3570 qemu_free(ioh);
3571 break;
3573 pioh = &ioh->next;
3575 } else {
3576 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3577 if (ioh->fd == fd)
3578 goto found;
3580 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3581 if (!ioh)
3582 return -1;
3583 ioh->next = first_io_handler;
3584 first_io_handler = ioh;
3585 found:
3586 ioh->fd = fd;
3587 ioh->fd_read_poll = fd_read_poll;
3588 ioh->fd_read = fd_read;
3589 ioh->fd_write = fd_write;
3590 ioh->opaque = opaque;
3592 return 0;
3595 int qemu_set_fd_handler(int fd,
3596 IOHandler *fd_read,
3597 IOHandler *fd_write,
3598 void *opaque)
3600 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3603 /***********************************************************/
3604 /* Polling handling */
3606 typedef struct PollingEntry {
3607 PollingFunc *func;
3608 void *opaque;
3609 struct PollingEntry *next;
3610 } PollingEntry;
3612 static PollingEntry *first_polling_entry;
3614 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3616 PollingEntry **ppe, *pe;
3617 pe = qemu_mallocz(sizeof(PollingEntry));
3618 if (!pe)
3619 return -1;
3620 pe->func = func;
3621 pe->opaque = opaque;
3622 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3623 *ppe = pe;
3624 return 0;
3627 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3629 PollingEntry **ppe, *pe;
3630 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3631 pe = *ppe;
3632 if (pe->func == func && pe->opaque == opaque) {
3633 *ppe = pe->next;
3634 qemu_free(pe);
3635 break;
3640 /***********************************************************/
3641 /* savevm/loadvm support */
3643 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3645 fwrite(buf, 1, size, f);
3648 void qemu_put_byte(QEMUFile *f, int v)
3650 fputc(v, f);
3653 void qemu_put_be16(QEMUFile *f, unsigned int v)
3655 qemu_put_byte(f, v >> 8);
3656 qemu_put_byte(f, v);
3659 void qemu_put_be32(QEMUFile *f, unsigned int v)
3661 qemu_put_byte(f, v >> 24);
3662 qemu_put_byte(f, v >> 16);
3663 qemu_put_byte(f, v >> 8);
3664 qemu_put_byte(f, v);
3667 void qemu_put_be64(QEMUFile *f, uint64_t v)
3669 qemu_put_be32(f, v >> 32);
3670 qemu_put_be32(f, v);
3673 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3675 return fread(buf, 1, size, f);
3678 int qemu_get_byte(QEMUFile *f)
3680 int v;
3681 v = fgetc(f);
3682 if (v == EOF)
3683 return 0;
3684 else
3685 return v;
3688 unsigned int qemu_get_be16(QEMUFile *f)
3690 unsigned int v;
3691 v = qemu_get_byte(f) << 8;
3692 v |= qemu_get_byte(f);
3693 return v;
3696 unsigned int qemu_get_be32(QEMUFile *f)
3698 unsigned int v;
3699 v = qemu_get_byte(f) << 24;
3700 v |= qemu_get_byte(f) << 16;
3701 v |= qemu_get_byte(f) << 8;
3702 v |= qemu_get_byte(f);
3703 return v;
3706 uint64_t qemu_get_be64(QEMUFile *f)
3708 uint64_t v;
3709 v = (uint64_t)qemu_get_be32(f) << 32;
3710 v |= qemu_get_be32(f);
3711 return v;
3714 int64_t qemu_ftell(QEMUFile *f)
3716 return ftell(f);
3719 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3721 if (fseek(f, pos, whence) < 0)
3722 return -1;
3723 return ftell(f);
3726 typedef struct SaveStateEntry {
3727 char idstr[256];
3728 int instance_id;
3729 int version_id;
3730 SaveStateHandler *save_state;
3731 LoadStateHandler *load_state;
3732 void *opaque;
3733 struct SaveStateEntry *next;
3734 } SaveStateEntry;
3736 static SaveStateEntry *first_se;
3738 int register_savevm(const char *idstr,
3739 int instance_id,
3740 int version_id,
3741 SaveStateHandler *save_state,
3742 LoadStateHandler *load_state,
3743 void *opaque)
3745 SaveStateEntry *se, **pse;
3747 se = qemu_malloc(sizeof(SaveStateEntry));
3748 if (!se)
3749 return -1;
3750 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3751 se->instance_id = instance_id;
3752 se->version_id = version_id;
3753 se->save_state = save_state;
3754 se->load_state = load_state;
3755 se->opaque = opaque;
3756 se->next = NULL;
3758 /* add at the end of list */
3759 pse = &first_se;
3760 while (*pse != NULL)
3761 pse = &(*pse)->next;
3762 *pse = se;
3763 return 0;
3766 #define QEMU_VM_FILE_MAGIC 0x5145564d
3767 #define QEMU_VM_FILE_VERSION 0x00000001
3769 int qemu_savevm(const char *filename)
3771 SaveStateEntry *se;
3772 QEMUFile *f;
3773 int len, len_pos, cur_pos, saved_vm_running, ret;
3775 saved_vm_running = vm_running;
3776 vm_stop(0);
3778 f = fopen(filename, "wb");
3779 if (!f) {
3780 ret = -1;
3781 goto the_end;
3784 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3785 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3787 for(se = first_se; se != NULL; se = se->next) {
3788 /* ID string */
3789 len = strlen(se->idstr);
3790 qemu_put_byte(f, len);
3791 qemu_put_buffer(f, se->idstr, len);
3793 qemu_put_be32(f, se->instance_id);
3794 qemu_put_be32(f, se->version_id);
3796 /* record size: filled later */
3797 len_pos = ftell(f);
3798 qemu_put_be32(f, 0);
3800 se->save_state(f, se->opaque);
3802 /* fill record size */
3803 cur_pos = ftell(f);
3804 len = ftell(f) - len_pos - 4;
3805 fseek(f, len_pos, SEEK_SET);
3806 qemu_put_be32(f, len);
3807 fseek(f, cur_pos, SEEK_SET);
3810 fclose(f);
3811 ret = 0;
3812 the_end:
3813 if (saved_vm_running)
3814 vm_start();
3815 return ret;
3818 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3820 SaveStateEntry *se;
3822 for(se = first_se; se != NULL; se = se->next) {
3823 if (!strcmp(se->idstr, idstr) &&
3824 instance_id == se->instance_id)
3825 return se;
3827 return NULL;
3830 int qemu_loadvm(const char *filename)
3832 SaveStateEntry *se;
3833 QEMUFile *f;
3834 int len, cur_pos, ret, instance_id, record_len, version_id;
3835 int saved_vm_running;
3836 unsigned int v;
3837 char idstr[256];
3839 saved_vm_running = vm_running;
3840 vm_stop(0);
3842 f = fopen(filename, "rb");
3843 if (!f) {
3844 ret = -1;
3845 goto the_end;
3848 v = qemu_get_be32(f);
3849 if (v != QEMU_VM_FILE_MAGIC)
3850 goto fail;
3851 v = qemu_get_be32(f);
3852 if (v != QEMU_VM_FILE_VERSION) {
3853 fail:
3854 fclose(f);
3855 ret = -1;
3856 goto the_end;
3858 for(;;) {
3859 len = qemu_get_byte(f);
3860 if (feof(f))
3861 break;
3862 qemu_get_buffer(f, idstr, len);
3863 idstr[len] = '\0';
3864 instance_id = qemu_get_be32(f);
3865 version_id = qemu_get_be32(f);
3866 record_len = qemu_get_be32(f);
3867 #if 0
3868 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3869 idstr, instance_id, version_id, record_len);
3870 #endif
3871 cur_pos = ftell(f);
3872 se = find_se(idstr, instance_id);
3873 if (!se) {
3874 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3875 instance_id, idstr);
3876 } else {
3877 ret = se->load_state(f, se->opaque, version_id);
3878 if (ret < 0) {
3879 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3880 instance_id, idstr);
3883 /* always seek to exact end of record */
3884 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3886 fclose(f);
3887 ret = 0;
3888 the_end:
3889 if (saved_vm_running)
3890 vm_start();
3891 return ret;
3894 #ifndef CONFIG_DM
3895 /***********************************************************/
3896 /* cpu save/restore */
3898 #if defined(TARGET_I386)
3900 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3902 qemu_put_be32(f, dt->selector);
3903 qemu_put_betl(f, dt->base);
3904 qemu_put_be32(f, dt->limit);
3905 qemu_put_be32(f, dt->flags);
3908 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3910 dt->selector = qemu_get_be32(f);
3911 dt->base = qemu_get_betl(f);
3912 dt->limit = qemu_get_be32(f);
3913 dt->flags = qemu_get_be32(f);
3916 void cpu_save(QEMUFile *f, void *opaque)
3918 CPUState *env = opaque;
3919 uint16_t fptag, fpus, fpuc, fpregs_format;
3920 uint32_t hflags;
3921 int i;
3923 for(i = 0; i < CPU_NB_REGS; i++)
3924 qemu_put_betls(f, &env->regs[i]);
3925 qemu_put_betls(f, &env->eip);
3926 qemu_put_betls(f, &env->eflags);
3927 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3928 qemu_put_be32s(f, &hflags);
3930 /* FPU */
3931 fpuc = env->fpuc;
3932 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3933 fptag = 0;
3934 for(i = 0; i < 8; i++) {
3935 fptag |= ((!env->fptags[i]) << i);
3938 qemu_put_be16s(f, &fpuc);
3939 qemu_put_be16s(f, &fpus);
3940 qemu_put_be16s(f, &fptag);
3942 #ifdef USE_X86LDOUBLE
3943 fpregs_format = 0;
3944 #else
3945 fpregs_format = 1;
3946 #endif
3947 qemu_put_be16s(f, &fpregs_format);
3949 for(i = 0; i < 8; i++) {
3950 #ifdef USE_X86LDOUBLE
3952 uint64_t mant;
3953 uint16_t exp;
3954 /* we save the real CPU data (in case of MMX usage only 'mant'
3955 contains the MMX register */
3956 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3957 qemu_put_be64(f, mant);
3958 qemu_put_be16(f, exp);
3960 #else
3961 /* if we use doubles for float emulation, we save the doubles to
3962 avoid losing information in case of MMX usage. It can give
3963 problems if the image is restored on a CPU where long
3964 doubles are used instead. */
3965 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3966 #endif
3969 for(i = 0; i < 6; i++)
3970 cpu_put_seg(f, &env->segs[i]);
3971 cpu_put_seg(f, &env->ldt);
3972 cpu_put_seg(f, &env->tr);
3973 cpu_put_seg(f, &env->gdt);
3974 cpu_put_seg(f, &env->idt);
3976 qemu_put_be32s(f, &env->sysenter_cs);
3977 qemu_put_be32s(f, &env->sysenter_esp);
3978 qemu_put_be32s(f, &env->sysenter_eip);
3980 qemu_put_betls(f, &env->cr[0]);
3981 qemu_put_betls(f, &env->cr[2]);
3982 qemu_put_betls(f, &env->cr[3]);
3983 qemu_put_betls(f, &env->cr[4]);
3985 for(i = 0; i < 8; i++)
3986 qemu_put_betls(f, &env->dr[i]);
3988 /* MMU */
3989 qemu_put_be32s(f, &env->a20_mask);
3991 /* XMM */
3992 qemu_put_be32s(f, &env->mxcsr);
3993 for(i = 0; i < CPU_NB_REGS; i++) {
3994 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3995 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3998 #ifdef TARGET_X86_64
3999 qemu_put_be64s(f, &env->efer);
4000 qemu_put_be64s(f, &env->star);
4001 qemu_put_be64s(f, &env->lstar);
4002 qemu_put_be64s(f, &env->cstar);
4003 qemu_put_be64s(f, &env->fmask);
4004 qemu_put_be64s(f, &env->kernelgsbase);
4005 #endif
4008 #ifdef USE_X86LDOUBLE
4009 /* XXX: add that in a FPU generic layer */
4010 union x86_longdouble {
4011 uint64_t mant;
4012 uint16_t exp;
4013 };
4015 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4016 #define EXPBIAS1 1023
4017 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4018 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4020 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4022 int e;
4023 /* mantissa */
4024 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4025 /* exponent + sign */
4026 e = EXPD1(temp) - EXPBIAS1 + 16383;
4027 e |= SIGND1(temp) >> 16;
4028 p->exp = e;
4030 #endif
4032 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4034 CPUState *env = opaque;
4035 int i, guess_mmx;
4036 uint32_t hflags;
4037 uint16_t fpus, fpuc, fptag, fpregs_format;
4039 if (version_id != 3)
4040 return -EINVAL;
4041 for(i = 0; i < CPU_NB_REGS; i++)
4042 qemu_get_betls(f, &env->regs[i]);
4043 qemu_get_betls(f, &env->eip);
4044 qemu_get_betls(f, &env->eflags);
4045 qemu_get_be32s(f, &hflags);
4047 qemu_get_be16s(f, &fpuc);
4048 qemu_get_be16s(f, &fpus);
4049 qemu_get_be16s(f, &fptag);
4050 qemu_get_be16s(f, &fpregs_format);
4052 /* NOTE: we cannot always restore the FPU state if the image come
4053 from a host with a different 'USE_X86LDOUBLE' define. We guess
4054 if we are in an MMX state to restore correctly in that case. */
4055 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4056 for(i = 0; i < 8; i++) {
4057 uint64_t mant;
4058 uint16_t exp;
4060 switch(fpregs_format) {
4061 case 0:
4062 mant = qemu_get_be64(f);
4063 exp = qemu_get_be16(f);
4064 #ifdef USE_X86LDOUBLE
4065 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4066 #else
4067 /* difficult case */
4068 if (guess_mmx)
4069 env->fpregs[i].mmx.MMX_Q(0) = mant;
4070 else
4071 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4072 #endif
4073 break;
4074 case 1:
4075 mant = qemu_get_be64(f);
4076 #ifdef USE_X86LDOUBLE
4078 union x86_longdouble *p;
4079 /* difficult case */
4080 p = (void *)&env->fpregs[i];
4081 if (guess_mmx) {
4082 p->mant = mant;
4083 p->exp = 0xffff;
4084 } else {
4085 fp64_to_fp80(p, mant);
4088 #else
4089 env->fpregs[i].mmx.MMX_Q(0) = mant;
4090 #endif
4091 break;
4092 default:
4093 return -EINVAL;
4097 env->fpuc = fpuc;
4098 /* XXX: restore FPU round state */
4099 env->fpstt = (fpus >> 11) & 7;
4100 env->fpus = fpus & ~0x3800;
4101 fptag ^= 0xff;
4102 for(i = 0; i < 8; i++) {
4103 env->fptags[i] = (fptag >> i) & 1;
4106 for(i = 0; i < 6; i++)
4107 cpu_get_seg(f, &env->segs[i]);
4108 cpu_get_seg(f, &env->ldt);
4109 cpu_get_seg(f, &env->tr);
4110 cpu_get_seg(f, &env->gdt);
4111 cpu_get_seg(f, &env->idt);
4113 qemu_get_be32s(f, &env->sysenter_cs);
4114 qemu_get_be32s(f, &env->sysenter_esp);
4115 qemu_get_be32s(f, &env->sysenter_eip);
4117 qemu_get_betls(f, &env->cr[0]);
4118 qemu_get_betls(f, &env->cr[2]);
4119 qemu_get_betls(f, &env->cr[3]);
4120 qemu_get_betls(f, &env->cr[4]);
4122 for(i = 0; i < 8; i++)
4123 qemu_get_betls(f, &env->dr[i]);
4125 /* MMU */
4126 qemu_get_be32s(f, &env->a20_mask);
4128 qemu_get_be32s(f, &env->mxcsr);
4129 for(i = 0; i < CPU_NB_REGS; i++) {
4130 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4131 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4134 #ifdef TARGET_X86_64
4135 qemu_get_be64s(f, &env->efer);
4136 qemu_get_be64s(f, &env->star);
4137 qemu_get_be64s(f, &env->lstar);
4138 qemu_get_be64s(f, &env->cstar);
4139 qemu_get_be64s(f, &env->fmask);
4140 qemu_get_be64s(f, &env->kernelgsbase);
4141 #endif
4143 /* XXX: compute hflags from scratch, except for CPL and IIF */
4144 env->hflags = hflags;
4145 tlb_flush(env, 1);
4146 return 0;
4149 #elif defined(TARGET_PPC)
4150 void cpu_save(QEMUFile *f, void *opaque)
4154 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4156 return 0;
4159 #elif defined(TARGET_MIPS)
4160 void cpu_save(QEMUFile *f, void *opaque)
4164 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4166 return 0;
4169 #elif defined(TARGET_SPARC)
4170 void cpu_save(QEMUFile *f, void *opaque)
4172 CPUState *env = opaque;
4173 int i;
4174 uint32_t tmp;
4176 for(i = 0; i < 8; i++)
4177 qemu_put_betls(f, &env->gregs[i]);
4178 for(i = 0; i < NWINDOWS * 16; i++)
4179 qemu_put_betls(f, &env->regbase[i]);
4181 /* FPU */
4182 for(i = 0; i < TARGET_FPREGS; i++) {
4183 union {
4184 TARGET_FPREG_T f;
4185 target_ulong i;
4186 } u;
4187 u.f = env->fpr[i];
4188 qemu_put_betl(f, u.i);
4191 qemu_put_betls(f, &env->pc);
4192 qemu_put_betls(f, &env->npc);
4193 qemu_put_betls(f, &env->y);
4194 tmp = GET_PSR(env);
4195 qemu_put_be32(f, tmp);
4196 qemu_put_betls(f, &env->fsr);
4197 qemu_put_betls(f, &env->tbr);
4198 #ifndef TARGET_SPARC64
4199 qemu_put_be32s(f, &env->wim);
4200 /* MMU */
4201 for(i = 0; i < 16; i++)
4202 qemu_put_be32s(f, &env->mmuregs[i]);
4203 #endif
4206 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4208 CPUState *env = opaque;
4209 int i;
4210 uint32_t tmp;
4212 for(i = 0; i < 8; i++)
4213 qemu_get_betls(f, &env->gregs[i]);
4214 for(i = 0; i < NWINDOWS * 16; i++)
4215 qemu_get_betls(f, &env->regbase[i]);
4217 /* FPU */
4218 for(i = 0; i < TARGET_FPREGS; i++) {
4219 union {
4220 TARGET_FPREG_T f;
4221 target_ulong i;
4222 } u;
4223 u.i = qemu_get_betl(f);
4224 env->fpr[i] = u.f;
4227 qemu_get_betls(f, &env->pc);
4228 qemu_get_betls(f, &env->npc);
4229 qemu_get_betls(f, &env->y);
4230 tmp = qemu_get_be32(f);
4231 env->cwp = 0; /* needed to ensure that the wrapping registers are
4232 correctly updated */
4233 PUT_PSR(env, tmp);
4234 qemu_get_betls(f, &env->fsr);
4235 qemu_get_betls(f, &env->tbr);
4236 #ifndef TARGET_SPARC64
4237 qemu_get_be32s(f, &env->wim);
4238 /* MMU */
4239 for(i = 0; i < 16; i++)
4240 qemu_get_be32s(f, &env->mmuregs[i]);
4241 #endif
4242 tlb_flush(env, 1);
4243 return 0;
4246 #elif defined(TARGET_ARM)
4248 /* ??? Need to implement these. */
4249 void cpu_save(QEMUFile *f, void *opaque)
4253 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4255 return 0;
4258 #else
4260 #warning No CPU save/restore functions
4262 #endif
4264 /***********************************************************/
4265 /* ram save/restore */
4267 /* we just avoid storing empty pages */
4268 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4270 int i, v;
4272 v = buf[0];
4273 for(i = 1; i < len; i++) {
4274 if (buf[i] != v)
4275 goto normal_save;
4277 qemu_put_byte(f, 1);
4278 qemu_put_byte(f, v);
4279 return;
4280 normal_save:
4281 qemu_put_byte(f, 0);
4282 qemu_put_buffer(f, buf, len);
4285 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4287 int v;
4289 v = qemu_get_byte(f);
4290 switch(v) {
4291 case 0:
4292 if (qemu_get_buffer(f, buf, len) != len)
4293 return -EIO;
4294 break;
4295 case 1:
4296 v = qemu_get_byte(f);
4297 memset(buf, v, len);
4298 break;
4299 default:
4300 return -EINVAL;
4302 return 0;
4305 static void ram_save(QEMUFile *f, void *opaque)
4307 int i;
4308 qemu_put_be32(f, phys_ram_size);
4309 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4310 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4314 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4316 int i, ret;
4318 if (version_id != 1)
4319 return -EINVAL;
4320 if (qemu_get_be32(f) != phys_ram_size)
4321 return -EINVAL;
4322 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4323 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4324 if (ret)
4325 return ret;
4327 return 0;
4329 #else /* CONFIG_DM */
4330 void cpu_save(QEMUFile *f, void *opaque)
4334 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4336 return 0;
4339 static void ram_save(QEMUFile *f, void *opaque)
4343 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4345 return 0;
4347 #endif /* CONFIG_DM */
4349 /***********************************************************/
4350 /* machine registration */
4352 QEMUMachine *first_machine = NULL;
4354 int qemu_register_machine(QEMUMachine *m)
4356 QEMUMachine **pm;
4357 pm = &first_machine;
4358 while (*pm != NULL)
4359 pm = &(*pm)->next;
4360 m->next = NULL;
4361 *pm = m;
4362 return 0;
4365 QEMUMachine *find_machine(const char *name)
4367 QEMUMachine *m;
4369 for(m = first_machine; m != NULL; m = m->next) {
4370 if (!strcmp(m->name, name))
4371 return m;
4373 return NULL;
4376 /***********************************************************/
4377 /* main execution loop */
4379 void gui_update(void *opaque)
4381 display_state.dpy_refresh(&display_state);
4382 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4385 struct vm_change_state_entry {
4386 VMChangeStateHandler *cb;
4387 void *opaque;
4388 LIST_ENTRY (vm_change_state_entry) entries;
4389 };
4391 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4393 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4394 void *opaque)
4396 VMChangeStateEntry *e;
4398 e = qemu_mallocz(sizeof (*e));
4399 if (!e)
4400 return NULL;
4402 e->cb = cb;
4403 e->opaque = opaque;
4404 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4405 return e;
4408 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4410 LIST_REMOVE (e, entries);
4411 qemu_free (e);
4414 static void vm_state_notify(int running)
4416 VMChangeStateEntry *e;
4418 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4419 e->cb(e->opaque, running);
4423 /* XXX: support several handlers */
4424 static VMStopHandler *vm_stop_cb;
4425 static void *vm_stop_opaque;
4427 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4429 vm_stop_cb = cb;
4430 vm_stop_opaque = opaque;
4431 return 0;
4434 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4436 vm_stop_cb = NULL;
4439 void vm_start(void)
4441 if (!vm_running) {
4442 cpu_enable_ticks();
4443 vm_running = 1;
4444 vm_state_notify(1);
4448 void vm_stop(int reason)
4450 if (vm_running) {
4451 cpu_disable_ticks();
4452 vm_running = 0;
4453 if (reason != 0) {
4454 if (vm_stop_cb) {
4455 vm_stop_cb(vm_stop_opaque, reason);
4458 vm_state_notify(0);
4462 /* reset/shutdown handler */
4464 typedef struct QEMUResetEntry {
4465 QEMUResetHandler *func;
4466 void *opaque;
4467 struct QEMUResetEntry *next;
4468 } QEMUResetEntry;
4470 static QEMUResetEntry *first_reset_entry;
4471 int reset_requested;
4472 int shutdown_requested;
4473 static int powerdown_requested;
4475 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4477 QEMUResetEntry **pre, *re;
4479 pre = &first_reset_entry;
4480 while (*pre != NULL)
4481 pre = &(*pre)->next;
4482 re = qemu_mallocz(sizeof(QEMUResetEntry));
4483 re->func = func;
4484 re->opaque = opaque;
4485 re->next = NULL;
4486 *pre = re;
4489 void qemu_system_reset(void)
4491 QEMUResetEntry *re;
4493 /* reset all devices */
4494 for(re = first_reset_entry; re != NULL; re = re->next) {
4495 re->func(re->opaque);
4499 void qemu_system_reset_request(void)
4501 reset_requested = 1;
4502 if (cpu_single_env)
4503 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4506 void qemu_system_shutdown_request(void)
4508 shutdown_requested = 1;
4509 if (cpu_single_env)
4510 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4513 void qemu_system_powerdown_request(void)
4515 powerdown_requested = 1;
4516 if (cpu_single_env)
4517 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4520 void main_loop_wait(int timeout)
4522 IOHandlerRecord *ioh, *ioh_next;
4523 fd_set rfds, wfds, xfds;
4524 int ret, nfds;
4525 struct timeval tv;
4526 PollingEntry *pe;
4529 /* XXX: need to suppress polling by better using win32 events */
4530 ret = 0;
4531 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4532 ret |= pe->func(pe->opaque);
4534 #ifdef _WIN32
4535 if (ret == 0 && timeout > 0) {
4536 int err;
4537 HANDLE hEvents[1];
4539 hEvents[0] = host_alarm;
4540 ret = WaitForMultipleObjects(1, hEvents, FALSE, timeout);
4541 switch(ret) {
4542 case WAIT_OBJECT_0 + 0:
4543 break;
4544 case WAIT_TIMEOUT:
4545 break;
4546 default:
4547 err = GetLastError();
4548 fprintf(stderr, "Wait error %d %d\n", ret, err);
4549 break;
4552 #endif
4553 /* poll any events */
4554 /* XXX: separate device handlers from system ones */
4555 nfds = -1;
4556 FD_ZERO(&rfds);
4557 FD_ZERO(&wfds);
4558 FD_ZERO(&xfds);
4559 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4560 if (ioh->fd_read &&
4561 (!ioh->fd_read_poll ||
4562 ioh->fd_read_poll(ioh->opaque) != 0)) {
4563 FD_SET(ioh->fd, &rfds);
4564 if (ioh->fd > nfds)
4565 nfds = ioh->fd;
4567 if (ioh->fd_write) {
4568 FD_SET(ioh->fd, &wfds);
4569 if (ioh->fd > nfds)
4570 nfds = ioh->fd;
4574 tv.tv_sec = 0;
4575 #ifdef _WIN32
4576 tv.tv_usec = 0;
4577 #else
4578 tv.tv_usec = timeout * 1000;
4579 #endif
4580 #if defined(CONFIG_SLIRP)
4581 if (slirp_inited) {
4582 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4584 #endif
4585 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4586 if (ret > 0) {
4587 /* XXX: better handling of removal */
4588 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4589 ioh_next = ioh->next;
4590 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4591 ioh->fd_read(ioh->opaque);
4593 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4594 ioh->fd_write(ioh->opaque);
4598 #if defined(CONFIG_SLIRP)
4599 if (slirp_inited) {
4600 if (ret < 0) {
4601 FD_ZERO(&rfds);
4602 FD_ZERO(&wfds);
4603 FD_ZERO(&xfds);
4605 slirp_select_poll(&rfds, &wfds, &xfds);
4607 #endif
4608 #ifdef _WIN32
4609 tap_win32_poll();
4610 #endif
4612 if (vm_running) {
4613 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4614 qemu_get_clock(vm_clock));
4615 /* run dma transfers, if any */
4616 DMA_run();
4619 /* real time timers */
4620 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4621 qemu_get_clock(rt_clock));
4624 #ifndef CONFIG_DM
4625 static CPUState *cur_cpu;
4627 int main_loop(void)
4629 int ret, timeout;
4630 #ifdef CONFIG_PROFILER
4631 int64_t ti;
4632 #endif
4633 CPUState *env;
4635 cur_cpu = first_cpu;
4636 for(;;) {
4637 if (vm_running) {
4639 env = cur_cpu;
4640 for(;;) {
4641 /* get next cpu */
4642 env = env->next_cpu;
4643 if (!env)
4644 env = first_cpu;
4645 #ifdef CONFIG_PROFILER
4646 ti = profile_getclock();
4647 #endif
4648 ret = cpu_exec(env);
4649 #ifdef CONFIG_PROFILER
4650 qemu_time += profile_getclock() - ti;
4651 #endif
4652 if (ret != EXCP_HALTED)
4653 break;
4654 /* all CPUs are halted ? */
4655 if (env == cur_cpu) {
4656 ret = EXCP_HLT;
4657 break;
4660 cur_cpu = env;
4662 if (shutdown_requested) {
4663 ret = EXCP_INTERRUPT;
4664 break;
4666 if (reset_requested) {
4667 reset_requested = 0;
4668 qemu_system_reset();
4669 ret = EXCP_INTERRUPT;
4671 if (powerdown_requested) {
4672 powerdown_requested = 0;
4673 qemu_system_powerdown();
4674 ret = EXCP_INTERRUPT;
4676 if (ret == EXCP_DEBUG) {
4677 vm_stop(EXCP_DEBUG);
4679 /* if hlt instruction, we wait until the next IRQ */
4680 /* XXX: use timeout computed from timers */
4681 if (ret == EXCP_HLT)
4682 timeout = 10;
4683 else
4684 timeout = 0;
4685 } else {
4686 timeout = 10;
4688 #ifdef CONFIG_PROFILER
4689 ti = profile_getclock();
4690 #endif
4691 main_loop_wait(timeout);
4692 #ifdef CONFIG_PROFILER
4693 dev_time += profile_getclock() - ti;
4694 #endif
4696 cpu_disable_ticks();
4697 return ret;
4699 #endif /* !CONFIG_DM */
4701 void help(void)
4703 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4704 "usage: %s [options] [disk_image]\n"
4705 "\n"
4706 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4707 "\n"
4708 "Standard options:\n"
4709 "-M machine select emulated machine (-M ? for list)\n"
4710 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4711 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4712 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4713 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4714 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4715 "-snapshot write to temporary files instead of disk image files\n"
4716 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4717 "-smp n set the number of CPUs to 'n' [default=1]\n"
4718 "-nographic disable graphical output and redirect serial I/Os to console\n"
4719 "-vcpus set CPU number of guest platform\n"
4720 #ifndef _WIN32
4721 "-k language use keyboard layout (for example \"fr\" for French)\n"
4722 #endif
4723 #ifdef HAS_AUDIO
4724 "-audio-help print list of audio drivers and their options\n"
4725 "-soundhw c1,... enable audio support\n"
4726 " and only specified sound cards (comma separated list)\n"
4727 " use -soundhw ? to get the list of supported cards\n"
4728 " use -soundhw all to enable all of them\n"
4729 #endif
4730 "-localtime set the real time clock to local time [default=utc]\n"
4731 "-full-screen start in full screen\n"
4732 #ifdef TARGET_I386
4733 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4734 #endif
4735 "-usb enable the USB driver (will be the default soon)\n"
4736 "-usbdevice name add the host or guest USB device 'name'\n"
4737 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4738 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4739 #endif
4740 "\n"
4741 "Network options:\n"
4742 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4743 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4744 #ifdef CONFIG_SLIRP
4745 "-net user[,vlan=n][,hostname=host]\n"
4746 " connect the user mode network stack to VLAN 'n' and send\n"
4747 " hostname 'host' to DHCP clients\n"
4748 #endif
4749 #ifdef _WIN32
4750 "-net tap[,vlan=n],ifname=name\n"
4751 " connect the host TAP network interface to VLAN 'n'\n"
4752 #else
4753 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
4754 " connect the host TAP network interface to VLAN 'n' and use\n"
4755 " the network script 'file' (default=%s);\n"
4756 " use 'fd=h' to connect to an already opened TAP interface\n"
4757 #endif
4758 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4759 " connect the vlan 'n' to another VLAN using a socket connection\n"
4760 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4761 " connect the vlan 'n' to multicast maddr and port\n"
4762 "-net none use it alone to have zero network devices; if no -net option\n"
4763 " is provided, the default is '-net nic -net user'\n"
4764 "\n"
4765 #ifdef CONFIG_SLIRP
4766 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4767 #ifndef _WIN32
4768 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4769 #endif
4770 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4771 " redirect TCP or UDP connections from host to guest [-net user]\n"
4772 #endif
4773 "\n"
4774 "Linux boot specific:\n"
4775 "-kernel bzImage use 'bzImage' as kernel image\n"
4776 "-append cmdline use 'cmdline' as kernel command line\n"
4777 "-initrd file use 'file' as initial ram disk\n"
4778 "\n"
4779 "Debug/Expert options:\n"
4780 "-monitor dev redirect the monitor to char device 'dev'\n"
4781 "-serial dev redirect the serial port to char device 'dev'\n"
4782 "-parallel dev redirect the parallel port to char device 'dev'\n"
4783 "-pidfile file Write PID to 'file'\n"
4784 "-S freeze CPU at startup (use 'c' to start execution)\n"
4785 "-s wait gdb connection to port %d\n"
4786 "-p port change gdb connection port\n"
4787 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
4788 "-d domain domain that we're serving\n"
4789 "-domain-name domain name that we're serving\n"
4790 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4791 " translation (t=none or lba) (usually qemu can guess them)\n"
4792 "-L path set the directory for the BIOS and VGA BIOS\n"
4793 #ifdef USE_KQEMU
4794 "-no-kqemu disable KQEMU kernel module usage\n"
4795 #endif
4796 #ifdef USE_CODE_COPY
4797 "-no-code-copy disable code copy acceleration\n"
4798 #endif
4799 #ifdef TARGET_I386
4800 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4801 " (default is CL-GD5446 PCI VGA)\n"
4802 #endif
4803 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4804 "-vnc display start a VNC server on display\n"
4805 "-vncviewer start a vncviewer process for this domain\n"
4806 "-timeoffset time offset (in seconds) from local time\n"
4807 "\n"
4808 "During emulation, the following keys are useful:\n"
4809 "ctrl-alt-f toggle full screen\n"
4810 "ctrl-alt-n switch to virtual console 'n'\n"
4811 "ctrl-alt toggle mouse and keyboard grab\n"
4812 "\n"
4813 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4815 #ifdef CONFIG_SOFTMMU
4816 "qemu",
4817 #else
4818 "qemu-fast",
4819 #endif
4820 DEFAULT_RAM_SIZE,
4821 #ifndef _WIN32
4822 DEFAULT_NETWORK_SCRIPT,
4823 #endif
4824 DEFAULT_GDBSTUB_PORT,
4825 "/tmp/qemu.log");
4826 #ifndef CONFIG_SOFTMMU
4827 printf("\n"
4828 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4829 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4830 "PC emulation.\n");
4831 #endif
4832 exit(1);
4835 #define HAS_ARG 0x0001
4837 enum {
4838 QEMU_OPTION_h,
4840 QEMU_OPTION_M,
4841 QEMU_OPTION_fda,
4842 QEMU_OPTION_fdb,
4843 QEMU_OPTION_hda,
4844 QEMU_OPTION_hdb,
4845 QEMU_OPTION_hdc,
4846 QEMU_OPTION_hdd,
4847 QEMU_OPTION_cdrom,
4848 QEMU_OPTION_boot,
4849 QEMU_OPTION_snapshot,
4850 QEMU_OPTION_m,
4851 QEMU_OPTION_nographic,
4852 #ifdef HAS_AUDIO
4853 QEMU_OPTION_audio_help,
4854 QEMU_OPTION_soundhw,
4855 #endif
4857 QEMU_OPTION_net,
4858 QEMU_OPTION_tftp,
4859 QEMU_OPTION_smb,
4860 QEMU_OPTION_redir,
4862 QEMU_OPTION_kernel,
4863 QEMU_OPTION_append,
4864 QEMU_OPTION_initrd,
4866 QEMU_OPTION_S,
4867 QEMU_OPTION_s,
4868 QEMU_OPTION_p,
4869 QEMU_OPTION_l,
4870 QEMU_OPTION_hdachs,
4871 QEMU_OPTION_L,
4872 #ifdef USE_CODE_COPY
4873 QEMU_OPTION_no_code_copy,
4874 #endif
4875 QEMU_OPTION_k,
4876 QEMU_OPTION_localtime,
4877 QEMU_OPTION_cirrusvga,
4878 QEMU_OPTION_g,
4879 QEMU_OPTION_std_vga,
4880 QEMU_OPTION_monitor,
4881 QEMU_OPTION_domainname,
4882 QEMU_OPTION_serial,
4883 QEMU_OPTION_parallel,
4884 QEMU_OPTION_loadvm,
4885 QEMU_OPTION_full_screen,
4886 QEMU_OPTION_pidfile,
4887 QEMU_OPTION_no_kqemu,
4888 QEMU_OPTION_kernel_kqemu,
4889 QEMU_OPTION_win2k_hack,
4890 QEMU_OPTION_usb,
4891 QEMU_OPTION_usbdevice,
4892 QEMU_OPTION_smp,
4893 QEMU_OPTION_vnc,
4894 QEMU_OPTION_vncviewer,
4896 QEMU_OPTION_d,
4897 QEMU_OPTION_vcpus,
4898 QEMU_OPTION_timeoffset,
4899 };
4901 typedef struct QEMUOption {
4902 const char *name;
4903 int flags;
4904 int index;
4905 } QEMUOption;
4907 const QEMUOption qemu_options[] = {
4908 { "h", 0, QEMU_OPTION_h },
4910 { "M", HAS_ARG, QEMU_OPTION_M },
4911 { "fda", HAS_ARG, QEMU_OPTION_fda },
4912 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4913 { "hda", HAS_ARG, QEMU_OPTION_hda },
4914 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4915 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4916 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4917 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4918 { "boot", HAS_ARG, QEMU_OPTION_boot },
4919 { "snapshot", 0, QEMU_OPTION_snapshot },
4920 { "m", HAS_ARG, QEMU_OPTION_m },
4921 { "nographic", 0, QEMU_OPTION_nographic },
4922 { "k", HAS_ARG, QEMU_OPTION_k },
4923 #ifdef HAS_AUDIO
4924 { "audio-help", 0, QEMU_OPTION_audio_help },
4925 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4926 #endif
4928 { "net", HAS_ARG, QEMU_OPTION_net},
4929 #ifdef CONFIG_SLIRP
4930 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4931 #ifndef _WIN32
4932 { "smb", HAS_ARG, QEMU_OPTION_smb },
4933 #endif
4934 { "redir", HAS_ARG, QEMU_OPTION_redir },
4935 #endif
4937 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4938 { "append", HAS_ARG, QEMU_OPTION_append },
4939 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4941 { "S", 0, QEMU_OPTION_S },
4942 { "s", 0, QEMU_OPTION_s },
4943 { "p", HAS_ARG, QEMU_OPTION_p },
4944 { "l", HAS_ARG, QEMU_OPTION_l },
4945 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4946 { "L", HAS_ARG, QEMU_OPTION_L },
4947 #ifdef USE_CODE_COPY
4948 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4949 #endif
4950 #ifdef USE_KQEMU
4951 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4952 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4953 #endif
4954 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4955 { "g", 1, QEMU_OPTION_g },
4956 #endif
4957 { "localtime", 0, QEMU_OPTION_localtime },
4958 { "std-vga", 0, QEMU_OPTION_std_vga },
4959 { "monitor", 1, QEMU_OPTION_monitor },
4960 { "domain-name", 1, QEMU_OPTION_domainname },
4961 { "serial", 1, QEMU_OPTION_serial },
4962 { "parallel", 1, QEMU_OPTION_parallel },
4963 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4964 { "full-screen", 0, QEMU_OPTION_full_screen },
4965 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4966 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4967 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4968 { "smp", HAS_ARG, QEMU_OPTION_smp },
4969 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4970 { "vncviewer", 0, QEMU_OPTION_vncviewer },
4972 /* temporary options */
4973 { "usb", 0, QEMU_OPTION_usb },
4974 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4976 { "d", HAS_ARG, QEMU_OPTION_d },
4977 { "vcpus", 1, QEMU_OPTION_vcpus },
4978 { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
4979 { NULL },
4980 };
4982 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4984 /* this stack is only used during signal handling */
4985 #define SIGNAL_STACK_SIZE 32768
4987 static uint8_t *signal_stack;
4989 #endif
4991 /* password input */
4993 static BlockDriverState *get_bdrv(int index)
4995 BlockDriverState *bs;
4997 if (index < 4) {
4998 bs = bs_table[index];
4999 } else if (index < 6) {
5000 bs = fd_table[index - 4];
5001 } else {
5002 bs = NULL;
5004 return bs;
5007 static void read_passwords(void)
5009 BlockDriverState *bs;
5010 int i, j;
5011 char password[256];
5013 for(i = 0; i < 6; i++) {
5014 bs = get_bdrv(i);
5015 if (bs && bdrv_is_encrypted(bs)) {
5016 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5017 for(j = 0; j < 3; j++) {
5018 monitor_readline("Password: ",
5019 1, password, sizeof(password));
5020 if (bdrv_set_key(bs, password) == 0)
5021 break;
5022 term_printf("invalid password\n");
5028 /* XXX: currently we cannot use simultaneously different CPUs */
5029 void register_machines(void)
5031 #if defined(TARGET_I386)
5032 qemu_register_machine(&pc_machine);
5033 qemu_register_machine(&isapc_machine);
5034 #elif defined(TARGET_PPC)
5035 qemu_register_machine(&heathrow_machine);
5036 qemu_register_machine(&core99_machine);
5037 qemu_register_machine(&prep_machine);
5038 #elif defined(TARGET_MIPS)
5039 qemu_register_machine(&mips_machine);
5040 #elif defined(TARGET_SPARC)
5041 #ifdef TARGET_SPARC64
5042 qemu_register_machine(&sun4u_machine);
5043 #else
5044 qemu_register_machine(&sun4m_machine);
5045 #endif
5046 #elif defined(TARGET_ARM)
5047 qemu_register_machine(&integratorcp926_machine);
5048 qemu_register_machine(&integratorcp1026_machine);
5049 qemu_register_machine(&versatilepb_machine);
5050 qemu_register_machine(&versatileab_machine);
5051 #elif defined(TARGET_SH4)
5052 qemu_register_machine(&shix_machine);
5053 #else
5054 #error unsupported CPU
5055 #endif
5058 #ifdef HAS_AUDIO
5059 struct soundhw soundhw[] = {
5060 #ifndef CONFIG_DM
5061 #ifdef TARGET_I386
5063 "pcspk",
5064 "PC speaker",
5065 0,
5066 1,
5067 { .init_isa = pcspk_audio_init }
5068 },
5069 #endif
5070 #endif /* !CONFIG_DM */
5072 "sb16",
5073 "Creative Sound Blaster 16",
5074 0,
5075 1,
5076 { .init_isa = SB16_init }
5077 },
5079 #ifdef CONFIG_ADLIB
5081 "adlib",
5082 #ifdef HAS_YMF262
5083 "Yamaha YMF262 (OPL3)",
5084 #else
5085 "Yamaha YM3812 (OPL2)",
5086 #endif
5087 0,
5088 1,
5089 { .init_isa = Adlib_init }
5090 },
5091 #endif
5093 #ifdef CONFIG_GUS
5095 "gus",
5096 "Gravis Ultrasound GF1",
5097 0,
5098 1,
5099 { .init_isa = GUS_init }
5100 },
5101 #endif
5104 "es1370",
5105 "ENSONIQ AudioPCI ES1370",
5106 0,
5107 0,
5108 { .init_pci = es1370_init }
5109 },
5111 { NULL, NULL, 0, 0, { NULL } }
5112 };
5114 static void select_soundhw (const char *optarg)
5116 struct soundhw *c;
5118 if (*optarg == '?') {
5119 show_valid_cards:
5121 printf ("Valid sound card names (comma separated):\n");
5122 for (c = soundhw; c->name; ++c) {
5123 printf ("%-11s %s\n", c->name, c->descr);
5125 printf ("\n-soundhw all will enable all of the above\n");
5126 exit (*optarg != '?');
5128 else {
5129 size_t l;
5130 const char *p;
5131 char *e;
5132 int bad_card = 0;
5134 if (!strcmp (optarg, "all")) {
5135 for (c = soundhw; c->name; ++c) {
5136 c->enabled = 1;
5138 return;
5141 p = optarg;
5142 while (*p) {
5143 e = strchr (p, ',');
5144 l = !e ? strlen (p) : (size_t) (e - p);
5146 for (c = soundhw; c->name; ++c) {
5147 if (!strncmp (c->name, p, l)) {
5148 c->enabled = 1;
5149 break;
5153 if (!c->name) {
5154 if (l > 80) {
5155 fprintf (stderr,
5156 "Unknown sound card name (too big to show)\n");
5158 else {
5159 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5160 (int) l, p);
5162 bad_card = 1;
5164 p += l + (e != NULL);
5167 if (bad_card)
5168 goto show_valid_cards;
5171 #endif
5173 #define MAX_NET_CLIENTS 32
5175 #include <xg_private.h>
5177 /* FIXME Flush the shadow page */
5178 int unset_mm_mapping(int xc_handle, uint32_t domid,
5179 unsigned long nr_pages, unsigned int address_bits,
5180 xen_pfn_t *extent_start)
5182 int err = 0;
5183 xc_dominfo_t info;
5185 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
5186 nr_pages, 0, extent_start);
5187 if (err)
5188 fprintf(stderr, "Failed to decrease physmap\n");
5190 xc_domain_getinfo(xc_handle, domid, 1, &info);
5192 if ((info.nr_pages - nr_pages) <= 0) {
5193 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
5194 err = -1;
5197 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
5198 PAGE_SIZE/1024) != 0) {
5199 fprintf(logfile, "set maxmem returned error %d\n", errno);
5200 err = -1;
5203 return err;
5206 int set_mm_mapping(int xc_handle, uint32_t domid,
5207 unsigned long nr_pages, unsigned int address_bits,
5208 xen_pfn_t *extent_start)
5210 #if 0
5211 int i;
5212 #endif
5213 xc_dominfo_t info;
5214 int err = 0;
5216 xc_domain_getinfo(xc_handle, domid, 1, &info);
5218 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
5219 nr_pages * PAGE_SIZE/1024) != 0) {
5220 fprintf(logfile, "set maxmem returned error %d\n", errno);
5221 return -1;
5224 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
5225 address_bits, extent_start);
5226 if (err) {
5227 fprintf(stderr, "Failed to populate physmap\n");
5228 return -1;
5231 err = xc_domain_translate_gpfn_list(xc_handle, domid, nr_pages,
5232 extent_start, extent_start);
5233 if (err) {
5234 fprintf(stderr, "Failed to translate gpfn list\n");
5235 return -1;
5238 #if 0 /* Generates lots of log file output - turn on for debugging */
5239 for (i = 0; i < nr_pages; i++)
5240 fprintf(stderr, "set_map result i %x result %lx\n", i,
5241 extent_start[i]);
5242 #endif
5244 return 0;
5247 int main(int argc, char **argv)
5249 #ifdef CONFIG_GDBSTUB
5250 int use_gdbstub, gdbstub_port;
5251 #endif
5252 int i, cdrom_index;
5253 int snapshot, linux_boot;
5254 const char *initrd_filename;
5255 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5256 const char *kernel_filename, *kernel_cmdline;
5257 DisplayState *ds = &display_state;
5258 int cyls, heads, secs, translation;
5259 int start_emulation = 1;
5260 char net_clients[MAX_NET_CLIENTS][256];
5261 int nb_net_clients;
5262 int optind;
5263 const char *r, *optarg;
5264 CharDriverState *monitor_hd;
5265 char monitor_device[128];
5266 char serial_devices[MAX_SERIAL_PORTS][128];
5267 int serial_device_index;
5268 char parallel_devices[MAX_PARALLEL_PORTS][128];
5269 int parallel_device_index;
5270 const char *loadvm = NULL;
5271 QEMUMachine *machine;
5272 char usb_devices[MAX_VM_USB_PORTS][128];
5273 int usb_devices_index;
5274 unsigned long nr_pages;
5275 xen_pfn_t *page_array;
5276 extern void *shared_page;
5278 char qemu_dm_logfilename[64];
5280 LIST_INIT (&vm_change_state_head);
5281 #if !defined(CONFIG_SOFTMMU)
5282 /* we never want that malloc() uses mmap() */
5283 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5284 #endif
5285 register_machines();
5286 machine = first_machine;
5287 initrd_filename = NULL;
5288 for(i = 0; i < MAX_FD; i++)
5289 fd_filename[i] = NULL;
5290 for(i = 0; i < MAX_DISKS; i++)
5291 hd_filename[i] = NULL;
5292 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5293 vga_ram_size = VGA_RAM_SIZE;
5294 bios_size = BIOS_SIZE;
5295 #ifdef CONFIG_GDBSTUB
5296 use_gdbstub = 0;
5297 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5298 #endif
5299 snapshot = 0;
5300 nographic = 0;
5301 vncviewer = 0;
5302 kernel_filename = NULL;
5303 kernel_cmdline = "";
5304 #ifdef TARGET_PPC
5305 cdrom_index = 1;
5306 #else
5307 cdrom_index = 2;
5308 #endif
5309 cyls = heads = secs = 0;
5310 translation = BIOS_ATA_TRANSLATION_AUTO;
5311 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5313 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5314 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5315 serial_devices[i][0] = '\0';
5316 serial_device_index = 0;
5318 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5319 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5320 parallel_devices[i][0] = '\0';
5321 parallel_device_index = 0;
5323 usb_devices_index = 0;
5325 nb_net_clients = 0;
5327 nb_nics = 0;
5328 /* default mac address of the first network interface */
5330 /* init debug */
5331 sprintf(qemu_dm_logfilename, "/var/log/qemu-dm.%d.log", getpid());
5332 cpu_set_log_filename(qemu_dm_logfilename);
5333 cpu_set_log(0);
5335 optind = 1;
5336 for(;;) {
5337 if (optind >= argc)
5338 break;
5339 r = argv[optind];
5340 if (r[0] != '-') {
5341 hd_filename[0] = argv[optind++];
5342 } else {
5343 const QEMUOption *popt;
5345 optind++;
5346 popt = qemu_options;
5347 for(;;) {
5348 if (!popt->name) {
5349 fprintf(stderr, "%s: invalid option -- '%s'\n",
5350 argv[0], r);
5351 exit(1);
5353 if (!strcmp(popt->name, r + 1))
5354 break;
5355 popt++;
5357 if (popt->flags & HAS_ARG) {
5358 if (optind >= argc) {
5359 fprintf(stderr, "%s: option '%s' requires an argument\n",
5360 argv[0], r);
5361 exit(1);
5363 optarg = argv[optind++];
5364 } else {
5365 optarg = NULL;
5368 switch(popt->index) {
5369 case QEMU_OPTION_M:
5370 machine = find_machine(optarg);
5371 if (!machine) {
5372 QEMUMachine *m;
5373 printf("Supported machines are:\n");
5374 for(m = first_machine; m != NULL; m = m->next) {
5375 printf("%-10s %s%s\n",
5376 m->name, m->desc,
5377 m == first_machine ? " (default)" : "");
5379 exit(1);
5381 break;
5382 case QEMU_OPTION_initrd:
5383 initrd_filename = optarg;
5384 break;
5385 case QEMU_OPTION_hda:
5386 case QEMU_OPTION_hdb:
5387 case QEMU_OPTION_hdc:
5388 case QEMU_OPTION_hdd:
5390 int hd_index;
5391 hd_index = popt->index - QEMU_OPTION_hda;
5392 hd_filename[hd_index] = optarg;
5393 if (hd_index == cdrom_index)
5394 cdrom_index = -1;
5396 break;
5397 case QEMU_OPTION_snapshot:
5398 snapshot = 1;
5399 break;
5400 case QEMU_OPTION_hdachs:
5402 const char *p;
5403 p = optarg;
5404 cyls = strtol(p, (char **)&p, 0);
5405 if (cyls < 1 || cyls > 16383)
5406 goto chs_fail;
5407 if (*p != ',')
5408 goto chs_fail;
5409 p++;
5410 heads = strtol(p, (char **)&p, 0);
5411 if (heads < 1 || heads > 16)
5412 goto chs_fail;
5413 if (*p != ',')
5414 goto chs_fail;
5415 p++;
5416 secs = strtol(p, (char **)&p, 0);
5417 if (secs < 1 || secs > 63)
5418 goto chs_fail;
5419 if (*p == ',') {
5420 p++;
5421 if (!strcmp(p, "none"))
5422 translation = BIOS_ATA_TRANSLATION_NONE;
5423 else if (!strcmp(p, "lba"))
5424 translation = BIOS_ATA_TRANSLATION_LBA;
5425 else if (!strcmp(p, "auto"))
5426 translation = BIOS_ATA_TRANSLATION_AUTO;
5427 else
5428 goto chs_fail;
5429 } else if (*p != '\0') {
5430 chs_fail:
5431 fprintf(stderr, "qemu: invalid physical CHS format\n");
5432 exit(1);
5435 break;
5436 case QEMU_OPTION_nographic:
5437 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5438 if(!strcmp(serial_devices[0], "vc"))
5439 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
5440 "stdio");
5441 nographic = 1;
5442 break;
5443 case QEMU_OPTION_kernel:
5444 kernel_filename = optarg;
5445 break;
5446 case QEMU_OPTION_append:
5447 kernel_cmdline = optarg;
5448 break;
5449 case QEMU_OPTION_cdrom:
5450 if (cdrom_index >= 0) {
5451 hd_filename[cdrom_index] = optarg;
5453 break;
5454 case QEMU_OPTION_boot:
5455 boot_device = optarg[0];
5456 if (boot_device != 'a' &&
5457 #ifdef TARGET_SPARC
5458 // Network boot
5459 boot_device != 'n' &&
5460 #endif
5461 boot_device != 'c' && boot_device != 'd') {
5462 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5463 exit(1);
5465 break;
5466 case QEMU_OPTION_fda:
5467 fd_filename[0] = optarg;
5468 break;
5469 case QEMU_OPTION_fdb:
5470 fd_filename[1] = optarg;
5471 break;
5472 #ifdef USE_CODE_COPY
5473 case QEMU_OPTION_no_code_copy:
5474 code_copy_enabled = 0;
5475 break;
5476 #endif
5477 case QEMU_OPTION_net:
5478 if (nb_net_clients >= MAX_NET_CLIENTS) {
5479 fprintf(stderr, "qemu: too many network clients\n");
5480 exit(1);
5482 pstrcpy(net_clients[nb_net_clients],
5483 sizeof(net_clients[0]),
5484 optarg);
5485 nb_net_clients++;
5486 break;
5487 #ifdef CONFIG_SLIRP
5488 case QEMU_OPTION_tftp:
5489 tftp_prefix = optarg;
5490 break;
5491 #ifndef _WIN32
5492 case QEMU_OPTION_smb:
5493 net_slirp_smb(optarg);
5494 break;
5495 #endif
5496 case QEMU_OPTION_redir:
5497 net_slirp_redir(optarg);
5498 break;
5499 #endif
5500 #ifdef HAS_AUDIO
5501 case QEMU_OPTION_audio_help:
5502 AUD_help ();
5503 exit (0);
5504 break;
5505 case QEMU_OPTION_soundhw:
5506 select_soundhw (optarg);
5507 break;
5508 #endif
5509 case QEMU_OPTION_h:
5510 help();
5511 break;
5512 case QEMU_OPTION_m:
5513 ram_size = atol(optarg) * 1024 * 1024;
5514 if (ram_size <= 0)
5515 help();
5516 #ifndef CONFIG_DM
5517 if (ram_size > PHYS_RAM_MAX_SIZE) {
5518 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5519 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5520 exit(1);
5522 #endif /* !CONFIG_DM */
5523 break;
5524 case QEMU_OPTION_l:
5526 int mask;
5527 CPULogItem *item;
5529 mask = cpu_str_to_log_mask(optarg);
5530 if (!mask) {
5531 printf("Log items (comma separated):\n");
5532 for(item = cpu_log_items; item->mask != 0; item++) {
5533 printf("%-10s %s\n", item->name, item->help);
5535 exit(1);
5537 cpu_set_log(mask);
5539 break;
5540 #ifdef CONFIG_GDBSTUB
5541 case QEMU_OPTION_s:
5542 use_gdbstub = 1;
5543 break;
5544 case QEMU_OPTION_p:
5545 gdbstub_port = atoi(optarg);
5546 break;
5547 #endif
5548 case QEMU_OPTION_L:
5549 bios_dir = optarg;
5550 break;
5551 case QEMU_OPTION_S:
5552 start_emulation = 0;
5553 break;
5554 case QEMU_OPTION_k:
5555 keyboard_layout = optarg;
5556 break;
5557 case QEMU_OPTION_localtime:
5558 rtc_utc = 0;
5559 break;
5560 case QEMU_OPTION_cirrusvga:
5561 cirrus_vga_enabled = 1;
5562 break;
5563 case QEMU_OPTION_std_vga:
5564 cirrus_vga_enabled = 0;
5565 break;
5566 case QEMU_OPTION_g:
5568 const char *p;
5569 int w, h, depth;
5570 p = optarg;
5571 w = strtol(p, (char **)&p, 10);
5572 if (w <= 0) {
5573 graphic_error:
5574 fprintf(stderr, "qemu: invalid resolution or depth\n");
5575 exit(1);
5577 if (*p != 'x')
5578 goto graphic_error;
5579 p++;
5580 h = strtol(p, (char **)&p, 10);
5581 if (h <= 0)
5582 goto graphic_error;
5583 if (*p == 'x') {
5584 p++;
5585 depth = strtol(p, (char **)&p, 10);
5586 if (depth != 8 && depth != 15 && depth != 16 &&
5587 depth != 24 && depth != 32)
5588 goto graphic_error;
5589 } else if (*p == '\0') {
5590 depth = graphic_depth;
5591 } else {
5592 goto graphic_error;
5595 graphic_width = w;
5596 graphic_height = h;
5597 graphic_depth = depth;
5599 break;
5600 case QEMU_OPTION_monitor:
5601 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5602 break;
5603 case QEMU_OPTION_serial:
5604 if (serial_device_index >= MAX_SERIAL_PORTS) {
5605 fprintf(stderr, "qemu: too many serial ports\n");
5606 exit(1);
5608 pstrcpy(serial_devices[serial_device_index],
5609 sizeof(serial_devices[0]), optarg);
5610 serial_device_index++;
5611 break;
5612 case QEMU_OPTION_parallel:
5613 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5614 fprintf(stderr, "qemu: too many parallel ports\n");
5615 exit(1);
5617 pstrcpy(parallel_devices[parallel_device_index],
5618 sizeof(parallel_devices[0]), optarg);
5619 parallel_device_index++;
5620 break;
5621 case QEMU_OPTION_loadvm:
5622 loadvm = optarg;
5623 break;
5624 case QEMU_OPTION_full_screen:
5625 full_screen = 1;
5626 break;
5627 case QEMU_OPTION_pidfile:
5628 create_pidfile(optarg);
5629 break;
5630 #ifdef TARGET_I386
5631 case QEMU_OPTION_win2k_hack:
5632 win2k_install_hack = 1;
5633 break;
5634 #endif
5635 #ifdef USE_KQEMU
5636 case QEMU_OPTION_no_kqemu:
5637 kqemu_allowed = 0;
5638 break;
5639 case QEMU_OPTION_kernel_kqemu:
5640 kqemu_allowed = 2;
5641 break;
5642 #endif
5643 case QEMU_OPTION_usb:
5644 usb_enabled = 1;
5645 break;
5646 case QEMU_OPTION_usbdevice:
5647 usb_enabled = 1;
5648 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5649 fprintf(stderr, "Too many USB devices\n");
5650 exit(1);
5652 pstrcpy(usb_devices[usb_devices_index],
5653 sizeof(usb_devices[usb_devices_index]),
5654 optarg);
5655 usb_devices_index++;
5656 break;
5657 case QEMU_OPTION_smp:
5658 smp_cpus = atoi(optarg);
5659 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5660 fprintf(stderr, "Invalid number of CPUs\n");
5661 exit(1);
5663 break;
5664 case QEMU_OPTION_vnc:
5665 vnc_display = atoi(optarg);
5666 if (vnc_display < 0) {
5667 fprintf(stderr, "Invalid VNC display\n");
5668 exit(1);
5670 break;
5671 case QEMU_OPTION_vncviewer:
5672 vncviewer++;
5673 break;
5674 case QEMU_OPTION_domainname:
5675 strncat(domain_name, optarg, sizeof(domain_name) - 20);
5676 break;
5677 case QEMU_OPTION_d:
5678 domid = atoi(optarg);
5679 fprintf(logfile, "domid: %d\n", domid);
5680 break;
5681 case QEMU_OPTION_vcpus:
5682 vcpus = atoi(optarg);
5683 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
5684 break;
5685 case QEMU_OPTION_timeoffset:
5686 timeoffset = strtol(optarg, NULL, 0);
5687 break;
5692 #ifdef USE_KQEMU
5693 if (smp_cpus > 1)
5694 kqemu_allowed = 0;
5695 #endif
5696 linux_boot = (kernel_filename != NULL);
5698 if (!linux_boot &&
5699 hd_filename[0] == '\0' &&
5700 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5701 fd_filename[0] == '\0')
5702 help();
5704 /* boot to cd by default if no hard disk */
5705 if (hd_filename[0] == '\0' && boot_device == 'c') {
5706 if (fd_filename[0] != '\0')
5707 boot_device = 'a';
5708 else
5709 boot_device = 'd';
5712 #if !defined(CONFIG_SOFTMMU)
5713 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5715 static uint8_t stdout_buf[4096];
5716 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5718 #else
5719 setvbuf(stdout, NULL, _IOLBF, 0);
5720 #endif
5722 #ifdef _WIN32
5723 socket_init();
5724 #endif
5726 #ifndef CONFIG_DM
5727 /* init network clients */
5728 if (nb_net_clients == 0) {
5729 /* if no clients, we use a default config */
5730 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5731 "nic");
5732 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5733 "user");
5734 nb_net_clients = 2;
5736 #endif /* !CONFIG_DM */
5738 for(i = 0;i < nb_net_clients; i++) {
5739 if (net_client_init(net_clients[i]) < 0)
5740 exit(1);
5743 /* init the memory */
5744 phys_ram_size = ram_size + vga_ram_size + bios_size;
5746 #ifdef CONFIG_DM
5748 nr_pages = ram_size/PAGE_SIZE;
5749 xc_handle = xc_interface_open();
5751 page_array = (xen_pfn_t *)malloc(nr_pages * sizeof(xen_pfn_t));
5752 if (page_array == NULL) {
5753 fprintf(logfile, "malloc returned error %d\n", errno);
5754 exit(-1);
5757 #if defined(__i386__) || defined(__x86_64__)
5758 if (xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages) {
5759 fprintf(logfile, "xc_get_pfn_list returned error %d\n", errno);
5760 exit(-1);
5763 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
5764 PROT_READ|PROT_WRITE, page_array,
5765 nr_pages - 1);
5766 if (phys_ram_base == 0) {
5767 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
5768 exit(-1);
5771 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
5772 PROT_READ|PROT_WRITE,
5773 page_array[nr_pages - 1]);
5775 fprintf(logfile, "shared page at pfn:%lx, mfn: %"PRIx64"\n", nr_pages - 1,
5776 (uint64_t)(page_array[nr_pages - 1]));
5778 #elif defined(__ia64__)
5779 if (xc_ia64_get_pfn_list(xc_handle, domid,
5780 page_array, 0, nr_pages) != nr_pages) {
5781 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
5782 exit(-1);
5785 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
5786 PROT_READ|PROT_WRITE,
5787 page_array, nr_pages);
5788 if (phys_ram_base == 0) {
5789 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
5790 exit(-1);
5793 if (xc_ia64_get_pfn_list(xc_handle, domid, page_array,
5794 nr_pages + (GFW_SIZE >> PAGE_SHIFT), 1)!= 1){
5795 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
5796 exit(-1);
5799 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
5800 PROT_READ|PROT_WRITE,
5801 page_array[0]);
5803 fprintf(logfile, "shared page at pfn:%lx, mfn: %l016x\n",
5804 IO_PAGE_START >> PAGE_SHIFT, page_array[0]);
5805 #endif
5806 #else /* !CONFIG_DM */
5808 #ifdef CONFIG_SOFTMMU
5809 phys_ram_base = qemu_vmalloc(phys_ram_size);
5810 if (!phys_ram_base) {
5811 fprintf(stderr, "Could not allocate physical memory\n");
5812 exit(1);
5814 #else
5815 /* as we must map the same page at several addresses, we must use
5816 a fd */
5818 const char *tmpdir;
5820 tmpdir = getenv("QEMU_TMPDIR");
5821 if (!tmpdir)
5822 tmpdir = "/tmp";
5823 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5824 if (mkstemp(phys_ram_file) < 0) {
5825 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5826 phys_ram_file);
5827 exit(1);
5829 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5830 if (phys_ram_fd < 0) {
5831 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5832 phys_ram_file);
5833 exit(1);
5835 ftruncate(phys_ram_fd, phys_ram_size);
5836 unlink(phys_ram_file);
5837 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5838 phys_ram_size,
5839 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5840 phys_ram_fd, 0);
5841 if (phys_ram_base == MAP_FAILED) {
5842 fprintf(stderr, "Could not map physical memory\n");
5843 exit(1);
5846 #endif
5848 #endif /* !CONFIG_DM */
5850 /* we always create the cdrom drive, even if no disk is there */
5851 bdrv_init();
5852 if (cdrom_index >= 0) {
5853 bs_table[cdrom_index] = bdrv_new("cdrom");
5854 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5857 /* open the virtual block devices */
5858 for(i = 0; i < MAX_DISKS; i++) {
5859 if (hd_filename[i]) {
5860 if (!bs_table[i]) {
5861 char buf[64];
5862 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5863 bs_table[i] = bdrv_new(buf);
5865 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5866 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5867 hd_filename[i]);
5868 exit(1);
5870 if (i == 0 && cyls != 0) {
5871 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5872 bdrv_set_translation_hint(bs_table[i], translation);
5877 /* we always create at least one floppy disk */
5878 fd_table[0] = bdrv_new("fda");
5879 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5881 for(i = 0; i < MAX_FD; i++) {
5882 if (fd_filename[i]) {
5883 if (!fd_table[i]) {
5884 char buf[64];
5885 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5886 fd_table[i] = bdrv_new(buf);
5887 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5889 if (fd_filename[i] != '\0') {
5890 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5891 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5892 fd_filename[i]);
5893 exit(1);
5899 /* init USB devices */
5900 if (usb_enabled) {
5901 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5902 for(i = 0; i < usb_devices_index; i++) {
5903 if (usb_device_add(usb_devices[i]) < 0) {
5904 fprintf(stderr, "Warning: could not add USB device %s\n",
5905 usb_devices[i]);
5910 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5911 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5913 init_ioports();
5914 cpu_calibrate_ticks();
5916 /* terminal init */
5917 if (nographic) {
5918 dumb_display_init(ds);
5919 } else if (vnc_display != -1) {
5920 vnc_display_init(ds, vnc_display);
5921 if (vncviewer)
5922 vnc_start_viewer(vnc_display);
5923 } else {
5924 #if defined(CONFIG_SDL)
5925 sdl_display_init(ds, full_screen);
5926 #elif defined(CONFIG_COCOA)
5927 cocoa_display_init(ds, full_screen);
5928 #else
5929 dumb_display_init(ds);
5930 #endif
5933 monitor_hd = qemu_chr_open(monitor_device);
5934 if (!monitor_hd) {
5935 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5936 exit(1);
5938 monitor_init(monitor_hd, !nographic);
5940 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5941 if (serial_devices[i][0] != '\0') {
5942 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5943 if (!serial_hds[i]) {
5944 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5945 serial_devices[i]);
5946 exit(1);
5948 if (!strcmp(serial_devices[i], "vc"))
5949 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5953 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5954 if (parallel_devices[i][0] != '\0') {
5955 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5956 if (!parallel_hds[i]) {
5957 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5958 parallel_devices[i]);
5959 exit(1);
5961 if (!strcmp(parallel_devices[i], "vc"))
5962 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5966 /* setup cpu signal handlers for MMU / self modifying code handling */
5967 #if !defined(CONFIG_SOFTMMU)
5969 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5971 stack_t stk;
5972 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5973 stk.ss_sp = signal_stack;
5974 stk.ss_size = SIGNAL_STACK_SIZE;
5975 stk.ss_flags = 0;
5977 if (sigaltstack(&stk, NULL) < 0) {
5978 fprintf(logfile, "sigaltstack returned error %d\n", errno);
5979 exit(1);
5982 #endif
5984 struct sigaction act;
5986 sigfillset(&act.sa_mask);
5987 act.sa_flags = SA_SIGINFO;
5988 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5989 act.sa_flags |= SA_ONSTACK;
5990 #endif
5991 act.sa_sigaction = host_segv_handler;
5992 sigaction(SIGSEGV, &act, NULL);
5993 sigaction(SIGBUS, &act, NULL);
5994 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5995 sigaction(SIGFPE, &act, NULL);
5996 #endif
5998 #endif
6000 #ifndef _WIN32
6002 struct sigaction act;
6003 sigfillset(&act.sa_mask);
6004 act.sa_flags = 0;
6005 act.sa_handler = SIG_IGN;
6006 sigaction(SIGPIPE, &act, NULL);
6008 #endif
6009 init_timers();
6011 machine->init(ram_size, vga_ram_size, boot_device,
6012 ds, fd_filename, snapshot,
6013 kernel_filename, kernel_cmdline, initrd_filename,
6014 timeoffset);
6016 if (vnc_display == -1) {
6017 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6018 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6021 #ifdef CONFIG_GDBSTUB
6022 if (use_gdbstub) {
6023 if (gdbserver_start(gdbstub_port) < 0) {
6024 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6025 gdbstub_port);
6026 exit(1);
6027 } else {
6028 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6030 } else
6031 #endif
6032 if (loadvm)
6033 qemu_loadvm(loadvm);
6036 /* XXX: simplify init */
6037 read_passwords();
6038 if (start_emulation) {
6039 vm_start();
6042 main_loop();
6043 quit_timers();
6044 return 0;