Only use /dev/shm hack when kqemu is enabled.
[qemu/mini2440.git] / vl.c
blobb641299cd7b8e054db2e956e2fdcd27043e9ca97
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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 <dirent.h>
43 #include <netdb.h>
44 #ifdef _BSD
45 #include <sys/stat.h>
46 #ifndef __APPLE__
47 #include <libutil.h>
48 #endif
49 #else
50 #ifndef __sun__
51 #include <linux/if.h>
52 #include <linux/if_tun.h>
53 #include <pty.h>
54 #include <malloc.h>
55 #include <linux/rtc.h>
56 #include <linux/ppdev.h>
57 #endif
58 #endif
59 #endif
61 #if defined(CONFIG_SLIRP)
62 #include "libslirp.h"
63 #endif
65 #ifdef _WIN32
66 #include <malloc.h>
67 #include <sys/timeb.h>
68 #include <windows.h>
69 #define getopt_long_only getopt_long
70 #define memalign(align, size) malloc(size)
71 #endif
73 #include "qemu_socket.h"
75 #ifdef CONFIG_SDL
76 #ifdef __APPLE__
77 #include <SDL/SDL.h>
78 #endif
79 #endif /* CONFIG_SDL */
81 #ifdef CONFIG_COCOA
82 #undef main
83 #define main qemu_main
84 #endif /* CONFIG_COCOA */
86 #include "disas.h"
88 #include "exec-all.h"
90 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92 //#define DEBUG_UNUSED_IOPORT
93 //#define DEBUG_IOPORT
95 #if !defined(CONFIG_SOFTMMU)
96 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
97 #else
98 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
99 #endif
101 #ifdef TARGET_PPC
102 #define DEFAULT_RAM_SIZE 144
103 #else
104 #define DEFAULT_RAM_SIZE 128
105 #endif
106 /* in ms */
107 #define GUI_REFRESH_INTERVAL 30
109 /* Max number of USB devices that can be specified on the commandline. */
110 #define MAX_USB_CMDLINE 8
112 /* XXX: use a two level table to limit memory usage */
113 #define MAX_IOPORTS 65536
115 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
116 char phys_ram_file[1024];
117 void *ioport_opaque[MAX_IOPORTS];
118 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
119 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
120 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
121 int vga_ram_size;
122 int bios_size;
123 static DisplayState display_state;
124 int nographic;
125 const char* keyboard_layout = NULL;
126 int64_t ticks_per_sec;
127 int boot_device = 'c';
128 int 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 static VLANState *first_vlan;
152 int smp_cpus = 1;
153 int vnc_display = -1;
154 #if defined(TARGET_SPARC)
155 #define MAX_CPUS 16
156 #elif defined(TARGET_I386)
157 #define MAX_CPUS 255
158 #else
159 #define MAX_CPUS 1
160 #endif
161 int acpi_enabled = 1;
163 /***********************************************************/
164 /* x86 ISA bus support */
166 target_phys_addr_t isa_mem_base = 0;
167 PicState2 *isa_pic;
169 uint32_t default_ioport_readb(void *opaque, uint32_t address)
171 #ifdef DEBUG_UNUSED_IOPORT
172 fprintf(stderr, "inb: port=0x%04x\n", address);
173 #endif
174 return 0xff;
177 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
179 #ifdef DEBUG_UNUSED_IOPORT
180 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
181 #endif
184 /* default is to make two byte accesses */
185 uint32_t default_ioport_readw(void *opaque, uint32_t address)
187 uint32_t data;
188 data = ioport_read_table[0][address](ioport_opaque[address], address);
189 address = (address + 1) & (MAX_IOPORTS - 1);
190 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
191 return data;
194 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
196 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
197 address = (address + 1) & (MAX_IOPORTS - 1);
198 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
201 uint32_t default_ioport_readl(void *opaque, uint32_t address)
203 #ifdef DEBUG_UNUSED_IOPORT
204 fprintf(stderr, "inl: port=0x%04x\n", address);
205 #endif
206 return 0xffffffff;
209 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
211 #ifdef DEBUG_UNUSED_IOPORT
212 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
213 #endif
216 void init_ioports(void)
218 int i;
220 for(i = 0; i < MAX_IOPORTS; i++) {
221 ioport_read_table[0][i] = default_ioport_readb;
222 ioport_write_table[0][i] = default_ioport_writeb;
223 ioport_read_table[1][i] = default_ioport_readw;
224 ioport_write_table[1][i] = default_ioport_writew;
225 ioport_read_table[2][i] = default_ioport_readl;
226 ioport_write_table[2][i] = default_ioport_writel;
230 /* size is the word size in byte */
231 int register_ioport_read(int start, int length, int size,
232 IOPortReadFunc *func, void *opaque)
234 int i, bsize;
236 if (size == 1) {
237 bsize = 0;
238 } else if (size == 2) {
239 bsize = 1;
240 } else if (size == 4) {
241 bsize = 2;
242 } else {
243 hw_error("register_ioport_read: invalid size");
244 return -1;
246 for(i = start; i < start + length; i += size) {
247 ioport_read_table[bsize][i] = func;
248 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
249 hw_error("register_ioport_read: invalid opaque");
250 ioport_opaque[i] = opaque;
252 return 0;
255 /* size is the word size in byte */
256 int register_ioport_write(int start, int length, int size,
257 IOPortWriteFunc *func, void *opaque)
259 int i, bsize;
261 if (size == 1) {
262 bsize = 0;
263 } else if (size == 2) {
264 bsize = 1;
265 } else if (size == 4) {
266 bsize = 2;
267 } else {
268 hw_error("register_ioport_write: invalid size");
269 return -1;
271 for(i = start; i < start + length; i += size) {
272 ioport_write_table[bsize][i] = func;
273 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
274 hw_error("register_ioport_read: invalid opaque");
275 ioport_opaque[i] = opaque;
277 return 0;
280 void isa_unassign_ioport(int start, int length)
282 int i;
284 for(i = start; i < start + length; i++) {
285 ioport_read_table[0][i] = default_ioport_readb;
286 ioport_read_table[1][i] = default_ioport_readw;
287 ioport_read_table[2][i] = default_ioport_readl;
289 ioport_write_table[0][i] = default_ioport_writeb;
290 ioport_write_table[1][i] = default_ioport_writew;
291 ioport_write_table[2][i] = default_ioport_writel;
295 /***********************************************************/
297 void pstrcpy(char *buf, int buf_size, const char *str)
299 int c;
300 char *q = buf;
302 if (buf_size <= 0)
303 return;
305 for(;;) {
306 c = *str++;
307 if (c == 0 || q >= buf + buf_size - 1)
308 break;
309 *q++ = c;
311 *q = '\0';
314 /* strcat and truncate. */
315 char *pstrcat(char *buf, int buf_size, const char *s)
317 int len;
318 len = strlen(buf);
319 if (len < buf_size)
320 pstrcpy(buf + len, buf_size - len, s);
321 return buf;
324 int strstart(const char *str, const char *val, const char **ptr)
326 const char *p, *q;
327 p = str;
328 q = val;
329 while (*q != '\0') {
330 if (*p != *q)
331 return 0;
332 p++;
333 q++;
335 if (ptr)
336 *ptr = p;
337 return 1;
340 void cpu_outb(CPUState *env, int addr, int val)
342 #ifdef DEBUG_IOPORT
343 if (loglevel & CPU_LOG_IOPORT)
344 fprintf(logfile, "outb: %04x %02x\n", addr, val);
345 #endif
346 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
347 #ifdef USE_KQEMU
348 if (env)
349 env->last_io_time = cpu_get_time_fast();
350 #endif
353 void cpu_outw(CPUState *env, int addr, int val)
355 #ifdef DEBUG_IOPORT
356 if (loglevel & CPU_LOG_IOPORT)
357 fprintf(logfile, "outw: %04x %04x\n", addr, val);
358 #endif
359 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
360 #ifdef USE_KQEMU
361 if (env)
362 env->last_io_time = cpu_get_time_fast();
363 #endif
366 void cpu_outl(CPUState *env, int addr, int val)
368 #ifdef DEBUG_IOPORT
369 if (loglevel & CPU_LOG_IOPORT)
370 fprintf(logfile, "outl: %04x %08x\n", addr, val);
371 #endif
372 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
373 #ifdef USE_KQEMU
374 if (env)
375 env->last_io_time = cpu_get_time_fast();
376 #endif
379 int cpu_inb(CPUState *env, int addr)
381 int val;
382 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
383 #ifdef DEBUG_IOPORT
384 if (loglevel & CPU_LOG_IOPORT)
385 fprintf(logfile, "inb : %04x %02x\n", addr, val);
386 #endif
387 #ifdef USE_KQEMU
388 if (env)
389 env->last_io_time = cpu_get_time_fast();
390 #endif
391 return val;
394 int cpu_inw(CPUState *env, int addr)
396 int val;
397 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
398 #ifdef DEBUG_IOPORT
399 if (loglevel & CPU_LOG_IOPORT)
400 fprintf(logfile, "inw : %04x %04x\n", addr, val);
401 #endif
402 #ifdef USE_KQEMU
403 if (env)
404 env->last_io_time = cpu_get_time_fast();
405 #endif
406 return val;
409 int cpu_inl(CPUState *env, int addr)
411 int val;
412 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
413 #ifdef DEBUG_IOPORT
414 if (loglevel & CPU_LOG_IOPORT)
415 fprintf(logfile, "inl : %04x %08x\n", addr, val);
416 #endif
417 #ifdef USE_KQEMU
418 if (env)
419 env->last_io_time = cpu_get_time_fast();
420 #endif
421 return val;
424 /***********************************************************/
425 void hw_error(const char *fmt, ...)
427 va_list ap;
428 CPUState *env;
430 va_start(ap, fmt);
431 fprintf(stderr, "qemu: hardware error: ");
432 vfprintf(stderr, fmt, ap);
433 fprintf(stderr, "\n");
434 for(env = first_cpu; env != NULL; env = env->next_cpu) {
435 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
436 #ifdef TARGET_I386
437 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
438 #else
439 cpu_dump_state(env, stderr, fprintf, 0);
440 #endif
442 va_end(ap);
443 abort();
446 /***********************************************************/
447 /* keyboard/mouse */
449 static QEMUPutKBDEvent *qemu_put_kbd_event;
450 static void *qemu_put_kbd_event_opaque;
451 static QEMUPutMouseEvent *qemu_put_mouse_event;
452 static void *qemu_put_mouse_event_opaque;
453 static int qemu_put_mouse_event_absolute;
455 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
457 qemu_put_kbd_event_opaque = opaque;
458 qemu_put_kbd_event = func;
461 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
463 qemu_put_mouse_event_opaque = opaque;
464 qemu_put_mouse_event = func;
465 qemu_put_mouse_event_absolute = absolute;
468 void kbd_put_keycode(int keycode)
470 if (qemu_put_kbd_event) {
471 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
475 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
477 if (qemu_put_mouse_event) {
478 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
479 dx, dy, dz, buttons_state);
483 int kbd_mouse_is_absolute(void)
485 return qemu_put_mouse_event_absolute;
488 /***********************************************************/
489 /* timers */
491 #if defined(__powerpc__)
493 static inline uint32_t get_tbl(void)
495 uint32_t tbl;
496 asm volatile("mftb %0" : "=r" (tbl));
497 return tbl;
500 static inline uint32_t get_tbu(void)
502 uint32_t tbl;
503 asm volatile("mftbu %0" : "=r" (tbl));
504 return tbl;
507 int64_t cpu_get_real_ticks(void)
509 uint32_t l, h, h1;
510 /* NOTE: we test if wrapping has occurred */
511 do {
512 h = get_tbu();
513 l = get_tbl();
514 h1 = get_tbu();
515 } while (h != h1);
516 return ((int64_t)h << 32) | l;
519 #elif defined(__i386__)
521 int64_t cpu_get_real_ticks(void)
523 #ifdef _WIN32
524 LARGE_INTEGER ti;
525 QueryPerformanceCounter(&ti);
526 return ti.QuadPart;
527 #else
528 int64_t val;
529 asm volatile ("rdtsc" : "=A" (val));
530 return val;
531 #endif
534 #elif defined(__x86_64__)
536 int64_t cpu_get_real_ticks(void)
538 uint32_t low,high;
539 int64_t val;
540 asm volatile("rdtsc" : "=a" (low), "=d" (high));
541 val = high;
542 val <<= 32;
543 val |= low;
544 return val;
547 #elif defined(__ia64)
549 int64_t cpu_get_real_ticks(void)
551 int64_t val;
552 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
553 return val;
556 #elif defined(__s390__)
558 int64_t cpu_get_real_ticks(void)
560 int64_t val;
561 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
562 return val;
565 #else
566 #error unsupported CPU
567 #endif
569 static int64_t cpu_ticks_prev;
570 static int64_t cpu_ticks_offset;
571 static int cpu_ticks_enabled;
573 static inline int64_t cpu_get_ticks(void)
575 if (!cpu_ticks_enabled) {
576 return cpu_ticks_offset;
577 } else {
578 int64_t ticks;
579 ticks = cpu_get_real_ticks();
580 if (cpu_ticks_prev > ticks) {
581 /* Note: non increasing ticks may happen if the host uses
582 software suspend */
583 cpu_ticks_offset += cpu_ticks_prev - ticks;
585 cpu_ticks_prev = ticks;
586 return ticks + cpu_ticks_offset;
590 /* enable cpu_get_ticks() */
591 void cpu_enable_ticks(void)
593 if (!cpu_ticks_enabled) {
594 cpu_ticks_offset -= cpu_get_real_ticks();
595 cpu_ticks_enabled = 1;
599 /* disable cpu_get_ticks() : the clock is stopped. You must not call
600 cpu_get_ticks() after that. */
601 void cpu_disable_ticks(void)
603 if (cpu_ticks_enabled) {
604 cpu_ticks_offset = cpu_get_ticks();
605 cpu_ticks_enabled = 0;
609 #ifdef _WIN32
610 void cpu_calibrate_ticks(void)
612 LARGE_INTEGER freq;
613 int ret;
615 ret = QueryPerformanceFrequency(&freq);
616 if (ret == 0) {
617 fprintf(stderr, "Could not calibrate ticks\n");
618 exit(1);
620 ticks_per_sec = freq.QuadPart;
623 #else
624 static int64_t get_clock(void)
626 struct timeval tv;
627 gettimeofday(&tv, NULL);
628 return tv.tv_sec * 1000000LL + tv.tv_usec;
631 void cpu_calibrate_ticks(void)
633 int64_t usec, ticks;
635 usec = get_clock();
636 ticks = cpu_get_real_ticks();
637 usleep(50 * 1000);
638 usec = get_clock() - usec;
639 ticks = cpu_get_real_ticks() - ticks;
640 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
642 #endif /* !_WIN32 */
644 /* compute with 96 bit intermediate result: (a*b)/c */
645 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
647 union {
648 uint64_t ll;
649 struct {
650 #ifdef WORDS_BIGENDIAN
651 uint32_t high, low;
652 #else
653 uint32_t low, high;
654 #endif
655 } l;
656 } u, res;
657 uint64_t rl, rh;
659 u.ll = a;
660 rl = (uint64_t)u.l.low * (uint64_t)b;
661 rh = (uint64_t)u.l.high * (uint64_t)b;
662 rh += (rl >> 32);
663 res.l.high = rh / c;
664 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
665 return res.ll;
668 #define QEMU_TIMER_REALTIME 0
669 #define QEMU_TIMER_VIRTUAL 1
671 struct QEMUClock {
672 int type;
673 /* XXX: add frequency */
676 struct QEMUTimer {
677 QEMUClock *clock;
678 int64_t expire_time;
679 QEMUTimerCB *cb;
680 void *opaque;
681 struct QEMUTimer *next;
684 QEMUClock *rt_clock;
685 QEMUClock *vm_clock;
687 static QEMUTimer *active_timers[2];
688 #ifdef _WIN32
689 static MMRESULT timerID;
690 static HANDLE host_alarm = NULL;
691 static unsigned int period = 1;
692 #else
693 /* frequency of the times() clock tick */
694 static int timer_freq;
695 #endif
697 QEMUClock *qemu_new_clock(int type)
699 QEMUClock *clock;
700 clock = qemu_mallocz(sizeof(QEMUClock));
701 if (!clock)
702 return NULL;
703 clock->type = type;
704 return clock;
707 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
709 QEMUTimer *ts;
711 ts = qemu_mallocz(sizeof(QEMUTimer));
712 ts->clock = clock;
713 ts->cb = cb;
714 ts->opaque = opaque;
715 return ts;
718 void qemu_free_timer(QEMUTimer *ts)
720 qemu_free(ts);
723 /* stop a timer, but do not dealloc it */
724 void qemu_del_timer(QEMUTimer *ts)
726 QEMUTimer **pt, *t;
728 /* NOTE: this code must be signal safe because
729 qemu_timer_expired() can be called from a signal. */
730 pt = &active_timers[ts->clock->type];
731 for(;;) {
732 t = *pt;
733 if (!t)
734 break;
735 if (t == ts) {
736 *pt = t->next;
737 break;
739 pt = &t->next;
743 /* modify the current timer so that it will be fired when current_time
744 >= expire_time. The corresponding callback will be called. */
745 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
747 QEMUTimer **pt, *t;
749 qemu_del_timer(ts);
751 /* add the timer in the sorted list */
752 /* NOTE: this code must be signal safe because
753 qemu_timer_expired() can be called from a signal. */
754 pt = &active_timers[ts->clock->type];
755 for(;;) {
756 t = *pt;
757 if (!t)
758 break;
759 if (t->expire_time > expire_time)
760 break;
761 pt = &t->next;
763 ts->expire_time = expire_time;
764 ts->next = *pt;
765 *pt = ts;
768 int qemu_timer_pending(QEMUTimer *ts)
770 QEMUTimer *t;
771 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
772 if (t == ts)
773 return 1;
775 return 0;
778 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
780 if (!timer_head)
781 return 0;
782 return (timer_head->expire_time <= current_time);
785 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
787 QEMUTimer *ts;
789 for(;;) {
790 ts = *ptimer_head;
791 if (!ts || ts->expire_time > current_time)
792 break;
793 /* remove timer from the list before calling the callback */
794 *ptimer_head = ts->next;
795 ts->next = NULL;
797 /* run the callback (the timer list can be modified) */
798 ts->cb(ts->opaque);
802 int64_t qemu_get_clock(QEMUClock *clock)
804 switch(clock->type) {
805 case QEMU_TIMER_REALTIME:
806 #ifdef _WIN32
807 return GetTickCount();
808 #else
810 struct tms tp;
812 /* Note that using gettimeofday() is not a good solution
813 for timers because its value change when the date is
814 modified. */
815 if (timer_freq == 100) {
816 return times(&tp) * 10;
817 } else {
818 return ((int64_t)times(&tp) * 1000) / timer_freq;
821 #endif
822 default:
823 case QEMU_TIMER_VIRTUAL:
824 return cpu_get_ticks();
828 /* save a timer */
829 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
831 uint64_t expire_time;
833 if (qemu_timer_pending(ts)) {
834 expire_time = ts->expire_time;
835 } else {
836 expire_time = -1;
838 qemu_put_be64(f, expire_time);
841 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
843 uint64_t expire_time;
845 expire_time = qemu_get_be64(f);
846 if (expire_time != -1) {
847 qemu_mod_timer(ts, expire_time);
848 } else {
849 qemu_del_timer(ts);
853 static void timer_save(QEMUFile *f, void *opaque)
855 if (cpu_ticks_enabled) {
856 hw_error("cannot save state if virtual timers are running");
858 qemu_put_be64s(f, &cpu_ticks_offset);
859 qemu_put_be64s(f, &ticks_per_sec);
862 static int timer_load(QEMUFile *f, void *opaque, int version_id)
864 if (version_id != 1)
865 return -EINVAL;
866 if (cpu_ticks_enabled) {
867 return -EINVAL;
869 qemu_get_be64s(f, &cpu_ticks_offset);
870 qemu_get_be64s(f, &ticks_per_sec);
871 return 0;
874 #ifdef _WIN32
875 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
876 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
877 #else
878 static void host_alarm_handler(int host_signum)
879 #endif
881 #if 0
882 #define DISP_FREQ 1000
884 static int64_t delta_min = INT64_MAX;
885 static int64_t delta_max, delta_cum, last_clock, delta, ti;
886 static int count;
887 ti = qemu_get_clock(vm_clock);
888 if (last_clock != 0) {
889 delta = ti - last_clock;
890 if (delta < delta_min)
891 delta_min = delta;
892 if (delta > delta_max)
893 delta_max = delta;
894 delta_cum += delta;
895 if (++count == DISP_FREQ) {
896 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
897 muldiv64(delta_min, 1000000, ticks_per_sec),
898 muldiv64(delta_max, 1000000, ticks_per_sec),
899 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
900 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
901 count = 0;
902 delta_min = INT64_MAX;
903 delta_max = 0;
904 delta_cum = 0;
907 last_clock = ti;
909 #endif
910 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
911 qemu_get_clock(vm_clock)) ||
912 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
913 qemu_get_clock(rt_clock))) {
914 #ifdef _WIN32
915 SetEvent(host_alarm);
916 #endif
917 CPUState *env = cpu_single_env;
918 if (env) {
919 /* stop the currently executing cpu because a timer occured */
920 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
921 #ifdef USE_KQEMU
922 if (env->kqemu_enabled) {
923 kqemu_cpu_interrupt(env);
925 #endif
930 #ifndef _WIN32
932 #if defined(__linux__)
934 #define RTC_FREQ 1024
936 static int rtc_fd;
938 static int start_rtc_timer(void)
940 rtc_fd = open("/dev/rtc", O_RDONLY);
941 if (rtc_fd < 0)
942 return -1;
943 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
944 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
945 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
946 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
947 goto fail;
949 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
950 fail:
951 close(rtc_fd);
952 return -1;
954 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
955 return 0;
958 #else
960 static int start_rtc_timer(void)
962 return -1;
965 #endif /* !defined(__linux__) */
967 #endif /* !defined(_WIN32) */
969 static void init_timers(void)
971 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
972 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
974 #ifdef _WIN32
976 int count=0;
977 TIMECAPS tc;
979 ZeroMemory(&tc, sizeof(TIMECAPS));
980 timeGetDevCaps(&tc, sizeof(TIMECAPS));
981 if (period < tc.wPeriodMin)
982 period = tc.wPeriodMin;
983 timeBeginPeriod(period);
984 timerID = timeSetEvent(1, // interval (ms)
985 period, // resolution
986 host_alarm_handler, // function
987 (DWORD)&count, // user parameter
988 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
989 if( !timerID ) {
990 perror("failed timer alarm");
991 exit(1);
993 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
994 if (!host_alarm) {
995 perror("failed CreateEvent");
996 exit(1);
998 ResetEvent(host_alarm);
1000 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1001 #else
1003 struct sigaction act;
1004 struct itimerval itv;
1006 /* get times() syscall frequency */
1007 timer_freq = sysconf(_SC_CLK_TCK);
1009 /* timer signal */
1010 sigfillset(&act.sa_mask);
1011 act.sa_flags = 0;
1012 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1013 act.sa_flags |= SA_ONSTACK;
1014 #endif
1015 act.sa_handler = host_alarm_handler;
1016 sigaction(SIGALRM, &act, NULL);
1018 itv.it_interval.tv_sec = 0;
1019 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1020 itv.it_value.tv_sec = 0;
1021 itv.it_value.tv_usec = 10 * 1000;
1022 setitimer(ITIMER_REAL, &itv, NULL);
1023 /* we probe the tick duration of the kernel to inform the user if
1024 the emulated kernel requested a too high timer frequency */
1025 getitimer(ITIMER_REAL, &itv);
1027 #if defined(__linux__)
1028 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1029 have timers with 1 ms resolution. The correct solution will
1030 be to use the POSIX real time timers available in recent
1031 2.6 kernels */
1032 if (itv.it_interval.tv_usec > 1000 || 1) {
1033 /* try to use /dev/rtc to have a faster timer */
1034 if (start_rtc_timer() < 0)
1035 goto use_itimer;
1036 /* disable itimer */
1037 itv.it_interval.tv_sec = 0;
1038 itv.it_interval.tv_usec = 0;
1039 itv.it_value.tv_sec = 0;
1040 itv.it_value.tv_usec = 0;
1041 setitimer(ITIMER_REAL, &itv, NULL);
1043 /* use the RTC */
1044 sigaction(SIGIO, &act, NULL);
1045 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1046 fcntl(rtc_fd, F_SETOWN, getpid());
1047 } else
1048 #endif /* defined(__linux__) */
1050 use_itimer:
1051 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1052 PIT_FREQ) / 1000000;
1055 #endif
1058 void quit_timers(void)
1060 #ifdef _WIN32
1061 timeKillEvent(timerID);
1062 timeEndPeriod(period);
1063 if (host_alarm) {
1064 CloseHandle(host_alarm);
1065 host_alarm = NULL;
1067 #endif
1070 /***********************************************************/
1071 /* character device */
1073 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1075 return s->chr_write(s, buf, len);
1078 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1080 if (!s->chr_ioctl)
1081 return -ENOTSUP;
1082 return s->chr_ioctl(s, cmd, arg);
1085 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1087 char buf[4096];
1088 va_list ap;
1089 va_start(ap, fmt);
1090 vsnprintf(buf, sizeof(buf), fmt, ap);
1091 qemu_chr_write(s, buf, strlen(buf));
1092 va_end(ap);
1095 void qemu_chr_send_event(CharDriverState *s, int event)
1097 if (s->chr_send_event)
1098 s->chr_send_event(s, event);
1101 void qemu_chr_add_read_handler(CharDriverState *s,
1102 IOCanRWHandler *fd_can_read,
1103 IOReadHandler *fd_read, void *opaque)
1105 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1108 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1110 s->chr_event = chr_event;
1113 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1115 return len;
1118 static void null_chr_add_read_handler(CharDriverState *chr,
1119 IOCanRWHandler *fd_can_read,
1120 IOReadHandler *fd_read, void *opaque)
1124 CharDriverState *qemu_chr_open_null(void)
1126 CharDriverState *chr;
1128 chr = qemu_mallocz(sizeof(CharDriverState));
1129 if (!chr)
1130 return NULL;
1131 chr->chr_write = null_chr_write;
1132 chr->chr_add_read_handler = null_chr_add_read_handler;
1133 return chr;
1136 #ifdef _WIN32
1138 static void socket_cleanup(void)
1140 WSACleanup();
1143 static int socket_init(void)
1145 WSADATA Data;
1146 int ret, err;
1148 ret = WSAStartup(MAKEWORD(2,2), &Data);
1149 if (ret != 0) {
1150 err = WSAGetLastError();
1151 fprintf(stderr, "WSAStartup: %d\n", err);
1152 return -1;
1154 atexit(socket_cleanup);
1155 return 0;
1158 static int send_all(int fd, const uint8_t *buf, int len1)
1160 int ret, len;
1162 len = len1;
1163 while (len > 0) {
1164 ret = send(fd, buf, len, 0);
1165 if (ret < 0) {
1166 int errno;
1167 errno = WSAGetLastError();
1168 if (errno != WSAEWOULDBLOCK) {
1169 return -1;
1171 } else if (ret == 0) {
1172 break;
1173 } else {
1174 buf += ret;
1175 len -= ret;
1178 return len1 - len;
1181 void socket_set_nonblock(int fd)
1183 unsigned long opt = 1;
1184 ioctlsocket(fd, FIONBIO, &opt);
1187 #else
1189 static int unix_write(int fd, const uint8_t *buf, int len1)
1191 int ret, len;
1193 len = len1;
1194 while (len > 0) {
1195 ret = write(fd, buf, len);
1196 if (ret < 0) {
1197 if (errno != EINTR && errno != EAGAIN)
1198 return -1;
1199 } else if (ret == 0) {
1200 break;
1201 } else {
1202 buf += ret;
1203 len -= ret;
1206 return len1 - len;
1209 static inline int send_all(int fd, const uint8_t *buf, int len1)
1211 return unix_write(fd, buf, len1);
1214 void socket_set_nonblock(int fd)
1216 fcntl(fd, F_SETFL, O_NONBLOCK);
1218 #endif /* !_WIN32 */
1220 #ifndef _WIN32
1222 typedef struct {
1223 int fd_in, fd_out;
1224 IOCanRWHandler *fd_can_read;
1225 IOReadHandler *fd_read;
1226 void *fd_opaque;
1227 int max_size;
1228 } FDCharDriver;
1230 #define STDIO_MAX_CLIENTS 2
1232 static int stdio_nb_clients;
1233 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1235 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1237 FDCharDriver *s = chr->opaque;
1238 return unix_write(s->fd_out, buf, len);
1241 static int fd_chr_read_poll(void *opaque)
1243 CharDriverState *chr = opaque;
1244 FDCharDriver *s = chr->opaque;
1246 s->max_size = s->fd_can_read(s->fd_opaque);
1247 return s->max_size;
1250 static void fd_chr_read(void *opaque)
1252 CharDriverState *chr = opaque;
1253 FDCharDriver *s = chr->opaque;
1254 int size, len;
1255 uint8_t buf[1024];
1257 len = sizeof(buf);
1258 if (len > s->max_size)
1259 len = s->max_size;
1260 if (len == 0)
1261 return;
1262 size = read(s->fd_in, buf, len);
1263 if (size > 0) {
1264 s->fd_read(s->fd_opaque, buf, size);
1268 static void fd_chr_add_read_handler(CharDriverState *chr,
1269 IOCanRWHandler *fd_can_read,
1270 IOReadHandler *fd_read, void *opaque)
1272 FDCharDriver *s = chr->opaque;
1274 if (s->fd_in >= 0) {
1275 s->fd_can_read = fd_can_read;
1276 s->fd_read = fd_read;
1277 s->fd_opaque = opaque;
1278 if (nographic && s->fd_in == 0) {
1279 } else {
1280 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1281 fd_chr_read, NULL, chr);
1286 /* open a character device to a unix fd */
1287 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1289 CharDriverState *chr;
1290 FDCharDriver *s;
1292 chr = qemu_mallocz(sizeof(CharDriverState));
1293 if (!chr)
1294 return NULL;
1295 s = qemu_mallocz(sizeof(FDCharDriver));
1296 if (!s) {
1297 free(chr);
1298 return NULL;
1300 s->fd_in = fd_in;
1301 s->fd_out = fd_out;
1302 chr->opaque = s;
1303 chr->chr_write = fd_chr_write;
1304 chr->chr_add_read_handler = fd_chr_add_read_handler;
1305 return chr;
1308 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1310 int fd_out;
1312 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1313 if (fd_out < 0)
1314 return NULL;
1315 return qemu_chr_open_fd(-1, fd_out);
1318 CharDriverState *qemu_chr_open_pipe(const char *filename)
1320 int fd;
1322 fd = open(filename, O_RDWR | O_BINARY);
1323 if (fd < 0)
1324 return NULL;
1325 return qemu_chr_open_fd(fd, fd);
1329 /* for STDIO, we handle the case where several clients use it
1330 (nographic mode) */
1332 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1334 #define TERM_FIFO_MAX_SIZE 1
1336 static int term_got_escape, client_index;
1337 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1338 int term_fifo_size;
1340 void term_print_help(void)
1342 printf("\n"
1343 "C-a h print this help\n"
1344 "C-a x exit emulator\n"
1345 "C-a s save disk data back to file (if -snapshot)\n"
1346 "C-a b send break (magic sysrq)\n"
1347 "C-a c switch between console and monitor\n"
1348 "C-a C-a send C-a\n"
1352 /* called when a char is received */
1353 static void stdio_received_byte(int ch)
1355 if (term_got_escape) {
1356 term_got_escape = 0;
1357 switch(ch) {
1358 case 'h':
1359 term_print_help();
1360 break;
1361 case 'x':
1362 exit(0);
1363 break;
1364 case 's':
1366 int i;
1367 for (i = 0; i < MAX_DISKS; i++) {
1368 if (bs_table[i])
1369 bdrv_commit(bs_table[i]);
1372 break;
1373 case 'b':
1374 if (client_index < stdio_nb_clients) {
1375 CharDriverState *chr;
1376 FDCharDriver *s;
1378 chr = stdio_clients[client_index];
1379 s = chr->opaque;
1380 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1382 break;
1383 case 'c':
1384 client_index++;
1385 if (client_index >= stdio_nb_clients)
1386 client_index = 0;
1387 if (client_index == 0) {
1388 /* send a new line in the monitor to get the prompt */
1389 ch = '\r';
1390 goto send_char;
1392 break;
1393 case TERM_ESCAPE:
1394 goto send_char;
1396 } else if (ch == TERM_ESCAPE) {
1397 term_got_escape = 1;
1398 } else {
1399 send_char:
1400 if (client_index < stdio_nb_clients) {
1401 uint8_t buf[1];
1402 CharDriverState *chr;
1403 FDCharDriver *s;
1405 chr = stdio_clients[client_index];
1406 s = chr->opaque;
1407 if (s->fd_can_read(s->fd_opaque) > 0) {
1408 buf[0] = ch;
1409 s->fd_read(s->fd_opaque, buf, 1);
1410 } else if (term_fifo_size == 0) {
1411 term_fifo[term_fifo_size++] = ch;
1417 static int stdio_read_poll(void *opaque)
1419 CharDriverState *chr;
1420 FDCharDriver *s;
1422 if (client_index < stdio_nb_clients) {
1423 chr = stdio_clients[client_index];
1424 s = chr->opaque;
1425 /* try to flush the queue if needed */
1426 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1427 s->fd_read(s->fd_opaque, term_fifo, 1);
1428 term_fifo_size = 0;
1430 /* see if we can absorb more chars */
1431 if (term_fifo_size == 0)
1432 return 1;
1433 else
1434 return 0;
1435 } else {
1436 return 1;
1440 static void stdio_read(void *opaque)
1442 int size;
1443 uint8_t buf[1];
1445 size = read(0, buf, 1);
1446 if (size > 0)
1447 stdio_received_byte(buf[0]);
1450 /* init terminal so that we can grab keys */
1451 static struct termios oldtty;
1452 static int old_fd0_flags;
1454 static void term_exit(void)
1456 tcsetattr (0, TCSANOW, &oldtty);
1457 fcntl(0, F_SETFL, old_fd0_flags);
1460 static void term_init(void)
1462 struct termios tty;
1464 tcgetattr (0, &tty);
1465 oldtty = tty;
1466 old_fd0_flags = fcntl(0, F_GETFL);
1468 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1469 |INLCR|IGNCR|ICRNL|IXON);
1470 tty.c_oflag |= OPOST;
1471 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1472 /* if graphical mode, we allow Ctrl-C handling */
1473 if (nographic)
1474 tty.c_lflag &= ~ISIG;
1475 tty.c_cflag &= ~(CSIZE|PARENB);
1476 tty.c_cflag |= CS8;
1477 tty.c_cc[VMIN] = 1;
1478 tty.c_cc[VTIME] = 0;
1480 tcsetattr (0, TCSANOW, &tty);
1482 atexit(term_exit);
1484 fcntl(0, F_SETFL, O_NONBLOCK);
1487 CharDriverState *qemu_chr_open_stdio(void)
1489 CharDriverState *chr;
1491 if (nographic) {
1492 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1493 return NULL;
1494 chr = qemu_chr_open_fd(0, 1);
1495 if (stdio_nb_clients == 0)
1496 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1497 client_index = stdio_nb_clients;
1498 } else {
1499 if (stdio_nb_clients != 0)
1500 return NULL;
1501 chr = qemu_chr_open_fd(0, 1);
1503 stdio_clients[stdio_nb_clients++] = chr;
1504 if (stdio_nb_clients == 1) {
1505 /* set the terminal in raw mode */
1506 term_init();
1508 return chr;
1511 #if defined(__linux__)
1512 CharDriverState *qemu_chr_open_pty(void)
1514 struct termios tty;
1515 char slave_name[1024];
1516 int master_fd, slave_fd;
1518 /* Not satisfying */
1519 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1520 return NULL;
1523 /* Disabling local echo and line-buffered output */
1524 tcgetattr (master_fd, &tty);
1525 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1526 tty.c_cc[VMIN] = 1;
1527 tty.c_cc[VTIME] = 0;
1528 tcsetattr (master_fd, TCSAFLUSH, &tty);
1530 fprintf(stderr, "char device redirected to %s\n", slave_name);
1531 return qemu_chr_open_fd(master_fd, master_fd);
1534 static void tty_serial_init(int fd, int speed,
1535 int parity, int data_bits, int stop_bits)
1537 struct termios tty;
1538 speed_t spd;
1540 #if 0
1541 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1542 speed, parity, data_bits, stop_bits);
1543 #endif
1544 tcgetattr (fd, &tty);
1546 switch(speed) {
1547 case 50:
1548 spd = B50;
1549 break;
1550 case 75:
1551 spd = B75;
1552 break;
1553 case 300:
1554 spd = B300;
1555 break;
1556 case 600:
1557 spd = B600;
1558 break;
1559 case 1200:
1560 spd = B1200;
1561 break;
1562 case 2400:
1563 spd = B2400;
1564 break;
1565 case 4800:
1566 spd = B4800;
1567 break;
1568 case 9600:
1569 spd = B9600;
1570 break;
1571 case 19200:
1572 spd = B19200;
1573 break;
1574 case 38400:
1575 spd = B38400;
1576 break;
1577 case 57600:
1578 spd = B57600;
1579 break;
1580 default:
1581 case 115200:
1582 spd = B115200;
1583 break;
1586 cfsetispeed(&tty, spd);
1587 cfsetospeed(&tty, spd);
1589 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1590 |INLCR|IGNCR|ICRNL|IXON);
1591 tty.c_oflag |= OPOST;
1592 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1593 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1594 switch(data_bits) {
1595 default:
1596 case 8:
1597 tty.c_cflag |= CS8;
1598 break;
1599 case 7:
1600 tty.c_cflag |= CS7;
1601 break;
1602 case 6:
1603 tty.c_cflag |= CS6;
1604 break;
1605 case 5:
1606 tty.c_cflag |= CS5;
1607 break;
1609 switch(parity) {
1610 default:
1611 case 'N':
1612 break;
1613 case 'E':
1614 tty.c_cflag |= PARENB;
1615 break;
1616 case 'O':
1617 tty.c_cflag |= PARENB | PARODD;
1618 break;
1621 tcsetattr (fd, TCSANOW, &tty);
1624 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1626 FDCharDriver *s = chr->opaque;
1628 switch(cmd) {
1629 case CHR_IOCTL_SERIAL_SET_PARAMS:
1631 QEMUSerialSetParams *ssp = arg;
1632 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1633 ssp->data_bits, ssp->stop_bits);
1635 break;
1636 case CHR_IOCTL_SERIAL_SET_BREAK:
1638 int enable = *(int *)arg;
1639 if (enable)
1640 tcsendbreak(s->fd_in, 1);
1642 break;
1643 default:
1644 return -ENOTSUP;
1646 return 0;
1649 CharDriverState *qemu_chr_open_tty(const char *filename)
1651 CharDriverState *chr;
1652 int fd;
1654 fd = open(filename, O_RDWR | O_NONBLOCK);
1655 if (fd < 0)
1656 return NULL;
1657 fcntl(fd, F_SETFL, O_NONBLOCK);
1658 tty_serial_init(fd, 115200, 'N', 8, 1);
1659 chr = qemu_chr_open_fd(fd, fd);
1660 if (!chr)
1661 return NULL;
1662 chr->chr_ioctl = tty_serial_ioctl;
1663 return chr;
1666 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1668 int fd = (int)chr->opaque;
1669 uint8_t b;
1671 switch(cmd) {
1672 case CHR_IOCTL_PP_READ_DATA:
1673 if (ioctl(fd, PPRDATA, &b) < 0)
1674 return -ENOTSUP;
1675 *(uint8_t *)arg = b;
1676 break;
1677 case CHR_IOCTL_PP_WRITE_DATA:
1678 b = *(uint8_t *)arg;
1679 if (ioctl(fd, PPWDATA, &b) < 0)
1680 return -ENOTSUP;
1681 break;
1682 case CHR_IOCTL_PP_READ_CONTROL:
1683 if (ioctl(fd, PPRCONTROL, &b) < 0)
1684 return -ENOTSUP;
1685 *(uint8_t *)arg = b;
1686 break;
1687 case CHR_IOCTL_PP_WRITE_CONTROL:
1688 b = *(uint8_t *)arg;
1689 if (ioctl(fd, PPWCONTROL, &b) < 0)
1690 return -ENOTSUP;
1691 break;
1692 case CHR_IOCTL_PP_READ_STATUS:
1693 if (ioctl(fd, PPRSTATUS, &b) < 0)
1694 return -ENOTSUP;
1695 *(uint8_t *)arg = b;
1696 break;
1697 default:
1698 return -ENOTSUP;
1700 return 0;
1703 CharDriverState *qemu_chr_open_pp(const char *filename)
1705 CharDriverState *chr;
1706 int fd;
1708 fd = open(filename, O_RDWR);
1709 if (fd < 0)
1710 return NULL;
1712 if (ioctl(fd, PPCLAIM) < 0) {
1713 close(fd);
1714 return NULL;
1717 chr = qemu_mallocz(sizeof(CharDriverState));
1718 if (!chr) {
1719 close(fd);
1720 return NULL;
1722 chr->opaque = (void *)fd;
1723 chr->chr_write = null_chr_write;
1724 chr->chr_add_read_handler = null_chr_add_read_handler;
1725 chr->chr_ioctl = pp_ioctl;
1726 return chr;
1729 #else
1730 CharDriverState *qemu_chr_open_pty(void)
1732 return NULL;
1734 #endif
1736 #endif /* !defined(_WIN32) */
1738 #ifdef _WIN32
1739 typedef struct {
1740 IOCanRWHandler *fd_can_read;
1741 IOReadHandler *fd_read;
1742 void *win_opaque;
1743 int max_size;
1744 HANDLE hcom, hrecv, hsend;
1745 OVERLAPPED orecv, osend;
1746 BOOL fpipe;
1747 DWORD len;
1748 } WinCharState;
1750 #define NSENDBUF 2048
1751 #define NRECVBUF 2048
1752 #define MAXCONNECT 1
1753 #define NTIMEOUT 5000
1755 static int win_chr_poll(void *opaque);
1756 static int win_chr_pipe_poll(void *opaque);
1758 static void win_chr_close2(WinCharState *s)
1760 if (s->hsend) {
1761 CloseHandle(s->hsend);
1762 s->hsend = NULL;
1764 if (s->hrecv) {
1765 CloseHandle(s->hrecv);
1766 s->hrecv = NULL;
1768 if (s->hcom) {
1769 CloseHandle(s->hcom);
1770 s->hcom = NULL;
1772 if (s->fpipe)
1773 qemu_del_polling_cb(win_chr_pipe_poll, s);
1774 else
1775 qemu_del_polling_cb(win_chr_poll, s);
1778 static void win_chr_close(CharDriverState *chr)
1780 WinCharState *s = chr->opaque;
1781 win_chr_close2(s);
1784 static int win_chr_init(WinCharState *s, const char *filename)
1786 COMMCONFIG comcfg;
1787 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1788 COMSTAT comstat;
1789 DWORD size;
1790 DWORD err;
1792 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1793 if (!s->hsend) {
1794 fprintf(stderr, "Failed CreateEvent\n");
1795 goto fail;
1797 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1798 if (!s->hrecv) {
1799 fprintf(stderr, "Failed CreateEvent\n");
1800 goto fail;
1803 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1804 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1805 if (s->hcom == INVALID_HANDLE_VALUE) {
1806 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1807 s->hcom = NULL;
1808 goto fail;
1811 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1812 fprintf(stderr, "Failed SetupComm\n");
1813 goto fail;
1816 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1817 size = sizeof(COMMCONFIG);
1818 GetDefaultCommConfig(filename, &comcfg, &size);
1819 comcfg.dcb.DCBlength = sizeof(DCB);
1820 CommConfigDialog(filename, NULL, &comcfg);
1822 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1823 fprintf(stderr, "Failed SetCommState\n");
1824 goto fail;
1827 if (!SetCommMask(s->hcom, EV_ERR)) {
1828 fprintf(stderr, "Failed SetCommMask\n");
1829 goto fail;
1832 cto.ReadIntervalTimeout = MAXDWORD;
1833 if (!SetCommTimeouts(s->hcom, &cto)) {
1834 fprintf(stderr, "Failed SetCommTimeouts\n");
1835 goto fail;
1838 if (!ClearCommError(s->hcom, &err, &comstat)) {
1839 fprintf(stderr, "Failed ClearCommError\n");
1840 goto fail;
1842 qemu_add_polling_cb(win_chr_poll, s);
1843 return 0;
1845 fail:
1846 win_chr_close2(s);
1847 return -1;
1850 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1852 WinCharState *s = chr->opaque;
1853 DWORD len, ret, size, err;
1855 len = len1;
1856 ZeroMemory(&s->osend, sizeof(s->osend));
1857 s->osend.hEvent = s->hsend;
1858 while (len > 0) {
1859 if (s->hsend)
1860 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1861 else
1862 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1863 if (!ret) {
1864 err = GetLastError();
1865 if (err == ERROR_IO_PENDING) {
1866 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1867 if (ret) {
1868 buf += size;
1869 len -= size;
1870 } else {
1871 break;
1873 } else {
1874 break;
1876 } else {
1877 buf += size;
1878 len -= size;
1881 return len1 - len;
1884 static int win_chr_read_poll(WinCharState *s)
1886 s->max_size = s->fd_can_read(s->win_opaque);
1887 return s->max_size;
1890 static void win_chr_readfile(WinCharState *s)
1892 int ret, err;
1893 uint8_t buf[1024];
1894 DWORD size;
1896 ZeroMemory(&s->orecv, sizeof(s->orecv));
1897 s->orecv.hEvent = s->hrecv;
1898 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1899 if (!ret) {
1900 err = GetLastError();
1901 if (err == ERROR_IO_PENDING) {
1902 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1906 if (size > 0) {
1907 s->fd_read(s->win_opaque, buf, size);
1911 static void win_chr_read(WinCharState *s)
1913 if (s->len > s->max_size)
1914 s->len = s->max_size;
1915 if (s->len == 0)
1916 return;
1918 win_chr_readfile(s);
1921 static int win_chr_poll(void *opaque)
1923 WinCharState *s = opaque;
1924 COMSTAT status;
1925 DWORD comerr;
1927 ClearCommError(s->hcom, &comerr, &status);
1928 if (status.cbInQue > 0) {
1929 s->len = status.cbInQue;
1930 win_chr_read_poll(s);
1931 win_chr_read(s);
1932 return 1;
1934 return 0;
1937 static void win_chr_add_read_handler(CharDriverState *chr,
1938 IOCanRWHandler *fd_can_read,
1939 IOReadHandler *fd_read, void *opaque)
1941 WinCharState *s = chr->opaque;
1943 s->fd_can_read = fd_can_read;
1944 s->fd_read = fd_read;
1945 s->win_opaque = opaque;
1948 CharDriverState *qemu_chr_open_win(const char *filename)
1950 CharDriverState *chr;
1951 WinCharState *s;
1953 chr = qemu_mallocz(sizeof(CharDriverState));
1954 if (!chr)
1955 return NULL;
1956 s = qemu_mallocz(sizeof(WinCharState));
1957 if (!s) {
1958 free(chr);
1959 return NULL;
1961 chr->opaque = s;
1962 chr->chr_write = win_chr_write;
1963 chr->chr_add_read_handler = win_chr_add_read_handler;
1964 chr->chr_close = win_chr_close;
1966 if (win_chr_init(s, filename) < 0) {
1967 free(s);
1968 free(chr);
1969 return NULL;
1971 return chr;
1974 static int win_chr_pipe_poll(void *opaque)
1976 WinCharState *s = opaque;
1977 DWORD size;
1979 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1980 if (size > 0) {
1981 s->len = size;
1982 win_chr_read_poll(s);
1983 win_chr_read(s);
1984 return 1;
1986 return 0;
1989 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1991 OVERLAPPED ov;
1992 int ret;
1993 DWORD size;
1994 char openname[256];
1996 s->fpipe = TRUE;
1998 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1999 if (!s->hsend) {
2000 fprintf(stderr, "Failed CreateEvent\n");
2001 goto fail;
2003 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2004 if (!s->hrecv) {
2005 fprintf(stderr, "Failed CreateEvent\n");
2006 goto fail;
2009 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2010 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2011 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2012 PIPE_WAIT,
2013 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2014 if (s->hcom == INVALID_HANDLE_VALUE) {
2015 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2016 s->hcom = NULL;
2017 goto fail;
2020 ZeroMemory(&ov, sizeof(ov));
2021 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2022 ret = ConnectNamedPipe(s->hcom, &ov);
2023 if (ret) {
2024 fprintf(stderr, "Failed ConnectNamedPipe\n");
2025 goto fail;
2028 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2029 if (!ret) {
2030 fprintf(stderr, "Failed GetOverlappedResult\n");
2031 if (ov.hEvent) {
2032 CloseHandle(ov.hEvent);
2033 ov.hEvent = NULL;
2035 goto fail;
2038 if (ov.hEvent) {
2039 CloseHandle(ov.hEvent);
2040 ov.hEvent = NULL;
2042 qemu_add_polling_cb(win_chr_pipe_poll, s);
2043 return 0;
2045 fail:
2046 win_chr_close2(s);
2047 return -1;
2051 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2053 CharDriverState *chr;
2054 WinCharState *s;
2056 chr = qemu_mallocz(sizeof(CharDriverState));
2057 if (!chr)
2058 return NULL;
2059 s = qemu_mallocz(sizeof(WinCharState));
2060 if (!s) {
2061 free(chr);
2062 return NULL;
2064 chr->opaque = s;
2065 chr->chr_write = win_chr_write;
2066 chr->chr_add_read_handler = win_chr_add_read_handler;
2067 chr->chr_close = win_chr_close;
2069 if (win_chr_pipe_init(s, filename) < 0) {
2070 free(s);
2071 free(chr);
2072 return NULL;
2074 return chr;
2077 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2079 CharDriverState *chr;
2080 WinCharState *s;
2082 chr = qemu_mallocz(sizeof(CharDriverState));
2083 if (!chr)
2084 return NULL;
2085 s = qemu_mallocz(sizeof(WinCharState));
2086 if (!s) {
2087 free(chr);
2088 return NULL;
2090 s->hcom = fd_out;
2091 chr->opaque = s;
2092 chr->chr_write = win_chr_write;
2093 chr->chr_add_read_handler = win_chr_add_read_handler;
2094 return chr;
2097 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2099 HANDLE fd_out;
2101 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2102 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2103 if (fd_out == INVALID_HANDLE_VALUE)
2104 return NULL;
2106 return qemu_chr_open_win_file(fd_out);
2108 #endif
2110 CharDriverState *qemu_chr_open(const char *filename)
2112 const char *p;
2114 if (!strcmp(filename, "vc")) {
2115 return text_console_init(&display_state);
2116 } else if (!strcmp(filename, "null")) {
2117 return qemu_chr_open_null();
2118 } else
2119 #ifndef _WIN32
2120 if (strstart(filename, "file:", &p)) {
2121 return qemu_chr_open_file_out(p);
2122 } else if (strstart(filename, "pipe:", &p)) {
2123 return qemu_chr_open_pipe(p);
2124 } else if (!strcmp(filename, "pty")) {
2125 return qemu_chr_open_pty();
2126 } else if (!strcmp(filename, "stdio")) {
2127 return qemu_chr_open_stdio();
2128 } else
2129 #endif
2130 #if defined(__linux__)
2131 if (strstart(filename, "/dev/parport", NULL)) {
2132 return qemu_chr_open_pp(filename);
2133 } else
2134 if (strstart(filename, "/dev/", NULL)) {
2135 return qemu_chr_open_tty(filename);
2136 } else
2137 #endif
2138 #ifdef _WIN32
2139 if (strstart(filename, "COM", NULL)) {
2140 return qemu_chr_open_win(filename);
2141 } else
2142 if (strstart(filename, "pipe:", &p)) {
2143 return qemu_chr_open_win_pipe(p);
2144 } else
2145 if (strstart(filename, "file:", &p)) {
2146 return qemu_chr_open_win_file_out(p);
2148 #endif
2150 return NULL;
2154 void qemu_chr_close(CharDriverState *chr)
2156 if (chr->chr_close)
2157 chr->chr_close(chr);
2160 /***********************************************************/
2161 /* network device redirectors */
2163 void hex_dump(FILE *f, const uint8_t *buf, int size)
2165 int len, i, j, c;
2167 for(i=0;i<size;i+=16) {
2168 len = size - i;
2169 if (len > 16)
2170 len = 16;
2171 fprintf(f, "%08x ", i);
2172 for(j=0;j<16;j++) {
2173 if (j < len)
2174 fprintf(f, " %02x", buf[i+j]);
2175 else
2176 fprintf(f, " ");
2178 fprintf(f, " ");
2179 for(j=0;j<len;j++) {
2180 c = buf[i+j];
2181 if (c < ' ' || c > '~')
2182 c = '.';
2183 fprintf(f, "%c", c);
2185 fprintf(f, "\n");
2189 static int parse_macaddr(uint8_t *macaddr, const char *p)
2191 int i;
2192 for(i = 0; i < 6; i++) {
2193 macaddr[i] = strtol(p, (char **)&p, 16);
2194 if (i == 5) {
2195 if (*p != '\0')
2196 return -1;
2197 } else {
2198 if (*p != ':')
2199 return -1;
2200 p++;
2203 return 0;
2206 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2208 const char *p, *p1;
2209 int len;
2210 p = *pp;
2211 p1 = strchr(p, sep);
2212 if (!p1)
2213 return -1;
2214 len = p1 - p;
2215 p1++;
2216 if (buf_size > 0) {
2217 if (len > buf_size - 1)
2218 len = buf_size - 1;
2219 memcpy(buf, p, len);
2220 buf[len] = '\0';
2222 *pp = p1;
2223 return 0;
2226 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2228 char buf[512];
2229 struct hostent *he;
2230 const char *p, *r;
2231 int port;
2233 p = str;
2234 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2235 return -1;
2236 saddr->sin_family = AF_INET;
2237 if (buf[0] == '\0') {
2238 saddr->sin_addr.s_addr = 0;
2239 } else {
2240 if (isdigit(buf[0])) {
2241 if (!inet_aton(buf, &saddr->sin_addr))
2242 return -1;
2243 } else {
2244 if ((he = gethostbyname(buf)) == NULL)
2245 return - 1;
2246 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2249 port = strtol(p, (char **)&r, 0);
2250 if (r == p)
2251 return -1;
2252 saddr->sin_port = htons(port);
2253 return 0;
2256 /* find or alloc a new VLAN */
2257 VLANState *qemu_find_vlan(int id)
2259 VLANState **pvlan, *vlan;
2260 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2261 if (vlan->id == id)
2262 return vlan;
2264 vlan = qemu_mallocz(sizeof(VLANState));
2265 if (!vlan)
2266 return NULL;
2267 vlan->id = id;
2268 vlan->next = NULL;
2269 pvlan = &first_vlan;
2270 while (*pvlan != NULL)
2271 pvlan = &(*pvlan)->next;
2272 *pvlan = vlan;
2273 return vlan;
2276 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2277 IOReadHandler *fd_read,
2278 IOCanRWHandler *fd_can_read,
2279 void *opaque)
2281 VLANClientState *vc, **pvc;
2282 vc = qemu_mallocz(sizeof(VLANClientState));
2283 if (!vc)
2284 return NULL;
2285 vc->fd_read = fd_read;
2286 vc->fd_can_read = fd_can_read;
2287 vc->opaque = opaque;
2288 vc->vlan = vlan;
2290 vc->next = NULL;
2291 pvc = &vlan->first_client;
2292 while (*pvc != NULL)
2293 pvc = &(*pvc)->next;
2294 *pvc = vc;
2295 return vc;
2298 int qemu_can_send_packet(VLANClientState *vc1)
2300 VLANState *vlan = vc1->vlan;
2301 VLANClientState *vc;
2303 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2304 if (vc != vc1) {
2305 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2306 return 0;
2309 return 1;
2312 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2314 VLANState *vlan = vc1->vlan;
2315 VLANClientState *vc;
2317 #if 0
2318 printf("vlan %d send:\n", vlan->id);
2319 hex_dump(stdout, buf, size);
2320 #endif
2321 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2322 if (vc != vc1) {
2323 vc->fd_read(vc->opaque, buf, size);
2328 #if defined(CONFIG_SLIRP)
2330 /* slirp network adapter */
2332 static int slirp_inited;
2333 static VLANClientState *slirp_vc;
2335 int slirp_can_output(void)
2337 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2340 void slirp_output(const uint8_t *pkt, int pkt_len)
2342 #if 0
2343 printf("slirp output:\n");
2344 hex_dump(stdout, pkt, pkt_len);
2345 #endif
2346 if (!slirp_vc)
2347 return;
2348 qemu_send_packet(slirp_vc, pkt, pkt_len);
2351 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2353 #if 0
2354 printf("slirp input:\n");
2355 hex_dump(stdout, buf, size);
2356 #endif
2357 slirp_input(buf, size);
2360 static int net_slirp_init(VLANState *vlan)
2362 if (!slirp_inited) {
2363 slirp_inited = 1;
2364 slirp_init();
2366 slirp_vc = qemu_new_vlan_client(vlan,
2367 slirp_receive, NULL, NULL);
2368 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2369 return 0;
2372 static void net_slirp_redir(const char *redir_str)
2374 int is_udp;
2375 char buf[256], *r;
2376 const char *p;
2377 struct in_addr guest_addr;
2378 int host_port, guest_port;
2380 if (!slirp_inited) {
2381 slirp_inited = 1;
2382 slirp_init();
2385 p = redir_str;
2386 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2387 goto fail;
2388 if (!strcmp(buf, "tcp")) {
2389 is_udp = 0;
2390 } else if (!strcmp(buf, "udp")) {
2391 is_udp = 1;
2392 } else {
2393 goto fail;
2396 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2397 goto fail;
2398 host_port = strtol(buf, &r, 0);
2399 if (r == buf)
2400 goto fail;
2402 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2403 goto fail;
2404 if (buf[0] == '\0') {
2405 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2407 if (!inet_aton(buf, &guest_addr))
2408 goto fail;
2410 guest_port = strtol(p, &r, 0);
2411 if (r == p)
2412 goto fail;
2414 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2415 fprintf(stderr, "qemu: could not set up redirection\n");
2416 exit(1);
2418 return;
2419 fail:
2420 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2421 exit(1);
2424 #ifndef _WIN32
2426 char smb_dir[1024];
2428 static void smb_exit(void)
2430 DIR *d;
2431 struct dirent *de;
2432 char filename[1024];
2434 /* erase all the files in the directory */
2435 d = opendir(smb_dir);
2436 for(;;) {
2437 de = readdir(d);
2438 if (!de)
2439 break;
2440 if (strcmp(de->d_name, ".") != 0 &&
2441 strcmp(de->d_name, "..") != 0) {
2442 snprintf(filename, sizeof(filename), "%s/%s",
2443 smb_dir, de->d_name);
2444 unlink(filename);
2447 closedir(d);
2448 rmdir(smb_dir);
2451 /* automatic user mode samba server configuration */
2452 void net_slirp_smb(const char *exported_dir)
2454 char smb_conf[1024];
2455 char smb_cmdline[1024];
2456 FILE *f;
2458 if (!slirp_inited) {
2459 slirp_inited = 1;
2460 slirp_init();
2463 /* XXX: better tmp dir construction */
2464 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2465 if (mkdir(smb_dir, 0700) < 0) {
2466 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2467 exit(1);
2469 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2471 f = fopen(smb_conf, "w");
2472 if (!f) {
2473 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2474 exit(1);
2476 fprintf(f,
2477 "[global]\n"
2478 "private dir=%s\n"
2479 "smb ports=0\n"
2480 "socket address=127.0.0.1\n"
2481 "pid directory=%s\n"
2482 "lock directory=%s\n"
2483 "log file=%s/log.smbd\n"
2484 "smb passwd file=%s/smbpasswd\n"
2485 "security = share\n"
2486 "[qemu]\n"
2487 "path=%s\n"
2488 "read only=no\n"
2489 "guest ok=yes\n",
2490 smb_dir,
2491 smb_dir,
2492 smb_dir,
2493 smb_dir,
2494 smb_dir,
2495 exported_dir
2497 fclose(f);
2498 atexit(smb_exit);
2500 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2501 smb_conf);
2503 slirp_add_exec(0, smb_cmdline, 4, 139);
2506 #endif /* !defined(_WIN32) */
2508 #endif /* CONFIG_SLIRP */
2510 #if !defined(_WIN32)
2512 typedef struct TAPState {
2513 VLANClientState *vc;
2514 int fd;
2515 } TAPState;
2517 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2519 TAPState *s = opaque;
2520 int ret;
2521 for(;;) {
2522 ret = write(s->fd, buf, size);
2523 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2524 } else {
2525 break;
2530 static void tap_send(void *opaque)
2532 TAPState *s = opaque;
2533 uint8_t buf[4096];
2534 int size;
2536 size = read(s->fd, buf, sizeof(buf));
2537 if (size > 0) {
2538 qemu_send_packet(s->vc, buf, size);
2542 /* fd support */
2544 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2546 TAPState *s;
2548 s = qemu_mallocz(sizeof(TAPState));
2549 if (!s)
2550 return NULL;
2551 s->fd = fd;
2552 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2553 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2554 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2555 return s;
2558 #ifdef _BSD
2559 static int tap_open(char *ifname, int ifname_size)
2561 int fd;
2562 char *dev;
2563 struct stat s;
2565 fd = open("/dev/tap", O_RDWR);
2566 if (fd < 0) {
2567 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2568 return -1;
2571 fstat(fd, &s);
2572 dev = devname(s.st_rdev, S_IFCHR);
2573 pstrcpy(ifname, ifname_size, dev);
2575 fcntl(fd, F_SETFL, O_NONBLOCK);
2576 return fd;
2578 #elif defined(__sun__)
2579 static int tap_open(char *ifname, int ifname_size)
2581 fprintf(stderr, "warning: tap_open not yet implemented\n");
2582 return -1;
2584 #else
2585 static int tap_open(char *ifname, int ifname_size)
2587 struct ifreq ifr;
2588 int fd, ret;
2590 fd = open("/dev/net/tun", O_RDWR);
2591 if (fd < 0) {
2592 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2593 return -1;
2595 memset(&ifr, 0, sizeof(ifr));
2596 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2597 if (ifname[0] != '\0')
2598 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2599 else
2600 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2601 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2602 if (ret != 0) {
2603 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2604 close(fd);
2605 return -1;
2607 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2608 fcntl(fd, F_SETFL, O_NONBLOCK);
2609 return fd;
2611 #endif
2613 static int net_tap_init(VLANState *vlan, const char *ifname1,
2614 const char *setup_script)
2616 TAPState *s;
2617 int pid, status, fd;
2618 char *args[3];
2619 char **parg;
2620 char ifname[128];
2622 if (ifname1 != NULL)
2623 pstrcpy(ifname, sizeof(ifname), ifname1);
2624 else
2625 ifname[0] = '\0';
2626 fd = tap_open(ifname, sizeof(ifname));
2627 if (fd < 0)
2628 return -1;
2630 if (!setup_script)
2631 setup_script = "";
2632 if (setup_script[0] != '\0') {
2633 /* try to launch network init script */
2634 pid = fork();
2635 if (pid >= 0) {
2636 if (pid == 0) {
2637 parg = args;
2638 *parg++ = (char *)setup_script;
2639 *parg++ = ifname;
2640 *parg++ = NULL;
2641 execv(setup_script, args);
2642 _exit(1);
2644 while (waitpid(pid, &status, 0) != pid);
2645 if (!WIFEXITED(status) ||
2646 WEXITSTATUS(status) != 0) {
2647 fprintf(stderr, "%s: could not launch network script\n",
2648 setup_script);
2649 return -1;
2653 s = net_tap_fd_init(vlan, fd);
2654 if (!s)
2655 return -1;
2656 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2657 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2658 return 0;
2661 #endif /* !_WIN32 */
2663 /* network connection */
2664 typedef struct NetSocketState {
2665 VLANClientState *vc;
2666 int fd;
2667 int state; /* 0 = getting length, 1 = getting data */
2668 int index;
2669 int packet_len;
2670 uint8_t buf[4096];
2671 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2672 } NetSocketState;
2674 typedef struct NetSocketListenState {
2675 VLANState *vlan;
2676 int fd;
2677 } NetSocketListenState;
2679 /* XXX: we consider we can send the whole packet without blocking */
2680 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2682 NetSocketState *s = opaque;
2683 uint32_t len;
2684 len = htonl(size);
2686 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2687 send_all(s->fd, buf, size);
2690 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2692 NetSocketState *s = opaque;
2693 sendto(s->fd, buf, size, 0,
2694 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2697 static void net_socket_send(void *opaque)
2699 NetSocketState *s = opaque;
2700 int l, size, err;
2701 uint8_t buf1[4096];
2702 const uint8_t *buf;
2704 size = recv(s->fd, buf1, sizeof(buf1), 0);
2705 if (size < 0) {
2706 err = socket_error();
2707 if (err != EWOULDBLOCK)
2708 goto eoc;
2709 } else if (size == 0) {
2710 /* end of connection */
2711 eoc:
2712 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2713 closesocket(s->fd);
2714 return;
2716 buf = buf1;
2717 while (size > 0) {
2718 /* reassemble a packet from the network */
2719 switch(s->state) {
2720 case 0:
2721 l = 4 - s->index;
2722 if (l > size)
2723 l = size;
2724 memcpy(s->buf + s->index, buf, l);
2725 buf += l;
2726 size -= l;
2727 s->index += l;
2728 if (s->index == 4) {
2729 /* got length */
2730 s->packet_len = ntohl(*(uint32_t *)s->buf);
2731 s->index = 0;
2732 s->state = 1;
2734 break;
2735 case 1:
2736 l = s->packet_len - s->index;
2737 if (l > size)
2738 l = size;
2739 memcpy(s->buf + s->index, buf, l);
2740 s->index += l;
2741 buf += l;
2742 size -= l;
2743 if (s->index >= s->packet_len) {
2744 qemu_send_packet(s->vc, s->buf, s->packet_len);
2745 s->index = 0;
2746 s->state = 0;
2748 break;
2753 static void net_socket_send_dgram(void *opaque)
2755 NetSocketState *s = opaque;
2756 int size;
2758 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2759 if (size < 0)
2760 return;
2761 if (size == 0) {
2762 /* end of connection */
2763 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2764 return;
2766 qemu_send_packet(s->vc, s->buf, size);
2769 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2771 struct ip_mreq imr;
2772 int fd;
2773 int val, ret;
2774 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2775 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2776 inet_ntoa(mcastaddr->sin_addr),
2777 (int)ntohl(mcastaddr->sin_addr.s_addr));
2778 return -1;
2781 fd = socket(PF_INET, SOCK_DGRAM, 0);
2782 if (fd < 0) {
2783 perror("socket(PF_INET, SOCK_DGRAM)");
2784 return -1;
2787 val = 1;
2788 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2789 (const char *)&val, sizeof(val));
2790 if (ret < 0) {
2791 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2792 goto fail;
2795 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2796 if (ret < 0) {
2797 perror("bind");
2798 goto fail;
2801 /* Add host to multicast group */
2802 imr.imr_multiaddr = mcastaddr->sin_addr;
2803 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2805 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2806 (const char *)&imr, sizeof(struct ip_mreq));
2807 if (ret < 0) {
2808 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2809 goto fail;
2812 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2813 val = 1;
2814 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2815 (const char *)&val, sizeof(val));
2816 if (ret < 0) {
2817 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2818 goto fail;
2821 socket_set_nonblock(fd);
2822 return fd;
2823 fail:
2824 if (fd>=0) close(fd);
2825 return -1;
2828 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2829 int is_connected)
2831 struct sockaddr_in saddr;
2832 int newfd;
2833 socklen_t saddr_len;
2834 NetSocketState *s;
2836 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2837 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2838 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2841 if (is_connected) {
2842 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2843 /* must be bound */
2844 if (saddr.sin_addr.s_addr==0) {
2845 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2846 fd);
2847 return NULL;
2849 /* clone dgram socket */
2850 newfd = net_socket_mcast_create(&saddr);
2851 if (newfd < 0) {
2852 /* error already reported by net_socket_mcast_create() */
2853 close(fd);
2854 return NULL;
2856 /* clone newfd to fd, close newfd */
2857 dup2(newfd, fd);
2858 close(newfd);
2860 } else {
2861 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2862 fd, strerror(errno));
2863 return NULL;
2867 s = qemu_mallocz(sizeof(NetSocketState));
2868 if (!s)
2869 return NULL;
2870 s->fd = fd;
2872 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2873 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2875 /* mcast: save bound address as dst */
2876 if (is_connected) s->dgram_dst=saddr;
2878 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2879 "socket: fd=%d (%s mcast=%s:%d)",
2880 fd, is_connected? "cloned" : "",
2881 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2882 return s;
2885 static void net_socket_connect(void *opaque)
2887 NetSocketState *s = opaque;
2888 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2891 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2892 int is_connected)
2894 NetSocketState *s;
2895 s = qemu_mallocz(sizeof(NetSocketState));
2896 if (!s)
2897 return NULL;
2898 s->fd = fd;
2899 s->vc = qemu_new_vlan_client(vlan,
2900 net_socket_receive, NULL, s);
2901 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2902 "socket: fd=%d", fd);
2903 if (is_connected) {
2904 net_socket_connect(s);
2905 } else {
2906 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2908 return s;
2911 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2912 int is_connected)
2914 int so_type=-1, optlen=sizeof(so_type);
2916 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2917 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2918 return NULL;
2920 switch(so_type) {
2921 case SOCK_DGRAM:
2922 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2923 case SOCK_STREAM:
2924 return net_socket_fd_init_stream(vlan, fd, is_connected);
2925 default:
2926 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2927 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2928 return net_socket_fd_init_stream(vlan, fd, is_connected);
2930 return NULL;
2933 static void net_socket_accept(void *opaque)
2935 NetSocketListenState *s = opaque;
2936 NetSocketState *s1;
2937 struct sockaddr_in saddr;
2938 socklen_t len;
2939 int fd;
2941 for(;;) {
2942 len = sizeof(saddr);
2943 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2944 if (fd < 0 && errno != EINTR) {
2945 return;
2946 } else if (fd >= 0) {
2947 break;
2950 s1 = net_socket_fd_init(s->vlan, fd, 1);
2951 if (!s1) {
2952 close(fd);
2953 } else {
2954 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2955 "socket: connection from %s:%d",
2956 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2960 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2962 NetSocketListenState *s;
2963 int fd, val, ret;
2964 struct sockaddr_in saddr;
2966 if (parse_host_port(&saddr, host_str) < 0)
2967 return -1;
2969 s = qemu_mallocz(sizeof(NetSocketListenState));
2970 if (!s)
2971 return -1;
2973 fd = socket(PF_INET, SOCK_STREAM, 0);
2974 if (fd < 0) {
2975 perror("socket");
2976 return -1;
2978 socket_set_nonblock(fd);
2980 /* allow fast reuse */
2981 val = 1;
2982 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2984 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2985 if (ret < 0) {
2986 perror("bind");
2987 return -1;
2989 ret = listen(fd, 0);
2990 if (ret < 0) {
2991 perror("listen");
2992 return -1;
2994 s->vlan = vlan;
2995 s->fd = fd;
2996 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2997 return 0;
3000 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3002 NetSocketState *s;
3003 int fd, connected, ret, err;
3004 struct sockaddr_in saddr;
3006 if (parse_host_port(&saddr, host_str) < 0)
3007 return -1;
3009 fd = socket(PF_INET, SOCK_STREAM, 0);
3010 if (fd < 0) {
3011 perror("socket");
3012 return -1;
3014 socket_set_nonblock(fd);
3016 connected = 0;
3017 for(;;) {
3018 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3019 if (ret < 0) {
3020 err = socket_error();
3021 if (err == EINTR || err == EWOULDBLOCK) {
3022 } else if (err == EINPROGRESS) {
3023 break;
3024 } else {
3025 perror("connect");
3026 closesocket(fd);
3027 return -1;
3029 } else {
3030 connected = 1;
3031 break;
3034 s = net_socket_fd_init(vlan, fd, connected);
3035 if (!s)
3036 return -1;
3037 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3038 "socket: connect to %s:%d",
3039 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3040 return 0;
3043 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3045 NetSocketState *s;
3046 int fd;
3047 struct sockaddr_in saddr;
3049 if (parse_host_port(&saddr, host_str) < 0)
3050 return -1;
3053 fd = net_socket_mcast_create(&saddr);
3054 if (fd < 0)
3055 return -1;
3057 s = net_socket_fd_init(vlan, fd, 0);
3058 if (!s)
3059 return -1;
3061 s->dgram_dst = saddr;
3063 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3064 "socket: mcast=%s:%d",
3065 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3066 return 0;
3070 static int get_param_value(char *buf, int buf_size,
3071 const char *tag, const char *str)
3073 const char *p;
3074 char *q;
3075 char option[128];
3077 p = str;
3078 for(;;) {
3079 q = option;
3080 while (*p != '\0' && *p != '=') {
3081 if ((q - option) < sizeof(option) - 1)
3082 *q++ = *p;
3083 p++;
3085 *q = '\0';
3086 if (*p != '=')
3087 break;
3088 p++;
3089 if (!strcmp(tag, option)) {
3090 q = buf;
3091 while (*p != '\0' && *p != ',') {
3092 if ((q - buf) < buf_size - 1)
3093 *q++ = *p;
3094 p++;
3096 *q = '\0';
3097 return q - buf;
3098 } else {
3099 while (*p != '\0' && *p != ',') {
3100 p++;
3103 if (*p != ',')
3104 break;
3105 p++;
3107 return 0;
3110 int net_client_init(const char *str)
3112 const char *p;
3113 char *q;
3114 char device[64];
3115 char buf[1024];
3116 int vlan_id, ret;
3117 VLANState *vlan;
3119 p = str;
3120 q = device;
3121 while (*p != '\0' && *p != ',') {
3122 if ((q - device) < sizeof(device) - 1)
3123 *q++ = *p;
3124 p++;
3126 *q = '\0';
3127 if (*p == ',')
3128 p++;
3129 vlan_id = 0;
3130 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3131 vlan_id = strtol(buf, NULL, 0);
3133 vlan = qemu_find_vlan(vlan_id);
3134 if (!vlan) {
3135 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3136 return -1;
3138 if (!strcmp(device, "nic")) {
3139 NICInfo *nd;
3140 uint8_t *macaddr;
3142 if (nb_nics >= MAX_NICS) {
3143 fprintf(stderr, "Too Many NICs\n");
3144 return -1;
3146 nd = &nd_table[nb_nics];
3147 macaddr = nd->macaddr;
3148 macaddr[0] = 0x52;
3149 macaddr[1] = 0x54;
3150 macaddr[2] = 0x00;
3151 macaddr[3] = 0x12;
3152 macaddr[4] = 0x34;
3153 macaddr[5] = 0x56 + nb_nics;
3155 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3156 if (parse_macaddr(macaddr, buf) < 0) {
3157 fprintf(stderr, "invalid syntax for ethernet address\n");
3158 return -1;
3161 if (get_param_value(buf, sizeof(buf), "model", p)) {
3162 nd->model = strdup(buf);
3164 nd->vlan = vlan;
3165 nb_nics++;
3166 ret = 0;
3167 } else
3168 if (!strcmp(device, "none")) {
3169 /* does nothing. It is needed to signal that no network cards
3170 are wanted */
3171 ret = 0;
3172 } else
3173 #ifdef CONFIG_SLIRP
3174 if (!strcmp(device, "user")) {
3175 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3176 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3178 ret = net_slirp_init(vlan);
3179 } else
3180 #endif
3181 #ifdef _WIN32
3182 if (!strcmp(device, "tap")) {
3183 char ifname[64];
3184 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3185 fprintf(stderr, "tap: no interface name\n");
3186 return -1;
3188 ret = tap_win32_init(vlan, ifname);
3189 } else
3190 #else
3191 if (!strcmp(device, "tap")) {
3192 char ifname[64];
3193 char setup_script[1024];
3194 int fd;
3195 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3196 fd = strtol(buf, NULL, 0);
3197 ret = -1;
3198 if (net_tap_fd_init(vlan, fd))
3199 ret = 0;
3200 } else {
3201 get_param_value(ifname, sizeof(ifname), "ifname", p);
3202 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3203 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3205 ret = net_tap_init(vlan, ifname, setup_script);
3207 } else
3208 #endif
3209 if (!strcmp(device, "socket")) {
3210 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3211 int fd;
3212 fd = strtol(buf, NULL, 0);
3213 ret = -1;
3214 if (net_socket_fd_init(vlan, fd, 1))
3215 ret = 0;
3216 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3217 ret = net_socket_listen_init(vlan, buf);
3218 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3219 ret = net_socket_connect_init(vlan, buf);
3220 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3221 ret = net_socket_mcast_init(vlan, buf);
3222 } else {
3223 fprintf(stderr, "Unknown socket options: %s\n", p);
3224 return -1;
3226 } else
3228 fprintf(stderr, "Unknown network device: %s\n", device);
3229 return -1;
3231 if (ret < 0) {
3232 fprintf(stderr, "Could not initialize device '%s'\n", device);
3235 return ret;
3238 void do_info_network(void)
3240 VLANState *vlan;
3241 VLANClientState *vc;
3243 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3244 term_printf("VLAN %d devices:\n", vlan->id);
3245 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3246 term_printf(" %s\n", vc->info_str);
3250 /***********************************************************/
3251 /* USB devices */
3253 static USBPort *used_usb_ports;
3254 static USBPort *free_usb_ports;
3256 /* ??? Maybe change this to register a hub to keep track of the topology. */
3257 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3258 usb_attachfn attach)
3260 port->opaque = opaque;
3261 port->index = index;
3262 port->attach = attach;
3263 port->next = free_usb_ports;
3264 free_usb_ports = port;
3267 static int usb_device_add(const char *devname)
3269 const char *p;
3270 USBDevice *dev;
3271 USBPort *port;
3273 if (!free_usb_ports)
3274 return -1;
3276 if (strstart(devname, "host:", &p)) {
3277 dev = usb_host_device_open(p);
3278 } else if (!strcmp(devname, "mouse")) {
3279 dev = usb_mouse_init();
3280 } else if (!strcmp(devname, "tablet")) {
3281 dev = usb_tablet_init();
3282 } else {
3283 return -1;
3285 if (!dev)
3286 return -1;
3288 /* Find a USB port to add the device to. */
3289 port = free_usb_ports;
3290 if (!port->next) {
3291 USBDevice *hub;
3293 /* Create a new hub and chain it on. */
3294 free_usb_ports = NULL;
3295 port->next = used_usb_ports;
3296 used_usb_ports = port;
3298 hub = usb_hub_init(VM_USB_HUB_SIZE);
3299 usb_attach(port, hub);
3300 port = free_usb_ports;
3303 free_usb_ports = port->next;
3304 port->next = used_usb_ports;
3305 used_usb_ports = port;
3306 usb_attach(port, dev);
3307 return 0;
3310 static int usb_device_del(const char *devname)
3312 USBPort *port;
3313 USBPort **lastp;
3314 int bus_num, addr;
3315 const char *p;
3317 if (!used_usb_ports)
3318 return -1;
3320 p = strchr(devname, '.');
3321 if (!p)
3322 return -1;
3323 bus_num = strtoul(devname, NULL, 0);
3324 addr = strtoul(p + 1, NULL, 0);
3325 if (bus_num != 0)
3326 return -1;
3328 lastp = &used_usb_ports;
3329 port = used_usb_ports;
3330 while (port && port->dev->addr != addr) {
3331 lastp = &port->next;
3332 port = port->next;
3335 if (!port)
3336 return -1;
3338 *lastp = port->next;
3339 usb_attach(port, NULL);
3340 port->next = free_usb_ports;
3341 free_usb_ports = port;
3342 return 0;
3345 void do_usb_add(const char *devname)
3347 int ret;
3348 ret = usb_device_add(devname);
3349 if (ret < 0)
3350 term_printf("Could not add USB device '%s'\n", devname);
3353 void do_usb_del(const char *devname)
3355 int ret;
3356 ret = usb_device_del(devname);
3357 if (ret < 0)
3358 term_printf("Could not remove USB device '%s'\n", devname);
3361 void usb_info(void)
3363 USBDevice *dev;
3364 USBPort *port;
3365 const char *speed_str;
3367 if (!usb_enabled) {
3368 term_printf("USB support not enabled\n");
3369 return;
3372 for (port = used_usb_ports; port; port = port->next) {
3373 dev = port->dev;
3374 if (!dev)
3375 continue;
3376 switch(dev->speed) {
3377 case USB_SPEED_LOW:
3378 speed_str = "1.5";
3379 break;
3380 case USB_SPEED_FULL:
3381 speed_str = "12";
3382 break;
3383 case USB_SPEED_HIGH:
3384 speed_str = "480";
3385 break;
3386 default:
3387 speed_str = "?";
3388 break;
3390 term_printf(" Device %d.%d, speed %s Mb/s\n",
3391 0, dev->addr, speed_str);
3395 /***********************************************************/
3396 /* pid file */
3398 static char *pid_filename;
3400 /* Remove PID file. Called on normal exit */
3402 static void remove_pidfile(void)
3404 unlink (pid_filename);
3407 static void create_pidfile(const char *filename)
3409 struct stat pidstat;
3410 FILE *f;
3412 /* Try to write our PID to the named file */
3413 if (stat(filename, &pidstat) < 0) {
3414 if (errno == ENOENT) {
3415 if ((f = fopen (filename, "w")) == NULL) {
3416 perror("Opening pidfile");
3417 exit(1);
3419 fprintf(f, "%d\n", getpid());
3420 fclose(f);
3421 pid_filename = qemu_strdup(filename);
3422 if (!pid_filename) {
3423 fprintf(stderr, "Could not save PID filename");
3424 exit(1);
3426 atexit(remove_pidfile);
3428 } else {
3429 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3430 filename);
3431 exit(1);
3435 /***********************************************************/
3436 /* dumb display */
3438 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3442 static void dumb_resize(DisplayState *ds, int w, int h)
3446 static void dumb_refresh(DisplayState *ds)
3448 vga_hw_update();
3451 void dumb_display_init(DisplayState *ds)
3453 ds->data = NULL;
3454 ds->linesize = 0;
3455 ds->depth = 0;
3456 ds->dpy_update = dumb_update;
3457 ds->dpy_resize = dumb_resize;
3458 ds->dpy_refresh = dumb_refresh;
3461 #if !defined(CONFIG_SOFTMMU)
3462 /***********************************************************/
3463 /* cpu signal handler */
3464 static void host_segv_handler(int host_signum, siginfo_t *info,
3465 void *puc)
3467 if (cpu_signal_handler(host_signum, info, puc))
3468 return;
3469 if (stdio_nb_clients > 0)
3470 term_exit();
3471 abort();
3473 #endif
3475 /***********************************************************/
3476 /* I/O handling */
3478 #define MAX_IO_HANDLERS 64
3480 typedef struct IOHandlerRecord {
3481 int fd;
3482 IOCanRWHandler *fd_read_poll;
3483 IOHandler *fd_read;
3484 IOHandler *fd_write;
3485 void *opaque;
3486 /* temporary data */
3487 struct pollfd *ufd;
3488 struct IOHandlerRecord *next;
3489 } IOHandlerRecord;
3491 static IOHandlerRecord *first_io_handler;
3493 /* XXX: fd_read_poll should be suppressed, but an API change is
3494 necessary in the character devices to suppress fd_can_read(). */
3495 int qemu_set_fd_handler2(int fd,
3496 IOCanRWHandler *fd_read_poll,
3497 IOHandler *fd_read,
3498 IOHandler *fd_write,
3499 void *opaque)
3501 IOHandlerRecord **pioh, *ioh;
3503 if (!fd_read && !fd_write) {
3504 pioh = &first_io_handler;
3505 for(;;) {
3506 ioh = *pioh;
3507 if (ioh == NULL)
3508 break;
3509 if (ioh->fd == fd) {
3510 *pioh = ioh->next;
3511 qemu_free(ioh);
3512 break;
3514 pioh = &ioh->next;
3516 } else {
3517 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3518 if (ioh->fd == fd)
3519 goto found;
3521 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3522 if (!ioh)
3523 return -1;
3524 ioh->next = first_io_handler;
3525 first_io_handler = ioh;
3526 found:
3527 ioh->fd = fd;
3528 ioh->fd_read_poll = fd_read_poll;
3529 ioh->fd_read = fd_read;
3530 ioh->fd_write = fd_write;
3531 ioh->opaque = opaque;
3533 return 0;
3536 int qemu_set_fd_handler(int fd,
3537 IOHandler *fd_read,
3538 IOHandler *fd_write,
3539 void *opaque)
3541 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3544 /***********************************************************/
3545 /* Polling handling */
3547 typedef struct PollingEntry {
3548 PollingFunc *func;
3549 void *opaque;
3550 struct PollingEntry *next;
3551 } PollingEntry;
3553 static PollingEntry *first_polling_entry;
3555 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3557 PollingEntry **ppe, *pe;
3558 pe = qemu_mallocz(sizeof(PollingEntry));
3559 if (!pe)
3560 return -1;
3561 pe->func = func;
3562 pe->opaque = opaque;
3563 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3564 *ppe = pe;
3565 return 0;
3568 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3570 PollingEntry **ppe, *pe;
3571 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3572 pe = *ppe;
3573 if (pe->func == func && pe->opaque == opaque) {
3574 *ppe = pe->next;
3575 qemu_free(pe);
3576 break;
3581 /***********************************************************/
3582 /* savevm/loadvm support */
3584 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3586 fwrite(buf, 1, size, f);
3589 void qemu_put_byte(QEMUFile *f, int v)
3591 fputc(v, f);
3594 void qemu_put_be16(QEMUFile *f, unsigned int v)
3596 qemu_put_byte(f, v >> 8);
3597 qemu_put_byte(f, v);
3600 void qemu_put_be32(QEMUFile *f, unsigned int v)
3602 qemu_put_byte(f, v >> 24);
3603 qemu_put_byte(f, v >> 16);
3604 qemu_put_byte(f, v >> 8);
3605 qemu_put_byte(f, v);
3608 void qemu_put_be64(QEMUFile *f, uint64_t v)
3610 qemu_put_be32(f, v >> 32);
3611 qemu_put_be32(f, v);
3614 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3616 return fread(buf, 1, size, f);
3619 int qemu_get_byte(QEMUFile *f)
3621 int v;
3622 v = fgetc(f);
3623 if (v == EOF)
3624 return 0;
3625 else
3626 return v;
3629 unsigned int qemu_get_be16(QEMUFile *f)
3631 unsigned int v;
3632 v = qemu_get_byte(f) << 8;
3633 v |= qemu_get_byte(f);
3634 return v;
3637 unsigned int qemu_get_be32(QEMUFile *f)
3639 unsigned int v;
3640 v = qemu_get_byte(f) << 24;
3641 v |= qemu_get_byte(f) << 16;
3642 v |= qemu_get_byte(f) << 8;
3643 v |= qemu_get_byte(f);
3644 return v;
3647 uint64_t qemu_get_be64(QEMUFile *f)
3649 uint64_t v;
3650 v = (uint64_t)qemu_get_be32(f) << 32;
3651 v |= qemu_get_be32(f);
3652 return v;
3655 int64_t qemu_ftell(QEMUFile *f)
3657 return ftell(f);
3660 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3662 if (fseek(f, pos, whence) < 0)
3663 return -1;
3664 return ftell(f);
3667 typedef struct SaveStateEntry {
3668 char idstr[256];
3669 int instance_id;
3670 int version_id;
3671 SaveStateHandler *save_state;
3672 LoadStateHandler *load_state;
3673 void *opaque;
3674 struct SaveStateEntry *next;
3675 } SaveStateEntry;
3677 static SaveStateEntry *first_se;
3679 int register_savevm(const char *idstr,
3680 int instance_id,
3681 int version_id,
3682 SaveStateHandler *save_state,
3683 LoadStateHandler *load_state,
3684 void *opaque)
3686 SaveStateEntry *se, **pse;
3688 se = qemu_malloc(sizeof(SaveStateEntry));
3689 if (!se)
3690 return -1;
3691 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3692 se->instance_id = instance_id;
3693 se->version_id = version_id;
3694 se->save_state = save_state;
3695 se->load_state = load_state;
3696 se->opaque = opaque;
3697 se->next = NULL;
3699 /* add at the end of list */
3700 pse = &first_se;
3701 while (*pse != NULL)
3702 pse = &(*pse)->next;
3703 *pse = se;
3704 return 0;
3707 #define QEMU_VM_FILE_MAGIC 0x5145564d
3708 #define QEMU_VM_FILE_VERSION 0x00000001
3710 int qemu_savevm(const char *filename)
3712 SaveStateEntry *se;
3713 QEMUFile *f;
3714 int len, len_pos, cur_pos, saved_vm_running, ret;
3716 saved_vm_running = vm_running;
3717 vm_stop(0);
3719 f = fopen(filename, "wb");
3720 if (!f) {
3721 ret = -1;
3722 goto the_end;
3725 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3726 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3728 for(se = first_se; se != NULL; se = se->next) {
3729 /* ID string */
3730 len = strlen(se->idstr);
3731 qemu_put_byte(f, len);
3732 qemu_put_buffer(f, se->idstr, len);
3734 qemu_put_be32(f, se->instance_id);
3735 qemu_put_be32(f, se->version_id);
3737 /* record size: filled later */
3738 len_pos = ftell(f);
3739 qemu_put_be32(f, 0);
3741 se->save_state(f, se->opaque);
3743 /* fill record size */
3744 cur_pos = ftell(f);
3745 len = ftell(f) - len_pos - 4;
3746 fseek(f, len_pos, SEEK_SET);
3747 qemu_put_be32(f, len);
3748 fseek(f, cur_pos, SEEK_SET);
3751 fclose(f);
3752 ret = 0;
3753 the_end:
3754 if (saved_vm_running)
3755 vm_start();
3756 return ret;
3759 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3761 SaveStateEntry *se;
3763 for(se = first_se; se != NULL; se = se->next) {
3764 if (!strcmp(se->idstr, idstr) &&
3765 instance_id == se->instance_id)
3766 return se;
3768 return NULL;
3771 int qemu_loadvm(const char *filename)
3773 SaveStateEntry *se;
3774 QEMUFile *f;
3775 int len, cur_pos, ret, instance_id, record_len, version_id;
3776 int saved_vm_running;
3777 unsigned int v;
3778 char idstr[256];
3780 saved_vm_running = vm_running;
3781 vm_stop(0);
3783 f = fopen(filename, "rb");
3784 if (!f) {
3785 ret = -1;
3786 goto the_end;
3789 v = qemu_get_be32(f);
3790 if (v != QEMU_VM_FILE_MAGIC)
3791 goto fail;
3792 v = qemu_get_be32(f);
3793 if (v != QEMU_VM_FILE_VERSION) {
3794 fail:
3795 fclose(f);
3796 ret = -1;
3797 goto the_end;
3799 for(;;) {
3800 len = qemu_get_byte(f);
3801 if (feof(f))
3802 break;
3803 qemu_get_buffer(f, idstr, len);
3804 idstr[len] = '\0';
3805 instance_id = qemu_get_be32(f);
3806 version_id = qemu_get_be32(f);
3807 record_len = qemu_get_be32(f);
3808 #if 0
3809 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3810 idstr, instance_id, version_id, record_len);
3811 #endif
3812 cur_pos = ftell(f);
3813 se = find_se(idstr, instance_id);
3814 if (!se) {
3815 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3816 instance_id, idstr);
3817 } else {
3818 ret = se->load_state(f, se->opaque, version_id);
3819 if (ret < 0) {
3820 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3821 instance_id, idstr);
3824 /* always seek to exact end of record */
3825 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3827 fclose(f);
3828 ret = 0;
3829 the_end:
3830 if (saved_vm_running)
3831 vm_start();
3832 return ret;
3835 /***********************************************************/
3836 /* cpu save/restore */
3838 #if defined(TARGET_I386)
3840 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3842 qemu_put_be32(f, dt->selector);
3843 qemu_put_betl(f, dt->base);
3844 qemu_put_be32(f, dt->limit);
3845 qemu_put_be32(f, dt->flags);
3848 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3850 dt->selector = qemu_get_be32(f);
3851 dt->base = qemu_get_betl(f);
3852 dt->limit = qemu_get_be32(f);
3853 dt->flags = qemu_get_be32(f);
3856 void cpu_save(QEMUFile *f, void *opaque)
3858 CPUState *env = opaque;
3859 uint16_t fptag, fpus, fpuc, fpregs_format;
3860 uint32_t hflags;
3861 int i;
3863 for(i = 0; i < CPU_NB_REGS; i++)
3864 qemu_put_betls(f, &env->regs[i]);
3865 qemu_put_betls(f, &env->eip);
3866 qemu_put_betls(f, &env->eflags);
3867 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3868 qemu_put_be32s(f, &hflags);
3870 /* FPU */
3871 fpuc = env->fpuc;
3872 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3873 fptag = 0;
3874 for(i = 0; i < 8; i++) {
3875 fptag |= ((!env->fptags[i]) << i);
3878 qemu_put_be16s(f, &fpuc);
3879 qemu_put_be16s(f, &fpus);
3880 qemu_put_be16s(f, &fptag);
3882 #ifdef USE_X86LDOUBLE
3883 fpregs_format = 0;
3884 #else
3885 fpregs_format = 1;
3886 #endif
3887 qemu_put_be16s(f, &fpregs_format);
3889 for(i = 0; i < 8; i++) {
3890 #ifdef USE_X86LDOUBLE
3892 uint64_t mant;
3893 uint16_t exp;
3894 /* we save the real CPU data (in case of MMX usage only 'mant'
3895 contains the MMX register */
3896 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3897 qemu_put_be64(f, mant);
3898 qemu_put_be16(f, exp);
3900 #else
3901 /* if we use doubles for float emulation, we save the doubles to
3902 avoid losing information in case of MMX usage. It can give
3903 problems if the image is restored on a CPU where long
3904 doubles are used instead. */
3905 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3906 #endif
3909 for(i = 0; i < 6; i++)
3910 cpu_put_seg(f, &env->segs[i]);
3911 cpu_put_seg(f, &env->ldt);
3912 cpu_put_seg(f, &env->tr);
3913 cpu_put_seg(f, &env->gdt);
3914 cpu_put_seg(f, &env->idt);
3916 qemu_put_be32s(f, &env->sysenter_cs);
3917 qemu_put_be32s(f, &env->sysenter_esp);
3918 qemu_put_be32s(f, &env->sysenter_eip);
3920 qemu_put_betls(f, &env->cr[0]);
3921 qemu_put_betls(f, &env->cr[2]);
3922 qemu_put_betls(f, &env->cr[3]);
3923 qemu_put_betls(f, &env->cr[4]);
3925 for(i = 0; i < 8; i++)
3926 qemu_put_betls(f, &env->dr[i]);
3928 /* MMU */
3929 qemu_put_be32s(f, &env->a20_mask);
3931 /* XMM */
3932 qemu_put_be32s(f, &env->mxcsr);
3933 for(i = 0; i < CPU_NB_REGS; i++) {
3934 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3935 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3938 #ifdef TARGET_X86_64
3939 qemu_put_be64s(f, &env->efer);
3940 qemu_put_be64s(f, &env->star);
3941 qemu_put_be64s(f, &env->lstar);
3942 qemu_put_be64s(f, &env->cstar);
3943 qemu_put_be64s(f, &env->fmask);
3944 qemu_put_be64s(f, &env->kernelgsbase);
3945 #endif
3948 #ifdef USE_X86LDOUBLE
3949 /* XXX: add that in a FPU generic layer */
3950 union x86_longdouble {
3951 uint64_t mant;
3952 uint16_t exp;
3955 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3956 #define EXPBIAS1 1023
3957 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3958 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3960 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3962 int e;
3963 /* mantissa */
3964 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3965 /* exponent + sign */
3966 e = EXPD1(temp) - EXPBIAS1 + 16383;
3967 e |= SIGND1(temp) >> 16;
3968 p->exp = e;
3970 #endif
3972 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3974 CPUState *env = opaque;
3975 int i, guess_mmx;
3976 uint32_t hflags;
3977 uint16_t fpus, fpuc, fptag, fpregs_format;
3979 if (version_id != 3)
3980 return -EINVAL;
3981 for(i = 0; i < CPU_NB_REGS; i++)
3982 qemu_get_betls(f, &env->regs[i]);
3983 qemu_get_betls(f, &env->eip);
3984 qemu_get_betls(f, &env->eflags);
3985 qemu_get_be32s(f, &hflags);
3987 qemu_get_be16s(f, &fpuc);
3988 qemu_get_be16s(f, &fpus);
3989 qemu_get_be16s(f, &fptag);
3990 qemu_get_be16s(f, &fpregs_format);
3992 /* NOTE: we cannot always restore the FPU state if the image come
3993 from a host with a different 'USE_X86LDOUBLE' define. We guess
3994 if we are in an MMX state to restore correctly in that case. */
3995 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3996 for(i = 0; i < 8; i++) {
3997 uint64_t mant;
3998 uint16_t exp;
4000 switch(fpregs_format) {
4001 case 0:
4002 mant = qemu_get_be64(f);
4003 exp = qemu_get_be16(f);
4004 #ifdef USE_X86LDOUBLE
4005 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4006 #else
4007 /* difficult case */
4008 if (guess_mmx)
4009 env->fpregs[i].mmx.MMX_Q(0) = mant;
4010 else
4011 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4012 #endif
4013 break;
4014 case 1:
4015 mant = qemu_get_be64(f);
4016 #ifdef USE_X86LDOUBLE
4018 union x86_longdouble *p;
4019 /* difficult case */
4020 p = (void *)&env->fpregs[i];
4021 if (guess_mmx) {
4022 p->mant = mant;
4023 p->exp = 0xffff;
4024 } else {
4025 fp64_to_fp80(p, mant);
4028 #else
4029 env->fpregs[i].mmx.MMX_Q(0) = mant;
4030 #endif
4031 break;
4032 default:
4033 return -EINVAL;
4037 env->fpuc = fpuc;
4038 /* XXX: restore FPU round state */
4039 env->fpstt = (fpus >> 11) & 7;
4040 env->fpus = fpus & ~0x3800;
4041 fptag ^= 0xff;
4042 for(i = 0; i < 8; i++) {
4043 env->fptags[i] = (fptag >> i) & 1;
4046 for(i = 0; i < 6; i++)
4047 cpu_get_seg(f, &env->segs[i]);
4048 cpu_get_seg(f, &env->ldt);
4049 cpu_get_seg(f, &env->tr);
4050 cpu_get_seg(f, &env->gdt);
4051 cpu_get_seg(f, &env->idt);
4053 qemu_get_be32s(f, &env->sysenter_cs);
4054 qemu_get_be32s(f, &env->sysenter_esp);
4055 qemu_get_be32s(f, &env->sysenter_eip);
4057 qemu_get_betls(f, &env->cr[0]);
4058 qemu_get_betls(f, &env->cr[2]);
4059 qemu_get_betls(f, &env->cr[3]);
4060 qemu_get_betls(f, &env->cr[4]);
4062 for(i = 0; i < 8; i++)
4063 qemu_get_betls(f, &env->dr[i]);
4065 /* MMU */
4066 qemu_get_be32s(f, &env->a20_mask);
4068 qemu_get_be32s(f, &env->mxcsr);
4069 for(i = 0; i < CPU_NB_REGS; i++) {
4070 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4071 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4074 #ifdef TARGET_X86_64
4075 qemu_get_be64s(f, &env->efer);
4076 qemu_get_be64s(f, &env->star);
4077 qemu_get_be64s(f, &env->lstar);
4078 qemu_get_be64s(f, &env->cstar);
4079 qemu_get_be64s(f, &env->fmask);
4080 qemu_get_be64s(f, &env->kernelgsbase);
4081 #endif
4083 /* XXX: compute hflags from scratch, except for CPL and IIF */
4084 env->hflags = hflags;
4085 tlb_flush(env, 1);
4086 return 0;
4089 #elif defined(TARGET_PPC)
4090 void cpu_save(QEMUFile *f, void *opaque)
4094 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4096 return 0;
4099 #elif defined(TARGET_MIPS)
4100 void cpu_save(QEMUFile *f, void *opaque)
4104 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4106 return 0;
4109 #elif defined(TARGET_SPARC)
4110 void cpu_save(QEMUFile *f, void *opaque)
4112 CPUState *env = opaque;
4113 int i;
4114 uint32_t tmp;
4116 for(i = 0; i < 8; i++)
4117 qemu_put_betls(f, &env->gregs[i]);
4118 for(i = 0; i < NWINDOWS * 16; i++)
4119 qemu_put_betls(f, &env->regbase[i]);
4121 /* FPU */
4122 for(i = 0; i < TARGET_FPREGS; i++) {
4123 union {
4124 TARGET_FPREG_T f;
4125 target_ulong i;
4126 } u;
4127 u.f = env->fpr[i];
4128 qemu_put_betl(f, u.i);
4131 qemu_put_betls(f, &env->pc);
4132 qemu_put_betls(f, &env->npc);
4133 qemu_put_betls(f, &env->y);
4134 tmp = GET_PSR(env);
4135 qemu_put_be32(f, tmp);
4136 qemu_put_betls(f, &env->fsr);
4137 qemu_put_betls(f, &env->tbr);
4138 #ifndef TARGET_SPARC64
4139 qemu_put_be32s(f, &env->wim);
4140 /* MMU */
4141 for(i = 0; i < 16; i++)
4142 qemu_put_be32s(f, &env->mmuregs[i]);
4143 #endif
4146 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4148 CPUState *env = opaque;
4149 int i;
4150 uint32_t tmp;
4152 for(i = 0; i < 8; i++)
4153 qemu_get_betls(f, &env->gregs[i]);
4154 for(i = 0; i < NWINDOWS * 16; i++)
4155 qemu_get_betls(f, &env->regbase[i]);
4157 /* FPU */
4158 for(i = 0; i < TARGET_FPREGS; i++) {
4159 union {
4160 TARGET_FPREG_T f;
4161 target_ulong i;
4162 } u;
4163 u.i = qemu_get_betl(f);
4164 env->fpr[i] = u.f;
4167 qemu_get_betls(f, &env->pc);
4168 qemu_get_betls(f, &env->npc);
4169 qemu_get_betls(f, &env->y);
4170 tmp = qemu_get_be32(f);
4171 env->cwp = 0; /* needed to ensure that the wrapping registers are
4172 correctly updated */
4173 PUT_PSR(env, tmp);
4174 qemu_get_betls(f, &env->fsr);
4175 qemu_get_betls(f, &env->tbr);
4176 #ifndef TARGET_SPARC64
4177 qemu_get_be32s(f, &env->wim);
4178 /* MMU */
4179 for(i = 0; i < 16; i++)
4180 qemu_get_be32s(f, &env->mmuregs[i]);
4181 #endif
4182 tlb_flush(env, 1);
4183 return 0;
4186 #elif defined(TARGET_ARM)
4188 /* ??? Need to implement these. */
4189 void cpu_save(QEMUFile *f, void *opaque)
4193 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4195 return 0;
4198 #else
4200 #warning No CPU save/restore functions
4202 #endif
4204 /***********************************************************/
4205 /* ram save/restore */
4207 /* we just avoid storing empty pages */
4208 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4210 int i, v;
4212 v = buf[0];
4213 for(i = 1; i < len; i++) {
4214 if (buf[i] != v)
4215 goto normal_save;
4217 qemu_put_byte(f, 1);
4218 qemu_put_byte(f, v);
4219 return;
4220 normal_save:
4221 qemu_put_byte(f, 0);
4222 qemu_put_buffer(f, buf, len);
4225 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4227 int v;
4229 v = qemu_get_byte(f);
4230 switch(v) {
4231 case 0:
4232 if (qemu_get_buffer(f, buf, len) != len)
4233 return -EIO;
4234 break;
4235 case 1:
4236 v = qemu_get_byte(f);
4237 memset(buf, v, len);
4238 break;
4239 default:
4240 return -EINVAL;
4242 return 0;
4245 static void ram_save(QEMUFile *f, void *opaque)
4247 int i;
4248 qemu_put_be32(f, phys_ram_size);
4249 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4250 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4254 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4256 int i, ret;
4258 if (version_id != 1)
4259 return -EINVAL;
4260 if (qemu_get_be32(f) != phys_ram_size)
4261 return -EINVAL;
4262 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4263 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4264 if (ret)
4265 return ret;
4267 return 0;
4270 /***********************************************************/
4271 /* machine registration */
4273 QEMUMachine *first_machine = NULL;
4275 int qemu_register_machine(QEMUMachine *m)
4277 QEMUMachine **pm;
4278 pm = &first_machine;
4279 while (*pm != NULL)
4280 pm = &(*pm)->next;
4281 m->next = NULL;
4282 *pm = m;
4283 return 0;
4286 QEMUMachine *find_machine(const char *name)
4288 QEMUMachine *m;
4290 for(m = first_machine; m != NULL; m = m->next) {
4291 if (!strcmp(m->name, name))
4292 return m;
4294 return NULL;
4297 /***********************************************************/
4298 /* main execution loop */
4300 void gui_update(void *opaque)
4302 display_state.dpy_refresh(&display_state);
4303 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4306 struct vm_change_state_entry {
4307 VMChangeStateHandler *cb;
4308 void *opaque;
4309 LIST_ENTRY (vm_change_state_entry) entries;
4312 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4314 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4315 void *opaque)
4317 VMChangeStateEntry *e;
4319 e = qemu_mallocz(sizeof (*e));
4320 if (!e)
4321 return NULL;
4323 e->cb = cb;
4324 e->opaque = opaque;
4325 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4326 return e;
4329 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4331 LIST_REMOVE (e, entries);
4332 qemu_free (e);
4335 static void vm_state_notify(int running)
4337 VMChangeStateEntry *e;
4339 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4340 e->cb(e->opaque, running);
4344 /* XXX: support several handlers */
4345 static VMStopHandler *vm_stop_cb;
4346 static void *vm_stop_opaque;
4348 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4350 vm_stop_cb = cb;
4351 vm_stop_opaque = opaque;
4352 return 0;
4355 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4357 vm_stop_cb = NULL;
4360 void vm_start(void)
4362 if (!vm_running) {
4363 cpu_enable_ticks();
4364 vm_running = 1;
4365 vm_state_notify(1);
4369 void vm_stop(int reason)
4371 if (vm_running) {
4372 cpu_disable_ticks();
4373 vm_running = 0;
4374 if (reason != 0) {
4375 if (vm_stop_cb) {
4376 vm_stop_cb(vm_stop_opaque, reason);
4379 vm_state_notify(0);
4383 /* reset/shutdown handler */
4385 typedef struct QEMUResetEntry {
4386 QEMUResetHandler *func;
4387 void *opaque;
4388 struct QEMUResetEntry *next;
4389 } QEMUResetEntry;
4391 static QEMUResetEntry *first_reset_entry;
4392 static int reset_requested;
4393 static int shutdown_requested;
4394 static int powerdown_requested;
4396 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4398 QEMUResetEntry **pre, *re;
4400 pre = &first_reset_entry;
4401 while (*pre != NULL)
4402 pre = &(*pre)->next;
4403 re = qemu_mallocz(sizeof(QEMUResetEntry));
4404 re->func = func;
4405 re->opaque = opaque;
4406 re->next = NULL;
4407 *pre = re;
4410 void qemu_system_reset(void)
4412 QEMUResetEntry *re;
4414 /* reset all devices */
4415 for(re = first_reset_entry; re != NULL; re = re->next) {
4416 re->func(re->opaque);
4420 void qemu_system_reset_request(void)
4422 reset_requested = 1;
4423 if (cpu_single_env)
4424 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4427 void qemu_system_shutdown_request(void)
4429 shutdown_requested = 1;
4430 if (cpu_single_env)
4431 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4434 void qemu_system_powerdown_request(void)
4436 powerdown_requested = 1;
4437 if (cpu_single_env)
4438 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4441 void main_loop_wait(int timeout)
4443 IOHandlerRecord *ioh, *ioh_next;
4444 fd_set rfds, wfds, xfds;
4445 int ret, nfds;
4446 struct timeval tv;
4447 PollingEntry *pe;
4450 /* XXX: need to suppress polling by better using win32 events */
4451 ret = 0;
4452 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4453 ret |= pe->func(pe->opaque);
4455 #ifdef _WIN32
4456 if (ret == 0 && timeout > 0) {
4457 int err;
4458 HANDLE hEvents[1];
4460 hEvents[0] = host_alarm;
4461 ret = WaitForMultipleObjects(1, hEvents, FALSE, timeout);
4462 switch(ret) {
4463 case WAIT_OBJECT_0 + 0:
4464 break;
4465 case WAIT_TIMEOUT:
4466 break;
4467 default:
4468 err = GetLastError();
4469 fprintf(stderr, "Wait error %d %d\n", ret, err);
4470 break;
4473 #endif
4474 /* poll any events */
4475 /* XXX: separate device handlers from system ones */
4476 nfds = -1;
4477 FD_ZERO(&rfds);
4478 FD_ZERO(&wfds);
4479 FD_ZERO(&xfds);
4480 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4481 if (ioh->fd_read &&
4482 (!ioh->fd_read_poll ||
4483 ioh->fd_read_poll(ioh->opaque) != 0)) {
4484 FD_SET(ioh->fd, &rfds);
4485 if (ioh->fd > nfds)
4486 nfds = ioh->fd;
4488 if (ioh->fd_write) {
4489 FD_SET(ioh->fd, &wfds);
4490 if (ioh->fd > nfds)
4491 nfds = ioh->fd;
4495 tv.tv_sec = 0;
4496 #ifdef _WIN32
4497 tv.tv_usec = 0;
4498 #else
4499 tv.tv_usec = timeout * 1000;
4500 #endif
4501 #if defined(CONFIG_SLIRP)
4502 if (slirp_inited) {
4503 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4505 #endif
4506 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4507 if (ret > 0) {
4508 /* XXX: better handling of removal */
4509 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4510 ioh_next = ioh->next;
4511 if (FD_ISSET(ioh->fd, &rfds)) {
4512 ioh->fd_read(ioh->opaque);
4514 if (FD_ISSET(ioh->fd, &wfds)) {
4515 ioh->fd_write(ioh->opaque);
4519 #if defined(CONFIG_SLIRP)
4520 if (slirp_inited) {
4521 if (ret < 0) {
4522 FD_ZERO(&rfds);
4523 FD_ZERO(&wfds);
4524 FD_ZERO(&xfds);
4526 slirp_select_poll(&rfds, &wfds, &xfds);
4528 #endif
4529 #ifdef _WIN32
4530 tap_win32_poll();
4531 #endif
4533 if (vm_running) {
4534 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4535 qemu_get_clock(vm_clock));
4536 /* run dma transfers, if any */
4537 DMA_run();
4540 /* real time timers */
4541 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4542 qemu_get_clock(rt_clock));
4545 static CPUState *cur_cpu;
4547 int main_loop(void)
4549 int ret, timeout;
4550 #ifdef CONFIG_PROFILER
4551 int64_t ti;
4552 #endif
4553 CPUState *env;
4555 cur_cpu = first_cpu;
4556 for(;;) {
4557 if (vm_running) {
4559 env = cur_cpu;
4560 for(;;) {
4561 /* get next cpu */
4562 env = env->next_cpu;
4563 if (!env)
4564 env = first_cpu;
4565 #ifdef CONFIG_PROFILER
4566 ti = profile_getclock();
4567 #endif
4568 ret = cpu_exec(env);
4569 #ifdef CONFIG_PROFILER
4570 qemu_time += profile_getclock() - ti;
4571 #endif
4572 if (ret != EXCP_HALTED)
4573 break;
4574 /* all CPUs are halted ? */
4575 if (env == cur_cpu) {
4576 ret = EXCP_HLT;
4577 break;
4580 cur_cpu = env;
4582 if (shutdown_requested) {
4583 ret = EXCP_INTERRUPT;
4584 break;
4586 if (reset_requested) {
4587 reset_requested = 0;
4588 qemu_system_reset();
4589 ret = EXCP_INTERRUPT;
4591 if (powerdown_requested) {
4592 powerdown_requested = 0;
4593 qemu_system_powerdown();
4594 ret = EXCP_INTERRUPT;
4596 if (ret == EXCP_DEBUG) {
4597 vm_stop(EXCP_DEBUG);
4599 /* if hlt instruction, we wait until the next IRQ */
4600 /* XXX: use timeout computed from timers */
4601 if (ret == EXCP_HLT)
4602 timeout = 10;
4603 else
4604 timeout = 0;
4605 } else {
4606 timeout = 10;
4608 #ifdef CONFIG_PROFILER
4609 ti = profile_getclock();
4610 #endif
4611 main_loop_wait(timeout);
4612 #ifdef CONFIG_PROFILER
4613 dev_time += profile_getclock() - ti;
4614 #endif
4616 cpu_disable_ticks();
4617 return ret;
4620 void help(void)
4622 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4623 "usage: %s [options] [disk_image]\n"
4624 "\n"
4625 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4626 "\n"
4627 "Standard options:\n"
4628 "-M machine select emulated machine (-M ? for list)\n"
4629 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4630 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4631 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4632 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4633 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4634 "-snapshot write to temporary files instead of disk image files\n"
4635 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4636 "-smp n set the number of CPUs to 'n' [default=1]\n"
4637 "-nographic disable graphical output and redirect serial I/Os to console\n"
4638 #ifndef _WIN32
4639 "-k language use keyboard layout (for example \"fr\" for French)\n"
4640 #endif
4641 #ifdef HAS_AUDIO
4642 "-audio-help print list of audio drivers and their options\n"
4643 "-soundhw c1,... enable audio support\n"
4644 " and only specified sound cards (comma separated list)\n"
4645 " use -soundhw ? to get the list of supported cards\n"
4646 " use -soundhw all to enable all of them\n"
4647 #endif
4648 "-localtime set the real time clock to local time [default=utc]\n"
4649 "-full-screen start in full screen\n"
4650 #ifdef TARGET_I386
4651 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4652 #endif
4653 "-usb enable the USB driver (will be the default soon)\n"
4654 "-usbdevice name add the host or guest USB device 'name'\n"
4655 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4656 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4657 #endif
4658 "\n"
4659 "Network options:\n"
4660 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4661 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4662 #ifdef CONFIG_SLIRP
4663 "-net user[,vlan=n][,hostname=host]\n"
4664 " connect the user mode network stack to VLAN 'n' and send\n"
4665 " hostname 'host' to DHCP clients\n"
4666 #endif
4667 #ifdef _WIN32
4668 "-net tap[,vlan=n],ifname=name\n"
4669 " connect the host TAP network interface to VLAN 'n'\n"
4670 #else
4671 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4672 " connect the host TAP network interface to VLAN 'n' and use\n"
4673 " the network script 'file' (default=%s);\n"
4674 " use 'fd=h' to connect to an already opened TAP interface\n"
4675 #endif
4676 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4677 " connect the vlan 'n' to another VLAN using a socket connection\n"
4678 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4679 " connect the vlan 'n' to multicast maddr and port\n"
4680 "-net none use it alone to have zero network devices; if no -net option\n"
4681 " is provided, the default is '-net nic -net user'\n"
4682 "\n"
4683 #ifdef CONFIG_SLIRP
4684 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4685 #ifndef _WIN32
4686 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4687 #endif
4688 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4689 " redirect TCP or UDP connections from host to guest [-net user]\n"
4690 #endif
4691 "\n"
4692 "Linux boot specific:\n"
4693 "-kernel bzImage use 'bzImage' as kernel image\n"
4694 "-append cmdline use 'cmdline' as kernel command line\n"
4695 "-initrd file use 'file' as initial ram disk\n"
4696 "\n"
4697 "Debug/Expert options:\n"
4698 "-monitor dev redirect the monitor to char device 'dev'\n"
4699 "-serial dev redirect the serial port to char device 'dev'\n"
4700 "-parallel dev redirect the parallel port to char device 'dev'\n"
4701 "-pidfile file Write PID to 'file'\n"
4702 "-S freeze CPU at startup (use 'c' to start execution)\n"
4703 "-s wait gdb connection to port %d\n"
4704 "-p port change gdb connection port\n"
4705 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4706 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4707 " translation (t=none or lba) (usually qemu can guess them)\n"
4708 "-L path set the directory for the BIOS and VGA BIOS\n"
4709 #ifdef USE_KQEMU
4710 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4711 "-no-kqemu disable KQEMU kernel module usage\n"
4712 #endif
4713 #ifdef USE_CODE_COPY
4714 "-no-code-copy disable code copy acceleration\n"
4715 #endif
4716 #ifdef TARGET_I386
4717 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4718 " (default is CL-GD5446 PCI VGA)\n"
4719 "-no-acpi disable ACPI\n"
4720 #endif
4721 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4722 "-vnc display start a VNC server on display\n"
4723 "\n"
4724 "During emulation, the following keys are useful:\n"
4725 "ctrl-alt-f toggle full screen\n"
4726 "ctrl-alt-n switch to virtual console 'n'\n"
4727 "ctrl-alt toggle mouse and keyboard grab\n"
4728 "\n"
4729 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4731 #ifdef CONFIG_SOFTMMU
4732 "qemu",
4733 #else
4734 "qemu-fast",
4735 #endif
4736 DEFAULT_RAM_SIZE,
4737 #ifndef _WIN32
4738 DEFAULT_NETWORK_SCRIPT,
4739 #endif
4740 DEFAULT_GDBSTUB_PORT,
4741 "/tmp/qemu.log");
4742 #ifndef CONFIG_SOFTMMU
4743 printf("\n"
4744 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4745 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4746 "PC emulation.\n");
4747 #endif
4748 exit(1);
4751 #define HAS_ARG 0x0001
4753 enum {
4754 QEMU_OPTION_h,
4756 QEMU_OPTION_M,
4757 QEMU_OPTION_fda,
4758 QEMU_OPTION_fdb,
4759 QEMU_OPTION_hda,
4760 QEMU_OPTION_hdb,
4761 QEMU_OPTION_hdc,
4762 QEMU_OPTION_hdd,
4763 QEMU_OPTION_cdrom,
4764 QEMU_OPTION_boot,
4765 QEMU_OPTION_snapshot,
4766 QEMU_OPTION_m,
4767 QEMU_OPTION_nographic,
4768 #ifdef HAS_AUDIO
4769 QEMU_OPTION_audio_help,
4770 QEMU_OPTION_soundhw,
4771 #endif
4773 QEMU_OPTION_net,
4774 QEMU_OPTION_tftp,
4775 QEMU_OPTION_smb,
4776 QEMU_OPTION_redir,
4778 QEMU_OPTION_kernel,
4779 QEMU_OPTION_append,
4780 QEMU_OPTION_initrd,
4782 QEMU_OPTION_S,
4783 QEMU_OPTION_s,
4784 QEMU_OPTION_p,
4785 QEMU_OPTION_d,
4786 QEMU_OPTION_hdachs,
4787 QEMU_OPTION_L,
4788 QEMU_OPTION_no_code_copy,
4789 QEMU_OPTION_k,
4790 QEMU_OPTION_localtime,
4791 QEMU_OPTION_cirrusvga,
4792 QEMU_OPTION_g,
4793 QEMU_OPTION_std_vga,
4794 QEMU_OPTION_monitor,
4795 QEMU_OPTION_serial,
4796 QEMU_OPTION_parallel,
4797 QEMU_OPTION_loadvm,
4798 QEMU_OPTION_full_screen,
4799 QEMU_OPTION_pidfile,
4800 QEMU_OPTION_no_kqemu,
4801 QEMU_OPTION_kernel_kqemu,
4802 QEMU_OPTION_win2k_hack,
4803 QEMU_OPTION_usb,
4804 QEMU_OPTION_usbdevice,
4805 QEMU_OPTION_smp,
4806 QEMU_OPTION_vnc,
4807 QEMU_OPTION_no_acpi,
4810 typedef struct QEMUOption {
4811 const char *name;
4812 int flags;
4813 int index;
4814 } QEMUOption;
4816 const QEMUOption qemu_options[] = {
4817 { "h", 0, QEMU_OPTION_h },
4819 { "M", HAS_ARG, QEMU_OPTION_M },
4820 { "fda", HAS_ARG, QEMU_OPTION_fda },
4821 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4822 { "hda", HAS_ARG, QEMU_OPTION_hda },
4823 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4824 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4825 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4826 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4827 { "boot", HAS_ARG, QEMU_OPTION_boot },
4828 { "snapshot", 0, QEMU_OPTION_snapshot },
4829 { "m", HAS_ARG, QEMU_OPTION_m },
4830 { "nographic", 0, QEMU_OPTION_nographic },
4831 { "k", HAS_ARG, QEMU_OPTION_k },
4832 #ifdef HAS_AUDIO
4833 { "audio-help", 0, QEMU_OPTION_audio_help },
4834 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4835 #endif
4837 { "net", HAS_ARG, QEMU_OPTION_net},
4838 #ifdef CONFIG_SLIRP
4839 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4840 #ifndef _WIN32
4841 { "smb", HAS_ARG, QEMU_OPTION_smb },
4842 #endif
4843 { "redir", HAS_ARG, QEMU_OPTION_redir },
4844 #endif
4846 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4847 { "append", HAS_ARG, QEMU_OPTION_append },
4848 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4850 { "S", 0, QEMU_OPTION_S },
4851 { "s", 0, QEMU_OPTION_s },
4852 { "p", HAS_ARG, QEMU_OPTION_p },
4853 { "d", HAS_ARG, QEMU_OPTION_d },
4854 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4855 { "L", HAS_ARG, QEMU_OPTION_L },
4856 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4857 #ifdef USE_KQEMU
4858 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4859 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4860 #endif
4861 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4862 { "g", 1, QEMU_OPTION_g },
4863 #endif
4864 { "localtime", 0, QEMU_OPTION_localtime },
4865 { "std-vga", 0, QEMU_OPTION_std_vga },
4866 { "monitor", 1, QEMU_OPTION_monitor },
4867 { "serial", 1, QEMU_OPTION_serial },
4868 { "parallel", 1, QEMU_OPTION_parallel },
4869 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4870 { "full-screen", 0, QEMU_OPTION_full_screen },
4871 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4872 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4873 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4874 { "smp", HAS_ARG, QEMU_OPTION_smp },
4875 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4877 /* temporary options */
4878 { "usb", 0, QEMU_OPTION_usb },
4879 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4880 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4881 { NULL },
4884 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4886 /* this stack is only used during signal handling */
4887 #define SIGNAL_STACK_SIZE 32768
4889 static uint8_t *signal_stack;
4891 #endif
4893 /* password input */
4895 static BlockDriverState *get_bdrv(int index)
4897 BlockDriverState *bs;
4899 if (index < 4) {
4900 bs = bs_table[index];
4901 } else if (index < 6) {
4902 bs = fd_table[index - 4];
4903 } else {
4904 bs = NULL;
4906 return bs;
4909 static void read_passwords(void)
4911 BlockDriverState *bs;
4912 int i, j;
4913 char password[256];
4915 for(i = 0; i < 6; i++) {
4916 bs = get_bdrv(i);
4917 if (bs && bdrv_is_encrypted(bs)) {
4918 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4919 for(j = 0; j < 3; j++) {
4920 monitor_readline("Password: ",
4921 1, password, sizeof(password));
4922 if (bdrv_set_key(bs, password) == 0)
4923 break;
4924 term_printf("invalid password\n");
4930 /* XXX: currently we cannot use simultaneously different CPUs */
4931 void register_machines(void)
4933 #if defined(TARGET_I386)
4934 qemu_register_machine(&pc_machine);
4935 qemu_register_machine(&isapc_machine);
4936 #elif defined(TARGET_PPC)
4937 qemu_register_machine(&heathrow_machine);
4938 qemu_register_machine(&core99_machine);
4939 qemu_register_machine(&prep_machine);
4940 #elif defined(TARGET_MIPS)
4941 qemu_register_machine(&mips_machine);
4942 #elif defined(TARGET_SPARC)
4943 #ifdef TARGET_SPARC64
4944 qemu_register_machine(&sun4u_machine);
4945 #else
4946 qemu_register_machine(&sun4m_machine);
4947 #endif
4948 #elif defined(TARGET_ARM)
4949 qemu_register_machine(&integratorcp926_machine);
4950 qemu_register_machine(&integratorcp1026_machine);
4951 qemu_register_machine(&versatilepb_machine);
4952 qemu_register_machine(&versatileab_machine);
4953 #elif defined(TARGET_SH4)
4954 qemu_register_machine(&shix_machine);
4955 #else
4956 #error unsupported CPU
4957 #endif
4960 #ifdef HAS_AUDIO
4961 struct soundhw soundhw[] = {
4962 #ifdef TARGET_I386
4964 "pcspk",
4965 "PC speaker",
4968 { .init_isa = pcspk_audio_init }
4970 #endif
4972 "sb16",
4973 "Creative Sound Blaster 16",
4976 { .init_isa = SB16_init }
4979 #ifdef CONFIG_ADLIB
4981 "adlib",
4982 #ifdef HAS_YMF262
4983 "Yamaha YMF262 (OPL3)",
4984 #else
4985 "Yamaha YM3812 (OPL2)",
4986 #endif
4989 { .init_isa = Adlib_init }
4991 #endif
4993 #ifdef CONFIG_GUS
4995 "gus",
4996 "Gravis Ultrasound GF1",
4999 { .init_isa = GUS_init }
5001 #endif
5004 "es1370",
5005 "ENSONIQ AudioPCI ES1370",
5008 { .init_pci = es1370_init }
5011 { NULL, NULL, 0, 0, { NULL } }
5014 static void select_soundhw (const char *optarg)
5016 struct soundhw *c;
5018 if (*optarg == '?') {
5019 show_valid_cards:
5021 printf ("Valid sound card names (comma separated):\n");
5022 for (c = soundhw; c->name; ++c) {
5023 printf ("%-11s %s\n", c->name, c->descr);
5025 printf ("\n-soundhw all will enable all of the above\n");
5026 exit (*optarg != '?');
5028 else {
5029 size_t l;
5030 const char *p;
5031 char *e;
5032 int bad_card = 0;
5034 if (!strcmp (optarg, "all")) {
5035 for (c = soundhw; c->name; ++c) {
5036 c->enabled = 1;
5038 return;
5041 p = optarg;
5042 while (*p) {
5043 e = strchr (p, ',');
5044 l = !e ? strlen (p) : (size_t) (e - p);
5046 for (c = soundhw; c->name; ++c) {
5047 if (!strncmp (c->name, p, l)) {
5048 c->enabled = 1;
5049 break;
5053 if (!c->name) {
5054 if (l > 80) {
5055 fprintf (stderr,
5056 "Unknown sound card name (too big to show)\n");
5058 else {
5059 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5060 (int) l, p);
5062 bad_card = 1;
5064 p += l + (e != NULL);
5067 if (bad_card)
5068 goto show_valid_cards;
5071 #endif
5073 #define MAX_NET_CLIENTS 32
5075 int main(int argc, char **argv)
5077 #ifdef CONFIG_GDBSTUB
5078 int use_gdbstub, gdbstub_port;
5079 #endif
5080 int i, cdrom_index;
5081 int snapshot, linux_boot;
5082 const char *initrd_filename;
5083 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5084 const char *kernel_filename, *kernel_cmdline;
5085 DisplayState *ds = &display_state;
5086 int cyls, heads, secs, translation;
5087 int start_emulation = 1;
5088 char net_clients[MAX_NET_CLIENTS][256];
5089 int nb_net_clients;
5090 int optind;
5091 const char *r, *optarg;
5092 CharDriverState *monitor_hd;
5093 char monitor_device[128];
5094 char serial_devices[MAX_SERIAL_PORTS][128];
5095 int serial_device_index;
5096 char parallel_devices[MAX_PARALLEL_PORTS][128];
5097 int parallel_device_index;
5098 const char *loadvm = NULL;
5099 QEMUMachine *machine;
5100 char usb_devices[MAX_USB_CMDLINE][128];
5101 int usb_devices_index;
5103 LIST_INIT (&vm_change_state_head);
5104 #if !defined(CONFIG_SOFTMMU)
5105 /* we never want that malloc() uses mmap() */
5106 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5107 #endif
5108 register_machines();
5109 machine = first_machine;
5110 initrd_filename = NULL;
5111 for(i = 0; i < MAX_FD; i++)
5112 fd_filename[i] = NULL;
5113 for(i = 0; i < MAX_DISKS; i++)
5114 hd_filename[i] = NULL;
5115 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5116 vga_ram_size = VGA_RAM_SIZE;
5117 bios_size = BIOS_SIZE;
5118 #ifdef CONFIG_GDBSTUB
5119 use_gdbstub = 0;
5120 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5121 #endif
5122 snapshot = 0;
5123 nographic = 0;
5124 kernel_filename = NULL;
5125 kernel_cmdline = "";
5126 #ifdef TARGET_PPC
5127 cdrom_index = 1;
5128 #else
5129 cdrom_index = 2;
5130 #endif
5131 cyls = heads = secs = 0;
5132 translation = BIOS_ATA_TRANSLATION_AUTO;
5133 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5135 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5136 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5137 serial_devices[i][0] = '\0';
5138 serial_device_index = 0;
5140 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5141 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5142 parallel_devices[i][0] = '\0';
5143 parallel_device_index = 0;
5145 usb_devices_index = 0;
5147 nb_net_clients = 0;
5149 nb_nics = 0;
5150 /* default mac address of the first network interface */
5152 optind = 1;
5153 for(;;) {
5154 if (optind >= argc)
5155 break;
5156 r = argv[optind];
5157 if (r[0] != '-') {
5158 hd_filename[0] = argv[optind++];
5159 } else {
5160 const QEMUOption *popt;
5162 optind++;
5163 popt = qemu_options;
5164 for(;;) {
5165 if (!popt->name) {
5166 fprintf(stderr, "%s: invalid option -- '%s'\n",
5167 argv[0], r);
5168 exit(1);
5170 if (!strcmp(popt->name, r + 1))
5171 break;
5172 popt++;
5174 if (popt->flags & HAS_ARG) {
5175 if (optind >= argc) {
5176 fprintf(stderr, "%s: option '%s' requires an argument\n",
5177 argv[0], r);
5178 exit(1);
5180 optarg = argv[optind++];
5181 } else {
5182 optarg = NULL;
5185 switch(popt->index) {
5186 case QEMU_OPTION_M:
5187 machine = find_machine(optarg);
5188 if (!machine) {
5189 QEMUMachine *m;
5190 printf("Supported machines are:\n");
5191 for(m = first_machine; m != NULL; m = m->next) {
5192 printf("%-10s %s%s\n",
5193 m->name, m->desc,
5194 m == first_machine ? " (default)" : "");
5196 exit(1);
5198 break;
5199 case QEMU_OPTION_initrd:
5200 initrd_filename = optarg;
5201 break;
5202 case QEMU_OPTION_hda:
5203 case QEMU_OPTION_hdb:
5204 case QEMU_OPTION_hdc:
5205 case QEMU_OPTION_hdd:
5207 int hd_index;
5208 hd_index = popt->index - QEMU_OPTION_hda;
5209 hd_filename[hd_index] = optarg;
5210 if (hd_index == cdrom_index)
5211 cdrom_index = -1;
5213 break;
5214 case QEMU_OPTION_snapshot:
5215 snapshot = 1;
5216 break;
5217 case QEMU_OPTION_hdachs:
5219 const char *p;
5220 p = optarg;
5221 cyls = strtol(p, (char **)&p, 0);
5222 if (cyls < 1 || cyls > 16383)
5223 goto chs_fail;
5224 if (*p != ',')
5225 goto chs_fail;
5226 p++;
5227 heads = strtol(p, (char **)&p, 0);
5228 if (heads < 1 || heads > 16)
5229 goto chs_fail;
5230 if (*p != ',')
5231 goto chs_fail;
5232 p++;
5233 secs = strtol(p, (char **)&p, 0);
5234 if (secs < 1 || secs > 63)
5235 goto chs_fail;
5236 if (*p == ',') {
5237 p++;
5238 if (!strcmp(p, "none"))
5239 translation = BIOS_ATA_TRANSLATION_NONE;
5240 else if (!strcmp(p, "lba"))
5241 translation = BIOS_ATA_TRANSLATION_LBA;
5242 else if (!strcmp(p, "auto"))
5243 translation = BIOS_ATA_TRANSLATION_AUTO;
5244 else
5245 goto chs_fail;
5246 } else if (*p != '\0') {
5247 chs_fail:
5248 fprintf(stderr, "qemu: invalid physical CHS format\n");
5249 exit(1);
5252 break;
5253 case QEMU_OPTION_nographic:
5254 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5255 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5256 nographic = 1;
5257 break;
5258 case QEMU_OPTION_kernel:
5259 kernel_filename = optarg;
5260 break;
5261 case QEMU_OPTION_append:
5262 kernel_cmdline = optarg;
5263 break;
5264 case QEMU_OPTION_cdrom:
5265 if (cdrom_index >= 0) {
5266 hd_filename[cdrom_index] = optarg;
5268 break;
5269 case QEMU_OPTION_boot:
5270 boot_device = optarg[0];
5271 if (boot_device != 'a' &&
5272 #ifdef TARGET_SPARC
5273 // Network boot
5274 boot_device != 'n' &&
5275 #endif
5276 boot_device != 'c' && boot_device != 'd') {
5277 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5278 exit(1);
5280 break;
5281 case QEMU_OPTION_fda:
5282 fd_filename[0] = optarg;
5283 break;
5284 case QEMU_OPTION_fdb:
5285 fd_filename[1] = optarg;
5286 break;
5287 case QEMU_OPTION_no_code_copy:
5288 code_copy_enabled = 0;
5289 break;
5290 case QEMU_OPTION_net:
5291 if (nb_net_clients >= MAX_NET_CLIENTS) {
5292 fprintf(stderr, "qemu: too many network clients\n");
5293 exit(1);
5295 pstrcpy(net_clients[nb_net_clients],
5296 sizeof(net_clients[0]),
5297 optarg);
5298 nb_net_clients++;
5299 break;
5300 #ifdef CONFIG_SLIRP
5301 case QEMU_OPTION_tftp:
5302 tftp_prefix = optarg;
5303 break;
5304 #ifndef _WIN32
5305 case QEMU_OPTION_smb:
5306 net_slirp_smb(optarg);
5307 break;
5308 #endif
5309 case QEMU_OPTION_redir:
5310 net_slirp_redir(optarg);
5311 break;
5312 #endif
5313 #ifdef HAS_AUDIO
5314 case QEMU_OPTION_audio_help:
5315 AUD_help ();
5316 exit (0);
5317 break;
5318 case QEMU_OPTION_soundhw:
5319 select_soundhw (optarg);
5320 break;
5321 #endif
5322 case QEMU_OPTION_h:
5323 help();
5324 break;
5325 case QEMU_OPTION_m:
5326 ram_size = atoi(optarg) * 1024 * 1024;
5327 if (ram_size <= 0)
5328 help();
5329 if (ram_size > PHYS_RAM_MAX_SIZE) {
5330 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5331 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5332 exit(1);
5334 break;
5335 case QEMU_OPTION_d:
5337 int mask;
5338 CPULogItem *item;
5340 mask = cpu_str_to_log_mask(optarg);
5341 if (!mask) {
5342 printf("Log items (comma separated):\n");
5343 for(item = cpu_log_items; item->mask != 0; item++) {
5344 printf("%-10s %s\n", item->name, item->help);
5346 exit(1);
5348 cpu_set_log(mask);
5350 break;
5351 #ifdef CONFIG_GDBSTUB
5352 case QEMU_OPTION_s:
5353 use_gdbstub = 1;
5354 break;
5355 case QEMU_OPTION_p:
5356 gdbstub_port = atoi(optarg);
5357 break;
5358 #endif
5359 case QEMU_OPTION_L:
5360 bios_dir = optarg;
5361 break;
5362 case QEMU_OPTION_S:
5363 start_emulation = 0;
5364 break;
5365 case QEMU_OPTION_k:
5366 keyboard_layout = optarg;
5367 break;
5368 case QEMU_OPTION_localtime:
5369 rtc_utc = 0;
5370 break;
5371 case QEMU_OPTION_cirrusvga:
5372 cirrus_vga_enabled = 1;
5373 break;
5374 case QEMU_OPTION_std_vga:
5375 cirrus_vga_enabled = 0;
5376 break;
5377 case QEMU_OPTION_g:
5379 const char *p;
5380 int w, h, depth;
5381 p = optarg;
5382 w = strtol(p, (char **)&p, 10);
5383 if (w <= 0) {
5384 graphic_error:
5385 fprintf(stderr, "qemu: invalid resolution or depth\n");
5386 exit(1);
5388 if (*p != 'x')
5389 goto graphic_error;
5390 p++;
5391 h = strtol(p, (char **)&p, 10);
5392 if (h <= 0)
5393 goto graphic_error;
5394 if (*p == 'x') {
5395 p++;
5396 depth = strtol(p, (char **)&p, 10);
5397 if (depth != 8 && depth != 15 && depth != 16 &&
5398 depth != 24 && depth != 32)
5399 goto graphic_error;
5400 } else if (*p == '\0') {
5401 depth = graphic_depth;
5402 } else {
5403 goto graphic_error;
5406 graphic_width = w;
5407 graphic_height = h;
5408 graphic_depth = depth;
5410 break;
5411 case QEMU_OPTION_monitor:
5412 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5413 break;
5414 case QEMU_OPTION_serial:
5415 if (serial_device_index >= MAX_SERIAL_PORTS) {
5416 fprintf(stderr, "qemu: too many serial ports\n");
5417 exit(1);
5419 pstrcpy(serial_devices[serial_device_index],
5420 sizeof(serial_devices[0]), optarg);
5421 serial_device_index++;
5422 break;
5423 case QEMU_OPTION_parallel:
5424 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5425 fprintf(stderr, "qemu: too many parallel ports\n");
5426 exit(1);
5428 pstrcpy(parallel_devices[parallel_device_index],
5429 sizeof(parallel_devices[0]), optarg);
5430 parallel_device_index++;
5431 break;
5432 case QEMU_OPTION_loadvm:
5433 loadvm = optarg;
5434 break;
5435 case QEMU_OPTION_full_screen:
5436 full_screen = 1;
5437 break;
5438 case QEMU_OPTION_pidfile:
5439 create_pidfile(optarg);
5440 break;
5441 #ifdef TARGET_I386
5442 case QEMU_OPTION_win2k_hack:
5443 win2k_install_hack = 1;
5444 break;
5445 #endif
5446 #ifdef USE_KQEMU
5447 case QEMU_OPTION_no_kqemu:
5448 kqemu_allowed = 0;
5449 break;
5450 case QEMU_OPTION_kernel_kqemu:
5451 kqemu_allowed = 2;
5452 break;
5453 #endif
5454 case QEMU_OPTION_usb:
5455 usb_enabled = 1;
5456 break;
5457 case QEMU_OPTION_usbdevice:
5458 usb_enabled = 1;
5459 if (usb_devices_index >= MAX_USB_CMDLINE) {
5460 fprintf(stderr, "Too many USB devices\n");
5461 exit(1);
5463 pstrcpy(usb_devices[usb_devices_index],
5464 sizeof(usb_devices[usb_devices_index]),
5465 optarg);
5466 usb_devices_index++;
5467 break;
5468 case QEMU_OPTION_smp:
5469 smp_cpus = atoi(optarg);
5470 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5471 fprintf(stderr, "Invalid number of CPUs\n");
5472 exit(1);
5474 break;
5475 case QEMU_OPTION_vnc:
5476 vnc_display = atoi(optarg);
5477 if (vnc_display < 0) {
5478 fprintf(stderr, "Invalid VNC display\n");
5479 exit(1);
5481 break;
5482 case QEMU_OPTION_no_acpi:
5483 acpi_enabled = 0;
5484 break;
5489 #ifdef USE_KQEMU
5490 if (smp_cpus > 1)
5491 kqemu_allowed = 0;
5492 #endif
5493 linux_boot = (kernel_filename != NULL);
5495 if (!linux_boot &&
5496 hd_filename[0] == '\0' &&
5497 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5498 fd_filename[0] == '\0')
5499 help();
5501 /* boot to cd by default if no hard disk */
5502 if (hd_filename[0] == '\0' && boot_device == 'c') {
5503 if (fd_filename[0] != '\0')
5504 boot_device = 'a';
5505 else
5506 boot_device = 'd';
5509 #if !defined(CONFIG_SOFTMMU)
5510 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5512 static uint8_t stdout_buf[4096];
5513 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5515 #else
5516 setvbuf(stdout, NULL, _IOLBF, 0);
5517 #endif
5519 #ifdef _WIN32
5520 socket_init();
5521 #endif
5523 /* init network clients */
5524 if (nb_net_clients == 0) {
5525 /* if no clients, we use a default config */
5526 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5527 "nic");
5528 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5529 "user");
5530 nb_net_clients = 2;
5533 for(i = 0;i < nb_net_clients; i++) {
5534 if (net_client_init(net_clients[i]) < 0)
5535 exit(1);
5538 /* init the memory */
5539 phys_ram_size = ram_size + vga_ram_size + bios_size;
5541 #ifdef CONFIG_SOFTMMU
5542 phys_ram_base = qemu_vmalloc(phys_ram_size);
5543 if (!phys_ram_base) {
5544 fprintf(stderr, "Could not allocate physical memory\n");
5545 exit(1);
5547 #else
5548 /* as we must map the same page at several addresses, we must use
5549 a fd */
5551 const char *tmpdir;
5553 tmpdir = getenv("QEMU_TMPDIR");
5554 if (!tmpdir)
5555 tmpdir = "/tmp";
5556 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5557 if (mkstemp(phys_ram_file) < 0) {
5558 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5559 phys_ram_file);
5560 exit(1);
5562 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5563 if (phys_ram_fd < 0) {
5564 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5565 phys_ram_file);
5566 exit(1);
5568 ftruncate(phys_ram_fd, phys_ram_size);
5569 unlink(phys_ram_file);
5570 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5571 phys_ram_size,
5572 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5573 phys_ram_fd, 0);
5574 if (phys_ram_base == MAP_FAILED) {
5575 fprintf(stderr, "Could not map physical memory\n");
5576 exit(1);
5579 #endif
5581 /* we always create the cdrom drive, even if no disk is there */
5582 bdrv_init();
5583 if (cdrom_index >= 0) {
5584 bs_table[cdrom_index] = bdrv_new("cdrom");
5585 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5588 /* open the virtual block devices */
5589 for(i = 0; i < MAX_DISKS; i++) {
5590 if (hd_filename[i]) {
5591 if (!bs_table[i]) {
5592 char buf[64];
5593 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5594 bs_table[i] = bdrv_new(buf);
5596 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5597 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5598 hd_filename[i]);
5599 exit(1);
5601 if (i == 0 && cyls != 0) {
5602 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5603 bdrv_set_translation_hint(bs_table[i], translation);
5608 /* we always create at least one floppy disk */
5609 fd_table[0] = bdrv_new("fda");
5610 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5612 for(i = 0; i < MAX_FD; i++) {
5613 if (fd_filename[i]) {
5614 if (!fd_table[i]) {
5615 char buf[64];
5616 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5617 fd_table[i] = bdrv_new(buf);
5618 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5620 if (fd_filename[i] != '\0') {
5621 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5622 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5623 fd_filename[i]);
5624 exit(1);
5630 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5631 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5633 init_ioports();
5634 cpu_calibrate_ticks();
5636 /* terminal init */
5637 if (nographic) {
5638 dumb_display_init(ds);
5639 } else if (vnc_display != -1) {
5640 vnc_display_init(ds, vnc_display);
5641 } else {
5642 #if defined(CONFIG_SDL)
5643 sdl_display_init(ds, full_screen);
5644 #elif defined(CONFIG_COCOA)
5645 cocoa_display_init(ds, full_screen);
5646 #else
5647 dumb_display_init(ds);
5648 #endif
5651 monitor_hd = qemu_chr_open(monitor_device);
5652 if (!monitor_hd) {
5653 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5654 exit(1);
5656 monitor_init(monitor_hd, !nographic);
5658 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5659 if (serial_devices[i][0] != '\0') {
5660 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5661 if (!serial_hds[i]) {
5662 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5663 serial_devices[i]);
5664 exit(1);
5666 if (!strcmp(serial_devices[i], "vc"))
5667 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5671 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5672 if (parallel_devices[i][0] != '\0') {
5673 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5674 if (!parallel_hds[i]) {
5675 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5676 parallel_devices[i]);
5677 exit(1);
5679 if (!strcmp(parallel_devices[i], "vc"))
5680 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5684 /* setup cpu signal handlers for MMU / self modifying code handling */
5685 #if !defined(CONFIG_SOFTMMU)
5687 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5689 stack_t stk;
5690 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5691 stk.ss_sp = signal_stack;
5692 stk.ss_size = SIGNAL_STACK_SIZE;
5693 stk.ss_flags = 0;
5695 if (sigaltstack(&stk, NULL) < 0) {
5696 perror("sigaltstack");
5697 exit(1);
5700 #endif
5702 struct sigaction act;
5704 sigfillset(&act.sa_mask);
5705 act.sa_flags = SA_SIGINFO;
5706 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5707 act.sa_flags |= SA_ONSTACK;
5708 #endif
5709 act.sa_sigaction = host_segv_handler;
5710 sigaction(SIGSEGV, &act, NULL);
5711 sigaction(SIGBUS, &act, NULL);
5712 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5713 sigaction(SIGFPE, &act, NULL);
5714 #endif
5716 #endif
5718 #ifndef _WIN32
5720 struct sigaction act;
5721 sigfillset(&act.sa_mask);
5722 act.sa_flags = 0;
5723 act.sa_handler = SIG_IGN;
5724 sigaction(SIGPIPE, &act, NULL);
5726 #endif
5727 init_timers();
5729 machine->init(ram_size, vga_ram_size, boot_device,
5730 ds, fd_filename, snapshot,
5731 kernel_filename, kernel_cmdline, initrd_filename);
5733 /* init USB devices */
5734 if (usb_enabled) {
5735 for(i = 0; i < usb_devices_index; i++) {
5736 if (usb_device_add(usb_devices[i]) < 0) {
5737 fprintf(stderr, "Warning: could not add USB device %s\n",
5738 usb_devices[i]);
5743 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5744 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5746 #ifdef CONFIG_GDBSTUB
5747 if (use_gdbstub) {
5748 if (gdbserver_start(gdbstub_port) < 0) {
5749 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5750 gdbstub_port);
5751 exit(1);
5752 } else {
5753 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5755 } else
5756 #endif
5757 if (loadvm)
5758 qemu_loadvm(loadvm);
5761 /* XXX: simplify init */
5762 read_passwords();
5763 if (start_emulation) {
5764 vm_start();
5767 main_loop();
5768 quit_timers();
5769 return 0;