Suppress int<->pointer compiler warnings.
[qemu/mini2440.git] / vl.c
blobbfdf5204ff0e0910d0ae05694421fb58758f9b52
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2007 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>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
51 #include <freebsd/stdlib.h>
52 #else
53 #ifndef __sun__
54 #include <linux/if.h>
55 #include <linux/if_tun.h>
56 #include <pty.h>
57 #include <malloc.h>
58 #include <linux/rtc.h>
59 #include <linux/hpet.h>
60 #include <linux/ppdev.h>
61 #include <linux/parport.h>
62 #else
63 #include <sys/stat.h>
64 #include <sys/ethernet.h>
65 #include <sys/sockio.h>
66 #include <arpa/inet.h>
67 #include <netinet/arp.h>
68 #include <netinet/in.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip_icmp.h> // must come after ip.h
72 #include <netinet/udp.h>
73 #include <netinet/tcp.h>
74 #include <net/if.h>
75 #include <syslog.h>
76 #include <stropts.h>
77 #endif
78 #endif
79 #endif
81 #if defined(CONFIG_SLIRP)
82 #include "libslirp.h"
83 #endif
85 #ifdef _WIN32
86 #include <malloc.h>
87 #include <sys/timeb.h>
88 #include <windows.h>
89 #define getopt_long_only getopt_long
90 #define memalign(align, size) malloc(size)
91 #endif
93 #include "qemu_socket.h"
95 #ifdef CONFIG_SDL
96 #ifdef __APPLE__
97 #include <SDL/SDL.h>
98 #endif
99 #endif /* CONFIG_SDL */
101 #ifdef CONFIG_COCOA
102 #undef main
103 #define main qemu_main
104 #endif /* CONFIG_COCOA */
106 #include "disas.h"
108 #include "exec-all.h"
110 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
111 #ifdef __sun__
112 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
113 #else
114 #define SMBD_COMMAND "/usr/sbin/smbd"
115 #endif
117 //#define DEBUG_UNUSED_IOPORT
118 //#define DEBUG_IOPORT
120 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
122 #ifdef TARGET_PPC
123 #define DEFAULT_RAM_SIZE 144
124 #else
125 #define DEFAULT_RAM_SIZE 128
126 #endif
127 /* in ms */
128 #define GUI_REFRESH_INTERVAL 30
130 /* Max number of USB devices that can be specified on the commandline. */
131 #define MAX_USB_CMDLINE 8
133 /* XXX: use a two level table to limit memory usage */
134 #define MAX_IOPORTS 65536
136 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
137 char phys_ram_file[1024];
138 void *ioport_opaque[MAX_IOPORTS];
139 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
140 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
141 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
142 to store the VM snapshots */
143 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
144 BlockDriverState *pflash_table[MAX_PFLASH];
145 BlockDriverState *sd_bdrv;
146 BlockDriverState *mtd_bdrv;
147 /* point to the block driver where the snapshots are managed */
148 BlockDriverState *bs_snapshots;
149 int vga_ram_size;
150 static DisplayState display_state;
151 int nographic;
152 const char* keyboard_layout = NULL;
153 int64_t ticks_per_sec;
154 int boot_device = 'c';
155 int ram_size;
156 int pit_min_timer_count = 0;
157 int nb_nics;
158 NICInfo nd_table[MAX_NICS];
159 int vm_running;
160 int rtc_utc = 1;
161 int cirrus_vga_enabled = 1;
162 int vmsvga_enabled = 0;
163 #ifdef TARGET_SPARC
164 int graphic_width = 1024;
165 int graphic_height = 768;
166 int graphic_depth = 8;
167 #else
168 int graphic_width = 800;
169 int graphic_height = 600;
170 int graphic_depth = 15;
171 #endif
172 int full_screen = 0;
173 int no_frame = 0;
174 int no_quit = 0;
175 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
176 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
177 #ifdef TARGET_I386
178 int win2k_install_hack = 0;
179 #endif
180 int usb_enabled = 0;
181 static VLANState *first_vlan;
182 int smp_cpus = 1;
183 const char *vnc_display;
184 #if defined(TARGET_SPARC)
185 #define MAX_CPUS 16
186 #elif defined(TARGET_I386)
187 #define MAX_CPUS 255
188 #else
189 #define MAX_CPUS 1
190 #endif
191 int acpi_enabled = 1;
192 int fd_bootchk = 1;
193 int no_reboot = 0;
194 int cursor_hide = 1;
195 int graphic_rotate = 0;
196 int daemonize = 0;
197 const char *option_rom[MAX_OPTION_ROMS];
198 int nb_option_roms;
199 int semihosting_enabled = 0;
200 int autostart = 1;
201 #ifdef TARGET_ARM
202 int old_param = 0;
203 #endif
204 const char *qemu_name;
205 int alt_grab = 0;
206 #ifdef TARGET_SPARC
207 unsigned int nb_prom_envs = 0;
208 const char *prom_envs[MAX_PROM_ENVS];
209 #endif
211 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
213 /***********************************************************/
214 /* x86 ISA bus support */
216 target_phys_addr_t isa_mem_base = 0;
217 PicState2 *isa_pic;
219 uint32_t default_ioport_readb(void *opaque, uint32_t address)
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr, "unused inb: port=0x%04x\n", address);
223 #endif
224 return 0xff;
227 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
229 #ifdef DEBUG_UNUSED_IOPORT
230 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
231 #endif
234 /* default is to make two byte accesses */
235 uint32_t default_ioport_readw(void *opaque, uint32_t address)
237 uint32_t data;
238 data = ioport_read_table[0][address](ioport_opaque[address], address);
239 address = (address + 1) & (MAX_IOPORTS - 1);
240 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
241 return data;
244 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
246 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
247 address = (address + 1) & (MAX_IOPORTS - 1);
248 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
251 uint32_t default_ioport_readl(void *opaque, uint32_t address)
253 #ifdef DEBUG_UNUSED_IOPORT
254 fprintf(stderr, "unused inl: port=0x%04x\n", address);
255 #endif
256 return 0xffffffff;
259 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
261 #ifdef DEBUG_UNUSED_IOPORT
262 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
263 #endif
266 void init_ioports(void)
268 int i;
270 for(i = 0; i < MAX_IOPORTS; i++) {
271 ioport_read_table[0][i] = default_ioport_readb;
272 ioport_write_table[0][i] = default_ioport_writeb;
273 ioport_read_table[1][i] = default_ioport_readw;
274 ioport_write_table[1][i] = default_ioport_writew;
275 ioport_read_table[2][i] = default_ioport_readl;
276 ioport_write_table[2][i] = default_ioport_writel;
280 /* size is the word size in byte */
281 int register_ioport_read(int start, int length, int size,
282 IOPortReadFunc *func, void *opaque)
284 int i, bsize;
286 if (size == 1) {
287 bsize = 0;
288 } else if (size == 2) {
289 bsize = 1;
290 } else if (size == 4) {
291 bsize = 2;
292 } else {
293 hw_error("register_ioport_read: invalid size");
294 return -1;
296 for(i = start; i < start + length; i += size) {
297 ioport_read_table[bsize][i] = func;
298 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
299 hw_error("register_ioport_read: invalid opaque");
300 ioport_opaque[i] = opaque;
302 return 0;
305 /* size is the word size in byte */
306 int register_ioport_write(int start, int length, int size,
307 IOPortWriteFunc *func, void *opaque)
309 int i, bsize;
311 if (size == 1) {
312 bsize = 0;
313 } else if (size == 2) {
314 bsize = 1;
315 } else if (size == 4) {
316 bsize = 2;
317 } else {
318 hw_error("register_ioport_write: invalid size");
319 return -1;
321 for(i = start; i < start + length; i += size) {
322 ioport_write_table[bsize][i] = func;
323 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
324 hw_error("register_ioport_write: invalid opaque");
325 ioport_opaque[i] = opaque;
327 return 0;
330 void isa_unassign_ioport(int start, int length)
332 int i;
334 for(i = start; i < start + length; i++) {
335 ioport_read_table[0][i] = default_ioport_readb;
336 ioport_read_table[1][i] = default_ioport_readw;
337 ioport_read_table[2][i] = default_ioport_readl;
339 ioport_write_table[0][i] = default_ioport_writeb;
340 ioport_write_table[1][i] = default_ioport_writew;
341 ioport_write_table[2][i] = default_ioport_writel;
345 /***********************************************************/
347 void cpu_outb(CPUState *env, int addr, int val)
349 #ifdef DEBUG_IOPORT
350 if (loglevel & CPU_LOG_IOPORT)
351 fprintf(logfile, "outb: %04x %02x\n", addr, val);
352 #endif
353 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
354 #ifdef USE_KQEMU
355 if (env)
356 env->last_io_time = cpu_get_time_fast();
357 #endif
360 void cpu_outw(CPUState *env, int addr, int val)
362 #ifdef DEBUG_IOPORT
363 if (loglevel & CPU_LOG_IOPORT)
364 fprintf(logfile, "outw: %04x %04x\n", addr, val);
365 #endif
366 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
367 #ifdef USE_KQEMU
368 if (env)
369 env->last_io_time = cpu_get_time_fast();
370 #endif
373 void cpu_outl(CPUState *env, int addr, int val)
375 #ifdef DEBUG_IOPORT
376 if (loglevel & CPU_LOG_IOPORT)
377 fprintf(logfile, "outl: %04x %08x\n", addr, val);
378 #endif
379 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
380 #ifdef USE_KQEMU
381 if (env)
382 env->last_io_time = cpu_get_time_fast();
383 #endif
386 int cpu_inb(CPUState *env, int addr)
388 int val;
389 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
390 #ifdef DEBUG_IOPORT
391 if (loglevel & CPU_LOG_IOPORT)
392 fprintf(logfile, "inb : %04x %02x\n", addr, val);
393 #endif
394 #ifdef USE_KQEMU
395 if (env)
396 env->last_io_time = cpu_get_time_fast();
397 #endif
398 return val;
401 int cpu_inw(CPUState *env, int addr)
403 int val;
404 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
405 #ifdef DEBUG_IOPORT
406 if (loglevel & CPU_LOG_IOPORT)
407 fprintf(logfile, "inw : %04x %04x\n", addr, val);
408 #endif
409 #ifdef USE_KQEMU
410 if (env)
411 env->last_io_time = cpu_get_time_fast();
412 #endif
413 return val;
416 int cpu_inl(CPUState *env, int addr)
418 int val;
419 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
420 #ifdef DEBUG_IOPORT
421 if (loglevel & CPU_LOG_IOPORT)
422 fprintf(logfile, "inl : %04x %08x\n", addr, val);
423 #endif
424 #ifdef USE_KQEMU
425 if (env)
426 env->last_io_time = cpu_get_time_fast();
427 #endif
428 return val;
431 /***********************************************************/
432 void hw_error(const char *fmt, ...)
434 va_list ap;
435 CPUState *env;
437 va_start(ap, fmt);
438 fprintf(stderr, "qemu: hardware error: ");
439 vfprintf(stderr, fmt, ap);
440 fprintf(stderr, "\n");
441 for(env = first_cpu; env != NULL; env = env->next_cpu) {
442 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
443 #ifdef TARGET_I386
444 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
445 #else
446 cpu_dump_state(env, stderr, fprintf, 0);
447 #endif
449 va_end(ap);
450 abort();
453 /***********************************************************/
454 /* keyboard/mouse */
456 static QEMUPutKBDEvent *qemu_put_kbd_event;
457 static void *qemu_put_kbd_event_opaque;
458 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
459 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
461 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
463 qemu_put_kbd_event_opaque = opaque;
464 qemu_put_kbd_event = func;
467 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
468 void *opaque, int absolute,
469 const char *name)
471 QEMUPutMouseEntry *s, *cursor;
473 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
474 if (!s)
475 return NULL;
477 s->qemu_put_mouse_event = func;
478 s->qemu_put_mouse_event_opaque = opaque;
479 s->qemu_put_mouse_event_absolute = absolute;
480 s->qemu_put_mouse_event_name = qemu_strdup(name);
481 s->next = NULL;
483 if (!qemu_put_mouse_event_head) {
484 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
485 return s;
488 cursor = qemu_put_mouse_event_head;
489 while (cursor->next != NULL)
490 cursor = cursor->next;
492 cursor->next = s;
493 qemu_put_mouse_event_current = s;
495 return s;
498 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
500 QEMUPutMouseEntry *prev = NULL, *cursor;
502 if (!qemu_put_mouse_event_head || entry == NULL)
503 return;
505 cursor = qemu_put_mouse_event_head;
506 while (cursor != NULL && cursor != entry) {
507 prev = cursor;
508 cursor = cursor->next;
511 if (cursor == NULL) // does not exist or list empty
512 return;
513 else if (prev == NULL) { // entry is head
514 qemu_put_mouse_event_head = cursor->next;
515 if (qemu_put_mouse_event_current == entry)
516 qemu_put_mouse_event_current = cursor->next;
517 qemu_free(entry->qemu_put_mouse_event_name);
518 qemu_free(entry);
519 return;
522 prev->next = entry->next;
524 if (qemu_put_mouse_event_current == entry)
525 qemu_put_mouse_event_current = prev;
527 qemu_free(entry->qemu_put_mouse_event_name);
528 qemu_free(entry);
531 void kbd_put_keycode(int keycode)
533 if (qemu_put_kbd_event) {
534 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
538 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
540 QEMUPutMouseEvent *mouse_event;
541 void *mouse_event_opaque;
542 int width;
544 if (!qemu_put_mouse_event_current) {
545 return;
548 mouse_event =
549 qemu_put_mouse_event_current->qemu_put_mouse_event;
550 mouse_event_opaque =
551 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
553 if (mouse_event) {
554 if (graphic_rotate) {
555 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
556 width = 0x7fff;
557 else
558 width = graphic_width;
559 mouse_event(mouse_event_opaque,
560 width - dy, dx, dz, buttons_state);
561 } else
562 mouse_event(mouse_event_opaque,
563 dx, dy, dz, buttons_state);
567 int kbd_mouse_is_absolute(void)
569 if (!qemu_put_mouse_event_current)
570 return 0;
572 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
575 void do_info_mice(void)
577 QEMUPutMouseEntry *cursor;
578 int index = 0;
580 if (!qemu_put_mouse_event_head) {
581 term_printf("No mouse devices connected\n");
582 return;
585 term_printf("Mouse devices available:\n");
586 cursor = qemu_put_mouse_event_head;
587 while (cursor != NULL) {
588 term_printf("%c Mouse #%d: %s\n",
589 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
590 index, cursor->qemu_put_mouse_event_name);
591 index++;
592 cursor = cursor->next;
596 void do_mouse_set(int index)
598 QEMUPutMouseEntry *cursor;
599 int i = 0;
601 if (!qemu_put_mouse_event_head) {
602 term_printf("No mouse devices connected\n");
603 return;
606 cursor = qemu_put_mouse_event_head;
607 while (cursor != NULL && index != i) {
608 i++;
609 cursor = cursor->next;
612 if (cursor != NULL)
613 qemu_put_mouse_event_current = cursor;
614 else
615 term_printf("Mouse at given index not found\n");
618 /* compute with 96 bit intermediate result: (a*b)/c */
619 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
621 union {
622 uint64_t ll;
623 struct {
624 #ifdef WORDS_BIGENDIAN
625 uint32_t high, low;
626 #else
627 uint32_t low, high;
628 #endif
629 } l;
630 } u, res;
631 uint64_t rl, rh;
633 u.ll = a;
634 rl = (uint64_t)u.l.low * (uint64_t)b;
635 rh = (uint64_t)u.l.high * (uint64_t)b;
636 rh += (rl >> 32);
637 res.l.high = rh / c;
638 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
639 return res.ll;
642 /***********************************************************/
643 /* real time host monotonic timer */
645 #define QEMU_TIMER_BASE 1000000000LL
647 #ifdef WIN32
649 static int64_t clock_freq;
651 static void init_get_clock(void)
653 LARGE_INTEGER freq;
654 int ret;
655 ret = QueryPerformanceFrequency(&freq);
656 if (ret == 0) {
657 fprintf(stderr, "Could not calibrate ticks\n");
658 exit(1);
660 clock_freq = freq.QuadPart;
663 static int64_t get_clock(void)
665 LARGE_INTEGER ti;
666 QueryPerformanceCounter(&ti);
667 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
670 #else
672 static int use_rt_clock;
674 static void init_get_clock(void)
676 use_rt_clock = 0;
677 #if defined(__linux__)
679 struct timespec ts;
680 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
681 use_rt_clock = 1;
684 #endif
687 static int64_t get_clock(void)
689 #if defined(__linux__)
690 if (use_rt_clock) {
691 struct timespec ts;
692 clock_gettime(CLOCK_MONOTONIC, &ts);
693 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
694 } else
695 #endif
697 /* XXX: using gettimeofday leads to problems if the date
698 changes, so it should be avoided. */
699 struct timeval tv;
700 gettimeofday(&tv, NULL);
701 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
705 #endif
707 /***********************************************************/
708 /* guest cycle counter */
710 static int64_t cpu_ticks_prev;
711 static int64_t cpu_ticks_offset;
712 static int64_t cpu_clock_offset;
713 static int cpu_ticks_enabled;
715 /* return the host CPU cycle counter and handle stop/restart */
716 int64_t cpu_get_ticks(void)
718 if (!cpu_ticks_enabled) {
719 return cpu_ticks_offset;
720 } else {
721 int64_t ticks;
722 ticks = cpu_get_real_ticks();
723 if (cpu_ticks_prev > ticks) {
724 /* Note: non increasing ticks may happen if the host uses
725 software suspend */
726 cpu_ticks_offset += cpu_ticks_prev - ticks;
728 cpu_ticks_prev = ticks;
729 return ticks + cpu_ticks_offset;
733 /* return the host CPU monotonic timer and handle stop/restart */
734 static int64_t cpu_get_clock(void)
736 int64_t ti;
737 if (!cpu_ticks_enabled) {
738 return cpu_clock_offset;
739 } else {
740 ti = get_clock();
741 return ti + cpu_clock_offset;
745 /* enable cpu_get_ticks() */
746 void cpu_enable_ticks(void)
748 if (!cpu_ticks_enabled) {
749 cpu_ticks_offset -= cpu_get_real_ticks();
750 cpu_clock_offset -= get_clock();
751 cpu_ticks_enabled = 1;
755 /* disable cpu_get_ticks() : the clock is stopped. You must not call
756 cpu_get_ticks() after that. */
757 void cpu_disable_ticks(void)
759 if (cpu_ticks_enabled) {
760 cpu_ticks_offset = cpu_get_ticks();
761 cpu_clock_offset = cpu_get_clock();
762 cpu_ticks_enabled = 0;
766 /***********************************************************/
767 /* timers */
769 #define QEMU_TIMER_REALTIME 0
770 #define QEMU_TIMER_VIRTUAL 1
772 struct QEMUClock {
773 int type;
774 /* XXX: add frequency */
777 struct QEMUTimer {
778 QEMUClock *clock;
779 int64_t expire_time;
780 QEMUTimerCB *cb;
781 void *opaque;
782 struct QEMUTimer *next;
785 struct qemu_alarm_timer {
786 char const *name;
788 int (*start)(struct qemu_alarm_timer *t);
789 void (*stop)(struct qemu_alarm_timer *t);
790 void *priv;
793 static struct qemu_alarm_timer *alarm_timer;
795 #ifdef _WIN32
797 struct qemu_alarm_win32 {
798 MMRESULT timerId;
799 HANDLE host_alarm;
800 unsigned int period;
801 } alarm_win32_data = {0, NULL, -1};
803 static int win32_start_timer(struct qemu_alarm_timer *t);
804 static void win32_stop_timer(struct qemu_alarm_timer *t);
806 #else
808 static int unix_start_timer(struct qemu_alarm_timer *t);
809 static void unix_stop_timer(struct qemu_alarm_timer *t);
811 #ifdef __linux__
813 static int hpet_start_timer(struct qemu_alarm_timer *t);
814 static void hpet_stop_timer(struct qemu_alarm_timer *t);
816 static int rtc_start_timer(struct qemu_alarm_timer *t);
817 static void rtc_stop_timer(struct qemu_alarm_timer *t);
819 #endif
821 #endif /* _WIN32 */
823 static struct qemu_alarm_timer alarm_timers[] = {
824 #ifdef __linux__
825 /* HPET - if available - is preferred */
826 {"hpet", hpet_start_timer, hpet_stop_timer, NULL},
827 /* ...otherwise try RTC */
828 {"rtc", rtc_start_timer, rtc_stop_timer, NULL},
829 #endif
830 #ifndef _WIN32
831 {"unix", unix_start_timer, unix_stop_timer, NULL},
832 #else
833 {"win32", win32_start_timer, win32_stop_timer, &alarm_win32_data},
834 #endif
835 {NULL, }
838 QEMUClock *rt_clock;
839 QEMUClock *vm_clock;
841 static QEMUTimer *active_timers[2];
843 QEMUClock *qemu_new_clock(int type)
845 QEMUClock *clock;
846 clock = qemu_mallocz(sizeof(QEMUClock));
847 if (!clock)
848 return NULL;
849 clock->type = type;
850 return clock;
853 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
855 QEMUTimer *ts;
857 ts = qemu_mallocz(sizeof(QEMUTimer));
858 ts->clock = clock;
859 ts->cb = cb;
860 ts->opaque = opaque;
861 return ts;
864 void qemu_free_timer(QEMUTimer *ts)
866 qemu_free(ts);
869 /* stop a timer, but do not dealloc it */
870 void qemu_del_timer(QEMUTimer *ts)
872 QEMUTimer **pt, *t;
874 /* NOTE: this code must be signal safe because
875 qemu_timer_expired() can be called from a signal. */
876 pt = &active_timers[ts->clock->type];
877 for(;;) {
878 t = *pt;
879 if (!t)
880 break;
881 if (t == ts) {
882 *pt = t->next;
883 break;
885 pt = &t->next;
889 /* modify the current timer so that it will be fired when current_time
890 >= expire_time. The corresponding callback will be called. */
891 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
893 QEMUTimer **pt, *t;
895 qemu_del_timer(ts);
897 /* add the timer in the sorted list */
898 /* NOTE: this code must be signal safe because
899 qemu_timer_expired() can be called from a signal. */
900 pt = &active_timers[ts->clock->type];
901 for(;;) {
902 t = *pt;
903 if (!t)
904 break;
905 if (t->expire_time > expire_time)
906 break;
907 pt = &t->next;
909 ts->expire_time = expire_time;
910 ts->next = *pt;
911 *pt = ts;
914 int qemu_timer_pending(QEMUTimer *ts)
916 QEMUTimer *t;
917 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
918 if (t == ts)
919 return 1;
921 return 0;
924 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
926 if (!timer_head)
927 return 0;
928 return (timer_head->expire_time <= current_time);
931 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
933 QEMUTimer *ts;
935 for(;;) {
936 ts = *ptimer_head;
937 if (!ts || ts->expire_time > current_time)
938 break;
939 /* remove timer from the list before calling the callback */
940 *ptimer_head = ts->next;
941 ts->next = NULL;
943 /* run the callback (the timer list can be modified) */
944 ts->cb(ts->opaque);
948 int64_t qemu_get_clock(QEMUClock *clock)
950 switch(clock->type) {
951 case QEMU_TIMER_REALTIME:
952 return get_clock() / 1000000;
953 default:
954 case QEMU_TIMER_VIRTUAL:
955 return cpu_get_clock();
959 static void init_timers(void)
961 init_get_clock();
962 ticks_per_sec = QEMU_TIMER_BASE;
963 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
964 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
967 /* save a timer */
968 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
970 uint64_t expire_time;
972 if (qemu_timer_pending(ts)) {
973 expire_time = ts->expire_time;
974 } else {
975 expire_time = -1;
977 qemu_put_be64(f, expire_time);
980 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
982 uint64_t expire_time;
984 expire_time = qemu_get_be64(f);
985 if (expire_time != -1) {
986 qemu_mod_timer(ts, expire_time);
987 } else {
988 qemu_del_timer(ts);
992 static void timer_save(QEMUFile *f, void *opaque)
994 if (cpu_ticks_enabled) {
995 hw_error("cannot save state if virtual timers are running");
997 qemu_put_be64s(f, &cpu_ticks_offset);
998 qemu_put_be64s(f, &ticks_per_sec);
999 qemu_put_be64s(f, &cpu_clock_offset);
1002 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1004 if (version_id != 1 && version_id != 2)
1005 return -EINVAL;
1006 if (cpu_ticks_enabled) {
1007 return -EINVAL;
1009 qemu_get_be64s(f, &cpu_ticks_offset);
1010 qemu_get_be64s(f, &ticks_per_sec);
1011 if (version_id == 2) {
1012 qemu_get_be64s(f, &cpu_clock_offset);
1014 return 0;
1017 #ifdef _WIN32
1018 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1019 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1020 #else
1021 static void host_alarm_handler(int host_signum)
1022 #endif
1024 #if 0
1025 #define DISP_FREQ 1000
1027 static int64_t delta_min = INT64_MAX;
1028 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1029 static int count;
1030 ti = qemu_get_clock(vm_clock);
1031 if (last_clock != 0) {
1032 delta = ti - last_clock;
1033 if (delta < delta_min)
1034 delta_min = delta;
1035 if (delta > delta_max)
1036 delta_max = delta;
1037 delta_cum += delta;
1038 if (++count == DISP_FREQ) {
1039 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1040 muldiv64(delta_min, 1000000, ticks_per_sec),
1041 muldiv64(delta_max, 1000000, ticks_per_sec),
1042 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1043 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1044 count = 0;
1045 delta_min = INT64_MAX;
1046 delta_max = 0;
1047 delta_cum = 0;
1050 last_clock = ti;
1052 #endif
1053 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1054 qemu_get_clock(vm_clock)) ||
1055 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1056 qemu_get_clock(rt_clock))) {
1057 #ifdef _WIN32
1058 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1059 SetEvent(data->host_alarm);
1060 #endif
1061 CPUState *env = cpu_single_env;
1062 if (env) {
1063 /* stop the currently executing cpu because a timer occured */
1064 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1065 #ifdef USE_KQEMU
1066 if (env->kqemu_enabled) {
1067 kqemu_cpu_interrupt(env);
1069 #endif
1074 #ifndef _WIN32
1076 #if defined(__linux__)
1078 #define RTC_FREQ 1024
1080 static void enable_sigio_timer(int fd)
1082 struct sigaction act;
1084 /* timer signal */
1085 sigfillset(&act.sa_mask);
1086 act.sa_flags = 0;
1087 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1088 act.sa_flags |= SA_ONSTACK;
1089 #endif
1090 act.sa_handler = host_alarm_handler;
1092 sigaction(SIGIO, &act, NULL);
1093 fcntl(fd, F_SETFL, O_ASYNC);
1094 fcntl(fd, F_SETOWN, getpid());
1097 static int hpet_start_timer(struct qemu_alarm_timer *t)
1099 struct hpet_info info;
1100 int r, fd;
1102 fd = open("/dev/hpet", O_RDONLY);
1103 if (fd < 0)
1104 return -1;
1106 /* Set frequency */
1107 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1108 if (r < 0) {
1109 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1110 "error, but for better emulation accuracy type:\n"
1111 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1112 goto fail;
1115 /* Check capabilities */
1116 r = ioctl(fd, HPET_INFO, &info);
1117 if (r < 0)
1118 goto fail;
1120 /* Enable periodic mode */
1121 r = ioctl(fd, HPET_EPI, 0);
1122 if (info.hi_flags && (r < 0))
1123 goto fail;
1125 /* Enable interrupt */
1126 r = ioctl(fd, HPET_IE_ON, 0);
1127 if (r < 0)
1128 goto fail;
1130 enable_sigio_timer(fd);
1131 t->priv = (void *)(long)fd;
1133 return 0;
1134 fail:
1135 close(fd);
1136 return -1;
1139 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1141 int fd = (long)t->priv;
1143 close(fd);
1146 static int rtc_start_timer(struct qemu_alarm_timer *t)
1148 int rtc_fd;
1150 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1151 if (rtc_fd < 0)
1152 return -1;
1153 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1154 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1155 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1156 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1157 goto fail;
1159 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1160 fail:
1161 close(rtc_fd);
1162 return -1;
1165 enable_sigio_timer(rtc_fd);
1167 t->priv = (void *)(long)rtc_fd;
1169 return 0;
1172 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1174 int rtc_fd = (long)t->priv;
1176 close(rtc_fd);
1179 #endif /* !defined(__linux__) */
1181 static int unix_start_timer(struct qemu_alarm_timer *t)
1183 struct sigaction act;
1184 struct itimerval itv;
1185 int err;
1187 /* timer signal */
1188 sigfillset(&act.sa_mask);
1189 act.sa_flags = 0;
1190 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1191 act.sa_flags |= SA_ONSTACK;
1192 #endif
1193 act.sa_handler = host_alarm_handler;
1195 sigaction(SIGALRM, &act, NULL);
1197 itv.it_interval.tv_sec = 0;
1198 /* for i386 kernel 2.6 to get 1 ms */
1199 itv.it_interval.tv_usec = 999;
1200 itv.it_value.tv_sec = 0;
1201 itv.it_value.tv_usec = 10 * 1000;
1203 err = setitimer(ITIMER_REAL, &itv, NULL);
1204 if (err)
1205 return -1;
1207 return 0;
1210 static void unix_stop_timer(struct qemu_alarm_timer *t)
1212 struct itimerval itv;
1214 memset(&itv, 0, sizeof(itv));
1215 setitimer(ITIMER_REAL, &itv, NULL);
1218 #endif /* !defined(_WIN32) */
1220 #ifdef _WIN32
1222 static int win32_start_timer(struct qemu_alarm_timer *t)
1224 TIMECAPS tc;
1225 struct qemu_alarm_win32 *data = t->priv;
1227 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1228 if (!data->host_alarm) {
1229 perror("Failed CreateEvent");
1230 return -1;
1233 memset(&tc, 0, sizeof(tc));
1234 timeGetDevCaps(&tc, sizeof(tc));
1236 if (data->period < tc.wPeriodMin)
1237 data->period = tc.wPeriodMin;
1239 timeBeginPeriod(data->period);
1241 data->timerId = timeSetEvent(1, // interval (ms)
1242 data->period, // resolution
1243 host_alarm_handler, // function
1244 (DWORD)t, // parameter
1245 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1247 if (!data->timerId) {
1248 perror("Failed to initialize win32 alarm timer");
1250 timeEndPeriod(data->period);
1251 CloseHandle(data->host_alarm);
1252 return -1;
1255 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1257 return 0;
1260 static void win32_stop_timer(struct qemu_alarm_timer *t)
1262 struct qemu_alarm_win32 *data = t->priv;
1264 timeKillEvent(data->timerId);
1265 timeEndPeriod(data->period);
1267 CloseHandle(data->host_alarm);
1270 #endif /* _WIN32 */
1272 static void init_timer_alarm(void)
1274 struct qemu_alarm_timer *t;
1275 int i, err = -1;
1277 for (i = 0; alarm_timers[i].name; i++) {
1278 t = &alarm_timers[i];
1280 printf("trying %s...\n", t->name);
1282 err = t->start(t);
1283 if (!err)
1284 break;
1287 if (err) {
1288 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1289 fprintf(stderr, "Terminating\n");
1290 exit(1);
1293 alarm_timer = t;
1296 void quit_timers(void)
1298 alarm_timer->stop(alarm_timer);
1299 alarm_timer = NULL;
1302 /***********************************************************/
1303 /* character device */
1305 static void qemu_chr_event(CharDriverState *s, int event)
1307 if (!s->chr_event)
1308 return;
1309 s->chr_event(s->handler_opaque, event);
1312 static void qemu_chr_reset_bh(void *opaque)
1314 CharDriverState *s = opaque;
1315 qemu_chr_event(s, CHR_EVENT_RESET);
1316 qemu_bh_delete(s->bh);
1317 s->bh = NULL;
1320 void qemu_chr_reset(CharDriverState *s)
1322 if (s->bh == NULL) {
1323 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1324 qemu_bh_schedule(s->bh);
1328 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1330 return s->chr_write(s, buf, len);
1333 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1335 if (!s->chr_ioctl)
1336 return -ENOTSUP;
1337 return s->chr_ioctl(s, cmd, arg);
1340 int qemu_chr_can_read(CharDriverState *s)
1342 if (!s->chr_can_read)
1343 return 0;
1344 return s->chr_can_read(s->handler_opaque);
1347 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1349 s->chr_read(s->handler_opaque, buf, len);
1353 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1355 char buf[4096];
1356 va_list ap;
1357 va_start(ap, fmt);
1358 vsnprintf(buf, sizeof(buf), fmt, ap);
1359 qemu_chr_write(s, buf, strlen(buf));
1360 va_end(ap);
1363 void qemu_chr_send_event(CharDriverState *s, int event)
1365 if (s->chr_send_event)
1366 s->chr_send_event(s, event);
1369 void qemu_chr_add_handlers(CharDriverState *s,
1370 IOCanRWHandler *fd_can_read,
1371 IOReadHandler *fd_read,
1372 IOEventHandler *fd_event,
1373 void *opaque)
1375 s->chr_can_read = fd_can_read;
1376 s->chr_read = fd_read;
1377 s->chr_event = fd_event;
1378 s->handler_opaque = opaque;
1379 if (s->chr_update_read_handler)
1380 s->chr_update_read_handler(s);
1383 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1385 return len;
1388 static CharDriverState *qemu_chr_open_null(void)
1390 CharDriverState *chr;
1392 chr = qemu_mallocz(sizeof(CharDriverState));
1393 if (!chr)
1394 return NULL;
1395 chr->chr_write = null_chr_write;
1396 return chr;
1399 /* MUX driver for serial I/O splitting */
1400 static int term_timestamps;
1401 static int64_t term_timestamps_start;
1402 #define MAX_MUX 4
1403 typedef struct {
1404 IOCanRWHandler *chr_can_read[MAX_MUX];
1405 IOReadHandler *chr_read[MAX_MUX];
1406 IOEventHandler *chr_event[MAX_MUX];
1407 void *ext_opaque[MAX_MUX];
1408 CharDriverState *drv;
1409 int mux_cnt;
1410 int term_got_escape;
1411 int max_size;
1412 } MuxDriver;
1415 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1417 MuxDriver *d = chr->opaque;
1418 int ret;
1419 if (!term_timestamps) {
1420 ret = d->drv->chr_write(d->drv, buf, len);
1421 } else {
1422 int i;
1424 ret = 0;
1425 for(i = 0; i < len; i++) {
1426 ret += d->drv->chr_write(d->drv, buf+i, 1);
1427 if (buf[i] == '\n') {
1428 char buf1[64];
1429 int64_t ti;
1430 int secs;
1432 ti = get_clock();
1433 if (term_timestamps_start == -1)
1434 term_timestamps_start = ti;
1435 ti -= term_timestamps_start;
1436 secs = ti / 1000000000;
1437 snprintf(buf1, sizeof(buf1),
1438 "[%02d:%02d:%02d.%03d] ",
1439 secs / 3600,
1440 (secs / 60) % 60,
1441 secs % 60,
1442 (int)((ti / 1000000) % 1000));
1443 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1447 return ret;
1450 static char *mux_help[] = {
1451 "% h print this help\n\r",
1452 "% x exit emulator\n\r",
1453 "% s save disk data back to file (if -snapshot)\n\r",
1454 "% t toggle console timestamps\n\r"
1455 "% b send break (magic sysrq)\n\r",
1456 "% c switch between console and monitor\n\r",
1457 "% % sends %\n\r",
1458 NULL
1461 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1462 static void mux_print_help(CharDriverState *chr)
1464 int i, j;
1465 char ebuf[15] = "Escape-Char";
1466 char cbuf[50] = "\n\r";
1468 if (term_escape_char > 0 && term_escape_char < 26) {
1469 sprintf(cbuf,"\n\r");
1470 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1471 } else {
1472 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1474 chr->chr_write(chr, cbuf, strlen(cbuf));
1475 for (i = 0; mux_help[i] != NULL; i++) {
1476 for (j=0; mux_help[i][j] != '\0'; j++) {
1477 if (mux_help[i][j] == '%')
1478 chr->chr_write(chr, ebuf, strlen(ebuf));
1479 else
1480 chr->chr_write(chr, &mux_help[i][j], 1);
1485 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1487 if (d->term_got_escape) {
1488 d->term_got_escape = 0;
1489 if (ch == term_escape_char)
1490 goto send_char;
1491 switch(ch) {
1492 case '?':
1493 case 'h':
1494 mux_print_help(chr);
1495 break;
1496 case 'x':
1498 char *term = "QEMU: Terminated\n\r";
1499 chr->chr_write(chr,term,strlen(term));
1500 exit(0);
1501 break;
1503 case 's':
1505 int i;
1506 for (i = 0; i < MAX_DISKS; i++) {
1507 if (bs_table[i])
1508 bdrv_commit(bs_table[i]);
1510 if (mtd_bdrv)
1511 bdrv_commit(mtd_bdrv);
1513 break;
1514 case 'b':
1515 qemu_chr_event(chr, CHR_EVENT_BREAK);
1516 break;
1517 case 'c':
1518 /* Switch to the next registered device */
1519 chr->focus++;
1520 if (chr->focus >= d->mux_cnt)
1521 chr->focus = 0;
1522 break;
1523 case 't':
1524 term_timestamps = !term_timestamps;
1525 term_timestamps_start = -1;
1526 break;
1528 } else if (ch == term_escape_char) {
1529 d->term_got_escape = 1;
1530 } else {
1531 send_char:
1532 return 1;
1534 return 0;
1537 static int mux_chr_can_read(void *opaque)
1539 CharDriverState *chr = opaque;
1540 MuxDriver *d = chr->opaque;
1541 if (d->chr_can_read[chr->focus])
1542 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1543 return 0;
1546 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1548 CharDriverState *chr = opaque;
1549 MuxDriver *d = chr->opaque;
1550 int i;
1551 for(i = 0; i < size; i++)
1552 if (mux_proc_byte(chr, d, buf[i]))
1553 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1556 static void mux_chr_event(void *opaque, int event)
1558 CharDriverState *chr = opaque;
1559 MuxDriver *d = chr->opaque;
1560 int i;
1562 /* Send the event to all registered listeners */
1563 for (i = 0; i < d->mux_cnt; i++)
1564 if (d->chr_event[i])
1565 d->chr_event[i](d->ext_opaque[i], event);
1568 static void mux_chr_update_read_handler(CharDriverState *chr)
1570 MuxDriver *d = chr->opaque;
1572 if (d->mux_cnt >= MAX_MUX) {
1573 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1574 return;
1576 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1577 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1578 d->chr_read[d->mux_cnt] = chr->chr_read;
1579 d->chr_event[d->mux_cnt] = chr->chr_event;
1580 /* Fix up the real driver with mux routines */
1581 if (d->mux_cnt == 0) {
1582 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1583 mux_chr_event, chr);
1585 chr->focus = d->mux_cnt;
1586 d->mux_cnt++;
1589 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1591 CharDriverState *chr;
1592 MuxDriver *d;
1594 chr = qemu_mallocz(sizeof(CharDriverState));
1595 if (!chr)
1596 return NULL;
1597 d = qemu_mallocz(sizeof(MuxDriver));
1598 if (!d) {
1599 free(chr);
1600 return NULL;
1603 chr->opaque = d;
1604 d->drv = drv;
1605 chr->focus = -1;
1606 chr->chr_write = mux_chr_write;
1607 chr->chr_update_read_handler = mux_chr_update_read_handler;
1608 return chr;
1612 #ifdef _WIN32
1614 static void socket_cleanup(void)
1616 WSACleanup();
1619 static int socket_init(void)
1621 WSADATA Data;
1622 int ret, err;
1624 ret = WSAStartup(MAKEWORD(2,2), &Data);
1625 if (ret != 0) {
1626 err = WSAGetLastError();
1627 fprintf(stderr, "WSAStartup: %d\n", err);
1628 return -1;
1630 atexit(socket_cleanup);
1631 return 0;
1634 static int send_all(int fd, const uint8_t *buf, int len1)
1636 int ret, len;
1638 len = len1;
1639 while (len > 0) {
1640 ret = send(fd, buf, len, 0);
1641 if (ret < 0) {
1642 int errno;
1643 errno = WSAGetLastError();
1644 if (errno != WSAEWOULDBLOCK) {
1645 return -1;
1647 } else if (ret == 0) {
1648 break;
1649 } else {
1650 buf += ret;
1651 len -= ret;
1654 return len1 - len;
1657 void socket_set_nonblock(int fd)
1659 unsigned long opt = 1;
1660 ioctlsocket(fd, FIONBIO, &opt);
1663 #else
1665 static int unix_write(int fd, const uint8_t *buf, int len1)
1667 int ret, len;
1669 len = len1;
1670 while (len > 0) {
1671 ret = write(fd, buf, len);
1672 if (ret < 0) {
1673 if (errno != EINTR && errno != EAGAIN)
1674 return -1;
1675 } else if (ret == 0) {
1676 break;
1677 } else {
1678 buf += ret;
1679 len -= ret;
1682 return len1 - len;
1685 static inline int send_all(int fd, const uint8_t *buf, int len1)
1687 return unix_write(fd, buf, len1);
1690 void socket_set_nonblock(int fd)
1692 fcntl(fd, F_SETFL, O_NONBLOCK);
1694 #endif /* !_WIN32 */
1696 #ifndef _WIN32
1698 typedef struct {
1699 int fd_in, fd_out;
1700 int max_size;
1701 } FDCharDriver;
1703 #define STDIO_MAX_CLIENTS 1
1704 static int stdio_nb_clients = 0;
1706 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1708 FDCharDriver *s = chr->opaque;
1709 return unix_write(s->fd_out, buf, len);
1712 static int fd_chr_read_poll(void *opaque)
1714 CharDriverState *chr = opaque;
1715 FDCharDriver *s = chr->opaque;
1717 s->max_size = qemu_chr_can_read(chr);
1718 return s->max_size;
1721 static void fd_chr_read(void *opaque)
1723 CharDriverState *chr = opaque;
1724 FDCharDriver *s = chr->opaque;
1725 int size, len;
1726 uint8_t buf[1024];
1728 len = sizeof(buf);
1729 if (len > s->max_size)
1730 len = s->max_size;
1731 if (len == 0)
1732 return;
1733 size = read(s->fd_in, buf, len);
1734 if (size == 0) {
1735 /* FD has been closed. Remove it from the active list. */
1736 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1737 return;
1739 if (size > 0) {
1740 qemu_chr_read(chr, buf, size);
1744 static void fd_chr_update_read_handler(CharDriverState *chr)
1746 FDCharDriver *s = chr->opaque;
1748 if (s->fd_in >= 0) {
1749 if (nographic && s->fd_in == 0) {
1750 } else {
1751 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1752 fd_chr_read, NULL, chr);
1757 /* open a character device to a unix fd */
1758 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1760 CharDriverState *chr;
1761 FDCharDriver *s;
1763 chr = qemu_mallocz(sizeof(CharDriverState));
1764 if (!chr)
1765 return NULL;
1766 s = qemu_mallocz(sizeof(FDCharDriver));
1767 if (!s) {
1768 free(chr);
1769 return NULL;
1771 s->fd_in = fd_in;
1772 s->fd_out = fd_out;
1773 chr->opaque = s;
1774 chr->chr_write = fd_chr_write;
1775 chr->chr_update_read_handler = fd_chr_update_read_handler;
1777 qemu_chr_reset(chr);
1779 return chr;
1782 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1784 int fd_out;
1786 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
1787 if (fd_out < 0)
1788 return NULL;
1789 return qemu_chr_open_fd(-1, fd_out);
1792 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1794 int fd_in, fd_out;
1795 char filename_in[256], filename_out[256];
1797 snprintf(filename_in, 256, "%s.in", filename);
1798 snprintf(filename_out, 256, "%s.out", filename);
1799 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
1800 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
1801 if (fd_in < 0 || fd_out < 0) {
1802 if (fd_in >= 0)
1803 close(fd_in);
1804 if (fd_out >= 0)
1805 close(fd_out);
1806 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
1807 if (fd_in < 0)
1808 return NULL;
1810 return qemu_chr_open_fd(fd_in, fd_out);
1814 /* for STDIO, we handle the case where several clients use it
1815 (nographic mode) */
1817 #define TERM_FIFO_MAX_SIZE 1
1819 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1820 static int term_fifo_size;
1822 static int stdio_read_poll(void *opaque)
1824 CharDriverState *chr = opaque;
1826 /* try to flush the queue if needed */
1827 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1828 qemu_chr_read(chr, term_fifo, 1);
1829 term_fifo_size = 0;
1831 /* see if we can absorb more chars */
1832 if (term_fifo_size == 0)
1833 return 1;
1834 else
1835 return 0;
1838 static void stdio_read(void *opaque)
1840 int size;
1841 uint8_t buf[1];
1842 CharDriverState *chr = opaque;
1844 size = read(0, buf, 1);
1845 if (size == 0) {
1846 /* stdin has been closed. Remove it from the active list. */
1847 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1848 return;
1850 if (size > 0) {
1851 if (qemu_chr_can_read(chr) > 0) {
1852 qemu_chr_read(chr, buf, 1);
1853 } else if (term_fifo_size == 0) {
1854 term_fifo[term_fifo_size++] = buf[0];
1859 /* init terminal so that we can grab keys */
1860 static struct termios oldtty;
1861 static int old_fd0_flags;
1863 static void term_exit(void)
1865 tcsetattr (0, TCSANOW, &oldtty);
1866 fcntl(0, F_SETFL, old_fd0_flags);
1869 static void term_init(void)
1871 struct termios tty;
1873 tcgetattr (0, &tty);
1874 oldtty = tty;
1875 old_fd0_flags = fcntl(0, F_GETFL);
1877 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1878 |INLCR|IGNCR|ICRNL|IXON);
1879 tty.c_oflag |= OPOST;
1880 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1881 /* if graphical mode, we allow Ctrl-C handling */
1882 if (nographic)
1883 tty.c_lflag &= ~ISIG;
1884 tty.c_cflag &= ~(CSIZE|PARENB);
1885 tty.c_cflag |= CS8;
1886 tty.c_cc[VMIN] = 1;
1887 tty.c_cc[VTIME] = 0;
1889 tcsetattr (0, TCSANOW, &tty);
1891 atexit(term_exit);
1893 fcntl(0, F_SETFL, O_NONBLOCK);
1896 static CharDriverState *qemu_chr_open_stdio(void)
1898 CharDriverState *chr;
1900 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1901 return NULL;
1902 chr = qemu_chr_open_fd(0, 1);
1903 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1904 stdio_nb_clients++;
1905 term_init();
1907 return chr;
1910 #if defined(__linux__) || defined(__sun__)
1911 static CharDriverState *qemu_chr_open_pty(void)
1913 struct termios tty;
1914 char slave_name[1024];
1915 int master_fd, slave_fd;
1917 #if defined(__linux__)
1918 /* Not satisfying */
1919 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1920 return NULL;
1922 #endif
1924 /* Disabling local echo and line-buffered output */
1925 tcgetattr (master_fd, &tty);
1926 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1927 tty.c_cc[VMIN] = 1;
1928 tty.c_cc[VTIME] = 0;
1929 tcsetattr (master_fd, TCSAFLUSH, &tty);
1931 fprintf(stderr, "char device redirected to %s\n", slave_name);
1932 return qemu_chr_open_fd(master_fd, master_fd);
1935 static void tty_serial_init(int fd, int speed,
1936 int parity, int data_bits, int stop_bits)
1938 struct termios tty;
1939 speed_t spd;
1941 #if 0
1942 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1943 speed, parity, data_bits, stop_bits);
1944 #endif
1945 tcgetattr (fd, &tty);
1947 switch(speed) {
1948 case 50:
1949 spd = B50;
1950 break;
1951 case 75:
1952 spd = B75;
1953 break;
1954 case 300:
1955 spd = B300;
1956 break;
1957 case 600:
1958 spd = B600;
1959 break;
1960 case 1200:
1961 spd = B1200;
1962 break;
1963 case 2400:
1964 spd = B2400;
1965 break;
1966 case 4800:
1967 spd = B4800;
1968 break;
1969 case 9600:
1970 spd = B9600;
1971 break;
1972 case 19200:
1973 spd = B19200;
1974 break;
1975 case 38400:
1976 spd = B38400;
1977 break;
1978 case 57600:
1979 spd = B57600;
1980 break;
1981 default:
1982 case 115200:
1983 spd = B115200;
1984 break;
1987 cfsetispeed(&tty, spd);
1988 cfsetospeed(&tty, spd);
1990 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1991 |INLCR|IGNCR|ICRNL|IXON);
1992 tty.c_oflag |= OPOST;
1993 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1994 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1995 switch(data_bits) {
1996 default:
1997 case 8:
1998 tty.c_cflag |= CS8;
1999 break;
2000 case 7:
2001 tty.c_cflag |= CS7;
2002 break;
2003 case 6:
2004 tty.c_cflag |= CS6;
2005 break;
2006 case 5:
2007 tty.c_cflag |= CS5;
2008 break;
2010 switch(parity) {
2011 default:
2012 case 'N':
2013 break;
2014 case 'E':
2015 tty.c_cflag |= PARENB;
2016 break;
2017 case 'O':
2018 tty.c_cflag |= PARENB | PARODD;
2019 break;
2021 if (stop_bits == 2)
2022 tty.c_cflag |= CSTOPB;
2024 tcsetattr (fd, TCSANOW, &tty);
2027 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2029 FDCharDriver *s = chr->opaque;
2031 switch(cmd) {
2032 case CHR_IOCTL_SERIAL_SET_PARAMS:
2034 QEMUSerialSetParams *ssp = arg;
2035 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2036 ssp->data_bits, ssp->stop_bits);
2038 break;
2039 case CHR_IOCTL_SERIAL_SET_BREAK:
2041 int enable = *(int *)arg;
2042 if (enable)
2043 tcsendbreak(s->fd_in, 1);
2045 break;
2046 default:
2047 return -ENOTSUP;
2049 return 0;
2052 static CharDriverState *qemu_chr_open_tty(const char *filename)
2054 CharDriverState *chr;
2055 int fd;
2057 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2058 fcntl(fd, F_SETFL, O_NONBLOCK);
2059 tty_serial_init(fd, 115200, 'N', 8, 1);
2060 chr = qemu_chr_open_fd(fd, fd);
2061 if (!chr) {
2062 close(fd);
2063 return NULL;
2065 chr->chr_ioctl = tty_serial_ioctl;
2066 qemu_chr_reset(chr);
2067 return chr;
2069 #else /* ! __linux__ && ! __sun__ */
2070 static CharDriverState *qemu_chr_open_pty(void)
2072 return NULL;
2074 #endif /* __linux__ || __sun__ */
2076 #if defined(__linux__)
2077 typedef struct {
2078 int fd;
2079 int mode;
2080 } ParallelCharDriver;
2082 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2084 if (s->mode != mode) {
2085 int m = mode;
2086 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2087 return 0;
2088 s->mode = mode;
2090 return 1;
2093 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2095 ParallelCharDriver *drv = chr->opaque;
2096 int fd = drv->fd;
2097 uint8_t b;
2099 switch(cmd) {
2100 case CHR_IOCTL_PP_READ_DATA:
2101 if (ioctl(fd, PPRDATA, &b) < 0)
2102 return -ENOTSUP;
2103 *(uint8_t *)arg = b;
2104 break;
2105 case CHR_IOCTL_PP_WRITE_DATA:
2106 b = *(uint8_t *)arg;
2107 if (ioctl(fd, PPWDATA, &b) < 0)
2108 return -ENOTSUP;
2109 break;
2110 case CHR_IOCTL_PP_READ_CONTROL:
2111 if (ioctl(fd, PPRCONTROL, &b) < 0)
2112 return -ENOTSUP;
2113 /* Linux gives only the lowest bits, and no way to know data
2114 direction! For better compatibility set the fixed upper
2115 bits. */
2116 *(uint8_t *)arg = b | 0xc0;
2117 break;
2118 case CHR_IOCTL_PP_WRITE_CONTROL:
2119 b = *(uint8_t *)arg;
2120 if (ioctl(fd, PPWCONTROL, &b) < 0)
2121 return -ENOTSUP;
2122 break;
2123 case CHR_IOCTL_PP_READ_STATUS:
2124 if (ioctl(fd, PPRSTATUS, &b) < 0)
2125 return -ENOTSUP;
2126 *(uint8_t *)arg = b;
2127 break;
2128 case CHR_IOCTL_PP_EPP_READ_ADDR:
2129 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2130 struct ParallelIOArg *parg = arg;
2131 int n = read(fd, parg->buffer, parg->count);
2132 if (n != parg->count) {
2133 return -EIO;
2136 break;
2137 case CHR_IOCTL_PP_EPP_READ:
2138 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2139 struct ParallelIOArg *parg = arg;
2140 int n = read(fd, parg->buffer, parg->count);
2141 if (n != parg->count) {
2142 return -EIO;
2145 break;
2146 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2147 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2148 struct ParallelIOArg *parg = arg;
2149 int n = write(fd, parg->buffer, parg->count);
2150 if (n != parg->count) {
2151 return -EIO;
2154 break;
2155 case CHR_IOCTL_PP_EPP_WRITE:
2156 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2157 struct ParallelIOArg *parg = arg;
2158 int n = write(fd, parg->buffer, parg->count);
2159 if (n != parg->count) {
2160 return -EIO;
2163 break;
2164 default:
2165 return -ENOTSUP;
2167 return 0;
2170 static void pp_close(CharDriverState *chr)
2172 ParallelCharDriver *drv = chr->opaque;
2173 int fd = drv->fd;
2175 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2176 ioctl(fd, PPRELEASE);
2177 close(fd);
2178 qemu_free(drv);
2181 static CharDriverState *qemu_chr_open_pp(const char *filename)
2183 CharDriverState *chr;
2184 ParallelCharDriver *drv;
2185 int fd;
2187 TFR(fd = open(filename, O_RDWR));
2188 if (fd < 0)
2189 return NULL;
2191 if (ioctl(fd, PPCLAIM) < 0) {
2192 close(fd);
2193 return NULL;
2196 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2197 if (!drv) {
2198 close(fd);
2199 return NULL;
2201 drv->fd = fd;
2202 drv->mode = IEEE1284_MODE_COMPAT;
2204 chr = qemu_mallocz(sizeof(CharDriverState));
2205 if (!chr) {
2206 qemu_free(drv);
2207 close(fd);
2208 return NULL;
2210 chr->chr_write = null_chr_write;
2211 chr->chr_ioctl = pp_ioctl;
2212 chr->chr_close = pp_close;
2213 chr->opaque = drv;
2215 qemu_chr_reset(chr);
2217 return chr;
2219 #endif /* __linux__ */
2221 #else /* _WIN32 */
2223 typedef struct {
2224 int max_size;
2225 HANDLE hcom, hrecv, hsend;
2226 OVERLAPPED orecv, osend;
2227 BOOL fpipe;
2228 DWORD len;
2229 } WinCharState;
2231 #define NSENDBUF 2048
2232 #define NRECVBUF 2048
2233 #define MAXCONNECT 1
2234 #define NTIMEOUT 5000
2236 static int win_chr_poll(void *opaque);
2237 static int win_chr_pipe_poll(void *opaque);
2239 static void win_chr_close(CharDriverState *chr)
2241 WinCharState *s = chr->opaque;
2243 if (s->hsend) {
2244 CloseHandle(s->hsend);
2245 s->hsend = NULL;
2247 if (s->hrecv) {
2248 CloseHandle(s->hrecv);
2249 s->hrecv = NULL;
2251 if (s->hcom) {
2252 CloseHandle(s->hcom);
2253 s->hcom = NULL;
2255 if (s->fpipe)
2256 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2257 else
2258 qemu_del_polling_cb(win_chr_poll, chr);
2261 static int win_chr_init(CharDriverState *chr, const char *filename)
2263 WinCharState *s = chr->opaque;
2264 COMMCONFIG comcfg;
2265 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2266 COMSTAT comstat;
2267 DWORD size;
2268 DWORD err;
2270 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2271 if (!s->hsend) {
2272 fprintf(stderr, "Failed CreateEvent\n");
2273 goto fail;
2275 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2276 if (!s->hrecv) {
2277 fprintf(stderr, "Failed CreateEvent\n");
2278 goto fail;
2281 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2282 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2283 if (s->hcom == INVALID_HANDLE_VALUE) {
2284 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2285 s->hcom = NULL;
2286 goto fail;
2289 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2290 fprintf(stderr, "Failed SetupComm\n");
2291 goto fail;
2294 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2295 size = sizeof(COMMCONFIG);
2296 GetDefaultCommConfig(filename, &comcfg, &size);
2297 comcfg.dcb.DCBlength = sizeof(DCB);
2298 CommConfigDialog(filename, NULL, &comcfg);
2300 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2301 fprintf(stderr, "Failed SetCommState\n");
2302 goto fail;
2305 if (!SetCommMask(s->hcom, EV_ERR)) {
2306 fprintf(stderr, "Failed SetCommMask\n");
2307 goto fail;
2310 cto.ReadIntervalTimeout = MAXDWORD;
2311 if (!SetCommTimeouts(s->hcom, &cto)) {
2312 fprintf(stderr, "Failed SetCommTimeouts\n");
2313 goto fail;
2316 if (!ClearCommError(s->hcom, &err, &comstat)) {
2317 fprintf(stderr, "Failed ClearCommError\n");
2318 goto fail;
2320 qemu_add_polling_cb(win_chr_poll, chr);
2321 return 0;
2323 fail:
2324 win_chr_close(chr);
2325 return -1;
2328 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2330 WinCharState *s = chr->opaque;
2331 DWORD len, ret, size, err;
2333 len = len1;
2334 ZeroMemory(&s->osend, sizeof(s->osend));
2335 s->osend.hEvent = s->hsend;
2336 while (len > 0) {
2337 if (s->hsend)
2338 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2339 else
2340 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2341 if (!ret) {
2342 err = GetLastError();
2343 if (err == ERROR_IO_PENDING) {
2344 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2345 if (ret) {
2346 buf += size;
2347 len -= size;
2348 } else {
2349 break;
2351 } else {
2352 break;
2354 } else {
2355 buf += size;
2356 len -= size;
2359 return len1 - len;
2362 static int win_chr_read_poll(CharDriverState *chr)
2364 WinCharState *s = chr->opaque;
2366 s->max_size = qemu_chr_can_read(chr);
2367 return s->max_size;
2370 static void win_chr_readfile(CharDriverState *chr)
2372 WinCharState *s = chr->opaque;
2373 int ret, err;
2374 uint8_t buf[1024];
2375 DWORD size;
2377 ZeroMemory(&s->orecv, sizeof(s->orecv));
2378 s->orecv.hEvent = s->hrecv;
2379 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2380 if (!ret) {
2381 err = GetLastError();
2382 if (err == ERROR_IO_PENDING) {
2383 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2387 if (size > 0) {
2388 qemu_chr_read(chr, buf, size);
2392 static void win_chr_read(CharDriverState *chr)
2394 WinCharState *s = chr->opaque;
2396 if (s->len > s->max_size)
2397 s->len = s->max_size;
2398 if (s->len == 0)
2399 return;
2401 win_chr_readfile(chr);
2404 static int win_chr_poll(void *opaque)
2406 CharDriverState *chr = opaque;
2407 WinCharState *s = chr->opaque;
2408 COMSTAT status;
2409 DWORD comerr;
2411 ClearCommError(s->hcom, &comerr, &status);
2412 if (status.cbInQue > 0) {
2413 s->len = status.cbInQue;
2414 win_chr_read_poll(chr);
2415 win_chr_read(chr);
2416 return 1;
2418 return 0;
2421 static CharDriverState *qemu_chr_open_win(const char *filename)
2423 CharDriverState *chr;
2424 WinCharState *s;
2426 chr = qemu_mallocz(sizeof(CharDriverState));
2427 if (!chr)
2428 return NULL;
2429 s = qemu_mallocz(sizeof(WinCharState));
2430 if (!s) {
2431 free(chr);
2432 return NULL;
2434 chr->opaque = s;
2435 chr->chr_write = win_chr_write;
2436 chr->chr_close = win_chr_close;
2438 if (win_chr_init(chr, filename) < 0) {
2439 free(s);
2440 free(chr);
2441 return NULL;
2443 qemu_chr_reset(chr);
2444 return chr;
2447 static int win_chr_pipe_poll(void *opaque)
2449 CharDriverState *chr = opaque;
2450 WinCharState *s = chr->opaque;
2451 DWORD size;
2453 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2454 if (size > 0) {
2455 s->len = size;
2456 win_chr_read_poll(chr);
2457 win_chr_read(chr);
2458 return 1;
2460 return 0;
2463 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2465 WinCharState *s = chr->opaque;
2466 OVERLAPPED ov;
2467 int ret;
2468 DWORD size;
2469 char openname[256];
2471 s->fpipe = TRUE;
2473 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2474 if (!s->hsend) {
2475 fprintf(stderr, "Failed CreateEvent\n");
2476 goto fail;
2478 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2479 if (!s->hrecv) {
2480 fprintf(stderr, "Failed CreateEvent\n");
2481 goto fail;
2484 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2485 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2486 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2487 PIPE_WAIT,
2488 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2489 if (s->hcom == INVALID_HANDLE_VALUE) {
2490 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2491 s->hcom = NULL;
2492 goto fail;
2495 ZeroMemory(&ov, sizeof(ov));
2496 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2497 ret = ConnectNamedPipe(s->hcom, &ov);
2498 if (ret) {
2499 fprintf(stderr, "Failed ConnectNamedPipe\n");
2500 goto fail;
2503 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2504 if (!ret) {
2505 fprintf(stderr, "Failed GetOverlappedResult\n");
2506 if (ov.hEvent) {
2507 CloseHandle(ov.hEvent);
2508 ov.hEvent = NULL;
2510 goto fail;
2513 if (ov.hEvent) {
2514 CloseHandle(ov.hEvent);
2515 ov.hEvent = NULL;
2517 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2518 return 0;
2520 fail:
2521 win_chr_close(chr);
2522 return -1;
2526 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2528 CharDriverState *chr;
2529 WinCharState *s;
2531 chr = qemu_mallocz(sizeof(CharDriverState));
2532 if (!chr)
2533 return NULL;
2534 s = qemu_mallocz(sizeof(WinCharState));
2535 if (!s) {
2536 free(chr);
2537 return NULL;
2539 chr->opaque = s;
2540 chr->chr_write = win_chr_write;
2541 chr->chr_close = win_chr_close;
2543 if (win_chr_pipe_init(chr, filename) < 0) {
2544 free(s);
2545 free(chr);
2546 return NULL;
2548 qemu_chr_reset(chr);
2549 return chr;
2552 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2554 CharDriverState *chr;
2555 WinCharState *s;
2557 chr = qemu_mallocz(sizeof(CharDriverState));
2558 if (!chr)
2559 return NULL;
2560 s = qemu_mallocz(sizeof(WinCharState));
2561 if (!s) {
2562 free(chr);
2563 return NULL;
2565 s->hcom = fd_out;
2566 chr->opaque = s;
2567 chr->chr_write = win_chr_write;
2568 qemu_chr_reset(chr);
2569 return chr;
2572 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2574 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2577 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2579 HANDLE fd_out;
2581 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2582 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2583 if (fd_out == INVALID_HANDLE_VALUE)
2584 return NULL;
2586 return qemu_chr_open_win_file(fd_out);
2588 #endif /* !_WIN32 */
2590 /***********************************************************/
2591 /* UDP Net console */
2593 typedef struct {
2594 int fd;
2595 struct sockaddr_in daddr;
2596 char buf[1024];
2597 int bufcnt;
2598 int bufptr;
2599 int max_size;
2600 } NetCharDriver;
2602 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2604 NetCharDriver *s = chr->opaque;
2606 return sendto(s->fd, buf, len, 0,
2607 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2610 static int udp_chr_read_poll(void *opaque)
2612 CharDriverState *chr = opaque;
2613 NetCharDriver *s = chr->opaque;
2615 s->max_size = qemu_chr_can_read(chr);
2617 /* If there were any stray characters in the queue process them
2618 * first
2620 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2621 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2622 s->bufptr++;
2623 s->max_size = qemu_chr_can_read(chr);
2625 return s->max_size;
2628 static void udp_chr_read(void *opaque)
2630 CharDriverState *chr = opaque;
2631 NetCharDriver *s = chr->opaque;
2633 if (s->max_size == 0)
2634 return;
2635 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2636 s->bufptr = s->bufcnt;
2637 if (s->bufcnt <= 0)
2638 return;
2640 s->bufptr = 0;
2641 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2642 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2643 s->bufptr++;
2644 s->max_size = qemu_chr_can_read(chr);
2648 static void udp_chr_update_read_handler(CharDriverState *chr)
2650 NetCharDriver *s = chr->opaque;
2652 if (s->fd >= 0) {
2653 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2654 udp_chr_read, NULL, chr);
2658 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2659 #ifndef _WIN32
2660 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2661 #endif
2662 int parse_host_src_port(struct sockaddr_in *haddr,
2663 struct sockaddr_in *saddr,
2664 const char *str);
2666 static CharDriverState *qemu_chr_open_udp(const char *def)
2668 CharDriverState *chr = NULL;
2669 NetCharDriver *s = NULL;
2670 int fd = -1;
2671 struct sockaddr_in saddr;
2673 chr = qemu_mallocz(sizeof(CharDriverState));
2674 if (!chr)
2675 goto return_err;
2676 s = qemu_mallocz(sizeof(NetCharDriver));
2677 if (!s)
2678 goto return_err;
2680 fd = socket(PF_INET, SOCK_DGRAM, 0);
2681 if (fd < 0) {
2682 perror("socket(PF_INET, SOCK_DGRAM)");
2683 goto return_err;
2686 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2687 printf("Could not parse: %s\n", def);
2688 goto return_err;
2691 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2693 perror("bind");
2694 goto return_err;
2697 s->fd = fd;
2698 s->bufcnt = 0;
2699 s->bufptr = 0;
2700 chr->opaque = s;
2701 chr->chr_write = udp_chr_write;
2702 chr->chr_update_read_handler = udp_chr_update_read_handler;
2703 return chr;
2705 return_err:
2706 if (chr)
2707 free(chr);
2708 if (s)
2709 free(s);
2710 if (fd >= 0)
2711 closesocket(fd);
2712 return NULL;
2715 /***********************************************************/
2716 /* TCP Net console */
2718 typedef struct {
2719 int fd, listen_fd;
2720 int connected;
2721 int max_size;
2722 int do_telnetopt;
2723 int do_nodelay;
2724 int is_unix;
2725 } TCPCharDriver;
2727 static void tcp_chr_accept(void *opaque);
2729 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2731 TCPCharDriver *s = chr->opaque;
2732 if (s->connected) {
2733 return send_all(s->fd, buf, len);
2734 } else {
2735 /* XXX: indicate an error ? */
2736 return len;
2740 static int tcp_chr_read_poll(void *opaque)
2742 CharDriverState *chr = opaque;
2743 TCPCharDriver *s = chr->opaque;
2744 if (!s->connected)
2745 return 0;
2746 s->max_size = qemu_chr_can_read(chr);
2747 return s->max_size;
2750 #define IAC 255
2751 #define IAC_BREAK 243
2752 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2753 TCPCharDriver *s,
2754 char *buf, int *size)
2756 /* Handle any telnet client's basic IAC options to satisfy char by
2757 * char mode with no echo. All IAC options will be removed from
2758 * the buf and the do_telnetopt variable will be used to track the
2759 * state of the width of the IAC information.
2761 * IAC commands come in sets of 3 bytes with the exception of the
2762 * "IAC BREAK" command and the double IAC.
2765 int i;
2766 int j = 0;
2768 for (i = 0; i < *size; i++) {
2769 if (s->do_telnetopt > 1) {
2770 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2771 /* Double IAC means send an IAC */
2772 if (j != i)
2773 buf[j] = buf[i];
2774 j++;
2775 s->do_telnetopt = 1;
2776 } else {
2777 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2778 /* Handle IAC break commands by sending a serial break */
2779 qemu_chr_event(chr, CHR_EVENT_BREAK);
2780 s->do_telnetopt++;
2782 s->do_telnetopt++;
2784 if (s->do_telnetopt >= 4) {
2785 s->do_telnetopt = 1;
2787 } else {
2788 if ((unsigned char)buf[i] == IAC) {
2789 s->do_telnetopt = 2;
2790 } else {
2791 if (j != i)
2792 buf[j] = buf[i];
2793 j++;
2797 *size = j;
2800 static void tcp_chr_read(void *opaque)
2802 CharDriverState *chr = opaque;
2803 TCPCharDriver *s = chr->opaque;
2804 uint8_t buf[1024];
2805 int len, size;
2807 if (!s->connected || s->max_size <= 0)
2808 return;
2809 len = sizeof(buf);
2810 if (len > s->max_size)
2811 len = s->max_size;
2812 size = recv(s->fd, buf, len, 0);
2813 if (size == 0) {
2814 /* connection closed */
2815 s->connected = 0;
2816 if (s->listen_fd >= 0) {
2817 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2819 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2820 closesocket(s->fd);
2821 s->fd = -1;
2822 } else if (size > 0) {
2823 if (s->do_telnetopt)
2824 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2825 if (size > 0)
2826 qemu_chr_read(chr, buf, size);
2830 static void tcp_chr_connect(void *opaque)
2832 CharDriverState *chr = opaque;
2833 TCPCharDriver *s = chr->opaque;
2835 s->connected = 1;
2836 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2837 tcp_chr_read, NULL, chr);
2838 qemu_chr_reset(chr);
2841 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2842 static void tcp_chr_telnet_init(int fd)
2844 char buf[3];
2845 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2846 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2847 send(fd, (char *)buf, 3, 0);
2848 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2849 send(fd, (char *)buf, 3, 0);
2850 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2851 send(fd, (char *)buf, 3, 0);
2852 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2853 send(fd, (char *)buf, 3, 0);
2856 static void socket_set_nodelay(int fd)
2858 int val = 1;
2859 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2862 static void tcp_chr_accept(void *opaque)
2864 CharDriverState *chr = opaque;
2865 TCPCharDriver *s = chr->opaque;
2866 struct sockaddr_in saddr;
2867 #ifndef _WIN32
2868 struct sockaddr_un uaddr;
2869 #endif
2870 struct sockaddr *addr;
2871 socklen_t len;
2872 int fd;
2874 for(;;) {
2875 #ifndef _WIN32
2876 if (s->is_unix) {
2877 len = sizeof(uaddr);
2878 addr = (struct sockaddr *)&uaddr;
2879 } else
2880 #endif
2882 len = sizeof(saddr);
2883 addr = (struct sockaddr *)&saddr;
2885 fd = accept(s->listen_fd, addr, &len);
2886 if (fd < 0 && errno != EINTR) {
2887 return;
2888 } else if (fd >= 0) {
2889 if (s->do_telnetopt)
2890 tcp_chr_telnet_init(fd);
2891 break;
2894 socket_set_nonblock(fd);
2895 if (s->do_nodelay)
2896 socket_set_nodelay(fd);
2897 s->fd = fd;
2898 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2899 tcp_chr_connect(chr);
2902 static void tcp_chr_close(CharDriverState *chr)
2904 TCPCharDriver *s = chr->opaque;
2905 if (s->fd >= 0)
2906 closesocket(s->fd);
2907 if (s->listen_fd >= 0)
2908 closesocket(s->listen_fd);
2909 qemu_free(s);
2912 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2913 int is_telnet,
2914 int is_unix)
2916 CharDriverState *chr = NULL;
2917 TCPCharDriver *s = NULL;
2918 int fd = -1, ret, err, val;
2919 int is_listen = 0;
2920 int is_waitconnect = 1;
2921 int do_nodelay = 0;
2922 const char *ptr;
2923 struct sockaddr_in saddr;
2924 #ifndef _WIN32
2925 struct sockaddr_un uaddr;
2926 #endif
2927 struct sockaddr *addr;
2928 socklen_t addrlen;
2930 #ifndef _WIN32
2931 if (is_unix) {
2932 addr = (struct sockaddr *)&uaddr;
2933 addrlen = sizeof(uaddr);
2934 if (parse_unix_path(&uaddr, host_str) < 0)
2935 goto fail;
2936 } else
2937 #endif
2939 addr = (struct sockaddr *)&saddr;
2940 addrlen = sizeof(saddr);
2941 if (parse_host_port(&saddr, host_str) < 0)
2942 goto fail;
2945 ptr = host_str;
2946 while((ptr = strchr(ptr,','))) {
2947 ptr++;
2948 if (!strncmp(ptr,"server",6)) {
2949 is_listen = 1;
2950 } else if (!strncmp(ptr,"nowait",6)) {
2951 is_waitconnect = 0;
2952 } else if (!strncmp(ptr,"nodelay",6)) {
2953 do_nodelay = 1;
2954 } else {
2955 printf("Unknown option: %s\n", ptr);
2956 goto fail;
2959 if (!is_listen)
2960 is_waitconnect = 0;
2962 chr = qemu_mallocz(sizeof(CharDriverState));
2963 if (!chr)
2964 goto fail;
2965 s = qemu_mallocz(sizeof(TCPCharDriver));
2966 if (!s)
2967 goto fail;
2969 #ifndef _WIN32
2970 if (is_unix)
2971 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2972 else
2973 #endif
2974 fd = socket(PF_INET, SOCK_STREAM, 0);
2976 if (fd < 0)
2977 goto fail;
2979 if (!is_waitconnect)
2980 socket_set_nonblock(fd);
2982 s->connected = 0;
2983 s->fd = -1;
2984 s->listen_fd = -1;
2985 s->is_unix = is_unix;
2986 s->do_nodelay = do_nodelay && !is_unix;
2988 chr->opaque = s;
2989 chr->chr_write = tcp_chr_write;
2990 chr->chr_close = tcp_chr_close;
2992 if (is_listen) {
2993 /* allow fast reuse */
2994 #ifndef _WIN32
2995 if (is_unix) {
2996 char path[109];
2997 strncpy(path, uaddr.sun_path, 108);
2998 path[108] = 0;
2999 unlink(path);
3000 } else
3001 #endif
3003 val = 1;
3004 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3007 ret = bind(fd, addr, addrlen);
3008 if (ret < 0)
3009 goto fail;
3011 ret = listen(fd, 0);
3012 if (ret < 0)
3013 goto fail;
3015 s->listen_fd = fd;
3016 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3017 if (is_telnet)
3018 s->do_telnetopt = 1;
3019 } else {
3020 for(;;) {
3021 ret = connect(fd, addr, addrlen);
3022 if (ret < 0) {
3023 err = socket_error();
3024 if (err == EINTR || err == EWOULDBLOCK) {
3025 } else if (err == EINPROGRESS) {
3026 break;
3027 #ifdef _WIN32
3028 } else if (err == WSAEALREADY) {
3029 break;
3030 #endif
3031 } else {
3032 goto fail;
3034 } else {
3035 s->connected = 1;
3036 break;
3039 s->fd = fd;
3040 socket_set_nodelay(fd);
3041 if (s->connected)
3042 tcp_chr_connect(chr);
3043 else
3044 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3047 if (is_listen && is_waitconnect) {
3048 printf("QEMU waiting for connection on: %s\n", host_str);
3049 tcp_chr_accept(chr);
3050 socket_set_nonblock(s->listen_fd);
3053 return chr;
3054 fail:
3055 if (fd >= 0)
3056 closesocket(fd);
3057 qemu_free(s);
3058 qemu_free(chr);
3059 return NULL;
3062 CharDriverState *qemu_chr_open(const char *filename)
3064 const char *p;
3066 if (!strcmp(filename, "vc")) {
3067 return text_console_init(&display_state, 0);
3068 } else if (strstart(filename, "vc:", &p)) {
3069 return text_console_init(&display_state, p);
3070 } else if (!strcmp(filename, "null")) {
3071 return qemu_chr_open_null();
3072 } else
3073 if (strstart(filename, "tcp:", &p)) {
3074 return qemu_chr_open_tcp(p, 0, 0);
3075 } else
3076 if (strstart(filename, "telnet:", &p)) {
3077 return qemu_chr_open_tcp(p, 1, 0);
3078 } else
3079 if (strstart(filename, "udp:", &p)) {
3080 return qemu_chr_open_udp(p);
3081 } else
3082 if (strstart(filename, "mon:", &p)) {
3083 CharDriverState *drv = qemu_chr_open(p);
3084 if (drv) {
3085 drv = qemu_chr_open_mux(drv);
3086 monitor_init(drv, !nographic);
3087 return drv;
3089 printf("Unable to open driver: %s\n", p);
3090 return 0;
3091 } else
3092 #ifndef _WIN32
3093 if (strstart(filename, "unix:", &p)) {
3094 return qemu_chr_open_tcp(p, 0, 1);
3095 } else if (strstart(filename, "file:", &p)) {
3096 return qemu_chr_open_file_out(p);
3097 } else if (strstart(filename, "pipe:", &p)) {
3098 return qemu_chr_open_pipe(p);
3099 } else if (!strcmp(filename, "pty")) {
3100 return qemu_chr_open_pty();
3101 } else if (!strcmp(filename, "stdio")) {
3102 return qemu_chr_open_stdio();
3103 } else
3104 #if defined(__linux__)
3105 if (strstart(filename, "/dev/parport", NULL)) {
3106 return qemu_chr_open_pp(filename);
3107 } else
3108 #endif
3109 #if defined(__linux__) || defined(__sun__)
3110 if (strstart(filename, "/dev/", NULL)) {
3111 return qemu_chr_open_tty(filename);
3112 } else
3113 #endif
3114 #else /* !_WIN32 */
3115 if (strstart(filename, "COM", NULL)) {
3116 return qemu_chr_open_win(filename);
3117 } else
3118 if (strstart(filename, "pipe:", &p)) {
3119 return qemu_chr_open_win_pipe(p);
3120 } else
3121 if (strstart(filename, "con:", NULL)) {
3122 return qemu_chr_open_win_con(filename);
3123 } else
3124 if (strstart(filename, "file:", &p)) {
3125 return qemu_chr_open_win_file_out(p);
3127 #endif
3129 return NULL;
3133 void qemu_chr_close(CharDriverState *chr)
3135 if (chr->chr_close)
3136 chr->chr_close(chr);
3139 /***********************************************************/
3140 /* network device redirectors */
3142 void hex_dump(FILE *f, const uint8_t *buf, int size)
3144 int len, i, j, c;
3146 for(i=0;i<size;i+=16) {
3147 len = size - i;
3148 if (len > 16)
3149 len = 16;
3150 fprintf(f, "%08x ", i);
3151 for(j=0;j<16;j++) {
3152 if (j < len)
3153 fprintf(f, " %02x", buf[i+j]);
3154 else
3155 fprintf(f, " ");
3157 fprintf(f, " ");
3158 for(j=0;j<len;j++) {
3159 c = buf[i+j];
3160 if (c < ' ' || c > '~')
3161 c = '.';
3162 fprintf(f, "%c", c);
3164 fprintf(f, "\n");
3168 static int parse_macaddr(uint8_t *macaddr, const char *p)
3170 int i;
3171 for(i = 0; i < 6; i++) {
3172 macaddr[i] = strtol(p, (char **)&p, 16);
3173 if (i == 5) {
3174 if (*p != '\0')
3175 return -1;
3176 } else {
3177 if (*p != ':')
3178 return -1;
3179 p++;
3182 return 0;
3185 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3187 const char *p, *p1;
3188 int len;
3189 p = *pp;
3190 p1 = strchr(p, sep);
3191 if (!p1)
3192 return -1;
3193 len = p1 - p;
3194 p1++;
3195 if (buf_size > 0) {
3196 if (len > buf_size - 1)
3197 len = buf_size - 1;
3198 memcpy(buf, p, len);
3199 buf[len] = '\0';
3201 *pp = p1;
3202 return 0;
3205 int parse_host_src_port(struct sockaddr_in *haddr,
3206 struct sockaddr_in *saddr,
3207 const char *input_str)
3209 char *str = strdup(input_str);
3210 char *host_str = str;
3211 char *src_str;
3212 char *ptr;
3215 * Chop off any extra arguments at the end of the string which
3216 * would start with a comma, then fill in the src port information
3217 * if it was provided else use the "any address" and "any port".
3219 if ((ptr = strchr(str,',')))
3220 *ptr = '\0';
3222 if ((src_str = strchr(input_str,'@'))) {
3223 *src_str = '\0';
3224 src_str++;
3227 if (parse_host_port(haddr, host_str) < 0)
3228 goto fail;
3230 if (!src_str || *src_str == '\0')
3231 src_str = ":0";
3233 if (parse_host_port(saddr, src_str) < 0)
3234 goto fail;
3236 free(str);
3237 return(0);
3239 fail:
3240 free(str);
3241 return -1;
3244 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3246 char buf[512];
3247 struct hostent *he;
3248 const char *p, *r;
3249 int port;
3251 p = str;
3252 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3253 return -1;
3254 saddr->sin_family = AF_INET;
3255 if (buf[0] == '\0') {
3256 saddr->sin_addr.s_addr = 0;
3257 } else {
3258 if (isdigit(buf[0])) {
3259 if (!inet_aton(buf, &saddr->sin_addr))
3260 return -1;
3261 } else {
3262 if ((he = gethostbyname(buf)) == NULL)
3263 return - 1;
3264 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3267 port = strtol(p, (char **)&r, 0);
3268 if (r == p)
3269 return -1;
3270 saddr->sin_port = htons(port);
3271 return 0;
3274 #ifndef _WIN32
3275 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3277 const char *p;
3278 int len;
3280 len = MIN(108, strlen(str));
3281 p = strchr(str, ',');
3282 if (p)
3283 len = MIN(len, p - str);
3285 memset(uaddr, 0, sizeof(*uaddr));
3287 uaddr->sun_family = AF_UNIX;
3288 memcpy(uaddr->sun_path, str, len);
3290 return 0;
3292 #endif
3294 /* find or alloc a new VLAN */
3295 VLANState *qemu_find_vlan(int id)
3297 VLANState **pvlan, *vlan;
3298 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3299 if (vlan->id == id)
3300 return vlan;
3302 vlan = qemu_mallocz(sizeof(VLANState));
3303 if (!vlan)
3304 return NULL;
3305 vlan->id = id;
3306 vlan->next = NULL;
3307 pvlan = &first_vlan;
3308 while (*pvlan != NULL)
3309 pvlan = &(*pvlan)->next;
3310 *pvlan = vlan;
3311 return vlan;
3314 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3315 IOReadHandler *fd_read,
3316 IOCanRWHandler *fd_can_read,
3317 void *opaque)
3319 VLANClientState *vc, **pvc;
3320 vc = qemu_mallocz(sizeof(VLANClientState));
3321 if (!vc)
3322 return NULL;
3323 vc->fd_read = fd_read;
3324 vc->fd_can_read = fd_can_read;
3325 vc->opaque = opaque;
3326 vc->vlan = vlan;
3328 vc->next = NULL;
3329 pvc = &vlan->first_client;
3330 while (*pvc != NULL)
3331 pvc = &(*pvc)->next;
3332 *pvc = vc;
3333 return vc;
3336 int qemu_can_send_packet(VLANClientState *vc1)
3338 VLANState *vlan = vc1->vlan;
3339 VLANClientState *vc;
3341 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3342 if (vc != vc1) {
3343 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3344 return 1;
3347 return 0;
3350 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3352 VLANState *vlan = vc1->vlan;
3353 VLANClientState *vc;
3355 #if 0
3356 printf("vlan %d send:\n", vlan->id);
3357 hex_dump(stdout, buf, size);
3358 #endif
3359 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3360 if (vc != vc1) {
3361 vc->fd_read(vc->opaque, buf, size);
3366 #if defined(CONFIG_SLIRP)
3368 /* slirp network adapter */
3370 static int slirp_inited;
3371 static VLANClientState *slirp_vc;
3373 int slirp_can_output(void)
3375 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3378 void slirp_output(const uint8_t *pkt, int pkt_len)
3380 #if 0
3381 printf("slirp output:\n");
3382 hex_dump(stdout, pkt, pkt_len);
3383 #endif
3384 if (!slirp_vc)
3385 return;
3386 qemu_send_packet(slirp_vc, pkt, pkt_len);
3389 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3391 #if 0
3392 printf("slirp input:\n");
3393 hex_dump(stdout, buf, size);
3394 #endif
3395 slirp_input(buf, size);
3398 static int net_slirp_init(VLANState *vlan)
3400 if (!slirp_inited) {
3401 slirp_inited = 1;
3402 slirp_init();
3404 slirp_vc = qemu_new_vlan_client(vlan,
3405 slirp_receive, NULL, NULL);
3406 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3407 return 0;
3410 static void net_slirp_redir(const char *redir_str)
3412 int is_udp;
3413 char buf[256], *r;
3414 const char *p;
3415 struct in_addr guest_addr;
3416 int host_port, guest_port;
3418 if (!slirp_inited) {
3419 slirp_inited = 1;
3420 slirp_init();
3423 p = redir_str;
3424 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3425 goto fail;
3426 if (!strcmp(buf, "tcp")) {
3427 is_udp = 0;
3428 } else if (!strcmp(buf, "udp")) {
3429 is_udp = 1;
3430 } else {
3431 goto fail;
3434 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3435 goto fail;
3436 host_port = strtol(buf, &r, 0);
3437 if (r == buf)
3438 goto fail;
3440 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3441 goto fail;
3442 if (buf[0] == '\0') {
3443 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3445 if (!inet_aton(buf, &guest_addr))
3446 goto fail;
3448 guest_port = strtol(p, &r, 0);
3449 if (r == p)
3450 goto fail;
3452 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3453 fprintf(stderr, "qemu: could not set up redirection\n");
3454 exit(1);
3456 return;
3457 fail:
3458 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3459 exit(1);
3462 #ifndef _WIN32
3464 char smb_dir[1024];
3466 static void smb_exit(void)
3468 DIR *d;
3469 struct dirent *de;
3470 char filename[1024];
3472 /* erase all the files in the directory */
3473 d = opendir(smb_dir);
3474 for(;;) {
3475 de = readdir(d);
3476 if (!de)
3477 break;
3478 if (strcmp(de->d_name, ".") != 0 &&
3479 strcmp(de->d_name, "..") != 0) {
3480 snprintf(filename, sizeof(filename), "%s/%s",
3481 smb_dir, de->d_name);
3482 unlink(filename);
3485 closedir(d);
3486 rmdir(smb_dir);
3489 /* automatic user mode samba server configuration */
3490 void net_slirp_smb(const char *exported_dir)
3492 char smb_conf[1024];
3493 char smb_cmdline[1024];
3494 FILE *f;
3496 if (!slirp_inited) {
3497 slirp_inited = 1;
3498 slirp_init();
3501 /* XXX: better tmp dir construction */
3502 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3503 if (mkdir(smb_dir, 0700) < 0) {
3504 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3505 exit(1);
3507 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3509 f = fopen(smb_conf, "w");
3510 if (!f) {
3511 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3512 exit(1);
3514 fprintf(f,
3515 "[global]\n"
3516 "private dir=%s\n"
3517 "smb ports=0\n"
3518 "socket address=127.0.0.1\n"
3519 "pid directory=%s\n"
3520 "lock directory=%s\n"
3521 "log file=%s/log.smbd\n"
3522 "smb passwd file=%s/smbpasswd\n"
3523 "security = share\n"
3524 "[qemu]\n"
3525 "path=%s\n"
3526 "read only=no\n"
3527 "guest ok=yes\n",
3528 smb_dir,
3529 smb_dir,
3530 smb_dir,
3531 smb_dir,
3532 smb_dir,
3533 exported_dir
3535 fclose(f);
3536 atexit(smb_exit);
3538 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3539 SMBD_COMMAND, smb_conf);
3541 slirp_add_exec(0, smb_cmdline, 4, 139);
3544 #endif /* !defined(_WIN32) */
3546 #endif /* CONFIG_SLIRP */
3548 #if !defined(_WIN32)
3550 typedef struct TAPState {
3551 VLANClientState *vc;
3552 int fd;
3553 } TAPState;
3555 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3557 TAPState *s = opaque;
3558 int ret;
3559 for(;;) {
3560 ret = write(s->fd, buf, size);
3561 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3562 } else {
3563 break;
3568 static void tap_send(void *opaque)
3570 TAPState *s = opaque;
3571 uint8_t buf[4096];
3572 int size;
3574 #ifdef __sun__
3575 struct strbuf sbuf;
3576 int f = 0;
3577 sbuf.maxlen = sizeof(buf);
3578 sbuf.buf = buf;
3579 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3580 #else
3581 size = read(s->fd, buf, sizeof(buf));
3582 #endif
3583 if (size > 0) {
3584 qemu_send_packet(s->vc, buf, size);
3588 /* fd support */
3590 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3592 TAPState *s;
3594 s = qemu_mallocz(sizeof(TAPState));
3595 if (!s)
3596 return NULL;
3597 s->fd = fd;
3598 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3599 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3600 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3601 return s;
3604 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3605 static int tap_open(char *ifname, int ifname_size)
3607 int fd;
3608 char *dev;
3609 struct stat s;
3611 TFR(fd = open("/dev/tap", O_RDWR));
3612 if (fd < 0) {
3613 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3614 return -1;
3617 fstat(fd, &s);
3618 dev = devname(s.st_rdev, S_IFCHR);
3619 pstrcpy(ifname, ifname_size, dev);
3621 fcntl(fd, F_SETFL, O_NONBLOCK);
3622 return fd;
3624 #elif defined(__sun__)
3625 #define TUNNEWPPA (('T'<<16) | 0x0001)
3627 * Allocate TAP device, returns opened fd.
3628 * Stores dev name in the first arg(must be large enough).
3630 int tap_alloc(char *dev)
3632 int tap_fd, if_fd, ppa = -1;
3633 static int ip_fd = 0;
3634 char *ptr;
3636 static int arp_fd = 0;
3637 int ip_muxid, arp_muxid;
3638 struct strioctl strioc_if, strioc_ppa;
3639 int link_type = I_PLINK;;
3640 struct lifreq ifr;
3641 char actual_name[32] = "";
3643 memset(&ifr, 0x0, sizeof(ifr));
3645 if( *dev ){
3646 ptr = dev;
3647 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3648 ppa = atoi(ptr);
3651 /* Check if IP device was opened */
3652 if( ip_fd )
3653 close(ip_fd);
3655 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3656 if (ip_fd < 0) {
3657 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3658 return -1;
3661 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3662 if (tap_fd < 0) {
3663 syslog(LOG_ERR, "Can't open /dev/tap");
3664 return -1;
3667 /* Assign a new PPA and get its unit number. */
3668 strioc_ppa.ic_cmd = TUNNEWPPA;
3669 strioc_ppa.ic_timout = 0;
3670 strioc_ppa.ic_len = sizeof(ppa);
3671 strioc_ppa.ic_dp = (char *)&ppa;
3672 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3673 syslog (LOG_ERR, "Can't assign new interface");
3675 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3676 if (if_fd < 0) {
3677 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3678 return -1;
3680 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3681 syslog(LOG_ERR, "Can't push IP module");
3682 return -1;
3685 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3686 syslog(LOG_ERR, "Can't get flags\n");
3688 snprintf (actual_name, 32, "tap%d", ppa);
3689 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3691 ifr.lifr_ppa = ppa;
3692 /* Assign ppa according to the unit number returned by tun device */
3694 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3695 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3696 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3697 syslog (LOG_ERR, "Can't get flags\n");
3698 /* Push arp module to if_fd */
3699 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3700 syslog (LOG_ERR, "Can't push ARP module (2)");
3702 /* Push arp module to ip_fd */
3703 if (ioctl (ip_fd, I_POP, NULL) < 0)
3704 syslog (LOG_ERR, "I_POP failed\n");
3705 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3706 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3707 /* Open arp_fd */
3708 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3709 if (arp_fd < 0)
3710 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3712 /* Set ifname to arp */
3713 strioc_if.ic_cmd = SIOCSLIFNAME;
3714 strioc_if.ic_timout = 0;
3715 strioc_if.ic_len = sizeof(ifr);
3716 strioc_if.ic_dp = (char *)&ifr;
3717 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3718 syslog (LOG_ERR, "Can't set ifname to arp\n");
3721 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3722 syslog(LOG_ERR, "Can't link TAP device to IP");
3723 return -1;
3726 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3727 syslog (LOG_ERR, "Can't link TAP device to ARP");
3729 close (if_fd);
3731 memset(&ifr, 0x0, sizeof(ifr));
3732 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3733 ifr.lifr_ip_muxid = ip_muxid;
3734 ifr.lifr_arp_muxid = arp_muxid;
3736 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3738 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3739 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3740 syslog (LOG_ERR, "Can't set multiplexor id");
3743 sprintf(dev, "tap%d", ppa);
3744 return tap_fd;
3747 static int tap_open(char *ifname, int ifname_size)
3749 char dev[10]="";
3750 int fd;
3751 if( (fd = tap_alloc(dev)) < 0 ){
3752 fprintf(stderr, "Cannot allocate TAP device\n");
3753 return -1;
3755 pstrcpy(ifname, ifname_size, dev);
3756 fcntl(fd, F_SETFL, O_NONBLOCK);
3757 return fd;
3759 #else
3760 static int tap_open(char *ifname, int ifname_size)
3762 struct ifreq ifr;
3763 int fd, ret;
3765 TFR(fd = open("/dev/net/tun", O_RDWR));
3766 if (fd < 0) {
3767 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3768 return -1;
3770 memset(&ifr, 0, sizeof(ifr));
3771 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3772 if (ifname[0] != '\0')
3773 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3774 else
3775 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3776 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3777 if (ret != 0) {
3778 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3779 close(fd);
3780 return -1;
3782 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3783 fcntl(fd, F_SETFL, O_NONBLOCK);
3784 return fd;
3786 #endif
3788 static int net_tap_init(VLANState *vlan, const char *ifname1,
3789 const char *setup_script)
3791 TAPState *s;
3792 int pid, status, fd;
3793 char *args[3];
3794 char **parg;
3795 char ifname[128];
3797 if (ifname1 != NULL)
3798 pstrcpy(ifname, sizeof(ifname), ifname1);
3799 else
3800 ifname[0] = '\0';
3801 TFR(fd = tap_open(ifname, sizeof(ifname)));
3802 if (fd < 0)
3803 return -1;
3805 if (!setup_script || !strcmp(setup_script, "no"))
3806 setup_script = "";
3807 if (setup_script[0] != '\0') {
3808 /* try to launch network init script */
3809 pid = fork();
3810 if (pid >= 0) {
3811 if (pid == 0) {
3812 int open_max = sysconf (_SC_OPEN_MAX), i;
3813 for (i = 0; i < open_max; i++)
3814 if (i != STDIN_FILENO &&
3815 i != STDOUT_FILENO &&
3816 i != STDERR_FILENO &&
3817 i != fd)
3818 close(i);
3820 parg = args;
3821 *parg++ = (char *)setup_script;
3822 *parg++ = ifname;
3823 *parg++ = NULL;
3824 execv(setup_script, args);
3825 _exit(1);
3827 while (waitpid(pid, &status, 0) != pid);
3828 if (!WIFEXITED(status) ||
3829 WEXITSTATUS(status) != 0) {
3830 fprintf(stderr, "%s: could not launch network script\n",
3831 setup_script);
3832 return -1;
3836 s = net_tap_fd_init(vlan, fd);
3837 if (!s)
3838 return -1;
3839 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3840 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3841 return 0;
3844 #endif /* !_WIN32 */
3846 /* network connection */
3847 typedef struct NetSocketState {
3848 VLANClientState *vc;
3849 int fd;
3850 int state; /* 0 = getting length, 1 = getting data */
3851 int index;
3852 int packet_len;
3853 uint8_t buf[4096];
3854 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3855 } NetSocketState;
3857 typedef struct NetSocketListenState {
3858 VLANState *vlan;
3859 int fd;
3860 } NetSocketListenState;
3862 /* XXX: we consider we can send the whole packet without blocking */
3863 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3865 NetSocketState *s = opaque;
3866 uint32_t len;
3867 len = htonl(size);
3869 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3870 send_all(s->fd, buf, size);
3873 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3875 NetSocketState *s = opaque;
3876 sendto(s->fd, buf, size, 0,
3877 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3880 static void net_socket_send(void *opaque)
3882 NetSocketState *s = opaque;
3883 int l, size, err;
3884 uint8_t buf1[4096];
3885 const uint8_t *buf;
3887 size = recv(s->fd, buf1, sizeof(buf1), 0);
3888 if (size < 0) {
3889 err = socket_error();
3890 if (err != EWOULDBLOCK)
3891 goto eoc;
3892 } else if (size == 0) {
3893 /* end of connection */
3894 eoc:
3895 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3896 closesocket(s->fd);
3897 return;
3899 buf = buf1;
3900 while (size > 0) {
3901 /* reassemble a packet from the network */
3902 switch(s->state) {
3903 case 0:
3904 l = 4 - s->index;
3905 if (l > size)
3906 l = size;
3907 memcpy(s->buf + s->index, buf, l);
3908 buf += l;
3909 size -= l;
3910 s->index += l;
3911 if (s->index == 4) {
3912 /* got length */
3913 s->packet_len = ntohl(*(uint32_t *)s->buf);
3914 s->index = 0;
3915 s->state = 1;
3917 break;
3918 case 1:
3919 l = s->packet_len - s->index;
3920 if (l > size)
3921 l = size;
3922 memcpy(s->buf + s->index, buf, l);
3923 s->index += l;
3924 buf += l;
3925 size -= l;
3926 if (s->index >= s->packet_len) {
3927 qemu_send_packet(s->vc, s->buf, s->packet_len);
3928 s->index = 0;
3929 s->state = 0;
3931 break;
3936 static void net_socket_send_dgram(void *opaque)
3938 NetSocketState *s = opaque;
3939 int size;
3941 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3942 if (size < 0)
3943 return;
3944 if (size == 0) {
3945 /* end of connection */
3946 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3947 return;
3949 qemu_send_packet(s->vc, s->buf, size);
3952 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3954 struct ip_mreq imr;
3955 int fd;
3956 int val, ret;
3957 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3958 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3959 inet_ntoa(mcastaddr->sin_addr),
3960 (int)ntohl(mcastaddr->sin_addr.s_addr));
3961 return -1;
3964 fd = socket(PF_INET, SOCK_DGRAM, 0);
3965 if (fd < 0) {
3966 perror("socket(PF_INET, SOCK_DGRAM)");
3967 return -1;
3970 val = 1;
3971 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3972 (const char *)&val, sizeof(val));
3973 if (ret < 0) {
3974 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3975 goto fail;
3978 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3979 if (ret < 0) {
3980 perror("bind");
3981 goto fail;
3984 /* Add host to multicast group */
3985 imr.imr_multiaddr = mcastaddr->sin_addr;
3986 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3988 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3989 (const char *)&imr, sizeof(struct ip_mreq));
3990 if (ret < 0) {
3991 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3992 goto fail;
3995 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3996 val = 1;
3997 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3998 (const char *)&val, sizeof(val));
3999 if (ret < 0) {
4000 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4001 goto fail;
4004 socket_set_nonblock(fd);
4005 return fd;
4006 fail:
4007 if (fd >= 0)
4008 closesocket(fd);
4009 return -1;
4012 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4013 int is_connected)
4015 struct sockaddr_in saddr;
4016 int newfd;
4017 socklen_t saddr_len;
4018 NetSocketState *s;
4020 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4021 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4022 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4025 if (is_connected) {
4026 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4027 /* must be bound */
4028 if (saddr.sin_addr.s_addr==0) {
4029 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4030 fd);
4031 return NULL;
4033 /* clone dgram socket */
4034 newfd = net_socket_mcast_create(&saddr);
4035 if (newfd < 0) {
4036 /* error already reported by net_socket_mcast_create() */
4037 close(fd);
4038 return NULL;
4040 /* clone newfd to fd, close newfd */
4041 dup2(newfd, fd);
4042 close(newfd);
4044 } else {
4045 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4046 fd, strerror(errno));
4047 return NULL;
4051 s = qemu_mallocz(sizeof(NetSocketState));
4052 if (!s)
4053 return NULL;
4054 s->fd = fd;
4056 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4057 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4059 /* mcast: save bound address as dst */
4060 if (is_connected) s->dgram_dst=saddr;
4062 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4063 "socket: fd=%d (%s mcast=%s:%d)",
4064 fd, is_connected? "cloned" : "",
4065 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4066 return s;
4069 static void net_socket_connect(void *opaque)
4071 NetSocketState *s = opaque;
4072 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4075 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4076 int is_connected)
4078 NetSocketState *s;
4079 s = qemu_mallocz(sizeof(NetSocketState));
4080 if (!s)
4081 return NULL;
4082 s->fd = fd;
4083 s->vc = qemu_new_vlan_client(vlan,
4084 net_socket_receive, NULL, s);
4085 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4086 "socket: fd=%d", fd);
4087 if (is_connected) {
4088 net_socket_connect(s);
4089 } else {
4090 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4092 return s;
4095 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4096 int is_connected)
4098 int so_type=-1, optlen=sizeof(so_type);
4100 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4101 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4102 return NULL;
4104 switch(so_type) {
4105 case SOCK_DGRAM:
4106 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4107 case SOCK_STREAM:
4108 return net_socket_fd_init_stream(vlan, fd, is_connected);
4109 default:
4110 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4111 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4112 return net_socket_fd_init_stream(vlan, fd, is_connected);
4114 return NULL;
4117 static void net_socket_accept(void *opaque)
4119 NetSocketListenState *s = opaque;
4120 NetSocketState *s1;
4121 struct sockaddr_in saddr;
4122 socklen_t len;
4123 int fd;
4125 for(;;) {
4126 len = sizeof(saddr);
4127 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4128 if (fd < 0 && errno != EINTR) {
4129 return;
4130 } else if (fd >= 0) {
4131 break;
4134 s1 = net_socket_fd_init(s->vlan, fd, 1);
4135 if (!s1) {
4136 closesocket(fd);
4137 } else {
4138 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4139 "socket: connection from %s:%d",
4140 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4144 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4146 NetSocketListenState *s;
4147 int fd, val, ret;
4148 struct sockaddr_in saddr;
4150 if (parse_host_port(&saddr, host_str) < 0)
4151 return -1;
4153 s = qemu_mallocz(sizeof(NetSocketListenState));
4154 if (!s)
4155 return -1;
4157 fd = socket(PF_INET, SOCK_STREAM, 0);
4158 if (fd < 0) {
4159 perror("socket");
4160 return -1;
4162 socket_set_nonblock(fd);
4164 /* allow fast reuse */
4165 val = 1;
4166 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4168 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4169 if (ret < 0) {
4170 perror("bind");
4171 return -1;
4173 ret = listen(fd, 0);
4174 if (ret < 0) {
4175 perror("listen");
4176 return -1;
4178 s->vlan = vlan;
4179 s->fd = fd;
4180 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4181 return 0;
4184 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4186 NetSocketState *s;
4187 int fd, connected, ret, err;
4188 struct sockaddr_in saddr;
4190 if (parse_host_port(&saddr, host_str) < 0)
4191 return -1;
4193 fd = socket(PF_INET, SOCK_STREAM, 0);
4194 if (fd < 0) {
4195 perror("socket");
4196 return -1;
4198 socket_set_nonblock(fd);
4200 connected = 0;
4201 for(;;) {
4202 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4203 if (ret < 0) {
4204 err = socket_error();
4205 if (err == EINTR || err == EWOULDBLOCK) {
4206 } else if (err == EINPROGRESS) {
4207 break;
4208 #ifdef _WIN32
4209 } else if (err == WSAEALREADY) {
4210 break;
4211 #endif
4212 } else {
4213 perror("connect");
4214 closesocket(fd);
4215 return -1;
4217 } else {
4218 connected = 1;
4219 break;
4222 s = net_socket_fd_init(vlan, fd, connected);
4223 if (!s)
4224 return -1;
4225 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4226 "socket: connect to %s:%d",
4227 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4228 return 0;
4231 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4233 NetSocketState *s;
4234 int fd;
4235 struct sockaddr_in saddr;
4237 if (parse_host_port(&saddr, host_str) < 0)
4238 return -1;
4241 fd = net_socket_mcast_create(&saddr);
4242 if (fd < 0)
4243 return -1;
4245 s = net_socket_fd_init(vlan, fd, 0);
4246 if (!s)
4247 return -1;
4249 s->dgram_dst = saddr;
4251 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4252 "socket: mcast=%s:%d",
4253 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4254 return 0;
4258 static int get_param_value(char *buf, int buf_size,
4259 const char *tag, const char *str)
4261 const char *p;
4262 char *q;
4263 char option[128];
4265 p = str;
4266 for(;;) {
4267 q = option;
4268 while (*p != '\0' && *p != '=') {
4269 if ((q - option) < sizeof(option) - 1)
4270 *q++ = *p;
4271 p++;
4273 *q = '\0';
4274 if (*p != '=')
4275 break;
4276 p++;
4277 if (!strcmp(tag, option)) {
4278 q = buf;
4279 while (*p != '\0' && *p != ',') {
4280 if ((q - buf) < buf_size - 1)
4281 *q++ = *p;
4282 p++;
4284 *q = '\0';
4285 return q - buf;
4286 } else {
4287 while (*p != '\0' && *p != ',') {
4288 p++;
4291 if (*p != ',')
4292 break;
4293 p++;
4295 return 0;
4298 static int net_client_init(const char *str)
4300 const char *p;
4301 char *q;
4302 char device[64];
4303 char buf[1024];
4304 int vlan_id, ret;
4305 VLANState *vlan;
4307 p = str;
4308 q = device;
4309 while (*p != '\0' && *p != ',') {
4310 if ((q - device) < sizeof(device) - 1)
4311 *q++ = *p;
4312 p++;
4314 *q = '\0';
4315 if (*p == ',')
4316 p++;
4317 vlan_id = 0;
4318 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4319 vlan_id = strtol(buf, NULL, 0);
4321 vlan = qemu_find_vlan(vlan_id);
4322 if (!vlan) {
4323 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4324 return -1;
4326 if (!strcmp(device, "nic")) {
4327 NICInfo *nd;
4328 uint8_t *macaddr;
4330 if (nb_nics >= MAX_NICS) {
4331 fprintf(stderr, "Too Many NICs\n");
4332 return -1;
4334 nd = &nd_table[nb_nics];
4335 macaddr = nd->macaddr;
4336 macaddr[0] = 0x52;
4337 macaddr[1] = 0x54;
4338 macaddr[2] = 0x00;
4339 macaddr[3] = 0x12;
4340 macaddr[4] = 0x34;
4341 macaddr[5] = 0x56 + nb_nics;
4343 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4344 if (parse_macaddr(macaddr, buf) < 0) {
4345 fprintf(stderr, "invalid syntax for ethernet address\n");
4346 return -1;
4349 if (get_param_value(buf, sizeof(buf), "model", p)) {
4350 nd->model = strdup(buf);
4352 nd->vlan = vlan;
4353 nb_nics++;
4354 vlan->nb_guest_devs++;
4355 ret = 0;
4356 } else
4357 if (!strcmp(device, "none")) {
4358 /* does nothing. It is needed to signal that no network cards
4359 are wanted */
4360 ret = 0;
4361 } else
4362 #ifdef CONFIG_SLIRP
4363 if (!strcmp(device, "user")) {
4364 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4365 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4367 vlan->nb_host_devs++;
4368 ret = net_slirp_init(vlan);
4369 } else
4370 #endif
4371 #ifdef _WIN32
4372 if (!strcmp(device, "tap")) {
4373 char ifname[64];
4374 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4375 fprintf(stderr, "tap: no interface name\n");
4376 return -1;
4378 vlan->nb_host_devs++;
4379 ret = tap_win32_init(vlan, ifname);
4380 } else
4381 #else
4382 if (!strcmp(device, "tap")) {
4383 char ifname[64];
4384 char setup_script[1024];
4385 int fd;
4386 vlan->nb_host_devs++;
4387 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4388 fd = strtol(buf, NULL, 0);
4389 ret = -1;
4390 if (net_tap_fd_init(vlan, fd))
4391 ret = 0;
4392 } else {
4393 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4394 ifname[0] = '\0';
4396 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4397 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4399 ret = net_tap_init(vlan, ifname, setup_script);
4401 } else
4402 #endif
4403 if (!strcmp(device, "socket")) {
4404 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4405 int fd;
4406 fd = strtol(buf, NULL, 0);
4407 ret = -1;
4408 if (net_socket_fd_init(vlan, fd, 1))
4409 ret = 0;
4410 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4411 ret = net_socket_listen_init(vlan, buf);
4412 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4413 ret = net_socket_connect_init(vlan, buf);
4414 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4415 ret = net_socket_mcast_init(vlan, buf);
4416 } else {
4417 fprintf(stderr, "Unknown socket options: %s\n", p);
4418 return -1;
4420 vlan->nb_host_devs++;
4421 } else
4423 fprintf(stderr, "Unknown network device: %s\n", device);
4424 return -1;
4426 if (ret < 0) {
4427 fprintf(stderr, "Could not initialize device '%s'\n", device);
4430 return ret;
4433 void do_info_network(void)
4435 VLANState *vlan;
4436 VLANClientState *vc;
4438 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4439 term_printf("VLAN %d devices:\n", vlan->id);
4440 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4441 term_printf(" %s\n", vc->info_str);
4445 /***********************************************************/
4446 /* USB devices */
4448 static USBPort *used_usb_ports;
4449 static USBPort *free_usb_ports;
4451 /* ??? Maybe change this to register a hub to keep track of the topology. */
4452 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4453 usb_attachfn attach)
4455 port->opaque = opaque;
4456 port->index = index;
4457 port->attach = attach;
4458 port->next = free_usb_ports;
4459 free_usb_ports = port;
4462 static int usb_device_add(const char *devname)
4464 const char *p;
4465 USBDevice *dev;
4466 USBPort *port;
4468 if (!free_usb_ports)
4469 return -1;
4471 if (strstart(devname, "host:", &p)) {
4472 dev = usb_host_device_open(p);
4473 } else if (!strcmp(devname, "mouse")) {
4474 dev = usb_mouse_init();
4475 } else if (!strcmp(devname, "tablet")) {
4476 dev = usb_tablet_init();
4477 } else if (!strcmp(devname, "keyboard")) {
4478 dev = usb_keyboard_init();
4479 } else if (strstart(devname, "disk:", &p)) {
4480 dev = usb_msd_init(p);
4481 } else if (!strcmp(devname, "wacom-tablet")) {
4482 dev = usb_wacom_init();
4483 } else {
4484 return -1;
4486 if (!dev)
4487 return -1;
4489 /* Find a USB port to add the device to. */
4490 port = free_usb_ports;
4491 if (!port->next) {
4492 USBDevice *hub;
4494 /* Create a new hub and chain it on. */
4495 free_usb_ports = NULL;
4496 port->next = used_usb_ports;
4497 used_usb_ports = port;
4499 hub = usb_hub_init(VM_USB_HUB_SIZE);
4500 usb_attach(port, hub);
4501 port = free_usb_ports;
4504 free_usb_ports = port->next;
4505 port->next = used_usb_ports;
4506 used_usb_ports = port;
4507 usb_attach(port, dev);
4508 return 0;
4511 static int usb_device_del(const char *devname)
4513 USBPort *port;
4514 USBPort **lastp;
4515 USBDevice *dev;
4516 int bus_num, addr;
4517 const char *p;
4519 if (!used_usb_ports)
4520 return -1;
4522 p = strchr(devname, '.');
4523 if (!p)
4524 return -1;
4525 bus_num = strtoul(devname, NULL, 0);
4526 addr = strtoul(p + 1, NULL, 0);
4527 if (bus_num != 0)
4528 return -1;
4530 lastp = &used_usb_ports;
4531 port = used_usb_ports;
4532 while (port && port->dev->addr != addr) {
4533 lastp = &port->next;
4534 port = port->next;
4537 if (!port)
4538 return -1;
4540 dev = port->dev;
4541 *lastp = port->next;
4542 usb_attach(port, NULL);
4543 dev->handle_destroy(dev);
4544 port->next = free_usb_ports;
4545 free_usb_ports = port;
4546 return 0;
4549 void do_usb_add(const char *devname)
4551 int ret;
4552 ret = usb_device_add(devname);
4553 if (ret < 0)
4554 term_printf("Could not add USB device '%s'\n", devname);
4557 void do_usb_del(const char *devname)
4559 int ret;
4560 ret = usb_device_del(devname);
4561 if (ret < 0)
4562 term_printf("Could not remove USB device '%s'\n", devname);
4565 void usb_info(void)
4567 USBDevice *dev;
4568 USBPort *port;
4569 const char *speed_str;
4571 if (!usb_enabled) {
4572 term_printf("USB support not enabled\n");
4573 return;
4576 for (port = used_usb_ports; port; port = port->next) {
4577 dev = port->dev;
4578 if (!dev)
4579 continue;
4580 switch(dev->speed) {
4581 case USB_SPEED_LOW:
4582 speed_str = "1.5";
4583 break;
4584 case USB_SPEED_FULL:
4585 speed_str = "12";
4586 break;
4587 case USB_SPEED_HIGH:
4588 speed_str = "480";
4589 break;
4590 default:
4591 speed_str = "?";
4592 break;
4594 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4595 0, dev->addr, speed_str, dev->devname);
4599 /***********************************************************/
4600 /* PCMCIA/Cardbus */
4602 static struct pcmcia_socket_entry_s {
4603 struct pcmcia_socket_s *socket;
4604 struct pcmcia_socket_entry_s *next;
4605 } *pcmcia_sockets = 0;
4607 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4609 struct pcmcia_socket_entry_s *entry;
4611 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4612 entry->socket = socket;
4613 entry->next = pcmcia_sockets;
4614 pcmcia_sockets = entry;
4617 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4619 struct pcmcia_socket_entry_s *entry, **ptr;
4621 ptr = &pcmcia_sockets;
4622 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4623 if (entry->socket == socket) {
4624 *ptr = entry->next;
4625 qemu_free(entry);
4629 void pcmcia_info(void)
4631 struct pcmcia_socket_entry_s *iter;
4632 if (!pcmcia_sockets)
4633 term_printf("No PCMCIA sockets\n");
4635 for (iter = pcmcia_sockets; iter; iter = iter->next)
4636 term_printf("%s: %s\n", iter->socket->slot_string,
4637 iter->socket->attached ? iter->socket->card_string :
4638 "Empty");
4641 /***********************************************************/
4642 /* dumb display */
4644 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4648 static void dumb_resize(DisplayState *ds, int w, int h)
4652 static void dumb_refresh(DisplayState *ds)
4654 #if defined(CONFIG_SDL)
4655 vga_hw_update();
4656 #endif
4659 static void dumb_display_init(DisplayState *ds)
4661 ds->data = NULL;
4662 ds->linesize = 0;
4663 ds->depth = 0;
4664 ds->dpy_update = dumb_update;
4665 ds->dpy_resize = dumb_resize;
4666 ds->dpy_refresh = dumb_refresh;
4669 /***********************************************************/
4670 /* I/O handling */
4672 #define MAX_IO_HANDLERS 64
4674 typedef struct IOHandlerRecord {
4675 int fd;
4676 IOCanRWHandler *fd_read_poll;
4677 IOHandler *fd_read;
4678 IOHandler *fd_write;
4679 int deleted;
4680 void *opaque;
4681 /* temporary data */
4682 struct pollfd *ufd;
4683 struct IOHandlerRecord *next;
4684 } IOHandlerRecord;
4686 static IOHandlerRecord *first_io_handler;
4688 /* XXX: fd_read_poll should be suppressed, but an API change is
4689 necessary in the character devices to suppress fd_can_read(). */
4690 int qemu_set_fd_handler2(int fd,
4691 IOCanRWHandler *fd_read_poll,
4692 IOHandler *fd_read,
4693 IOHandler *fd_write,
4694 void *opaque)
4696 IOHandlerRecord **pioh, *ioh;
4698 if (!fd_read && !fd_write) {
4699 pioh = &first_io_handler;
4700 for(;;) {
4701 ioh = *pioh;
4702 if (ioh == NULL)
4703 break;
4704 if (ioh->fd == fd) {
4705 ioh->deleted = 1;
4706 break;
4708 pioh = &ioh->next;
4710 } else {
4711 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4712 if (ioh->fd == fd)
4713 goto found;
4715 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4716 if (!ioh)
4717 return -1;
4718 ioh->next = first_io_handler;
4719 first_io_handler = ioh;
4720 found:
4721 ioh->fd = fd;
4722 ioh->fd_read_poll = fd_read_poll;
4723 ioh->fd_read = fd_read;
4724 ioh->fd_write = fd_write;
4725 ioh->opaque = opaque;
4726 ioh->deleted = 0;
4728 return 0;
4731 int qemu_set_fd_handler(int fd,
4732 IOHandler *fd_read,
4733 IOHandler *fd_write,
4734 void *opaque)
4736 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4739 /***********************************************************/
4740 /* Polling handling */
4742 typedef struct PollingEntry {
4743 PollingFunc *func;
4744 void *opaque;
4745 struct PollingEntry *next;
4746 } PollingEntry;
4748 static PollingEntry *first_polling_entry;
4750 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4752 PollingEntry **ppe, *pe;
4753 pe = qemu_mallocz(sizeof(PollingEntry));
4754 if (!pe)
4755 return -1;
4756 pe->func = func;
4757 pe->opaque = opaque;
4758 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4759 *ppe = pe;
4760 return 0;
4763 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4765 PollingEntry **ppe, *pe;
4766 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4767 pe = *ppe;
4768 if (pe->func == func && pe->opaque == opaque) {
4769 *ppe = pe->next;
4770 qemu_free(pe);
4771 break;
4776 #ifdef _WIN32
4777 /***********************************************************/
4778 /* Wait objects support */
4779 typedef struct WaitObjects {
4780 int num;
4781 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4782 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4783 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4784 } WaitObjects;
4786 static WaitObjects wait_objects = {0};
4788 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4790 WaitObjects *w = &wait_objects;
4792 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4793 return -1;
4794 w->events[w->num] = handle;
4795 w->func[w->num] = func;
4796 w->opaque[w->num] = opaque;
4797 w->num++;
4798 return 0;
4801 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4803 int i, found;
4804 WaitObjects *w = &wait_objects;
4806 found = 0;
4807 for (i = 0; i < w->num; i++) {
4808 if (w->events[i] == handle)
4809 found = 1;
4810 if (found) {
4811 w->events[i] = w->events[i + 1];
4812 w->func[i] = w->func[i + 1];
4813 w->opaque[i] = w->opaque[i + 1];
4816 if (found)
4817 w->num--;
4819 #endif
4821 /***********************************************************/
4822 /* savevm/loadvm support */
4824 #define IO_BUF_SIZE 32768
4826 struct QEMUFile {
4827 FILE *outfile;
4828 BlockDriverState *bs;
4829 int is_file;
4830 int is_writable;
4831 int64_t base_offset;
4832 int64_t buf_offset; /* start of buffer when writing, end of buffer
4833 when reading */
4834 int buf_index;
4835 int buf_size; /* 0 when writing */
4836 uint8_t buf[IO_BUF_SIZE];
4839 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4841 QEMUFile *f;
4843 f = qemu_mallocz(sizeof(QEMUFile));
4844 if (!f)
4845 return NULL;
4846 if (!strcmp(mode, "wb")) {
4847 f->is_writable = 1;
4848 } else if (!strcmp(mode, "rb")) {
4849 f->is_writable = 0;
4850 } else {
4851 goto fail;
4853 f->outfile = fopen(filename, mode);
4854 if (!f->outfile)
4855 goto fail;
4856 f->is_file = 1;
4857 return f;
4858 fail:
4859 if (f->outfile)
4860 fclose(f->outfile);
4861 qemu_free(f);
4862 return NULL;
4865 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4867 QEMUFile *f;
4869 f = qemu_mallocz(sizeof(QEMUFile));
4870 if (!f)
4871 return NULL;
4872 f->is_file = 0;
4873 f->bs = bs;
4874 f->is_writable = is_writable;
4875 f->base_offset = offset;
4876 return f;
4879 void qemu_fflush(QEMUFile *f)
4881 if (!f->is_writable)
4882 return;
4883 if (f->buf_index > 0) {
4884 if (f->is_file) {
4885 fseek(f->outfile, f->buf_offset, SEEK_SET);
4886 fwrite(f->buf, 1, f->buf_index, f->outfile);
4887 } else {
4888 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4889 f->buf, f->buf_index);
4891 f->buf_offset += f->buf_index;
4892 f->buf_index = 0;
4896 static void qemu_fill_buffer(QEMUFile *f)
4898 int len;
4900 if (f->is_writable)
4901 return;
4902 if (f->is_file) {
4903 fseek(f->outfile, f->buf_offset, SEEK_SET);
4904 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4905 if (len < 0)
4906 len = 0;
4907 } else {
4908 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4909 f->buf, IO_BUF_SIZE);
4910 if (len < 0)
4911 len = 0;
4913 f->buf_index = 0;
4914 f->buf_size = len;
4915 f->buf_offset += len;
4918 void qemu_fclose(QEMUFile *f)
4920 if (f->is_writable)
4921 qemu_fflush(f);
4922 if (f->is_file) {
4923 fclose(f->outfile);
4925 qemu_free(f);
4928 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4930 int l;
4931 while (size > 0) {
4932 l = IO_BUF_SIZE - f->buf_index;
4933 if (l > size)
4934 l = size;
4935 memcpy(f->buf + f->buf_index, buf, l);
4936 f->buf_index += l;
4937 buf += l;
4938 size -= l;
4939 if (f->buf_index >= IO_BUF_SIZE)
4940 qemu_fflush(f);
4944 void qemu_put_byte(QEMUFile *f, int v)
4946 f->buf[f->buf_index++] = v;
4947 if (f->buf_index >= IO_BUF_SIZE)
4948 qemu_fflush(f);
4951 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4953 int size, l;
4955 size = size1;
4956 while (size > 0) {
4957 l = f->buf_size - f->buf_index;
4958 if (l == 0) {
4959 qemu_fill_buffer(f);
4960 l = f->buf_size - f->buf_index;
4961 if (l == 0)
4962 break;
4964 if (l > size)
4965 l = size;
4966 memcpy(buf, f->buf + f->buf_index, l);
4967 f->buf_index += l;
4968 buf += l;
4969 size -= l;
4971 return size1 - size;
4974 int qemu_get_byte(QEMUFile *f)
4976 if (f->buf_index >= f->buf_size) {
4977 qemu_fill_buffer(f);
4978 if (f->buf_index >= f->buf_size)
4979 return 0;
4981 return f->buf[f->buf_index++];
4984 int64_t qemu_ftell(QEMUFile *f)
4986 return f->buf_offset - f->buf_size + f->buf_index;
4989 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4991 if (whence == SEEK_SET) {
4992 /* nothing to do */
4993 } else if (whence == SEEK_CUR) {
4994 pos += qemu_ftell(f);
4995 } else {
4996 /* SEEK_END not supported */
4997 return -1;
4999 if (f->is_writable) {
5000 qemu_fflush(f);
5001 f->buf_offset = pos;
5002 } else {
5003 f->buf_offset = pos;
5004 f->buf_index = 0;
5005 f->buf_size = 0;
5007 return pos;
5010 void qemu_put_be16(QEMUFile *f, unsigned int v)
5012 qemu_put_byte(f, v >> 8);
5013 qemu_put_byte(f, v);
5016 void qemu_put_be32(QEMUFile *f, unsigned int v)
5018 qemu_put_byte(f, v >> 24);
5019 qemu_put_byte(f, v >> 16);
5020 qemu_put_byte(f, v >> 8);
5021 qemu_put_byte(f, v);
5024 void qemu_put_be64(QEMUFile *f, uint64_t v)
5026 qemu_put_be32(f, v >> 32);
5027 qemu_put_be32(f, v);
5030 unsigned int qemu_get_be16(QEMUFile *f)
5032 unsigned int v;
5033 v = qemu_get_byte(f) << 8;
5034 v |= qemu_get_byte(f);
5035 return v;
5038 unsigned int qemu_get_be32(QEMUFile *f)
5040 unsigned int v;
5041 v = qemu_get_byte(f) << 24;
5042 v |= qemu_get_byte(f) << 16;
5043 v |= qemu_get_byte(f) << 8;
5044 v |= qemu_get_byte(f);
5045 return v;
5048 uint64_t qemu_get_be64(QEMUFile *f)
5050 uint64_t v;
5051 v = (uint64_t)qemu_get_be32(f) << 32;
5052 v |= qemu_get_be32(f);
5053 return v;
5056 typedef struct SaveStateEntry {
5057 char idstr[256];
5058 int instance_id;
5059 int version_id;
5060 SaveStateHandler *save_state;
5061 LoadStateHandler *load_state;
5062 void *opaque;
5063 struct SaveStateEntry *next;
5064 } SaveStateEntry;
5066 static SaveStateEntry *first_se;
5068 int register_savevm(const char *idstr,
5069 int instance_id,
5070 int version_id,
5071 SaveStateHandler *save_state,
5072 LoadStateHandler *load_state,
5073 void *opaque)
5075 SaveStateEntry *se, **pse;
5077 se = qemu_malloc(sizeof(SaveStateEntry));
5078 if (!se)
5079 return -1;
5080 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5081 se->instance_id = instance_id;
5082 se->version_id = version_id;
5083 se->save_state = save_state;
5084 se->load_state = load_state;
5085 se->opaque = opaque;
5086 se->next = NULL;
5088 /* add at the end of list */
5089 pse = &first_se;
5090 while (*pse != NULL)
5091 pse = &(*pse)->next;
5092 *pse = se;
5093 return 0;
5096 #define QEMU_VM_FILE_MAGIC 0x5145564d
5097 #define QEMU_VM_FILE_VERSION 0x00000002
5099 int qemu_savevm_state(QEMUFile *f)
5101 SaveStateEntry *se;
5102 int len, ret;
5103 int64_t cur_pos, len_pos, total_len_pos;
5105 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5106 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5107 total_len_pos = qemu_ftell(f);
5108 qemu_put_be64(f, 0); /* total size */
5110 for(se = first_se; se != NULL; se = se->next) {
5111 /* ID string */
5112 len = strlen(se->idstr);
5113 qemu_put_byte(f, len);
5114 qemu_put_buffer(f, se->idstr, len);
5116 qemu_put_be32(f, se->instance_id);
5117 qemu_put_be32(f, se->version_id);
5119 /* record size: filled later */
5120 len_pos = qemu_ftell(f);
5121 qemu_put_be32(f, 0);
5123 se->save_state(f, se->opaque);
5125 /* fill record size */
5126 cur_pos = qemu_ftell(f);
5127 len = cur_pos - len_pos - 4;
5128 qemu_fseek(f, len_pos, SEEK_SET);
5129 qemu_put_be32(f, len);
5130 qemu_fseek(f, cur_pos, SEEK_SET);
5132 cur_pos = qemu_ftell(f);
5133 qemu_fseek(f, total_len_pos, SEEK_SET);
5134 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5135 qemu_fseek(f, cur_pos, SEEK_SET);
5137 ret = 0;
5138 return ret;
5141 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5143 SaveStateEntry *se;
5145 for(se = first_se; se != NULL; se = se->next) {
5146 if (!strcmp(se->idstr, idstr) &&
5147 instance_id == se->instance_id)
5148 return se;
5150 return NULL;
5153 int qemu_loadvm_state(QEMUFile *f)
5155 SaveStateEntry *se;
5156 int len, ret, instance_id, record_len, version_id;
5157 int64_t total_len, end_pos, cur_pos;
5158 unsigned int v;
5159 char idstr[256];
5161 v = qemu_get_be32(f);
5162 if (v != QEMU_VM_FILE_MAGIC)
5163 goto fail;
5164 v = qemu_get_be32(f);
5165 if (v != QEMU_VM_FILE_VERSION) {
5166 fail:
5167 ret = -1;
5168 goto the_end;
5170 total_len = qemu_get_be64(f);
5171 end_pos = total_len + qemu_ftell(f);
5172 for(;;) {
5173 if (qemu_ftell(f) >= end_pos)
5174 break;
5175 len = qemu_get_byte(f);
5176 qemu_get_buffer(f, idstr, len);
5177 idstr[len] = '\0';
5178 instance_id = qemu_get_be32(f);
5179 version_id = qemu_get_be32(f);
5180 record_len = qemu_get_be32(f);
5181 #if 0
5182 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5183 idstr, instance_id, version_id, record_len);
5184 #endif
5185 cur_pos = qemu_ftell(f);
5186 se = find_se(idstr, instance_id);
5187 if (!se) {
5188 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5189 instance_id, idstr);
5190 } else {
5191 ret = se->load_state(f, se->opaque, version_id);
5192 if (ret < 0) {
5193 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5194 instance_id, idstr);
5197 /* always seek to exact end of record */
5198 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5200 ret = 0;
5201 the_end:
5202 return ret;
5205 /* device can contain snapshots */
5206 static int bdrv_can_snapshot(BlockDriverState *bs)
5208 return (bs &&
5209 !bdrv_is_removable(bs) &&
5210 !bdrv_is_read_only(bs));
5213 /* device must be snapshots in order to have a reliable snapshot */
5214 static int bdrv_has_snapshot(BlockDriverState *bs)
5216 return (bs &&
5217 !bdrv_is_removable(bs) &&
5218 !bdrv_is_read_only(bs));
5221 static BlockDriverState *get_bs_snapshots(void)
5223 BlockDriverState *bs;
5224 int i;
5226 if (bs_snapshots)
5227 return bs_snapshots;
5228 for(i = 0; i <= MAX_DISKS; i++) {
5229 bs = bs_table[i];
5230 if (bdrv_can_snapshot(bs))
5231 goto ok;
5233 return NULL;
5235 bs_snapshots = bs;
5236 return bs;
5239 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5240 const char *name)
5242 QEMUSnapshotInfo *sn_tab, *sn;
5243 int nb_sns, i, ret;
5245 ret = -ENOENT;
5246 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5247 if (nb_sns < 0)
5248 return ret;
5249 for(i = 0; i < nb_sns; i++) {
5250 sn = &sn_tab[i];
5251 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5252 *sn_info = *sn;
5253 ret = 0;
5254 break;
5257 qemu_free(sn_tab);
5258 return ret;
5261 void do_savevm(const char *name)
5263 BlockDriverState *bs, *bs1;
5264 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5265 int must_delete, ret, i;
5266 BlockDriverInfo bdi1, *bdi = &bdi1;
5267 QEMUFile *f;
5268 int saved_vm_running;
5269 #ifdef _WIN32
5270 struct _timeb tb;
5271 #else
5272 struct timeval tv;
5273 #endif
5275 bs = get_bs_snapshots();
5276 if (!bs) {
5277 term_printf("No block device can accept snapshots\n");
5278 return;
5281 /* ??? Should this occur after vm_stop? */
5282 qemu_aio_flush();
5284 saved_vm_running = vm_running;
5285 vm_stop(0);
5287 must_delete = 0;
5288 if (name) {
5289 ret = bdrv_snapshot_find(bs, old_sn, name);
5290 if (ret >= 0) {
5291 must_delete = 1;
5294 memset(sn, 0, sizeof(*sn));
5295 if (must_delete) {
5296 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5297 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5298 } else {
5299 if (name)
5300 pstrcpy(sn->name, sizeof(sn->name), name);
5303 /* fill auxiliary fields */
5304 #ifdef _WIN32
5305 _ftime(&tb);
5306 sn->date_sec = tb.time;
5307 sn->date_nsec = tb.millitm * 1000000;
5308 #else
5309 gettimeofday(&tv, NULL);
5310 sn->date_sec = tv.tv_sec;
5311 sn->date_nsec = tv.tv_usec * 1000;
5312 #endif
5313 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5315 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5316 term_printf("Device %s does not support VM state snapshots\n",
5317 bdrv_get_device_name(bs));
5318 goto the_end;
5321 /* save the VM state */
5322 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5323 if (!f) {
5324 term_printf("Could not open VM state file\n");
5325 goto the_end;
5327 ret = qemu_savevm_state(f);
5328 sn->vm_state_size = qemu_ftell(f);
5329 qemu_fclose(f);
5330 if (ret < 0) {
5331 term_printf("Error %d while writing VM\n", ret);
5332 goto the_end;
5335 /* create the snapshots */
5337 for(i = 0; i < MAX_DISKS; i++) {
5338 bs1 = bs_table[i];
5339 if (bdrv_has_snapshot(bs1)) {
5340 if (must_delete) {
5341 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5342 if (ret < 0) {
5343 term_printf("Error while deleting snapshot on '%s'\n",
5344 bdrv_get_device_name(bs1));
5347 ret = bdrv_snapshot_create(bs1, sn);
5348 if (ret < 0) {
5349 term_printf("Error while creating snapshot on '%s'\n",
5350 bdrv_get_device_name(bs1));
5355 the_end:
5356 if (saved_vm_running)
5357 vm_start();
5360 void do_loadvm(const char *name)
5362 BlockDriverState *bs, *bs1;
5363 BlockDriverInfo bdi1, *bdi = &bdi1;
5364 QEMUFile *f;
5365 int i, ret;
5366 int saved_vm_running;
5368 bs = get_bs_snapshots();
5369 if (!bs) {
5370 term_printf("No block device supports snapshots\n");
5371 return;
5374 /* Flush all IO requests so they don't interfere with the new state. */
5375 qemu_aio_flush();
5377 saved_vm_running = vm_running;
5378 vm_stop(0);
5380 for(i = 0; i <= MAX_DISKS; i++) {
5381 bs1 = bs_table[i];
5382 if (bdrv_has_snapshot(bs1)) {
5383 ret = bdrv_snapshot_goto(bs1, name);
5384 if (ret < 0) {
5385 if (bs != bs1)
5386 term_printf("Warning: ");
5387 switch(ret) {
5388 case -ENOTSUP:
5389 term_printf("Snapshots not supported on device '%s'\n",
5390 bdrv_get_device_name(bs1));
5391 break;
5392 case -ENOENT:
5393 term_printf("Could not find snapshot '%s' on device '%s'\n",
5394 name, bdrv_get_device_name(bs1));
5395 break;
5396 default:
5397 term_printf("Error %d while activating snapshot on '%s'\n",
5398 ret, bdrv_get_device_name(bs1));
5399 break;
5401 /* fatal on snapshot block device */
5402 if (bs == bs1)
5403 goto the_end;
5408 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5409 term_printf("Device %s does not support VM state snapshots\n",
5410 bdrv_get_device_name(bs));
5411 return;
5414 /* restore the VM state */
5415 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5416 if (!f) {
5417 term_printf("Could not open VM state file\n");
5418 goto the_end;
5420 ret = qemu_loadvm_state(f);
5421 qemu_fclose(f);
5422 if (ret < 0) {
5423 term_printf("Error %d while loading VM state\n", ret);
5425 the_end:
5426 if (saved_vm_running)
5427 vm_start();
5430 void do_delvm(const char *name)
5432 BlockDriverState *bs, *bs1;
5433 int i, ret;
5435 bs = get_bs_snapshots();
5436 if (!bs) {
5437 term_printf("No block device supports snapshots\n");
5438 return;
5441 for(i = 0; i <= MAX_DISKS; i++) {
5442 bs1 = bs_table[i];
5443 if (bdrv_has_snapshot(bs1)) {
5444 ret = bdrv_snapshot_delete(bs1, name);
5445 if (ret < 0) {
5446 if (ret == -ENOTSUP)
5447 term_printf("Snapshots not supported on device '%s'\n",
5448 bdrv_get_device_name(bs1));
5449 else
5450 term_printf("Error %d while deleting snapshot on '%s'\n",
5451 ret, bdrv_get_device_name(bs1));
5457 void do_info_snapshots(void)
5459 BlockDriverState *bs, *bs1;
5460 QEMUSnapshotInfo *sn_tab, *sn;
5461 int nb_sns, i;
5462 char buf[256];
5464 bs = get_bs_snapshots();
5465 if (!bs) {
5466 term_printf("No available block device supports snapshots\n");
5467 return;
5469 term_printf("Snapshot devices:");
5470 for(i = 0; i <= MAX_DISKS; i++) {
5471 bs1 = bs_table[i];
5472 if (bdrv_has_snapshot(bs1)) {
5473 if (bs == bs1)
5474 term_printf(" %s", bdrv_get_device_name(bs1));
5477 term_printf("\n");
5479 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5480 if (nb_sns < 0) {
5481 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5482 return;
5484 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5485 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5486 for(i = 0; i < nb_sns; i++) {
5487 sn = &sn_tab[i];
5488 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5490 qemu_free(sn_tab);
5493 /***********************************************************/
5494 /* cpu save/restore */
5496 #if defined(TARGET_I386)
5498 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5500 qemu_put_be32(f, dt->selector);
5501 qemu_put_betl(f, dt->base);
5502 qemu_put_be32(f, dt->limit);
5503 qemu_put_be32(f, dt->flags);
5506 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5508 dt->selector = qemu_get_be32(f);
5509 dt->base = qemu_get_betl(f);
5510 dt->limit = qemu_get_be32(f);
5511 dt->flags = qemu_get_be32(f);
5514 void cpu_save(QEMUFile *f, void *opaque)
5516 CPUState *env = opaque;
5517 uint16_t fptag, fpus, fpuc, fpregs_format;
5518 uint32_t hflags;
5519 int i;
5521 for(i = 0; i < CPU_NB_REGS; i++)
5522 qemu_put_betls(f, &env->regs[i]);
5523 qemu_put_betls(f, &env->eip);
5524 qemu_put_betls(f, &env->eflags);
5525 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5526 qemu_put_be32s(f, &hflags);
5528 /* FPU */
5529 fpuc = env->fpuc;
5530 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5531 fptag = 0;
5532 for(i = 0; i < 8; i++) {
5533 fptag |= ((!env->fptags[i]) << i);
5536 qemu_put_be16s(f, &fpuc);
5537 qemu_put_be16s(f, &fpus);
5538 qemu_put_be16s(f, &fptag);
5540 #ifdef USE_X86LDOUBLE
5541 fpregs_format = 0;
5542 #else
5543 fpregs_format = 1;
5544 #endif
5545 qemu_put_be16s(f, &fpregs_format);
5547 for(i = 0; i < 8; i++) {
5548 #ifdef USE_X86LDOUBLE
5550 uint64_t mant;
5551 uint16_t exp;
5552 /* we save the real CPU data (in case of MMX usage only 'mant'
5553 contains the MMX register */
5554 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5555 qemu_put_be64(f, mant);
5556 qemu_put_be16(f, exp);
5558 #else
5559 /* if we use doubles for float emulation, we save the doubles to
5560 avoid losing information in case of MMX usage. It can give
5561 problems if the image is restored on a CPU where long
5562 doubles are used instead. */
5563 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5564 #endif
5567 for(i = 0; i < 6; i++)
5568 cpu_put_seg(f, &env->segs[i]);
5569 cpu_put_seg(f, &env->ldt);
5570 cpu_put_seg(f, &env->tr);
5571 cpu_put_seg(f, &env->gdt);
5572 cpu_put_seg(f, &env->idt);
5574 qemu_put_be32s(f, &env->sysenter_cs);
5575 qemu_put_be32s(f, &env->sysenter_esp);
5576 qemu_put_be32s(f, &env->sysenter_eip);
5578 qemu_put_betls(f, &env->cr[0]);
5579 qemu_put_betls(f, &env->cr[2]);
5580 qemu_put_betls(f, &env->cr[3]);
5581 qemu_put_betls(f, &env->cr[4]);
5583 for(i = 0; i < 8; i++)
5584 qemu_put_betls(f, &env->dr[i]);
5586 /* MMU */
5587 qemu_put_be32s(f, &env->a20_mask);
5589 /* XMM */
5590 qemu_put_be32s(f, &env->mxcsr);
5591 for(i = 0; i < CPU_NB_REGS; i++) {
5592 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5593 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5596 #ifdef TARGET_X86_64
5597 qemu_put_be64s(f, &env->efer);
5598 qemu_put_be64s(f, &env->star);
5599 qemu_put_be64s(f, &env->lstar);
5600 qemu_put_be64s(f, &env->cstar);
5601 qemu_put_be64s(f, &env->fmask);
5602 qemu_put_be64s(f, &env->kernelgsbase);
5603 #endif
5604 qemu_put_be32s(f, &env->smbase);
5607 #ifdef USE_X86LDOUBLE
5608 /* XXX: add that in a FPU generic layer */
5609 union x86_longdouble {
5610 uint64_t mant;
5611 uint16_t exp;
5614 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5615 #define EXPBIAS1 1023
5616 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5617 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5619 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5621 int e;
5622 /* mantissa */
5623 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5624 /* exponent + sign */
5625 e = EXPD1(temp) - EXPBIAS1 + 16383;
5626 e |= SIGND1(temp) >> 16;
5627 p->exp = e;
5629 #endif
5631 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5633 CPUState *env = opaque;
5634 int i, guess_mmx;
5635 uint32_t hflags;
5636 uint16_t fpus, fpuc, fptag, fpregs_format;
5638 if (version_id != 3 && version_id != 4)
5639 return -EINVAL;
5640 for(i = 0; i < CPU_NB_REGS; i++)
5641 qemu_get_betls(f, &env->regs[i]);
5642 qemu_get_betls(f, &env->eip);
5643 qemu_get_betls(f, &env->eflags);
5644 qemu_get_be32s(f, &hflags);
5646 qemu_get_be16s(f, &fpuc);
5647 qemu_get_be16s(f, &fpus);
5648 qemu_get_be16s(f, &fptag);
5649 qemu_get_be16s(f, &fpregs_format);
5651 /* NOTE: we cannot always restore the FPU state if the image come
5652 from a host with a different 'USE_X86LDOUBLE' define. We guess
5653 if we are in an MMX state to restore correctly in that case. */
5654 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5655 for(i = 0; i < 8; i++) {
5656 uint64_t mant;
5657 uint16_t exp;
5659 switch(fpregs_format) {
5660 case 0:
5661 mant = qemu_get_be64(f);
5662 exp = qemu_get_be16(f);
5663 #ifdef USE_X86LDOUBLE
5664 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5665 #else
5666 /* difficult case */
5667 if (guess_mmx)
5668 env->fpregs[i].mmx.MMX_Q(0) = mant;
5669 else
5670 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5671 #endif
5672 break;
5673 case 1:
5674 mant = qemu_get_be64(f);
5675 #ifdef USE_X86LDOUBLE
5677 union x86_longdouble *p;
5678 /* difficult case */
5679 p = (void *)&env->fpregs[i];
5680 if (guess_mmx) {
5681 p->mant = mant;
5682 p->exp = 0xffff;
5683 } else {
5684 fp64_to_fp80(p, mant);
5687 #else
5688 env->fpregs[i].mmx.MMX_Q(0) = mant;
5689 #endif
5690 break;
5691 default:
5692 return -EINVAL;
5696 env->fpuc = fpuc;
5697 /* XXX: restore FPU round state */
5698 env->fpstt = (fpus >> 11) & 7;
5699 env->fpus = fpus & ~0x3800;
5700 fptag ^= 0xff;
5701 for(i = 0; i < 8; i++) {
5702 env->fptags[i] = (fptag >> i) & 1;
5705 for(i = 0; i < 6; i++)
5706 cpu_get_seg(f, &env->segs[i]);
5707 cpu_get_seg(f, &env->ldt);
5708 cpu_get_seg(f, &env->tr);
5709 cpu_get_seg(f, &env->gdt);
5710 cpu_get_seg(f, &env->idt);
5712 qemu_get_be32s(f, &env->sysenter_cs);
5713 qemu_get_be32s(f, &env->sysenter_esp);
5714 qemu_get_be32s(f, &env->sysenter_eip);
5716 qemu_get_betls(f, &env->cr[0]);
5717 qemu_get_betls(f, &env->cr[2]);
5718 qemu_get_betls(f, &env->cr[3]);
5719 qemu_get_betls(f, &env->cr[4]);
5721 for(i = 0; i < 8; i++)
5722 qemu_get_betls(f, &env->dr[i]);
5724 /* MMU */
5725 qemu_get_be32s(f, &env->a20_mask);
5727 qemu_get_be32s(f, &env->mxcsr);
5728 for(i = 0; i < CPU_NB_REGS; i++) {
5729 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5730 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5733 #ifdef TARGET_X86_64
5734 qemu_get_be64s(f, &env->efer);
5735 qemu_get_be64s(f, &env->star);
5736 qemu_get_be64s(f, &env->lstar);
5737 qemu_get_be64s(f, &env->cstar);
5738 qemu_get_be64s(f, &env->fmask);
5739 qemu_get_be64s(f, &env->kernelgsbase);
5740 #endif
5741 if (version_id >= 4)
5742 qemu_get_be32s(f, &env->smbase);
5744 /* XXX: compute hflags from scratch, except for CPL and IIF */
5745 env->hflags = hflags;
5746 tlb_flush(env, 1);
5747 return 0;
5750 #elif defined(TARGET_PPC)
5751 void cpu_save(QEMUFile *f, void *opaque)
5755 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5757 return 0;
5760 #elif defined(TARGET_MIPS)
5761 void cpu_save(QEMUFile *f, void *opaque)
5765 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5767 return 0;
5770 #elif defined(TARGET_SPARC)
5771 void cpu_save(QEMUFile *f, void *opaque)
5773 CPUState *env = opaque;
5774 int i;
5775 uint32_t tmp;
5777 for(i = 0; i < 8; i++)
5778 qemu_put_betls(f, &env->gregs[i]);
5779 for(i = 0; i < NWINDOWS * 16; i++)
5780 qemu_put_betls(f, &env->regbase[i]);
5782 /* FPU */
5783 for(i = 0; i < TARGET_FPREGS; i++) {
5784 union {
5785 float32 f;
5786 uint32_t i;
5787 } u;
5788 u.f = env->fpr[i];
5789 qemu_put_be32(f, u.i);
5792 qemu_put_betls(f, &env->pc);
5793 qemu_put_betls(f, &env->npc);
5794 qemu_put_betls(f, &env->y);
5795 tmp = GET_PSR(env);
5796 qemu_put_be32(f, tmp);
5797 qemu_put_betls(f, &env->fsr);
5798 qemu_put_betls(f, &env->tbr);
5799 #ifndef TARGET_SPARC64
5800 qemu_put_be32s(f, &env->wim);
5801 /* MMU */
5802 for(i = 0; i < 16; i++)
5803 qemu_put_be32s(f, &env->mmuregs[i]);
5804 #endif
5807 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5809 CPUState *env = opaque;
5810 int i;
5811 uint32_t tmp;
5813 for(i = 0; i < 8; i++)
5814 qemu_get_betls(f, &env->gregs[i]);
5815 for(i = 0; i < NWINDOWS * 16; i++)
5816 qemu_get_betls(f, &env->regbase[i]);
5818 /* FPU */
5819 for(i = 0; i < TARGET_FPREGS; i++) {
5820 union {
5821 float32 f;
5822 uint32_t i;
5823 } u;
5824 u.i = qemu_get_be32(f);
5825 env->fpr[i] = u.f;
5828 qemu_get_betls(f, &env->pc);
5829 qemu_get_betls(f, &env->npc);
5830 qemu_get_betls(f, &env->y);
5831 tmp = qemu_get_be32(f);
5832 env->cwp = 0; /* needed to ensure that the wrapping registers are
5833 correctly updated */
5834 PUT_PSR(env, tmp);
5835 qemu_get_betls(f, &env->fsr);
5836 qemu_get_betls(f, &env->tbr);
5837 #ifndef TARGET_SPARC64
5838 qemu_get_be32s(f, &env->wim);
5839 /* MMU */
5840 for(i = 0; i < 16; i++)
5841 qemu_get_be32s(f, &env->mmuregs[i]);
5842 #endif
5843 tlb_flush(env, 1);
5844 return 0;
5847 #elif defined(TARGET_ARM)
5849 void cpu_save(QEMUFile *f, void *opaque)
5851 int i;
5852 CPUARMState *env = (CPUARMState *)opaque;
5854 for (i = 0; i < 16; i++) {
5855 qemu_put_be32(f, env->regs[i]);
5857 qemu_put_be32(f, cpsr_read(env));
5858 qemu_put_be32(f, env->spsr);
5859 for (i = 0; i < 6; i++) {
5860 qemu_put_be32(f, env->banked_spsr[i]);
5861 qemu_put_be32(f, env->banked_r13[i]);
5862 qemu_put_be32(f, env->banked_r14[i]);
5864 for (i = 0; i < 5; i++) {
5865 qemu_put_be32(f, env->usr_regs[i]);
5866 qemu_put_be32(f, env->fiq_regs[i]);
5868 qemu_put_be32(f, env->cp15.c0_cpuid);
5869 qemu_put_be32(f, env->cp15.c0_cachetype);
5870 qemu_put_be32(f, env->cp15.c1_sys);
5871 qemu_put_be32(f, env->cp15.c1_coproc);
5872 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5873 qemu_put_be32(f, env->cp15.c2_base);
5874 qemu_put_be32(f, env->cp15.c2_data);
5875 qemu_put_be32(f, env->cp15.c2_insn);
5876 qemu_put_be32(f, env->cp15.c3);
5877 qemu_put_be32(f, env->cp15.c5_insn);
5878 qemu_put_be32(f, env->cp15.c5_data);
5879 for (i = 0; i < 8; i++) {
5880 qemu_put_be32(f, env->cp15.c6_region[i]);
5882 qemu_put_be32(f, env->cp15.c6_insn);
5883 qemu_put_be32(f, env->cp15.c6_data);
5884 qemu_put_be32(f, env->cp15.c9_insn);
5885 qemu_put_be32(f, env->cp15.c9_data);
5886 qemu_put_be32(f, env->cp15.c13_fcse);
5887 qemu_put_be32(f, env->cp15.c13_context);
5888 qemu_put_be32(f, env->cp15.c15_cpar);
5890 qemu_put_be32(f, env->features);
5892 if (arm_feature(env, ARM_FEATURE_VFP)) {
5893 for (i = 0; i < 16; i++) {
5894 CPU_DoubleU u;
5895 u.d = env->vfp.regs[i];
5896 qemu_put_be32(f, u.l.upper);
5897 qemu_put_be32(f, u.l.lower);
5899 for (i = 0; i < 16; i++) {
5900 qemu_put_be32(f, env->vfp.xregs[i]);
5903 /* TODO: Should use proper FPSCR access functions. */
5904 qemu_put_be32(f, env->vfp.vec_len);
5905 qemu_put_be32(f, env->vfp.vec_stride);
5908 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5909 for (i = 0; i < 16; i++) {
5910 qemu_put_be64(f, env->iwmmxt.regs[i]);
5912 for (i = 0; i < 16; i++) {
5913 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5918 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5920 CPUARMState *env = (CPUARMState *)opaque;
5921 int i;
5923 if (version_id != 0)
5924 return -EINVAL;
5926 for (i = 0; i < 16; i++) {
5927 env->regs[i] = qemu_get_be32(f);
5929 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5930 env->spsr = qemu_get_be32(f);
5931 for (i = 0; i < 6; i++) {
5932 env->banked_spsr[i] = qemu_get_be32(f);
5933 env->banked_r13[i] = qemu_get_be32(f);
5934 env->banked_r14[i] = qemu_get_be32(f);
5936 for (i = 0; i < 5; i++) {
5937 env->usr_regs[i] = qemu_get_be32(f);
5938 env->fiq_regs[i] = qemu_get_be32(f);
5940 env->cp15.c0_cpuid = qemu_get_be32(f);
5941 env->cp15.c0_cachetype = qemu_get_be32(f);
5942 env->cp15.c1_sys = qemu_get_be32(f);
5943 env->cp15.c1_coproc = qemu_get_be32(f);
5944 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5945 env->cp15.c2_base = qemu_get_be32(f);
5946 env->cp15.c2_data = qemu_get_be32(f);
5947 env->cp15.c2_insn = qemu_get_be32(f);
5948 env->cp15.c3 = qemu_get_be32(f);
5949 env->cp15.c5_insn = qemu_get_be32(f);
5950 env->cp15.c5_data = qemu_get_be32(f);
5951 for (i = 0; i < 8; i++) {
5952 env->cp15.c6_region[i] = qemu_get_be32(f);
5954 env->cp15.c6_insn = qemu_get_be32(f);
5955 env->cp15.c6_data = qemu_get_be32(f);
5956 env->cp15.c9_insn = qemu_get_be32(f);
5957 env->cp15.c9_data = qemu_get_be32(f);
5958 env->cp15.c13_fcse = qemu_get_be32(f);
5959 env->cp15.c13_context = qemu_get_be32(f);
5960 env->cp15.c15_cpar = qemu_get_be32(f);
5962 env->features = qemu_get_be32(f);
5964 if (arm_feature(env, ARM_FEATURE_VFP)) {
5965 for (i = 0; i < 16; i++) {
5966 CPU_DoubleU u;
5967 u.l.upper = qemu_get_be32(f);
5968 u.l.lower = qemu_get_be32(f);
5969 env->vfp.regs[i] = u.d;
5971 for (i = 0; i < 16; i++) {
5972 env->vfp.xregs[i] = qemu_get_be32(f);
5975 /* TODO: Should use proper FPSCR access functions. */
5976 env->vfp.vec_len = qemu_get_be32(f);
5977 env->vfp.vec_stride = qemu_get_be32(f);
5980 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5981 for (i = 0; i < 16; i++) {
5982 env->iwmmxt.regs[i] = qemu_get_be64(f);
5984 for (i = 0; i < 16; i++) {
5985 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5989 return 0;
5992 #else
5994 #warning No CPU save/restore functions
5996 #endif
5998 /***********************************************************/
5999 /* ram save/restore */
6001 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6003 int v;
6005 v = qemu_get_byte(f);
6006 switch(v) {
6007 case 0:
6008 if (qemu_get_buffer(f, buf, len) != len)
6009 return -EIO;
6010 break;
6011 case 1:
6012 v = qemu_get_byte(f);
6013 memset(buf, v, len);
6014 break;
6015 default:
6016 return -EINVAL;
6018 return 0;
6021 static int ram_load_v1(QEMUFile *f, void *opaque)
6023 int i, ret;
6025 if (qemu_get_be32(f) != phys_ram_size)
6026 return -EINVAL;
6027 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6028 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6029 if (ret)
6030 return ret;
6032 return 0;
6035 #define BDRV_HASH_BLOCK_SIZE 1024
6036 #define IOBUF_SIZE 4096
6037 #define RAM_CBLOCK_MAGIC 0xfabe
6039 typedef struct RamCompressState {
6040 z_stream zstream;
6041 QEMUFile *f;
6042 uint8_t buf[IOBUF_SIZE];
6043 } RamCompressState;
6045 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6047 int ret;
6048 memset(s, 0, sizeof(*s));
6049 s->f = f;
6050 ret = deflateInit2(&s->zstream, 1,
6051 Z_DEFLATED, 15,
6052 9, Z_DEFAULT_STRATEGY);
6053 if (ret != Z_OK)
6054 return -1;
6055 s->zstream.avail_out = IOBUF_SIZE;
6056 s->zstream.next_out = s->buf;
6057 return 0;
6060 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6062 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6063 qemu_put_be16(s->f, len);
6064 qemu_put_buffer(s->f, buf, len);
6067 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6069 int ret;
6071 s->zstream.avail_in = len;
6072 s->zstream.next_in = (uint8_t *)buf;
6073 while (s->zstream.avail_in > 0) {
6074 ret = deflate(&s->zstream, Z_NO_FLUSH);
6075 if (ret != Z_OK)
6076 return -1;
6077 if (s->zstream.avail_out == 0) {
6078 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6079 s->zstream.avail_out = IOBUF_SIZE;
6080 s->zstream.next_out = s->buf;
6083 return 0;
6086 static void ram_compress_close(RamCompressState *s)
6088 int len, ret;
6090 /* compress last bytes */
6091 for(;;) {
6092 ret = deflate(&s->zstream, Z_FINISH);
6093 if (ret == Z_OK || ret == Z_STREAM_END) {
6094 len = IOBUF_SIZE - s->zstream.avail_out;
6095 if (len > 0) {
6096 ram_put_cblock(s, s->buf, len);
6098 s->zstream.avail_out = IOBUF_SIZE;
6099 s->zstream.next_out = s->buf;
6100 if (ret == Z_STREAM_END)
6101 break;
6102 } else {
6103 goto fail;
6106 fail:
6107 deflateEnd(&s->zstream);
6110 typedef struct RamDecompressState {
6111 z_stream zstream;
6112 QEMUFile *f;
6113 uint8_t buf[IOBUF_SIZE];
6114 } RamDecompressState;
6116 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6118 int ret;
6119 memset(s, 0, sizeof(*s));
6120 s->f = f;
6121 ret = inflateInit(&s->zstream);
6122 if (ret != Z_OK)
6123 return -1;
6124 return 0;
6127 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6129 int ret, clen;
6131 s->zstream.avail_out = len;
6132 s->zstream.next_out = buf;
6133 while (s->zstream.avail_out > 0) {
6134 if (s->zstream.avail_in == 0) {
6135 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6136 return -1;
6137 clen = qemu_get_be16(s->f);
6138 if (clen > IOBUF_SIZE)
6139 return -1;
6140 qemu_get_buffer(s->f, s->buf, clen);
6141 s->zstream.avail_in = clen;
6142 s->zstream.next_in = s->buf;
6144 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6145 if (ret != Z_OK && ret != Z_STREAM_END) {
6146 return -1;
6149 return 0;
6152 static void ram_decompress_close(RamDecompressState *s)
6154 inflateEnd(&s->zstream);
6157 static void ram_save(QEMUFile *f, void *opaque)
6159 int i;
6160 RamCompressState s1, *s = &s1;
6161 uint8_t buf[10];
6163 qemu_put_be32(f, phys_ram_size);
6164 if (ram_compress_open(s, f) < 0)
6165 return;
6166 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6167 #if 0
6168 if (tight_savevm_enabled) {
6169 int64_t sector_num;
6170 int j;
6172 /* find if the memory block is available on a virtual
6173 block device */
6174 sector_num = -1;
6175 for(j = 0; j < MAX_DISKS; j++) {
6176 if (bs_table[j]) {
6177 sector_num = bdrv_hash_find(bs_table[j],
6178 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6179 if (sector_num >= 0)
6180 break;
6183 if (j == MAX_DISKS)
6184 goto normal_compress;
6185 buf[0] = 1;
6186 buf[1] = j;
6187 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6188 ram_compress_buf(s, buf, 10);
6189 } else
6190 #endif
6192 // normal_compress:
6193 buf[0] = 0;
6194 ram_compress_buf(s, buf, 1);
6195 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6198 ram_compress_close(s);
6201 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6203 RamDecompressState s1, *s = &s1;
6204 uint8_t buf[10];
6205 int i;
6207 if (version_id == 1)
6208 return ram_load_v1(f, opaque);
6209 if (version_id != 2)
6210 return -EINVAL;
6211 if (qemu_get_be32(f) != phys_ram_size)
6212 return -EINVAL;
6213 if (ram_decompress_open(s, f) < 0)
6214 return -EINVAL;
6215 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6216 if (ram_decompress_buf(s, buf, 1) < 0) {
6217 fprintf(stderr, "Error while reading ram block header\n");
6218 goto error;
6220 if (buf[0] == 0) {
6221 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6222 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6223 goto error;
6225 } else
6226 #if 0
6227 if (buf[0] == 1) {
6228 int bs_index;
6229 int64_t sector_num;
6231 ram_decompress_buf(s, buf + 1, 9);
6232 bs_index = buf[1];
6233 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6234 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6235 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6236 goto error;
6238 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6239 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6240 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6241 bs_index, sector_num);
6242 goto error;
6244 } else
6245 #endif
6247 error:
6248 printf("Error block header\n");
6249 return -EINVAL;
6252 ram_decompress_close(s);
6253 return 0;
6256 /***********************************************************/
6257 /* bottom halves (can be seen as timers which expire ASAP) */
6259 struct QEMUBH {
6260 QEMUBHFunc *cb;
6261 void *opaque;
6262 int scheduled;
6263 QEMUBH *next;
6266 static QEMUBH *first_bh = NULL;
6268 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6270 QEMUBH *bh;
6271 bh = qemu_mallocz(sizeof(QEMUBH));
6272 if (!bh)
6273 return NULL;
6274 bh->cb = cb;
6275 bh->opaque = opaque;
6276 return bh;
6279 int qemu_bh_poll(void)
6281 QEMUBH *bh, **pbh;
6282 int ret;
6284 ret = 0;
6285 for(;;) {
6286 pbh = &first_bh;
6287 bh = *pbh;
6288 if (!bh)
6289 break;
6290 ret = 1;
6291 *pbh = bh->next;
6292 bh->scheduled = 0;
6293 bh->cb(bh->opaque);
6295 return ret;
6298 void qemu_bh_schedule(QEMUBH *bh)
6300 CPUState *env = cpu_single_env;
6301 if (bh->scheduled)
6302 return;
6303 bh->scheduled = 1;
6304 bh->next = first_bh;
6305 first_bh = bh;
6307 /* stop the currently executing CPU to execute the BH ASAP */
6308 if (env) {
6309 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6313 void qemu_bh_cancel(QEMUBH *bh)
6315 QEMUBH **pbh;
6316 if (bh->scheduled) {
6317 pbh = &first_bh;
6318 while (*pbh != bh)
6319 pbh = &(*pbh)->next;
6320 *pbh = bh->next;
6321 bh->scheduled = 0;
6325 void qemu_bh_delete(QEMUBH *bh)
6327 qemu_bh_cancel(bh);
6328 qemu_free(bh);
6331 /***********************************************************/
6332 /* machine registration */
6334 QEMUMachine *first_machine = NULL;
6336 int qemu_register_machine(QEMUMachine *m)
6338 QEMUMachine **pm;
6339 pm = &first_machine;
6340 while (*pm != NULL)
6341 pm = &(*pm)->next;
6342 m->next = NULL;
6343 *pm = m;
6344 return 0;
6347 QEMUMachine *find_machine(const char *name)
6349 QEMUMachine *m;
6351 for(m = first_machine; m != NULL; m = m->next) {
6352 if (!strcmp(m->name, name))
6353 return m;
6355 return NULL;
6358 /***********************************************************/
6359 /* main execution loop */
6361 void gui_update(void *opaque)
6363 DisplayState *ds = opaque;
6364 ds->dpy_refresh(ds);
6365 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6368 struct vm_change_state_entry {
6369 VMChangeStateHandler *cb;
6370 void *opaque;
6371 LIST_ENTRY (vm_change_state_entry) entries;
6374 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6376 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6377 void *opaque)
6379 VMChangeStateEntry *e;
6381 e = qemu_mallocz(sizeof (*e));
6382 if (!e)
6383 return NULL;
6385 e->cb = cb;
6386 e->opaque = opaque;
6387 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6388 return e;
6391 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6393 LIST_REMOVE (e, entries);
6394 qemu_free (e);
6397 static void vm_state_notify(int running)
6399 VMChangeStateEntry *e;
6401 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6402 e->cb(e->opaque, running);
6406 /* XXX: support several handlers */
6407 static VMStopHandler *vm_stop_cb;
6408 static void *vm_stop_opaque;
6410 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6412 vm_stop_cb = cb;
6413 vm_stop_opaque = opaque;
6414 return 0;
6417 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6419 vm_stop_cb = NULL;
6422 void vm_start(void)
6424 if (!vm_running) {
6425 cpu_enable_ticks();
6426 vm_running = 1;
6427 vm_state_notify(1);
6431 void vm_stop(int reason)
6433 if (vm_running) {
6434 cpu_disable_ticks();
6435 vm_running = 0;
6436 if (reason != 0) {
6437 if (vm_stop_cb) {
6438 vm_stop_cb(vm_stop_opaque, reason);
6441 vm_state_notify(0);
6445 /* reset/shutdown handler */
6447 typedef struct QEMUResetEntry {
6448 QEMUResetHandler *func;
6449 void *opaque;
6450 struct QEMUResetEntry *next;
6451 } QEMUResetEntry;
6453 static QEMUResetEntry *first_reset_entry;
6454 static int reset_requested;
6455 static int shutdown_requested;
6456 static int powerdown_requested;
6458 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6460 QEMUResetEntry **pre, *re;
6462 pre = &first_reset_entry;
6463 while (*pre != NULL)
6464 pre = &(*pre)->next;
6465 re = qemu_mallocz(sizeof(QEMUResetEntry));
6466 re->func = func;
6467 re->opaque = opaque;
6468 re->next = NULL;
6469 *pre = re;
6472 static void qemu_system_reset(void)
6474 QEMUResetEntry *re;
6476 /* reset all devices */
6477 for(re = first_reset_entry; re != NULL; re = re->next) {
6478 re->func(re->opaque);
6482 void qemu_system_reset_request(void)
6484 if (no_reboot) {
6485 shutdown_requested = 1;
6486 } else {
6487 reset_requested = 1;
6489 if (cpu_single_env)
6490 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6493 void qemu_system_shutdown_request(void)
6495 shutdown_requested = 1;
6496 if (cpu_single_env)
6497 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6500 void qemu_system_powerdown_request(void)
6502 powerdown_requested = 1;
6503 if (cpu_single_env)
6504 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6507 void main_loop_wait(int timeout)
6509 IOHandlerRecord *ioh;
6510 fd_set rfds, wfds, xfds;
6511 int ret, nfds;
6512 #ifdef _WIN32
6513 int ret2, i;
6514 #endif
6515 struct timeval tv;
6516 PollingEntry *pe;
6519 /* XXX: need to suppress polling by better using win32 events */
6520 ret = 0;
6521 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6522 ret |= pe->func(pe->opaque);
6524 #ifdef _WIN32
6525 if (ret == 0) {
6526 int err;
6527 WaitObjects *w = &wait_objects;
6529 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6530 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6531 if (w->func[ret - WAIT_OBJECT_0])
6532 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6534 /* Check for additional signaled events */
6535 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6537 /* Check if event is signaled */
6538 ret2 = WaitForSingleObject(w->events[i], 0);
6539 if(ret2 == WAIT_OBJECT_0) {
6540 if (w->func[i])
6541 w->func[i](w->opaque[i]);
6542 } else if (ret2 == WAIT_TIMEOUT) {
6543 } else {
6544 err = GetLastError();
6545 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6548 } else if (ret == WAIT_TIMEOUT) {
6549 } else {
6550 err = GetLastError();
6551 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6554 #endif
6555 /* poll any events */
6556 /* XXX: separate device handlers from system ones */
6557 nfds = -1;
6558 FD_ZERO(&rfds);
6559 FD_ZERO(&wfds);
6560 FD_ZERO(&xfds);
6561 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6562 if (ioh->deleted)
6563 continue;
6564 if (ioh->fd_read &&
6565 (!ioh->fd_read_poll ||
6566 ioh->fd_read_poll(ioh->opaque) != 0)) {
6567 FD_SET(ioh->fd, &rfds);
6568 if (ioh->fd > nfds)
6569 nfds = ioh->fd;
6571 if (ioh->fd_write) {
6572 FD_SET(ioh->fd, &wfds);
6573 if (ioh->fd > nfds)
6574 nfds = ioh->fd;
6578 tv.tv_sec = 0;
6579 #ifdef _WIN32
6580 tv.tv_usec = 0;
6581 #else
6582 tv.tv_usec = timeout * 1000;
6583 #endif
6584 #if defined(CONFIG_SLIRP)
6585 if (slirp_inited) {
6586 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6588 #endif
6589 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6590 if (ret > 0) {
6591 IOHandlerRecord **pioh;
6593 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6594 if (ioh->deleted)
6595 continue;
6596 if (FD_ISSET(ioh->fd, &rfds)) {
6597 ioh->fd_read(ioh->opaque);
6599 if (FD_ISSET(ioh->fd, &wfds)) {
6600 ioh->fd_write(ioh->opaque);
6604 /* remove deleted IO handlers */
6605 pioh = &first_io_handler;
6606 while (*pioh) {
6607 ioh = *pioh;
6608 if (ioh->deleted) {
6609 *pioh = ioh->next;
6610 qemu_free(ioh);
6611 } else
6612 pioh = &ioh->next;
6615 #if defined(CONFIG_SLIRP)
6616 if (slirp_inited) {
6617 if (ret < 0) {
6618 FD_ZERO(&rfds);
6619 FD_ZERO(&wfds);
6620 FD_ZERO(&xfds);
6622 slirp_select_poll(&rfds, &wfds, &xfds);
6624 #endif
6625 qemu_aio_poll();
6627 if (vm_running) {
6628 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6629 qemu_get_clock(vm_clock));
6630 /* run dma transfers, if any */
6631 DMA_run();
6634 /* real time timers */
6635 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6636 qemu_get_clock(rt_clock));
6638 /* Check bottom-halves last in case any of the earlier events triggered
6639 them. */
6640 qemu_bh_poll();
6644 static CPUState *cur_cpu;
6646 int main_loop(void)
6648 int ret, timeout;
6649 #ifdef CONFIG_PROFILER
6650 int64_t ti;
6651 #endif
6652 CPUState *env;
6654 cur_cpu = first_cpu;
6655 for(;;) {
6656 if (vm_running) {
6658 env = cur_cpu;
6659 for(;;) {
6660 /* get next cpu */
6661 env = env->next_cpu;
6662 if (!env)
6663 env = first_cpu;
6664 #ifdef CONFIG_PROFILER
6665 ti = profile_getclock();
6666 #endif
6667 ret = cpu_exec(env);
6668 #ifdef CONFIG_PROFILER
6669 qemu_time += profile_getclock() - ti;
6670 #endif
6671 if (ret == EXCP_HLT) {
6672 /* Give the next CPU a chance to run. */
6673 cur_cpu = env;
6674 continue;
6676 if (ret != EXCP_HALTED)
6677 break;
6678 /* all CPUs are halted ? */
6679 if (env == cur_cpu)
6680 break;
6682 cur_cpu = env;
6684 if (shutdown_requested) {
6685 ret = EXCP_INTERRUPT;
6686 break;
6688 if (reset_requested) {
6689 reset_requested = 0;
6690 qemu_system_reset();
6691 ret = EXCP_INTERRUPT;
6693 if (powerdown_requested) {
6694 powerdown_requested = 0;
6695 qemu_system_powerdown();
6696 ret = EXCP_INTERRUPT;
6698 if (ret == EXCP_DEBUG) {
6699 vm_stop(EXCP_DEBUG);
6701 /* If all cpus are halted then wait until the next IRQ */
6702 /* XXX: use timeout computed from timers */
6703 if (ret == EXCP_HALTED)
6704 timeout = 10;
6705 else
6706 timeout = 0;
6707 } else {
6708 timeout = 10;
6710 #ifdef CONFIG_PROFILER
6711 ti = profile_getclock();
6712 #endif
6713 main_loop_wait(timeout);
6714 #ifdef CONFIG_PROFILER
6715 dev_time += profile_getclock() - ti;
6716 #endif
6718 cpu_disable_ticks();
6719 return ret;
6722 static void help(int exitcode)
6724 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6725 "usage: %s [options] [disk_image]\n"
6726 "\n"
6727 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6728 "\n"
6729 "Standard options:\n"
6730 "-M machine select emulated machine (-M ? for list)\n"
6731 "-cpu cpu select CPU (-cpu ? for list)\n"
6732 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6733 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6734 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6735 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6736 "-mtdblock file use 'file' as on-board Flash memory image\n"
6737 "-sd file use 'file' as SecureDigital card image\n"
6738 "-pflash file use 'file' as a parallel flash image\n"
6739 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6740 "-snapshot write to temporary files instead of disk image files\n"
6741 #ifdef CONFIG_SDL
6742 "-no-frame open SDL window without a frame and window decorations\n"
6743 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6744 "-no-quit disable SDL window close capability\n"
6745 #endif
6746 #ifdef TARGET_I386
6747 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6748 #endif
6749 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6750 "-smp n set the number of CPUs to 'n' [default=1]\n"
6751 "-nographic disable graphical output and redirect serial I/Os to console\n"
6752 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6753 #ifndef _WIN32
6754 "-k language use keyboard layout (for example \"fr\" for French)\n"
6755 #endif
6756 #ifdef HAS_AUDIO
6757 "-audio-help print list of audio drivers and their options\n"
6758 "-soundhw c1,... enable audio support\n"
6759 " and only specified sound cards (comma separated list)\n"
6760 " use -soundhw ? to get the list of supported cards\n"
6761 " use -soundhw all to enable all of them\n"
6762 #endif
6763 "-localtime set the real time clock to local time [default=utc]\n"
6764 "-full-screen start in full screen\n"
6765 #ifdef TARGET_I386
6766 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6767 #endif
6768 "-usb enable the USB driver (will be the default soon)\n"
6769 "-usbdevice name add the host or guest USB device 'name'\n"
6770 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6771 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6772 #endif
6773 "-name string set the name of the guest\n"
6774 "\n"
6775 "Network options:\n"
6776 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6777 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6778 #ifdef CONFIG_SLIRP
6779 "-net user[,vlan=n][,hostname=host]\n"
6780 " connect the user mode network stack to VLAN 'n' and send\n"
6781 " hostname 'host' to DHCP clients\n"
6782 #endif
6783 #ifdef _WIN32
6784 "-net tap[,vlan=n],ifname=name\n"
6785 " connect the host TAP network interface to VLAN 'n'\n"
6786 #else
6787 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6788 " connect the host TAP network interface to VLAN 'n' and use\n"
6789 " the network script 'file' (default=%s);\n"
6790 " use 'script=no' to disable script execution;\n"
6791 " use 'fd=h' to connect to an already opened TAP interface\n"
6792 #endif
6793 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6794 " connect the vlan 'n' to another VLAN using a socket connection\n"
6795 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6796 " connect the vlan 'n' to multicast maddr and port\n"
6797 "-net none use it alone to have zero network devices; if no -net option\n"
6798 " is provided, the default is '-net nic -net user'\n"
6799 "\n"
6800 #ifdef CONFIG_SLIRP
6801 "-tftp dir allow tftp access to files in dir [-net user]\n"
6802 "-bootp file advertise file in BOOTP replies\n"
6803 #ifndef _WIN32
6804 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6805 #endif
6806 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6807 " redirect TCP or UDP connections from host to guest [-net user]\n"
6808 #endif
6809 "\n"
6810 "Linux boot specific:\n"
6811 "-kernel bzImage use 'bzImage' as kernel image\n"
6812 "-append cmdline use 'cmdline' as kernel command line\n"
6813 "-initrd file use 'file' as initial ram disk\n"
6814 "\n"
6815 "Debug/Expert options:\n"
6816 "-monitor dev redirect the monitor to char device 'dev'\n"
6817 "-serial dev redirect the serial port to char device 'dev'\n"
6818 "-parallel dev redirect the parallel port to char device 'dev'\n"
6819 "-pidfile file Write PID to 'file'\n"
6820 "-S freeze CPU at startup (use 'c' to start execution)\n"
6821 "-s wait gdb connection to port\n"
6822 "-p port set gdb connection port [default=%s]\n"
6823 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6824 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6825 " translation (t=none or lba) (usually qemu can guess them)\n"
6826 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6827 #ifdef USE_KQEMU
6828 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6829 "-no-kqemu disable KQEMU kernel module usage\n"
6830 #endif
6831 #ifdef USE_CODE_COPY
6832 "-no-code-copy disable code copy acceleration\n"
6833 #endif
6834 #ifdef TARGET_I386
6835 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6836 " (default is CL-GD5446 PCI VGA)\n"
6837 "-no-acpi disable ACPI\n"
6838 #endif
6839 "-no-reboot exit instead of rebooting\n"
6840 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6841 "-vnc display start a VNC server on display\n"
6842 #ifndef _WIN32
6843 "-daemonize daemonize QEMU after initializing\n"
6844 #endif
6845 "-option-rom rom load a file, rom, into the option ROM space\n"
6846 #ifdef TARGET_SPARC
6847 "-prom-env variable=value set OpenBIOS nvram variables\n"
6848 #endif
6849 "\n"
6850 "During emulation, the following keys are useful:\n"
6851 "ctrl-alt-f toggle full screen\n"
6852 "ctrl-alt-n switch to virtual console 'n'\n"
6853 "ctrl-alt toggle mouse and keyboard grab\n"
6854 "\n"
6855 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6857 "qemu",
6858 DEFAULT_RAM_SIZE,
6859 #ifndef _WIN32
6860 DEFAULT_NETWORK_SCRIPT,
6861 #endif
6862 DEFAULT_GDBSTUB_PORT,
6863 "/tmp/qemu.log");
6864 exit(exitcode);
6867 #define HAS_ARG 0x0001
6869 enum {
6870 QEMU_OPTION_h,
6872 QEMU_OPTION_M,
6873 QEMU_OPTION_cpu,
6874 QEMU_OPTION_fda,
6875 QEMU_OPTION_fdb,
6876 QEMU_OPTION_hda,
6877 QEMU_OPTION_hdb,
6878 QEMU_OPTION_hdc,
6879 QEMU_OPTION_hdd,
6880 QEMU_OPTION_cdrom,
6881 QEMU_OPTION_mtdblock,
6882 QEMU_OPTION_sd,
6883 QEMU_OPTION_pflash,
6884 QEMU_OPTION_boot,
6885 QEMU_OPTION_snapshot,
6886 #ifdef TARGET_I386
6887 QEMU_OPTION_no_fd_bootchk,
6888 #endif
6889 QEMU_OPTION_m,
6890 QEMU_OPTION_nographic,
6891 QEMU_OPTION_portrait,
6892 #ifdef HAS_AUDIO
6893 QEMU_OPTION_audio_help,
6894 QEMU_OPTION_soundhw,
6895 #endif
6897 QEMU_OPTION_net,
6898 QEMU_OPTION_tftp,
6899 QEMU_OPTION_bootp,
6900 QEMU_OPTION_smb,
6901 QEMU_OPTION_redir,
6903 QEMU_OPTION_kernel,
6904 QEMU_OPTION_append,
6905 QEMU_OPTION_initrd,
6907 QEMU_OPTION_S,
6908 QEMU_OPTION_s,
6909 QEMU_OPTION_p,
6910 QEMU_OPTION_d,
6911 QEMU_OPTION_hdachs,
6912 QEMU_OPTION_L,
6913 QEMU_OPTION_no_code_copy,
6914 QEMU_OPTION_k,
6915 QEMU_OPTION_localtime,
6916 QEMU_OPTION_cirrusvga,
6917 QEMU_OPTION_vmsvga,
6918 QEMU_OPTION_g,
6919 QEMU_OPTION_std_vga,
6920 QEMU_OPTION_echr,
6921 QEMU_OPTION_monitor,
6922 QEMU_OPTION_serial,
6923 QEMU_OPTION_parallel,
6924 QEMU_OPTION_loadvm,
6925 QEMU_OPTION_full_screen,
6926 QEMU_OPTION_no_frame,
6927 QEMU_OPTION_alt_grab,
6928 QEMU_OPTION_no_quit,
6929 QEMU_OPTION_pidfile,
6930 QEMU_OPTION_no_kqemu,
6931 QEMU_OPTION_kernel_kqemu,
6932 QEMU_OPTION_win2k_hack,
6933 QEMU_OPTION_usb,
6934 QEMU_OPTION_usbdevice,
6935 QEMU_OPTION_smp,
6936 QEMU_OPTION_vnc,
6937 QEMU_OPTION_no_acpi,
6938 QEMU_OPTION_no_reboot,
6939 QEMU_OPTION_show_cursor,
6940 QEMU_OPTION_daemonize,
6941 QEMU_OPTION_option_rom,
6942 QEMU_OPTION_semihosting,
6943 QEMU_OPTION_name,
6944 QEMU_OPTION_prom_env,
6945 QEMU_OPTION_old_param,
6948 typedef struct QEMUOption {
6949 const char *name;
6950 int flags;
6951 int index;
6952 } QEMUOption;
6954 const QEMUOption qemu_options[] = {
6955 { "h", 0, QEMU_OPTION_h },
6956 { "help", 0, QEMU_OPTION_h },
6958 { "M", HAS_ARG, QEMU_OPTION_M },
6959 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6960 { "fda", HAS_ARG, QEMU_OPTION_fda },
6961 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6962 { "hda", HAS_ARG, QEMU_OPTION_hda },
6963 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6964 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6965 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6966 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6967 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6968 { "sd", HAS_ARG, QEMU_OPTION_sd },
6969 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6970 { "boot", HAS_ARG, QEMU_OPTION_boot },
6971 { "snapshot", 0, QEMU_OPTION_snapshot },
6972 #ifdef TARGET_I386
6973 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6974 #endif
6975 { "m", HAS_ARG, QEMU_OPTION_m },
6976 { "nographic", 0, QEMU_OPTION_nographic },
6977 { "portrait", 0, QEMU_OPTION_portrait },
6978 { "k", HAS_ARG, QEMU_OPTION_k },
6979 #ifdef HAS_AUDIO
6980 { "audio-help", 0, QEMU_OPTION_audio_help },
6981 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6982 #endif
6984 { "net", HAS_ARG, QEMU_OPTION_net},
6985 #ifdef CONFIG_SLIRP
6986 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6987 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6988 #ifndef _WIN32
6989 { "smb", HAS_ARG, QEMU_OPTION_smb },
6990 #endif
6991 { "redir", HAS_ARG, QEMU_OPTION_redir },
6992 #endif
6994 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6995 { "append", HAS_ARG, QEMU_OPTION_append },
6996 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6998 { "S", 0, QEMU_OPTION_S },
6999 { "s", 0, QEMU_OPTION_s },
7000 { "p", HAS_ARG, QEMU_OPTION_p },
7001 { "d", HAS_ARG, QEMU_OPTION_d },
7002 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7003 { "L", HAS_ARG, QEMU_OPTION_L },
7004 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7005 #ifdef USE_KQEMU
7006 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7007 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7008 #endif
7009 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7010 { "g", 1, QEMU_OPTION_g },
7011 #endif
7012 { "localtime", 0, QEMU_OPTION_localtime },
7013 { "std-vga", 0, QEMU_OPTION_std_vga },
7014 { "echr", HAS_ARG, QEMU_OPTION_echr },
7015 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7016 { "serial", HAS_ARG, QEMU_OPTION_serial },
7017 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7018 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7019 { "full-screen", 0, QEMU_OPTION_full_screen },
7020 #ifdef CONFIG_SDL
7021 { "no-frame", 0, QEMU_OPTION_no_frame },
7022 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7023 { "no-quit", 0, QEMU_OPTION_no_quit },
7024 #endif
7025 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7026 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7027 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7028 { "smp", HAS_ARG, QEMU_OPTION_smp },
7029 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7031 /* temporary options */
7032 { "usb", 0, QEMU_OPTION_usb },
7033 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7034 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7035 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7036 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7037 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7038 { "daemonize", 0, QEMU_OPTION_daemonize },
7039 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7040 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7041 { "semihosting", 0, QEMU_OPTION_semihosting },
7042 #endif
7043 { "name", HAS_ARG, QEMU_OPTION_name },
7044 #if defined(TARGET_SPARC)
7045 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7046 #endif
7047 #if defined(TARGET_ARM)
7048 { "old-param", 0, QEMU_OPTION_old_param },
7049 #endif
7050 { NULL },
7053 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
7055 /* this stack is only used during signal handling */
7056 #define SIGNAL_STACK_SIZE 32768
7058 static uint8_t *signal_stack;
7060 #endif
7062 /* password input */
7064 int qemu_key_check(BlockDriverState *bs, const char *name)
7066 char password[256];
7067 int i;
7069 if (!bdrv_is_encrypted(bs))
7070 return 0;
7072 term_printf("%s is encrypted.\n", name);
7073 for(i = 0; i < 3; i++) {
7074 monitor_readline("Password: ", 1, password, sizeof(password));
7075 if (bdrv_set_key(bs, password) == 0)
7076 return 0;
7077 term_printf("invalid password\n");
7079 return -EPERM;
7082 static BlockDriverState *get_bdrv(int index)
7084 BlockDriverState *bs;
7086 if (index < 4) {
7087 bs = bs_table[index];
7088 } else if (index < 6) {
7089 bs = fd_table[index - 4];
7090 } else {
7091 bs = NULL;
7093 return bs;
7096 static void read_passwords(void)
7098 BlockDriverState *bs;
7099 int i;
7101 for(i = 0; i < 6; i++) {
7102 bs = get_bdrv(i);
7103 if (bs)
7104 qemu_key_check(bs, bdrv_get_device_name(bs));
7108 /* XXX: currently we cannot use simultaneously different CPUs */
7109 void register_machines(void)
7111 #if defined(TARGET_I386)
7112 qemu_register_machine(&pc_machine);
7113 qemu_register_machine(&isapc_machine);
7114 #elif defined(TARGET_PPC)
7115 qemu_register_machine(&heathrow_machine);
7116 qemu_register_machine(&core99_machine);
7117 qemu_register_machine(&prep_machine);
7118 qemu_register_machine(&ref405ep_machine);
7119 qemu_register_machine(&taihu_machine);
7120 #elif defined(TARGET_MIPS)
7121 qemu_register_machine(&mips_machine);
7122 qemu_register_machine(&mips_malta_machine);
7123 qemu_register_machine(&mips_pica61_machine);
7124 #elif defined(TARGET_SPARC)
7125 #ifdef TARGET_SPARC64
7126 qemu_register_machine(&sun4u_machine);
7127 #else
7128 qemu_register_machine(&ss5_machine);
7129 qemu_register_machine(&ss10_machine);
7130 #endif
7131 #elif defined(TARGET_ARM)
7132 qemu_register_machine(&integratorcp_machine);
7133 qemu_register_machine(&versatilepb_machine);
7134 qemu_register_machine(&versatileab_machine);
7135 qemu_register_machine(&realview_machine);
7136 qemu_register_machine(&akitapda_machine);
7137 qemu_register_machine(&spitzpda_machine);
7138 qemu_register_machine(&borzoipda_machine);
7139 qemu_register_machine(&terrierpda_machine);
7140 qemu_register_machine(&palmte_machine);
7141 #elif defined(TARGET_SH4)
7142 qemu_register_machine(&shix_machine);
7143 #elif defined(TARGET_ALPHA)
7144 /* XXX: TODO */
7145 #elif defined(TARGET_M68K)
7146 qemu_register_machine(&mcf5208evb_machine);
7147 qemu_register_machine(&an5206_machine);
7148 #else
7149 #error unsupported CPU
7150 #endif
7153 #ifdef HAS_AUDIO
7154 struct soundhw soundhw[] = {
7155 #ifdef HAS_AUDIO_CHOICE
7156 #ifdef TARGET_I386
7158 "pcspk",
7159 "PC speaker",
7162 { .init_isa = pcspk_audio_init }
7164 #endif
7166 "sb16",
7167 "Creative Sound Blaster 16",
7170 { .init_isa = SB16_init }
7173 #ifdef CONFIG_ADLIB
7175 "adlib",
7176 #ifdef HAS_YMF262
7177 "Yamaha YMF262 (OPL3)",
7178 #else
7179 "Yamaha YM3812 (OPL2)",
7180 #endif
7183 { .init_isa = Adlib_init }
7185 #endif
7187 #ifdef CONFIG_GUS
7189 "gus",
7190 "Gravis Ultrasound GF1",
7193 { .init_isa = GUS_init }
7195 #endif
7198 "es1370",
7199 "ENSONIQ AudioPCI ES1370",
7202 { .init_pci = es1370_init }
7204 #endif
7206 { NULL, NULL, 0, 0, { NULL } }
7209 static void select_soundhw (const char *optarg)
7211 struct soundhw *c;
7213 if (*optarg == '?') {
7214 show_valid_cards:
7216 printf ("Valid sound card names (comma separated):\n");
7217 for (c = soundhw; c->name; ++c) {
7218 printf ("%-11s %s\n", c->name, c->descr);
7220 printf ("\n-soundhw all will enable all of the above\n");
7221 exit (*optarg != '?');
7223 else {
7224 size_t l;
7225 const char *p;
7226 char *e;
7227 int bad_card = 0;
7229 if (!strcmp (optarg, "all")) {
7230 for (c = soundhw; c->name; ++c) {
7231 c->enabled = 1;
7233 return;
7236 p = optarg;
7237 while (*p) {
7238 e = strchr (p, ',');
7239 l = !e ? strlen (p) : (size_t) (e - p);
7241 for (c = soundhw; c->name; ++c) {
7242 if (!strncmp (c->name, p, l)) {
7243 c->enabled = 1;
7244 break;
7248 if (!c->name) {
7249 if (l > 80) {
7250 fprintf (stderr,
7251 "Unknown sound card name (too big to show)\n");
7253 else {
7254 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7255 (int) l, p);
7257 bad_card = 1;
7259 p += l + (e != NULL);
7262 if (bad_card)
7263 goto show_valid_cards;
7266 #endif
7268 #ifdef _WIN32
7269 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7271 exit(STATUS_CONTROL_C_EXIT);
7272 return TRUE;
7274 #endif
7276 #define MAX_NET_CLIENTS 32
7278 int main(int argc, char **argv)
7280 #ifdef CONFIG_GDBSTUB
7281 int use_gdbstub;
7282 const char *gdbstub_port;
7283 #endif
7284 int i, cdrom_index, pflash_index;
7285 int snapshot, linux_boot;
7286 const char *initrd_filename;
7287 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7288 const char *pflash_filename[MAX_PFLASH];
7289 const char *sd_filename;
7290 const char *mtd_filename;
7291 const char *kernel_filename, *kernel_cmdline;
7292 DisplayState *ds = &display_state;
7293 int cyls, heads, secs, translation;
7294 char net_clients[MAX_NET_CLIENTS][256];
7295 int nb_net_clients;
7296 int optind;
7297 const char *r, *optarg;
7298 CharDriverState *monitor_hd;
7299 char monitor_device[128];
7300 char serial_devices[MAX_SERIAL_PORTS][128];
7301 int serial_device_index;
7302 char parallel_devices[MAX_PARALLEL_PORTS][128];
7303 int parallel_device_index;
7304 const char *loadvm = NULL;
7305 QEMUMachine *machine;
7306 const char *cpu_model;
7307 char usb_devices[MAX_USB_CMDLINE][128];
7308 int usb_devices_index;
7309 int fds[2];
7310 const char *pid_file = NULL;
7311 VLANState *vlan;
7313 LIST_INIT (&vm_change_state_head);
7314 #ifndef _WIN32
7316 struct sigaction act;
7317 sigfillset(&act.sa_mask);
7318 act.sa_flags = 0;
7319 act.sa_handler = SIG_IGN;
7320 sigaction(SIGPIPE, &act, NULL);
7322 #else
7323 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7324 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7325 QEMU to run on a single CPU */
7327 HANDLE h;
7328 DWORD mask, smask;
7329 int i;
7330 h = GetCurrentProcess();
7331 if (GetProcessAffinityMask(h, &mask, &smask)) {
7332 for(i = 0; i < 32; i++) {
7333 if (mask & (1 << i))
7334 break;
7336 if (i != 32) {
7337 mask = 1 << i;
7338 SetProcessAffinityMask(h, mask);
7342 #endif
7344 register_machines();
7345 machine = first_machine;
7346 cpu_model = NULL;
7347 initrd_filename = NULL;
7348 for(i = 0; i < MAX_FD; i++)
7349 fd_filename[i] = NULL;
7350 for(i = 0; i < MAX_DISKS; i++)
7351 hd_filename[i] = NULL;
7352 for(i = 0; i < MAX_PFLASH; i++)
7353 pflash_filename[i] = NULL;
7354 pflash_index = 0;
7355 sd_filename = NULL;
7356 mtd_filename = NULL;
7357 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7358 vga_ram_size = VGA_RAM_SIZE;
7359 #ifdef CONFIG_GDBSTUB
7360 use_gdbstub = 0;
7361 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7362 #endif
7363 snapshot = 0;
7364 nographic = 0;
7365 kernel_filename = NULL;
7366 kernel_cmdline = "";
7367 #ifdef TARGET_PPC
7368 cdrom_index = 1;
7369 #else
7370 cdrom_index = 2;
7371 #endif
7372 cyls = heads = secs = 0;
7373 translation = BIOS_ATA_TRANSLATION_AUTO;
7374 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7376 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7377 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7378 serial_devices[i][0] = '\0';
7379 serial_device_index = 0;
7381 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7382 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7383 parallel_devices[i][0] = '\0';
7384 parallel_device_index = 0;
7386 usb_devices_index = 0;
7388 nb_net_clients = 0;
7390 nb_nics = 0;
7391 /* default mac address of the first network interface */
7393 optind = 1;
7394 for(;;) {
7395 if (optind >= argc)
7396 break;
7397 r = argv[optind];
7398 if (r[0] != '-') {
7399 hd_filename[0] = argv[optind++];
7400 } else {
7401 const QEMUOption *popt;
7403 optind++;
7404 /* Treat --foo the same as -foo. */
7405 if (r[1] == '-')
7406 r++;
7407 popt = qemu_options;
7408 for(;;) {
7409 if (!popt->name) {
7410 fprintf(stderr, "%s: invalid option -- '%s'\n",
7411 argv[0], r);
7412 exit(1);
7414 if (!strcmp(popt->name, r + 1))
7415 break;
7416 popt++;
7418 if (popt->flags & HAS_ARG) {
7419 if (optind >= argc) {
7420 fprintf(stderr, "%s: option '%s' requires an argument\n",
7421 argv[0], r);
7422 exit(1);
7424 optarg = argv[optind++];
7425 } else {
7426 optarg = NULL;
7429 switch(popt->index) {
7430 case QEMU_OPTION_M:
7431 machine = find_machine(optarg);
7432 if (!machine) {
7433 QEMUMachine *m;
7434 printf("Supported machines are:\n");
7435 for(m = first_machine; m != NULL; m = m->next) {
7436 printf("%-10s %s%s\n",
7437 m->name, m->desc,
7438 m == first_machine ? " (default)" : "");
7440 exit(*optarg != '?');
7442 break;
7443 case QEMU_OPTION_cpu:
7444 /* hw initialization will check this */
7445 if (*optarg == '?') {
7446 #if defined(TARGET_PPC)
7447 ppc_cpu_list(stdout, &fprintf);
7448 #elif defined(TARGET_ARM)
7449 arm_cpu_list();
7450 #elif defined(TARGET_MIPS)
7451 mips_cpu_list(stdout, &fprintf);
7452 #elif defined(TARGET_SPARC)
7453 sparc_cpu_list(stdout, &fprintf);
7454 #endif
7455 exit(0);
7456 } else {
7457 cpu_model = optarg;
7459 break;
7460 case QEMU_OPTION_initrd:
7461 initrd_filename = optarg;
7462 break;
7463 case QEMU_OPTION_hda:
7464 case QEMU_OPTION_hdb:
7465 case QEMU_OPTION_hdc:
7466 case QEMU_OPTION_hdd:
7468 int hd_index;
7469 hd_index = popt->index - QEMU_OPTION_hda;
7470 hd_filename[hd_index] = optarg;
7471 if (hd_index == cdrom_index)
7472 cdrom_index = -1;
7474 break;
7475 case QEMU_OPTION_mtdblock:
7476 mtd_filename = optarg;
7477 break;
7478 case QEMU_OPTION_sd:
7479 sd_filename = optarg;
7480 break;
7481 case QEMU_OPTION_pflash:
7482 if (pflash_index >= MAX_PFLASH) {
7483 fprintf(stderr, "qemu: too many parallel flash images\n");
7484 exit(1);
7486 pflash_filename[pflash_index++] = optarg;
7487 break;
7488 case QEMU_OPTION_snapshot:
7489 snapshot = 1;
7490 break;
7491 case QEMU_OPTION_hdachs:
7493 const char *p;
7494 p = optarg;
7495 cyls = strtol(p, (char **)&p, 0);
7496 if (cyls < 1 || cyls > 16383)
7497 goto chs_fail;
7498 if (*p != ',')
7499 goto chs_fail;
7500 p++;
7501 heads = strtol(p, (char **)&p, 0);
7502 if (heads < 1 || heads > 16)
7503 goto chs_fail;
7504 if (*p != ',')
7505 goto chs_fail;
7506 p++;
7507 secs = strtol(p, (char **)&p, 0);
7508 if (secs < 1 || secs > 63)
7509 goto chs_fail;
7510 if (*p == ',') {
7511 p++;
7512 if (!strcmp(p, "none"))
7513 translation = BIOS_ATA_TRANSLATION_NONE;
7514 else if (!strcmp(p, "lba"))
7515 translation = BIOS_ATA_TRANSLATION_LBA;
7516 else if (!strcmp(p, "auto"))
7517 translation = BIOS_ATA_TRANSLATION_AUTO;
7518 else
7519 goto chs_fail;
7520 } else if (*p != '\0') {
7521 chs_fail:
7522 fprintf(stderr, "qemu: invalid physical CHS format\n");
7523 exit(1);
7526 break;
7527 case QEMU_OPTION_nographic:
7528 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7529 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7530 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7531 nographic = 1;
7532 break;
7533 case QEMU_OPTION_portrait:
7534 graphic_rotate = 1;
7535 break;
7536 case QEMU_OPTION_kernel:
7537 kernel_filename = optarg;
7538 break;
7539 case QEMU_OPTION_append:
7540 kernel_cmdline = optarg;
7541 break;
7542 case QEMU_OPTION_cdrom:
7543 if (cdrom_index >= 0) {
7544 hd_filename[cdrom_index] = optarg;
7546 break;
7547 case QEMU_OPTION_boot:
7548 boot_device = optarg[0];
7549 if (boot_device != 'a' &&
7550 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7551 // Network boot
7552 boot_device != 'n' &&
7553 #endif
7554 boot_device != 'c' && boot_device != 'd') {
7555 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7556 exit(1);
7558 break;
7559 case QEMU_OPTION_fda:
7560 fd_filename[0] = optarg;
7561 break;
7562 case QEMU_OPTION_fdb:
7563 fd_filename[1] = optarg;
7564 break;
7565 #ifdef TARGET_I386
7566 case QEMU_OPTION_no_fd_bootchk:
7567 fd_bootchk = 0;
7568 break;
7569 #endif
7570 case QEMU_OPTION_no_code_copy:
7571 code_copy_enabled = 0;
7572 break;
7573 case QEMU_OPTION_net:
7574 if (nb_net_clients >= MAX_NET_CLIENTS) {
7575 fprintf(stderr, "qemu: too many network clients\n");
7576 exit(1);
7578 pstrcpy(net_clients[nb_net_clients],
7579 sizeof(net_clients[0]),
7580 optarg);
7581 nb_net_clients++;
7582 break;
7583 #ifdef CONFIG_SLIRP
7584 case QEMU_OPTION_tftp:
7585 tftp_prefix = optarg;
7586 break;
7587 case QEMU_OPTION_bootp:
7588 bootp_filename = optarg;
7589 break;
7590 #ifndef _WIN32
7591 case QEMU_OPTION_smb:
7592 net_slirp_smb(optarg);
7593 break;
7594 #endif
7595 case QEMU_OPTION_redir:
7596 net_slirp_redir(optarg);
7597 break;
7598 #endif
7599 #ifdef HAS_AUDIO
7600 case QEMU_OPTION_audio_help:
7601 AUD_help ();
7602 exit (0);
7603 break;
7604 case QEMU_OPTION_soundhw:
7605 select_soundhw (optarg);
7606 break;
7607 #endif
7608 case QEMU_OPTION_h:
7609 help(0);
7610 break;
7611 case QEMU_OPTION_m:
7612 ram_size = atoi(optarg) * 1024 * 1024;
7613 if (ram_size <= 0)
7614 help(1);
7615 if (ram_size > PHYS_RAM_MAX_SIZE) {
7616 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7617 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7618 exit(1);
7620 break;
7621 case QEMU_OPTION_d:
7623 int mask;
7624 CPULogItem *item;
7626 mask = cpu_str_to_log_mask(optarg);
7627 if (!mask) {
7628 printf("Log items (comma separated):\n");
7629 for(item = cpu_log_items; item->mask != 0; item++) {
7630 printf("%-10s %s\n", item->name, item->help);
7632 exit(1);
7634 cpu_set_log(mask);
7636 break;
7637 #ifdef CONFIG_GDBSTUB
7638 case QEMU_OPTION_s:
7639 use_gdbstub = 1;
7640 break;
7641 case QEMU_OPTION_p:
7642 gdbstub_port = optarg;
7643 break;
7644 #endif
7645 case QEMU_OPTION_L:
7646 bios_dir = optarg;
7647 break;
7648 case QEMU_OPTION_S:
7649 autostart = 0;
7650 break;
7651 case QEMU_OPTION_k:
7652 keyboard_layout = optarg;
7653 break;
7654 case QEMU_OPTION_localtime:
7655 rtc_utc = 0;
7656 break;
7657 case QEMU_OPTION_cirrusvga:
7658 cirrus_vga_enabled = 1;
7659 vmsvga_enabled = 0;
7660 break;
7661 case QEMU_OPTION_vmsvga:
7662 cirrus_vga_enabled = 0;
7663 vmsvga_enabled = 1;
7664 break;
7665 case QEMU_OPTION_std_vga:
7666 cirrus_vga_enabled = 0;
7667 vmsvga_enabled = 0;
7668 break;
7669 case QEMU_OPTION_g:
7671 const char *p;
7672 int w, h, depth;
7673 p = optarg;
7674 w = strtol(p, (char **)&p, 10);
7675 if (w <= 0) {
7676 graphic_error:
7677 fprintf(stderr, "qemu: invalid resolution or depth\n");
7678 exit(1);
7680 if (*p != 'x')
7681 goto graphic_error;
7682 p++;
7683 h = strtol(p, (char **)&p, 10);
7684 if (h <= 0)
7685 goto graphic_error;
7686 if (*p == 'x') {
7687 p++;
7688 depth = strtol(p, (char **)&p, 10);
7689 if (depth != 8 && depth != 15 && depth != 16 &&
7690 depth != 24 && depth != 32)
7691 goto graphic_error;
7692 } else if (*p == '\0') {
7693 depth = graphic_depth;
7694 } else {
7695 goto graphic_error;
7698 graphic_width = w;
7699 graphic_height = h;
7700 graphic_depth = depth;
7702 break;
7703 case QEMU_OPTION_echr:
7705 char *r;
7706 term_escape_char = strtol(optarg, &r, 0);
7707 if (r == optarg)
7708 printf("Bad argument to echr\n");
7709 break;
7711 case QEMU_OPTION_monitor:
7712 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7713 break;
7714 case QEMU_OPTION_serial:
7715 if (serial_device_index >= MAX_SERIAL_PORTS) {
7716 fprintf(stderr, "qemu: too many serial ports\n");
7717 exit(1);
7719 pstrcpy(serial_devices[serial_device_index],
7720 sizeof(serial_devices[0]), optarg);
7721 serial_device_index++;
7722 break;
7723 case QEMU_OPTION_parallel:
7724 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7725 fprintf(stderr, "qemu: too many parallel ports\n");
7726 exit(1);
7728 pstrcpy(parallel_devices[parallel_device_index],
7729 sizeof(parallel_devices[0]), optarg);
7730 parallel_device_index++;
7731 break;
7732 case QEMU_OPTION_loadvm:
7733 loadvm = optarg;
7734 break;
7735 case QEMU_OPTION_full_screen:
7736 full_screen = 1;
7737 break;
7738 #ifdef CONFIG_SDL
7739 case QEMU_OPTION_no_frame:
7740 no_frame = 1;
7741 break;
7742 case QEMU_OPTION_alt_grab:
7743 alt_grab = 1;
7744 break;
7745 case QEMU_OPTION_no_quit:
7746 no_quit = 1;
7747 break;
7748 #endif
7749 case QEMU_OPTION_pidfile:
7750 pid_file = optarg;
7751 break;
7752 #ifdef TARGET_I386
7753 case QEMU_OPTION_win2k_hack:
7754 win2k_install_hack = 1;
7755 break;
7756 #endif
7757 #ifdef USE_KQEMU
7758 case QEMU_OPTION_no_kqemu:
7759 kqemu_allowed = 0;
7760 break;
7761 case QEMU_OPTION_kernel_kqemu:
7762 kqemu_allowed = 2;
7763 break;
7764 #endif
7765 case QEMU_OPTION_usb:
7766 usb_enabled = 1;
7767 break;
7768 case QEMU_OPTION_usbdevice:
7769 usb_enabled = 1;
7770 if (usb_devices_index >= MAX_USB_CMDLINE) {
7771 fprintf(stderr, "Too many USB devices\n");
7772 exit(1);
7774 pstrcpy(usb_devices[usb_devices_index],
7775 sizeof(usb_devices[usb_devices_index]),
7776 optarg);
7777 usb_devices_index++;
7778 break;
7779 case QEMU_OPTION_smp:
7780 smp_cpus = atoi(optarg);
7781 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7782 fprintf(stderr, "Invalid number of CPUs\n");
7783 exit(1);
7785 break;
7786 case QEMU_OPTION_vnc:
7787 vnc_display = optarg;
7788 break;
7789 case QEMU_OPTION_no_acpi:
7790 acpi_enabled = 0;
7791 break;
7792 case QEMU_OPTION_no_reboot:
7793 no_reboot = 1;
7794 break;
7795 case QEMU_OPTION_show_cursor:
7796 cursor_hide = 0;
7797 break;
7798 case QEMU_OPTION_daemonize:
7799 daemonize = 1;
7800 break;
7801 case QEMU_OPTION_option_rom:
7802 if (nb_option_roms >= MAX_OPTION_ROMS) {
7803 fprintf(stderr, "Too many option ROMs\n");
7804 exit(1);
7806 option_rom[nb_option_roms] = optarg;
7807 nb_option_roms++;
7808 break;
7809 case QEMU_OPTION_semihosting:
7810 semihosting_enabled = 1;
7811 break;
7812 case QEMU_OPTION_name:
7813 qemu_name = optarg;
7814 break;
7815 #ifdef TARGET_SPARC
7816 case QEMU_OPTION_prom_env:
7817 if (nb_prom_envs >= MAX_PROM_ENVS) {
7818 fprintf(stderr, "Too many prom variables\n");
7819 exit(1);
7821 prom_envs[nb_prom_envs] = optarg;
7822 nb_prom_envs++;
7823 break;
7824 #endif
7825 #ifdef TARGET_ARM
7826 case QEMU_OPTION_old_param:
7827 old_param = 1;
7828 #endif
7833 #ifndef _WIN32
7834 if (daemonize && !nographic && vnc_display == NULL) {
7835 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7836 daemonize = 0;
7839 if (daemonize) {
7840 pid_t pid;
7842 if (pipe(fds) == -1)
7843 exit(1);
7845 pid = fork();
7846 if (pid > 0) {
7847 uint8_t status;
7848 ssize_t len;
7850 close(fds[1]);
7852 again:
7853 len = read(fds[0], &status, 1);
7854 if (len == -1 && (errno == EINTR))
7855 goto again;
7857 if (len != 1)
7858 exit(1);
7859 else if (status == 1) {
7860 fprintf(stderr, "Could not acquire pidfile\n");
7861 exit(1);
7862 } else
7863 exit(0);
7864 } else if (pid < 0)
7865 exit(1);
7867 setsid();
7869 pid = fork();
7870 if (pid > 0)
7871 exit(0);
7872 else if (pid < 0)
7873 exit(1);
7875 umask(027);
7876 chdir("/");
7878 signal(SIGTSTP, SIG_IGN);
7879 signal(SIGTTOU, SIG_IGN);
7880 signal(SIGTTIN, SIG_IGN);
7882 #endif
7884 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7885 if (daemonize) {
7886 uint8_t status = 1;
7887 write(fds[1], &status, 1);
7888 } else
7889 fprintf(stderr, "Could not acquire pid file\n");
7890 exit(1);
7893 #ifdef USE_KQEMU
7894 if (smp_cpus > 1)
7895 kqemu_allowed = 0;
7896 #endif
7897 linux_boot = (kernel_filename != NULL);
7899 if (!linux_boot &&
7900 boot_device != 'n' &&
7901 hd_filename[0] == '\0' &&
7902 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7903 fd_filename[0] == '\0')
7904 help(1);
7906 /* boot to floppy or the default cd if no hard disk defined yet */
7907 if (hd_filename[0] == '\0' && boot_device == 'c') {
7908 if (fd_filename[0] != '\0')
7909 boot_device = 'a';
7910 else
7911 boot_device = 'd';
7914 setvbuf(stdout, NULL, _IOLBF, 0);
7916 init_timers();
7917 init_timer_alarm();
7918 qemu_aio_init();
7920 #ifdef _WIN32
7921 socket_init();
7922 #endif
7924 /* init network clients */
7925 if (nb_net_clients == 0) {
7926 /* if no clients, we use a default config */
7927 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7928 "nic");
7929 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7930 "user");
7931 nb_net_clients = 2;
7934 for(i = 0;i < nb_net_clients; i++) {
7935 if (net_client_init(net_clients[i]) < 0)
7936 exit(1);
7938 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7939 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7940 continue;
7941 if (vlan->nb_guest_devs == 0) {
7942 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7943 exit(1);
7945 if (vlan->nb_host_devs == 0)
7946 fprintf(stderr,
7947 "Warning: vlan %d is not connected to host network\n",
7948 vlan->id);
7951 #ifdef TARGET_I386
7952 if (boot_device == 'n') {
7953 for (i = 0; i < nb_nics; i++) {
7954 const char *model = nd_table[i].model;
7955 char buf[1024];
7956 if (model == NULL)
7957 model = "ne2k_pci";
7958 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7959 if (get_image_size(buf) > 0) {
7960 option_rom[nb_option_roms] = strdup(buf);
7961 nb_option_roms++;
7962 break;
7965 if (i == nb_nics) {
7966 fprintf(stderr, "No valid PXE rom found for network device\n");
7967 exit(1);
7969 boot_device = 'c'; /* to prevent confusion by the BIOS */
7971 #endif
7973 /* init the memory */
7974 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7976 phys_ram_base = qemu_vmalloc(phys_ram_size);
7977 if (!phys_ram_base) {
7978 fprintf(stderr, "Could not allocate physical memory\n");
7979 exit(1);
7982 /* we always create the cdrom drive, even if no disk is there */
7983 bdrv_init();
7984 if (cdrom_index >= 0) {
7985 bs_table[cdrom_index] = bdrv_new("cdrom");
7986 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7989 /* open the virtual block devices */
7990 for(i = 0; i < MAX_DISKS; i++) {
7991 if (hd_filename[i]) {
7992 if (!bs_table[i]) {
7993 char buf[64];
7994 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7995 bs_table[i] = bdrv_new(buf);
7997 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7998 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7999 hd_filename[i]);
8000 exit(1);
8002 if (i == 0 && cyls != 0) {
8003 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8004 bdrv_set_translation_hint(bs_table[i], translation);
8009 /* we always create at least one floppy disk */
8010 fd_table[0] = bdrv_new("fda");
8011 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8013 for(i = 0; i < MAX_FD; i++) {
8014 if (fd_filename[i]) {
8015 if (!fd_table[i]) {
8016 char buf[64];
8017 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8018 fd_table[i] = bdrv_new(buf);
8019 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8021 if (fd_filename[i][0] != '\0') {
8022 if (bdrv_open(fd_table[i], fd_filename[i],
8023 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8024 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8025 fd_filename[i]);
8026 exit(1);
8032 /* Open the virtual parallel flash block devices */
8033 for(i = 0; i < MAX_PFLASH; i++) {
8034 if (pflash_filename[i]) {
8035 if (!pflash_table[i]) {
8036 char buf[64];
8037 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8038 pflash_table[i] = bdrv_new(buf);
8040 if (bdrv_open(pflash_table[i], pflash_filename[i],
8041 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8042 fprintf(stderr, "qemu: could not open flash image '%s'\n",
8043 pflash_filename[i]);
8044 exit(1);
8049 sd_bdrv = bdrv_new ("sd");
8050 /* FIXME: This isn't really a floppy, but it's a reasonable
8051 approximation. */
8052 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8053 if (sd_filename) {
8054 if (bdrv_open(sd_bdrv, sd_filename,
8055 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8056 fprintf(stderr, "qemu: could not open SD card image %s\n",
8057 sd_filename);
8058 } else
8059 qemu_key_check(sd_bdrv, sd_filename);
8062 if (mtd_filename) {
8063 mtd_bdrv = bdrv_new ("mtd");
8064 if (bdrv_open(mtd_bdrv, mtd_filename,
8065 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8066 qemu_key_check(mtd_bdrv, mtd_filename)) {
8067 fprintf(stderr, "qemu: could not open Flash image %s\n",
8068 mtd_filename);
8069 bdrv_delete(mtd_bdrv);
8070 mtd_bdrv = 0;
8074 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8075 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8077 init_ioports();
8079 /* terminal init */
8080 memset(&display_state, 0, sizeof(display_state));
8081 if (nographic) {
8082 /* nearly nothing to do */
8083 dumb_display_init(ds);
8084 } else if (vnc_display != NULL) {
8085 vnc_display_init(ds, vnc_display);
8086 } else {
8087 #if defined(CONFIG_SDL)
8088 sdl_display_init(ds, full_screen, no_frame);
8089 #elif defined(CONFIG_COCOA)
8090 cocoa_display_init(ds, full_screen);
8091 #endif
8094 /* Maintain compatibility with multiple stdio monitors */
8095 if (!strcmp(monitor_device,"stdio")) {
8096 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8097 if (!strcmp(serial_devices[i],"mon:stdio")) {
8098 monitor_device[0] = '\0';
8099 break;
8100 } else if (!strcmp(serial_devices[i],"stdio")) {
8101 monitor_device[0] = '\0';
8102 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8103 break;
8107 if (monitor_device[0] != '\0') {
8108 monitor_hd = qemu_chr_open(monitor_device);
8109 if (!monitor_hd) {
8110 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8111 exit(1);
8113 monitor_init(monitor_hd, !nographic);
8116 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8117 const char *devname = serial_devices[i];
8118 if (devname[0] != '\0' && strcmp(devname, "none")) {
8119 serial_hds[i] = qemu_chr_open(devname);
8120 if (!serial_hds[i]) {
8121 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8122 devname);
8123 exit(1);
8125 if (strstart(devname, "vc", 0))
8126 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8130 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8131 const char *devname = parallel_devices[i];
8132 if (devname[0] != '\0' && strcmp(devname, "none")) {
8133 parallel_hds[i] = qemu_chr_open(devname);
8134 if (!parallel_hds[i]) {
8135 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8136 devname);
8137 exit(1);
8139 if (strstart(devname, "vc", 0))
8140 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8144 machine->init(ram_size, vga_ram_size, boot_device,
8145 ds, fd_filename, snapshot,
8146 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8148 /* init USB devices */
8149 if (usb_enabled) {
8150 for(i = 0; i < usb_devices_index; i++) {
8151 if (usb_device_add(usb_devices[i]) < 0) {
8152 fprintf(stderr, "Warning: could not add USB device %s\n",
8153 usb_devices[i]);
8158 if (display_state.dpy_refresh) {
8159 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8160 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8163 #ifdef CONFIG_GDBSTUB
8164 if (use_gdbstub) {
8165 /* XXX: use standard host:port notation and modify options
8166 accordingly. */
8167 if (gdbserver_start(gdbstub_port) < 0) {
8168 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8169 gdbstub_port);
8170 exit(1);
8173 #endif
8175 if (loadvm)
8176 do_loadvm(loadvm);
8179 /* XXX: simplify init */
8180 read_passwords();
8181 if (autostart) {
8182 vm_start();
8186 if (daemonize) {
8187 uint8_t status = 0;
8188 ssize_t len;
8189 int fd;
8191 again1:
8192 len = write(fds[1], &status, 1);
8193 if (len == -1 && (errno == EINTR))
8194 goto again1;
8196 if (len != 1)
8197 exit(1);
8199 TFR(fd = open("/dev/null", O_RDWR));
8200 if (fd == -1)
8201 exit(1);
8203 dup2(fd, 0);
8204 dup2(fd, 1);
8205 dup2(fd, 2);
8207 close(fd);
8210 main_loop();
8211 quit_timers();
8212 return 0;