Fix char* signedness, by Andre Przywara.
[qemu/qemu_0_9_1_stable.git] / vl.c
blob3c8ba25ed2b3fb0fe7a84b441644d00a8cc93575
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2007 Fabrice Bellard
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 "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/fdc.h"
30 #include "hw/audiodev.h"
31 #include "hw/isa.h"
32 #include "net.h"
33 #include "console.h"
34 #include "sysemu.h"
35 #include "gdbstub.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
38 #include "block.h"
39 #include "audio/audio.h"
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <time.h>
45 #include <errno.h>
46 #include <sys/time.h>
47 #include <zlib.h>
49 #ifndef _WIN32
50 #include <sys/times.h>
51 #include <sys/wait.h>
52 #include <termios.h>
53 #include <sys/poll.h>
54 #include <sys/mman.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <dirent.h>
59 #include <netdb.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
62 #ifdef _BSD
63 #include <sys/stat.h>
64 #ifndef __APPLE__
65 #include <libutil.h>
66 #endif
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
69 #else
70 #ifndef __sun__
71 #include <linux/if.h>
72 #include <linux/if_tun.h>
73 #include <pty.h>
74 #include <malloc.h>
75 #include <linux/rtc.h>
77 /* For the benefit of older linux systems which don't supply it,
78 we use a local copy of hpet.h. */
79 /* #include <linux/hpet.h> */
80 #include "hpet.h"
82 #include <linux/ppdev.h>
83 #include <linux/parport.h>
84 #else
85 #include <sys/stat.h>
86 #include <sys/ethernet.h>
87 #include <sys/sockio.h>
88 #include <netinet/arp.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> // must come after ip.h
93 #include <netinet/udp.h>
94 #include <netinet/tcp.h>
95 #include <net/if.h>
96 #include <syslog.h>
97 #include <stropts.h>
98 #endif
99 #endif
100 #else
101 #include <winsock2.h>
102 int inet_aton(const char *cp, struct in_addr *ia);
103 #endif
105 #if defined(CONFIG_SLIRP)
106 #include "libslirp.h"
107 #endif
109 #ifdef _WIN32
110 #include <malloc.h>
111 #include <sys/timeb.h>
112 #include <windows.h>
113 #define getopt_long_only getopt_long
114 #define memalign(align, size) malloc(size)
115 #endif
117 #include "qemu_socket.h"
119 #ifdef CONFIG_SDL
120 #ifdef __APPLE__
121 #include <SDL/SDL.h>
122 #endif
123 #endif /* CONFIG_SDL */
125 #ifdef CONFIG_COCOA
126 #undef main
127 #define main qemu_main
128 #endif /* CONFIG_COCOA */
130 #include "disas.h"
132 #include "exec-all.h"
134 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
136 #ifdef __sun__
137 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
138 #else
139 #define SMBD_COMMAND "/usr/sbin/smbd"
140 #endif
142 //#define DEBUG_UNUSED_IOPORT
143 //#define DEBUG_IOPORT
145 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
147 #ifdef TARGET_PPC
148 #define DEFAULT_RAM_SIZE 144
149 #else
150 #define DEFAULT_RAM_SIZE 128
151 #endif
152 /* in ms */
153 #define GUI_REFRESH_INTERVAL 30
155 /* Max number of USB devices that can be specified on the commandline. */
156 #define MAX_USB_CMDLINE 8
158 /* XXX: use a two level table to limit memory usage */
159 #define MAX_IOPORTS 65536
161 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
162 const char *bios_name = NULL;
163 void *ioport_opaque[MAX_IOPORTS];
164 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
165 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
166 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
167 to store the VM snapshots */
168 DriveInfo drives_table[MAX_DRIVES+1];
169 int nb_drives;
170 /* point to the block driver where the snapshots are managed */
171 BlockDriverState *bs_snapshots;
172 int vga_ram_size;
173 static DisplayState display_state;
174 int nographic;
175 const char* keyboard_layout = NULL;
176 int64_t ticks_per_sec;
177 int ram_size;
178 int pit_min_timer_count = 0;
179 int nb_nics;
180 NICInfo nd_table[MAX_NICS];
181 int vm_running;
182 int rtc_utc = 1;
183 int rtc_start_date = -1; /* -1 means now */
184 int cirrus_vga_enabled = 1;
185 int vmsvga_enabled = 0;
186 #ifdef TARGET_SPARC
187 int graphic_width = 1024;
188 int graphic_height = 768;
189 int graphic_depth = 8;
190 #else
191 int graphic_width = 800;
192 int graphic_height = 600;
193 int graphic_depth = 15;
194 #endif
195 int full_screen = 0;
196 int no_frame = 0;
197 int no_quit = 0;
198 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
199 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
200 #ifdef TARGET_I386
201 int win2k_install_hack = 0;
202 #endif
203 int usb_enabled = 0;
204 static VLANState *first_vlan;
205 int smp_cpus = 1;
206 const char *vnc_display;
207 #if defined(TARGET_SPARC)
208 #define MAX_CPUS 16
209 #elif defined(TARGET_I386)
210 #define MAX_CPUS 255
211 #else
212 #define MAX_CPUS 1
213 #endif
214 int acpi_enabled = 1;
215 int fd_bootchk = 1;
216 int no_reboot = 0;
217 int cursor_hide = 1;
218 int graphic_rotate = 0;
219 int daemonize = 0;
220 const char *option_rom[MAX_OPTION_ROMS];
221 int nb_option_roms;
222 int semihosting_enabled = 0;
223 int autostart = 1;
224 #ifdef TARGET_ARM
225 int old_param = 0;
226 #endif
227 const char *qemu_name;
228 int alt_grab = 0;
229 #ifdef TARGET_SPARC
230 unsigned int nb_prom_envs = 0;
231 const char *prom_envs[MAX_PROM_ENVS];
232 #endif
233 int nb_drives_opt;
234 char drives_opt[MAX_DRIVES][1024];
236 static CPUState *cur_cpu;
237 static CPUState *next_cpu;
238 static int event_pending;
240 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
242 /***********************************************************/
243 /* x86 ISA bus support */
245 target_phys_addr_t isa_mem_base = 0;
246 PicState2 *isa_pic;
248 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
250 #ifdef DEBUG_UNUSED_IOPORT
251 fprintf(stderr, "unused inb: port=0x%04x\n", address);
252 #endif
253 return 0xff;
256 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
258 #ifdef DEBUG_UNUSED_IOPORT
259 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
260 #endif
263 /* default is to make two byte accesses */
264 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
266 uint32_t data;
267 data = ioport_read_table[0][address](ioport_opaque[address], address);
268 address = (address + 1) & (MAX_IOPORTS - 1);
269 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
270 return data;
273 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
275 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
276 address = (address + 1) & (MAX_IOPORTS - 1);
277 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
280 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
282 #ifdef DEBUG_UNUSED_IOPORT
283 fprintf(stderr, "unused inl: port=0x%04x\n", address);
284 #endif
285 return 0xffffffff;
288 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
290 #ifdef DEBUG_UNUSED_IOPORT
291 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
292 #endif
295 static void init_ioports(void)
297 int i;
299 for(i = 0; i < MAX_IOPORTS; i++) {
300 ioport_read_table[0][i] = default_ioport_readb;
301 ioport_write_table[0][i] = default_ioport_writeb;
302 ioport_read_table[1][i] = default_ioport_readw;
303 ioport_write_table[1][i] = default_ioport_writew;
304 ioport_read_table[2][i] = default_ioport_readl;
305 ioport_write_table[2][i] = default_ioport_writel;
309 /* size is the word size in byte */
310 int register_ioport_read(int start, int length, int size,
311 IOPortReadFunc *func, void *opaque)
313 int i, bsize;
315 if (size == 1) {
316 bsize = 0;
317 } else if (size == 2) {
318 bsize = 1;
319 } else if (size == 4) {
320 bsize = 2;
321 } else {
322 hw_error("register_ioport_read: invalid size");
323 return -1;
325 for(i = start; i < start + length; i += size) {
326 ioport_read_table[bsize][i] = func;
327 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
328 hw_error("register_ioport_read: invalid opaque");
329 ioport_opaque[i] = opaque;
331 return 0;
334 /* size is the word size in byte */
335 int register_ioport_write(int start, int length, int size,
336 IOPortWriteFunc *func, void *opaque)
338 int i, bsize;
340 if (size == 1) {
341 bsize = 0;
342 } else if (size == 2) {
343 bsize = 1;
344 } else if (size == 4) {
345 bsize = 2;
346 } else {
347 hw_error("register_ioport_write: invalid size");
348 return -1;
350 for(i = start; i < start + length; i += size) {
351 ioport_write_table[bsize][i] = func;
352 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
353 hw_error("register_ioport_write: invalid opaque");
354 ioport_opaque[i] = opaque;
356 return 0;
359 void isa_unassign_ioport(int start, int length)
361 int i;
363 for(i = start; i < start + length; i++) {
364 ioport_read_table[0][i] = default_ioport_readb;
365 ioport_read_table[1][i] = default_ioport_readw;
366 ioport_read_table[2][i] = default_ioport_readl;
368 ioport_write_table[0][i] = default_ioport_writeb;
369 ioport_write_table[1][i] = default_ioport_writew;
370 ioport_write_table[2][i] = default_ioport_writel;
374 /***********************************************************/
376 void cpu_outb(CPUState *env, int addr, int val)
378 #ifdef DEBUG_IOPORT
379 if (loglevel & CPU_LOG_IOPORT)
380 fprintf(logfile, "outb: %04x %02x\n", addr, val);
381 #endif
382 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
383 #ifdef USE_KQEMU
384 if (env)
385 env->last_io_time = cpu_get_time_fast();
386 #endif
389 void cpu_outw(CPUState *env, int addr, int val)
391 #ifdef DEBUG_IOPORT
392 if (loglevel & CPU_LOG_IOPORT)
393 fprintf(logfile, "outw: %04x %04x\n", addr, val);
394 #endif
395 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
396 #ifdef USE_KQEMU
397 if (env)
398 env->last_io_time = cpu_get_time_fast();
399 #endif
402 void cpu_outl(CPUState *env, int addr, int val)
404 #ifdef DEBUG_IOPORT
405 if (loglevel & CPU_LOG_IOPORT)
406 fprintf(logfile, "outl: %04x %08x\n", addr, val);
407 #endif
408 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
409 #ifdef USE_KQEMU
410 if (env)
411 env->last_io_time = cpu_get_time_fast();
412 #endif
415 int cpu_inb(CPUState *env, int addr)
417 int val;
418 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
419 #ifdef DEBUG_IOPORT
420 if (loglevel & CPU_LOG_IOPORT)
421 fprintf(logfile, "inb : %04x %02x\n", addr, val);
422 #endif
423 #ifdef USE_KQEMU
424 if (env)
425 env->last_io_time = cpu_get_time_fast();
426 #endif
427 return val;
430 int cpu_inw(CPUState *env, int addr)
432 int val;
433 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
434 #ifdef DEBUG_IOPORT
435 if (loglevel & CPU_LOG_IOPORT)
436 fprintf(logfile, "inw : %04x %04x\n", addr, val);
437 #endif
438 #ifdef USE_KQEMU
439 if (env)
440 env->last_io_time = cpu_get_time_fast();
441 #endif
442 return val;
445 int cpu_inl(CPUState *env, int addr)
447 int val;
448 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
449 #ifdef DEBUG_IOPORT
450 if (loglevel & CPU_LOG_IOPORT)
451 fprintf(logfile, "inl : %04x %08x\n", addr, val);
452 #endif
453 #ifdef USE_KQEMU
454 if (env)
455 env->last_io_time = cpu_get_time_fast();
456 #endif
457 return val;
460 /***********************************************************/
461 void hw_error(const char *fmt, ...)
463 va_list ap;
464 CPUState *env;
466 va_start(ap, fmt);
467 fprintf(stderr, "qemu: hardware error: ");
468 vfprintf(stderr, fmt, ap);
469 fprintf(stderr, "\n");
470 for(env = first_cpu; env != NULL; env = env->next_cpu) {
471 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
472 #ifdef TARGET_I386
473 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
474 #else
475 cpu_dump_state(env, stderr, fprintf, 0);
476 #endif
478 va_end(ap);
479 abort();
482 /***********************************************************/
483 /* keyboard/mouse */
485 static QEMUPutKBDEvent *qemu_put_kbd_event;
486 static void *qemu_put_kbd_event_opaque;
487 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
488 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
490 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
492 qemu_put_kbd_event_opaque = opaque;
493 qemu_put_kbd_event = func;
496 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
497 void *opaque, int absolute,
498 const char *name)
500 QEMUPutMouseEntry *s, *cursor;
502 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
503 if (!s)
504 return NULL;
506 s->qemu_put_mouse_event = func;
507 s->qemu_put_mouse_event_opaque = opaque;
508 s->qemu_put_mouse_event_absolute = absolute;
509 s->qemu_put_mouse_event_name = qemu_strdup(name);
510 s->next = NULL;
512 if (!qemu_put_mouse_event_head) {
513 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
514 return s;
517 cursor = qemu_put_mouse_event_head;
518 while (cursor->next != NULL)
519 cursor = cursor->next;
521 cursor->next = s;
522 qemu_put_mouse_event_current = s;
524 return s;
527 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
529 QEMUPutMouseEntry *prev = NULL, *cursor;
531 if (!qemu_put_mouse_event_head || entry == NULL)
532 return;
534 cursor = qemu_put_mouse_event_head;
535 while (cursor != NULL && cursor != entry) {
536 prev = cursor;
537 cursor = cursor->next;
540 if (cursor == NULL) // does not exist or list empty
541 return;
542 else if (prev == NULL) { // entry is head
543 qemu_put_mouse_event_head = cursor->next;
544 if (qemu_put_mouse_event_current == entry)
545 qemu_put_mouse_event_current = cursor->next;
546 qemu_free(entry->qemu_put_mouse_event_name);
547 qemu_free(entry);
548 return;
551 prev->next = entry->next;
553 if (qemu_put_mouse_event_current == entry)
554 qemu_put_mouse_event_current = prev;
556 qemu_free(entry->qemu_put_mouse_event_name);
557 qemu_free(entry);
560 void kbd_put_keycode(int keycode)
562 if (qemu_put_kbd_event) {
563 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
567 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
569 QEMUPutMouseEvent *mouse_event;
570 void *mouse_event_opaque;
571 int width;
573 if (!qemu_put_mouse_event_current) {
574 return;
577 mouse_event =
578 qemu_put_mouse_event_current->qemu_put_mouse_event;
579 mouse_event_opaque =
580 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
582 if (mouse_event) {
583 if (graphic_rotate) {
584 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
585 width = 0x7fff;
586 else
587 width = graphic_width;
588 mouse_event(mouse_event_opaque,
589 width - dy, dx, dz, buttons_state);
590 } else
591 mouse_event(mouse_event_opaque,
592 dx, dy, dz, buttons_state);
596 int kbd_mouse_is_absolute(void)
598 if (!qemu_put_mouse_event_current)
599 return 0;
601 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
604 void do_info_mice(void)
606 QEMUPutMouseEntry *cursor;
607 int index = 0;
609 if (!qemu_put_mouse_event_head) {
610 term_printf("No mouse devices connected\n");
611 return;
614 term_printf("Mouse devices available:\n");
615 cursor = qemu_put_mouse_event_head;
616 while (cursor != NULL) {
617 term_printf("%c Mouse #%d: %s\n",
618 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
619 index, cursor->qemu_put_mouse_event_name);
620 index++;
621 cursor = cursor->next;
625 void do_mouse_set(int index)
627 QEMUPutMouseEntry *cursor;
628 int i = 0;
630 if (!qemu_put_mouse_event_head) {
631 term_printf("No mouse devices connected\n");
632 return;
635 cursor = qemu_put_mouse_event_head;
636 while (cursor != NULL && index != i) {
637 i++;
638 cursor = cursor->next;
641 if (cursor != NULL)
642 qemu_put_mouse_event_current = cursor;
643 else
644 term_printf("Mouse at given index not found\n");
647 /* compute with 96 bit intermediate result: (a*b)/c */
648 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
650 union {
651 uint64_t ll;
652 struct {
653 #ifdef WORDS_BIGENDIAN
654 uint32_t high, low;
655 #else
656 uint32_t low, high;
657 #endif
658 } l;
659 } u, res;
660 uint64_t rl, rh;
662 u.ll = a;
663 rl = (uint64_t)u.l.low * (uint64_t)b;
664 rh = (uint64_t)u.l.high * (uint64_t)b;
665 rh += (rl >> 32);
666 res.l.high = rh / c;
667 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
668 return res.ll;
671 /***********************************************************/
672 /* real time host monotonic timer */
674 #define QEMU_TIMER_BASE 1000000000LL
676 #ifdef WIN32
678 static int64_t clock_freq;
680 static void init_get_clock(void)
682 LARGE_INTEGER freq;
683 int ret;
684 ret = QueryPerformanceFrequency(&freq);
685 if (ret == 0) {
686 fprintf(stderr, "Could not calibrate ticks\n");
687 exit(1);
689 clock_freq = freq.QuadPart;
692 static int64_t get_clock(void)
694 LARGE_INTEGER ti;
695 QueryPerformanceCounter(&ti);
696 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
699 #else
701 static int use_rt_clock;
703 static void init_get_clock(void)
705 use_rt_clock = 0;
706 #if defined(__linux__)
708 struct timespec ts;
709 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
710 use_rt_clock = 1;
713 #endif
716 static int64_t get_clock(void)
718 #if defined(__linux__)
719 if (use_rt_clock) {
720 struct timespec ts;
721 clock_gettime(CLOCK_MONOTONIC, &ts);
722 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
723 } else
724 #endif
726 /* XXX: using gettimeofday leads to problems if the date
727 changes, so it should be avoided. */
728 struct timeval tv;
729 gettimeofday(&tv, NULL);
730 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
734 #endif
736 /***********************************************************/
737 /* guest cycle counter */
739 static int64_t cpu_ticks_prev;
740 static int64_t cpu_ticks_offset;
741 static int64_t cpu_clock_offset;
742 static int cpu_ticks_enabled;
744 /* return the host CPU cycle counter and handle stop/restart */
745 int64_t cpu_get_ticks(void)
747 if (!cpu_ticks_enabled) {
748 return cpu_ticks_offset;
749 } else {
750 int64_t ticks;
751 ticks = cpu_get_real_ticks();
752 if (cpu_ticks_prev > ticks) {
753 /* Note: non increasing ticks may happen if the host uses
754 software suspend */
755 cpu_ticks_offset += cpu_ticks_prev - ticks;
757 cpu_ticks_prev = ticks;
758 return ticks + cpu_ticks_offset;
762 /* return the host CPU monotonic timer and handle stop/restart */
763 static int64_t cpu_get_clock(void)
765 int64_t ti;
766 if (!cpu_ticks_enabled) {
767 return cpu_clock_offset;
768 } else {
769 ti = get_clock();
770 return ti + cpu_clock_offset;
774 /* enable cpu_get_ticks() */
775 void cpu_enable_ticks(void)
777 if (!cpu_ticks_enabled) {
778 cpu_ticks_offset -= cpu_get_real_ticks();
779 cpu_clock_offset -= get_clock();
780 cpu_ticks_enabled = 1;
784 /* disable cpu_get_ticks() : the clock is stopped. You must not call
785 cpu_get_ticks() after that. */
786 void cpu_disable_ticks(void)
788 if (cpu_ticks_enabled) {
789 cpu_ticks_offset = cpu_get_ticks();
790 cpu_clock_offset = cpu_get_clock();
791 cpu_ticks_enabled = 0;
795 /***********************************************************/
796 /* timers */
798 #define QEMU_TIMER_REALTIME 0
799 #define QEMU_TIMER_VIRTUAL 1
801 struct QEMUClock {
802 int type;
803 /* XXX: add frequency */
806 struct QEMUTimer {
807 QEMUClock *clock;
808 int64_t expire_time;
809 QEMUTimerCB *cb;
810 void *opaque;
811 struct QEMUTimer *next;
814 struct qemu_alarm_timer {
815 char const *name;
816 unsigned int flags;
818 int (*start)(struct qemu_alarm_timer *t);
819 void (*stop)(struct qemu_alarm_timer *t);
820 void (*rearm)(struct qemu_alarm_timer *t);
821 void *priv;
824 #define ALARM_FLAG_DYNTICKS 0x1
826 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
828 return t->flags & ALARM_FLAG_DYNTICKS;
831 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
833 if (!alarm_has_dynticks(t))
834 return;
836 t->rearm(t);
839 /* TODO: MIN_TIMER_REARM_US should be optimized */
840 #define MIN_TIMER_REARM_US 250
842 static struct qemu_alarm_timer *alarm_timer;
844 #ifdef _WIN32
846 struct qemu_alarm_win32 {
847 MMRESULT timerId;
848 HANDLE host_alarm;
849 unsigned int period;
850 } alarm_win32_data = {0, NULL, -1};
852 static int win32_start_timer(struct qemu_alarm_timer *t);
853 static void win32_stop_timer(struct qemu_alarm_timer *t);
854 static void win32_rearm_timer(struct qemu_alarm_timer *t);
856 #else
858 static int unix_start_timer(struct qemu_alarm_timer *t);
859 static void unix_stop_timer(struct qemu_alarm_timer *t);
861 #ifdef __linux__
863 static int dynticks_start_timer(struct qemu_alarm_timer *t);
864 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
865 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
867 static int hpet_start_timer(struct qemu_alarm_timer *t);
868 static void hpet_stop_timer(struct qemu_alarm_timer *t);
870 static int rtc_start_timer(struct qemu_alarm_timer *t);
871 static void rtc_stop_timer(struct qemu_alarm_timer *t);
873 #endif /* __linux__ */
875 #endif /* _WIN32 */
877 static struct qemu_alarm_timer alarm_timers[] = {
878 #ifndef _WIN32
879 #ifdef __linux__
880 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
881 dynticks_stop_timer, dynticks_rearm_timer, NULL},
882 /* HPET - if available - is preferred */
883 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
884 /* ...otherwise try RTC */
885 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
886 #endif
887 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
888 #else
889 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
890 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
891 {"win32", 0, win32_start_timer,
892 win32_stop_timer, NULL, &alarm_win32_data},
893 #endif
894 {NULL, }
897 static void show_available_alarms()
899 int i;
901 printf("Available alarm timers, in order of precedence:\n");
902 for (i = 0; alarm_timers[i].name; i++)
903 printf("%s\n", alarm_timers[i].name);
906 static void configure_alarms(char const *opt)
908 int i;
909 int cur = 0;
910 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
911 char *arg;
912 char *name;
914 if (!strcmp(opt, "help")) {
915 show_available_alarms();
916 exit(0);
919 arg = strdup(opt);
921 /* Reorder the array */
922 name = strtok(arg, ",");
923 while (name) {
924 struct qemu_alarm_timer tmp;
926 for (i = 0; i < count && alarm_timers[i].name; i++) {
927 if (!strcmp(alarm_timers[i].name, name))
928 break;
931 if (i == count) {
932 fprintf(stderr, "Unknown clock %s\n", name);
933 goto next;
936 if (i < cur)
937 /* Ignore */
938 goto next;
940 /* Swap */
941 tmp = alarm_timers[i];
942 alarm_timers[i] = alarm_timers[cur];
943 alarm_timers[cur] = tmp;
945 cur++;
946 next:
947 name = strtok(NULL, ",");
950 free(arg);
952 if (cur) {
953 /* Disable remaining timers */
954 for (i = cur; i < count; i++)
955 alarm_timers[i].name = NULL;
958 /* debug */
959 show_available_alarms();
962 QEMUClock *rt_clock;
963 QEMUClock *vm_clock;
965 static QEMUTimer *active_timers[2];
967 static QEMUClock *qemu_new_clock(int type)
969 QEMUClock *clock;
970 clock = qemu_mallocz(sizeof(QEMUClock));
971 if (!clock)
972 return NULL;
973 clock->type = type;
974 return clock;
977 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
979 QEMUTimer *ts;
981 ts = qemu_mallocz(sizeof(QEMUTimer));
982 ts->clock = clock;
983 ts->cb = cb;
984 ts->opaque = opaque;
985 return ts;
988 void qemu_free_timer(QEMUTimer *ts)
990 qemu_free(ts);
993 /* stop a timer, but do not dealloc it */
994 void qemu_del_timer(QEMUTimer *ts)
996 QEMUTimer **pt, *t;
998 /* NOTE: this code must be signal safe because
999 qemu_timer_expired() can be called from a signal. */
1000 pt = &active_timers[ts->clock->type];
1001 for(;;) {
1002 t = *pt;
1003 if (!t)
1004 break;
1005 if (t == ts) {
1006 *pt = t->next;
1007 break;
1009 pt = &t->next;
1013 /* modify the current timer so that it will be fired when current_time
1014 >= expire_time. The corresponding callback will be called. */
1015 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1017 QEMUTimer **pt, *t;
1019 qemu_del_timer(ts);
1021 /* add the timer in the sorted list */
1022 /* NOTE: this code must be signal safe because
1023 qemu_timer_expired() can be called from a signal. */
1024 pt = &active_timers[ts->clock->type];
1025 for(;;) {
1026 t = *pt;
1027 if (!t)
1028 break;
1029 if (t->expire_time > expire_time)
1030 break;
1031 pt = &t->next;
1033 ts->expire_time = expire_time;
1034 ts->next = *pt;
1035 *pt = ts;
1038 int qemu_timer_pending(QEMUTimer *ts)
1040 QEMUTimer *t;
1041 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1042 if (t == ts)
1043 return 1;
1045 return 0;
1048 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1050 if (!timer_head)
1051 return 0;
1052 return (timer_head->expire_time <= current_time);
1055 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1057 QEMUTimer *ts;
1059 for(;;) {
1060 ts = *ptimer_head;
1061 if (!ts || ts->expire_time > current_time)
1062 break;
1063 /* remove timer from the list before calling the callback */
1064 *ptimer_head = ts->next;
1065 ts->next = NULL;
1067 /* run the callback (the timer list can be modified) */
1068 ts->cb(ts->opaque);
1070 qemu_rearm_alarm_timer(alarm_timer);
1073 int64_t qemu_get_clock(QEMUClock *clock)
1075 switch(clock->type) {
1076 case QEMU_TIMER_REALTIME:
1077 return get_clock() / 1000000;
1078 default:
1079 case QEMU_TIMER_VIRTUAL:
1080 return cpu_get_clock();
1084 static void init_timers(void)
1086 init_get_clock();
1087 ticks_per_sec = QEMU_TIMER_BASE;
1088 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1089 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1092 /* save a timer */
1093 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1095 uint64_t expire_time;
1097 if (qemu_timer_pending(ts)) {
1098 expire_time = ts->expire_time;
1099 } else {
1100 expire_time = -1;
1102 qemu_put_be64(f, expire_time);
1105 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1107 uint64_t expire_time;
1109 expire_time = qemu_get_be64(f);
1110 if (expire_time != -1) {
1111 qemu_mod_timer(ts, expire_time);
1112 } else {
1113 qemu_del_timer(ts);
1117 static void timer_save(QEMUFile *f, void *opaque)
1119 if (cpu_ticks_enabled) {
1120 hw_error("cannot save state if virtual timers are running");
1122 qemu_put_be64s(f, &cpu_ticks_offset);
1123 qemu_put_be64s(f, &ticks_per_sec);
1124 qemu_put_be64s(f, &cpu_clock_offset);
1127 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1129 if (version_id != 1 && version_id != 2)
1130 return -EINVAL;
1131 if (cpu_ticks_enabled) {
1132 return -EINVAL;
1134 qemu_get_be64s(f, &cpu_ticks_offset);
1135 qemu_get_be64s(f, &ticks_per_sec);
1136 if (version_id == 2) {
1137 qemu_get_be64s(f, &cpu_clock_offset);
1139 return 0;
1142 #ifdef _WIN32
1143 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1144 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1145 #else
1146 static void host_alarm_handler(int host_signum)
1147 #endif
1149 #if 0
1150 #define DISP_FREQ 1000
1152 static int64_t delta_min = INT64_MAX;
1153 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1154 static int count;
1155 ti = qemu_get_clock(vm_clock);
1156 if (last_clock != 0) {
1157 delta = ti - last_clock;
1158 if (delta < delta_min)
1159 delta_min = delta;
1160 if (delta > delta_max)
1161 delta_max = delta;
1162 delta_cum += delta;
1163 if (++count == DISP_FREQ) {
1164 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1165 muldiv64(delta_min, 1000000, ticks_per_sec),
1166 muldiv64(delta_max, 1000000, ticks_per_sec),
1167 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1168 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1169 count = 0;
1170 delta_min = INT64_MAX;
1171 delta_max = 0;
1172 delta_cum = 0;
1175 last_clock = ti;
1177 #endif
1178 if (alarm_has_dynticks(alarm_timer) ||
1179 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1180 qemu_get_clock(vm_clock)) ||
1181 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1182 qemu_get_clock(rt_clock))) {
1183 #ifdef _WIN32
1184 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1185 SetEvent(data->host_alarm);
1186 #endif
1187 CPUState *env = next_cpu;
1189 /* stop the currently executing cpu because a timer occured */
1190 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1191 #ifdef USE_KQEMU
1192 if (env->kqemu_enabled) {
1193 kqemu_cpu_interrupt(env);
1195 #endif
1196 event_pending = 1;
1200 static uint64_t qemu_next_deadline(void)
1202 int64_t nearest_delta_us = INT64_MAX;
1203 int64_t vmdelta_us;
1205 if (active_timers[QEMU_TIMER_REALTIME])
1206 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1207 qemu_get_clock(rt_clock))*1000;
1209 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1210 /* round up */
1211 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1212 qemu_get_clock(vm_clock)+999)/1000;
1213 if (vmdelta_us < nearest_delta_us)
1214 nearest_delta_us = vmdelta_us;
1217 /* Avoid arming the timer to negative, zero, or too low values */
1218 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1219 nearest_delta_us = MIN_TIMER_REARM_US;
1221 return nearest_delta_us;
1224 #ifndef _WIN32
1226 #if defined(__linux__)
1228 #define RTC_FREQ 1024
1230 static void enable_sigio_timer(int fd)
1232 struct sigaction act;
1234 /* timer signal */
1235 sigfillset(&act.sa_mask);
1236 act.sa_flags = 0;
1237 act.sa_handler = host_alarm_handler;
1239 sigaction(SIGIO, &act, NULL);
1240 fcntl(fd, F_SETFL, O_ASYNC);
1241 fcntl(fd, F_SETOWN, getpid());
1244 static int hpet_start_timer(struct qemu_alarm_timer *t)
1246 struct hpet_info info;
1247 int r, fd;
1249 fd = open("/dev/hpet", O_RDONLY);
1250 if (fd < 0)
1251 return -1;
1253 /* Set frequency */
1254 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1255 if (r < 0) {
1256 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1257 "error, but for better emulation accuracy type:\n"
1258 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1259 goto fail;
1262 /* Check capabilities */
1263 r = ioctl(fd, HPET_INFO, &info);
1264 if (r < 0)
1265 goto fail;
1267 /* Enable periodic mode */
1268 r = ioctl(fd, HPET_EPI, 0);
1269 if (info.hi_flags && (r < 0))
1270 goto fail;
1272 /* Enable interrupt */
1273 r = ioctl(fd, HPET_IE_ON, 0);
1274 if (r < 0)
1275 goto fail;
1277 enable_sigio_timer(fd);
1278 t->priv = (void *)(long)fd;
1280 return 0;
1281 fail:
1282 close(fd);
1283 return -1;
1286 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1288 int fd = (long)t->priv;
1290 close(fd);
1293 static int rtc_start_timer(struct qemu_alarm_timer *t)
1295 int rtc_fd;
1297 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1298 if (rtc_fd < 0)
1299 return -1;
1300 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1301 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1302 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1303 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1304 goto fail;
1306 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1307 fail:
1308 close(rtc_fd);
1309 return -1;
1312 enable_sigio_timer(rtc_fd);
1314 t->priv = (void *)(long)rtc_fd;
1316 return 0;
1319 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1321 int rtc_fd = (long)t->priv;
1323 close(rtc_fd);
1326 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1328 struct sigevent ev;
1329 timer_t host_timer;
1330 struct sigaction act;
1332 sigfillset(&act.sa_mask);
1333 act.sa_flags = 0;
1334 act.sa_handler = host_alarm_handler;
1336 sigaction(SIGALRM, &act, NULL);
1338 ev.sigev_value.sival_int = 0;
1339 ev.sigev_notify = SIGEV_SIGNAL;
1340 ev.sigev_signo = SIGALRM;
1342 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1343 perror("timer_create");
1345 /* disable dynticks */
1346 fprintf(stderr, "Dynamic Ticks disabled\n");
1348 return -1;
1351 t->priv = (void *)host_timer;
1353 return 0;
1356 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1358 timer_t host_timer = (timer_t)t->priv;
1360 timer_delete(host_timer);
1363 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1365 timer_t host_timer = (timer_t)t->priv;
1366 struct itimerspec timeout;
1367 int64_t nearest_delta_us = INT64_MAX;
1368 int64_t current_us;
1370 if (!active_timers[QEMU_TIMER_REALTIME] &&
1371 !active_timers[QEMU_TIMER_VIRTUAL])
1372 return;
1374 nearest_delta_us = qemu_next_deadline();
1376 /* check whether a timer is already running */
1377 if (timer_gettime(host_timer, &timeout)) {
1378 perror("gettime");
1379 fprintf(stderr, "Internal timer error: aborting\n");
1380 exit(1);
1382 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1383 if (current_us && current_us <= nearest_delta_us)
1384 return;
1386 timeout.it_interval.tv_sec = 0;
1387 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1388 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1389 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1390 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1391 perror("settime");
1392 fprintf(stderr, "Internal timer error: aborting\n");
1393 exit(1);
1397 #endif /* defined(__linux__) */
1399 static int unix_start_timer(struct qemu_alarm_timer *t)
1401 struct sigaction act;
1402 struct itimerval itv;
1403 int err;
1405 /* timer signal */
1406 sigfillset(&act.sa_mask);
1407 act.sa_flags = 0;
1408 act.sa_handler = host_alarm_handler;
1410 sigaction(SIGALRM, &act, NULL);
1412 itv.it_interval.tv_sec = 0;
1413 /* for i386 kernel 2.6 to get 1 ms */
1414 itv.it_interval.tv_usec = 999;
1415 itv.it_value.tv_sec = 0;
1416 itv.it_value.tv_usec = 10 * 1000;
1418 err = setitimer(ITIMER_REAL, &itv, NULL);
1419 if (err)
1420 return -1;
1422 return 0;
1425 static void unix_stop_timer(struct qemu_alarm_timer *t)
1427 struct itimerval itv;
1429 memset(&itv, 0, sizeof(itv));
1430 setitimer(ITIMER_REAL, &itv, NULL);
1433 #endif /* !defined(_WIN32) */
1435 #ifdef _WIN32
1437 static int win32_start_timer(struct qemu_alarm_timer *t)
1439 TIMECAPS tc;
1440 struct qemu_alarm_win32 *data = t->priv;
1441 UINT flags;
1443 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1444 if (!data->host_alarm) {
1445 perror("Failed CreateEvent");
1446 return -1;
1449 memset(&tc, 0, sizeof(tc));
1450 timeGetDevCaps(&tc, sizeof(tc));
1452 if (data->period < tc.wPeriodMin)
1453 data->period = tc.wPeriodMin;
1455 timeBeginPeriod(data->period);
1457 flags = TIME_CALLBACK_FUNCTION;
1458 if (alarm_has_dynticks(t))
1459 flags |= TIME_ONESHOT;
1460 else
1461 flags |= TIME_PERIODIC;
1463 data->timerId = timeSetEvent(1, // interval (ms)
1464 data->period, // resolution
1465 host_alarm_handler, // function
1466 (DWORD)t, // parameter
1467 flags);
1469 if (!data->timerId) {
1470 perror("Failed to initialize win32 alarm timer");
1472 timeEndPeriod(data->period);
1473 CloseHandle(data->host_alarm);
1474 return -1;
1477 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1479 return 0;
1482 static void win32_stop_timer(struct qemu_alarm_timer *t)
1484 struct qemu_alarm_win32 *data = t->priv;
1486 timeKillEvent(data->timerId);
1487 timeEndPeriod(data->period);
1489 CloseHandle(data->host_alarm);
1492 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1494 struct qemu_alarm_win32 *data = t->priv;
1495 uint64_t nearest_delta_us;
1497 if (!active_timers[QEMU_TIMER_REALTIME] &&
1498 !active_timers[QEMU_TIMER_VIRTUAL])
1499 return;
1501 nearest_delta_us = qemu_next_deadline();
1502 nearest_delta_us /= 1000;
1504 timeKillEvent(data->timerId);
1506 data->timerId = timeSetEvent(1,
1507 data->period,
1508 host_alarm_handler,
1509 (DWORD)t,
1510 TIME_ONESHOT | TIME_PERIODIC);
1512 if (!data->timerId) {
1513 perror("Failed to re-arm win32 alarm timer");
1515 timeEndPeriod(data->period);
1516 CloseHandle(data->host_alarm);
1517 exit(1);
1521 #endif /* _WIN32 */
1523 static void init_timer_alarm(void)
1525 struct qemu_alarm_timer *t;
1526 int i, err = -1;
1528 for (i = 0; alarm_timers[i].name; i++) {
1529 t = &alarm_timers[i];
1531 err = t->start(t);
1532 if (!err)
1533 break;
1536 if (err) {
1537 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1538 fprintf(stderr, "Terminating\n");
1539 exit(1);
1542 alarm_timer = t;
1545 static void quit_timers(void)
1547 alarm_timer->stop(alarm_timer);
1548 alarm_timer = NULL;
1551 /***********************************************************/
1552 /* character device */
1554 static void qemu_chr_event(CharDriverState *s, int event)
1556 if (!s->chr_event)
1557 return;
1558 s->chr_event(s->handler_opaque, event);
1561 static void qemu_chr_reset_bh(void *opaque)
1563 CharDriverState *s = opaque;
1564 qemu_chr_event(s, CHR_EVENT_RESET);
1565 qemu_bh_delete(s->bh);
1566 s->bh = NULL;
1569 void qemu_chr_reset(CharDriverState *s)
1571 if (s->bh == NULL) {
1572 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1573 qemu_bh_schedule(s->bh);
1577 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1579 return s->chr_write(s, buf, len);
1582 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1584 if (!s->chr_ioctl)
1585 return -ENOTSUP;
1586 return s->chr_ioctl(s, cmd, arg);
1589 int qemu_chr_can_read(CharDriverState *s)
1591 if (!s->chr_can_read)
1592 return 0;
1593 return s->chr_can_read(s->handler_opaque);
1596 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1598 s->chr_read(s->handler_opaque, buf, len);
1601 void qemu_chr_accept_input(CharDriverState *s)
1603 if (s->chr_accept_input)
1604 s->chr_accept_input(s);
1607 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1609 char buf[4096];
1610 va_list ap;
1611 va_start(ap, fmt);
1612 vsnprintf(buf, sizeof(buf), fmt, ap);
1613 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1614 va_end(ap);
1617 void qemu_chr_send_event(CharDriverState *s, int event)
1619 if (s->chr_send_event)
1620 s->chr_send_event(s, event);
1623 void qemu_chr_add_handlers(CharDriverState *s,
1624 IOCanRWHandler *fd_can_read,
1625 IOReadHandler *fd_read,
1626 IOEventHandler *fd_event,
1627 void *opaque)
1629 s->chr_can_read = fd_can_read;
1630 s->chr_read = fd_read;
1631 s->chr_event = fd_event;
1632 s->handler_opaque = opaque;
1633 if (s->chr_update_read_handler)
1634 s->chr_update_read_handler(s);
1637 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1639 return len;
1642 static CharDriverState *qemu_chr_open_null(void)
1644 CharDriverState *chr;
1646 chr = qemu_mallocz(sizeof(CharDriverState));
1647 if (!chr)
1648 return NULL;
1649 chr->chr_write = null_chr_write;
1650 return chr;
1653 /* MUX driver for serial I/O splitting */
1654 static int term_timestamps;
1655 static int64_t term_timestamps_start;
1656 #define MAX_MUX 4
1657 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1658 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1659 typedef struct {
1660 IOCanRWHandler *chr_can_read[MAX_MUX];
1661 IOReadHandler *chr_read[MAX_MUX];
1662 IOEventHandler *chr_event[MAX_MUX];
1663 void *ext_opaque[MAX_MUX];
1664 CharDriverState *drv;
1665 unsigned char buffer[MUX_BUFFER_SIZE];
1666 int prod;
1667 int cons;
1668 int mux_cnt;
1669 int term_got_escape;
1670 int max_size;
1671 } MuxDriver;
1674 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1676 MuxDriver *d = chr->opaque;
1677 int ret;
1678 if (!term_timestamps) {
1679 ret = d->drv->chr_write(d->drv, buf, len);
1680 } else {
1681 int i;
1683 ret = 0;
1684 for(i = 0; i < len; i++) {
1685 ret += d->drv->chr_write(d->drv, buf+i, 1);
1686 if (buf[i] == '\n') {
1687 char buf1[64];
1688 int64_t ti;
1689 int secs;
1691 ti = get_clock();
1692 if (term_timestamps_start == -1)
1693 term_timestamps_start = ti;
1694 ti -= term_timestamps_start;
1695 secs = ti / 1000000000;
1696 snprintf(buf1, sizeof(buf1),
1697 "[%02d:%02d:%02d.%03d] ",
1698 secs / 3600,
1699 (secs / 60) % 60,
1700 secs % 60,
1701 (int)((ti / 1000000) % 1000));
1702 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1706 return ret;
1709 static char *mux_help[] = {
1710 "% h print this help\n\r",
1711 "% x exit emulator\n\r",
1712 "% s save disk data back to file (if -snapshot)\n\r",
1713 "% t toggle console timestamps\n\r"
1714 "% b send break (magic sysrq)\n\r",
1715 "% c switch between console and monitor\n\r",
1716 "% % sends %\n\r",
1717 NULL
1720 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1721 static void mux_print_help(CharDriverState *chr)
1723 int i, j;
1724 char ebuf[15] = "Escape-Char";
1725 char cbuf[50] = "\n\r";
1727 if (term_escape_char > 0 && term_escape_char < 26) {
1728 sprintf(cbuf,"\n\r");
1729 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1730 } else {
1731 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1732 term_escape_char);
1734 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1735 for (i = 0; mux_help[i] != NULL; i++) {
1736 for (j=0; mux_help[i][j] != '\0'; j++) {
1737 if (mux_help[i][j] == '%')
1738 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1739 else
1740 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1745 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1747 if (d->term_got_escape) {
1748 d->term_got_escape = 0;
1749 if (ch == term_escape_char)
1750 goto send_char;
1751 switch(ch) {
1752 case '?':
1753 case 'h':
1754 mux_print_help(chr);
1755 break;
1756 case 'x':
1758 char *term = "QEMU: Terminated\n\r";
1759 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1760 exit(0);
1761 break;
1763 case 's':
1765 int i;
1766 for (i = 0; i < nb_drives; i++) {
1767 bdrv_commit(drives_table[i].bdrv);
1770 break;
1771 case 'b':
1772 qemu_chr_event(chr, CHR_EVENT_BREAK);
1773 break;
1774 case 'c':
1775 /* Switch to the next registered device */
1776 chr->focus++;
1777 if (chr->focus >= d->mux_cnt)
1778 chr->focus = 0;
1779 break;
1780 case 't':
1781 term_timestamps = !term_timestamps;
1782 term_timestamps_start = -1;
1783 break;
1785 } else if (ch == term_escape_char) {
1786 d->term_got_escape = 1;
1787 } else {
1788 send_char:
1789 return 1;
1791 return 0;
1794 static void mux_chr_accept_input(CharDriverState *chr)
1796 int m = chr->focus;
1797 MuxDriver *d = chr->opaque;
1799 while (d->prod != d->cons &&
1800 d->chr_can_read[m] &&
1801 d->chr_can_read[m](d->ext_opaque[m])) {
1802 d->chr_read[m](d->ext_opaque[m],
1803 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1807 static int mux_chr_can_read(void *opaque)
1809 CharDriverState *chr = opaque;
1810 MuxDriver *d = chr->opaque;
1812 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1813 return 1;
1814 if (d->chr_can_read[chr->focus])
1815 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1816 return 0;
1819 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1821 CharDriverState *chr = opaque;
1822 MuxDriver *d = chr->opaque;
1823 int m = chr->focus;
1824 int i;
1826 mux_chr_accept_input (opaque);
1828 for(i = 0; i < size; i++)
1829 if (mux_proc_byte(chr, d, buf[i])) {
1830 if (d->prod == d->cons &&
1831 d->chr_can_read[m] &&
1832 d->chr_can_read[m](d->ext_opaque[m]))
1833 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1834 else
1835 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1839 static void mux_chr_event(void *opaque, int event)
1841 CharDriverState *chr = opaque;
1842 MuxDriver *d = chr->opaque;
1843 int i;
1845 /* Send the event to all registered listeners */
1846 for (i = 0; i < d->mux_cnt; i++)
1847 if (d->chr_event[i])
1848 d->chr_event[i](d->ext_opaque[i], event);
1851 static void mux_chr_update_read_handler(CharDriverState *chr)
1853 MuxDriver *d = chr->opaque;
1855 if (d->mux_cnt >= MAX_MUX) {
1856 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1857 return;
1859 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1860 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1861 d->chr_read[d->mux_cnt] = chr->chr_read;
1862 d->chr_event[d->mux_cnt] = chr->chr_event;
1863 /* Fix up the real driver with mux routines */
1864 if (d->mux_cnt == 0) {
1865 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1866 mux_chr_event, chr);
1868 chr->focus = d->mux_cnt;
1869 d->mux_cnt++;
1872 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1874 CharDriverState *chr;
1875 MuxDriver *d;
1877 chr = qemu_mallocz(sizeof(CharDriverState));
1878 if (!chr)
1879 return NULL;
1880 d = qemu_mallocz(sizeof(MuxDriver));
1881 if (!d) {
1882 free(chr);
1883 return NULL;
1886 chr->opaque = d;
1887 d->drv = drv;
1888 chr->focus = -1;
1889 chr->chr_write = mux_chr_write;
1890 chr->chr_update_read_handler = mux_chr_update_read_handler;
1891 chr->chr_accept_input = mux_chr_accept_input;
1892 return chr;
1896 #ifdef _WIN32
1898 static void socket_cleanup(void)
1900 WSACleanup();
1903 static int socket_init(void)
1905 WSADATA Data;
1906 int ret, err;
1908 ret = WSAStartup(MAKEWORD(2,2), &Data);
1909 if (ret != 0) {
1910 err = WSAGetLastError();
1911 fprintf(stderr, "WSAStartup: %d\n", err);
1912 return -1;
1914 atexit(socket_cleanup);
1915 return 0;
1918 static int send_all(int fd, const uint8_t *buf, int len1)
1920 int ret, len;
1922 len = len1;
1923 while (len > 0) {
1924 ret = send(fd, buf, len, 0);
1925 if (ret < 0) {
1926 int errno;
1927 errno = WSAGetLastError();
1928 if (errno != WSAEWOULDBLOCK) {
1929 return -1;
1931 } else if (ret == 0) {
1932 break;
1933 } else {
1934 buf += ret;
1935 len -= ret;
1938 return len1 - len;
1941 void socket_set_nonblock(int fd)
1943 unsigned long opt = 1;
1944 ioctlsocket(fd, FIONBIO, &opt);
1947 #else
1949 static int unix_write(int fd, const uint8_t *buf, int len1)
1951 int ret, len;
1953 len = len1;
1954 while (len > 0) {
1955 ret = write(fd, buf, len);
1956 if (ret < 0) {
1957 if (errno != EINTR && errno != EAGAIN)
1958 return -1;
1959 } else if (ret == 0) {
1960 break;
1961 } else {
1962 buf += ret;
1963 len -= ret;
1966 return len1 - len;
1969 static inline int send_all(int fd, const uint8_t *buf, int len1)
1971 return unix_write(fd, buf, len1);
1974 void socket_set_nonblock(int fd)
1976 fcntl(fd, F_SETFL, O_NONBLOCK);
1978 #endif /* !_WIN32 */
1980 #ifndef _WIN32
1982 typedef struct {
1983 int fd_in, fd_out;
1984 int max_size;
1985 } FDCharDriver;
1987 #define STDIO_MAX_CLIENTS 1
1988 static int stdio_nb_clients = 0;
1990 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1992 FDCharDriver *s = chr->opaque;
1993 return unix_write(s->fd_out, buf, len);
1996 static int fd_chr_read_poll(void *opaque)
1998 CharDriverState *chr = opaque;
1999 FDCharDriver *s = chr->opaque;
2001 s->max_size = qemu_chr_can_read(chr);
2002 return s->max_size;
2005 static void fd_chr_read(void *opaque)
2007 CharDriverState *chr = opaque;
2008 FDCharDriver *s = chr->opaque;
2009 int size, len;
2010 uint8_t buf[1024];
2012 len = sizeof(buf);
2013 if (len > s->max_size)
2014 len = s->max_size;
2015 if (len == 0)
2016 return;
2017 size = read(s->fd_in, buf, len);
2018 if (size == 0) {
2019 /* FD has been closed. Remove it from the active list. */
2020 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2021 return;
2023 if (size > 0) {
2024 qemu_chr_read(chr, buf, size);
2028 static void fd_chr_update_read_handler(CharDriverState *chr)
2030 FDCharDriver *s = chr->opaque;
2032 if (s->fd_in >= 0) {
2033 if (nographic && s->fd_in == 0) {
2034 } else {
2035 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2036 fd_chr_read, NULL, chr);
2041 /* open a character device to a unix fd */
2042 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2044 CharDriverState *chr;
2045 FDCharDriver *s;
2047 chr = qemu_mallocz(sizeof(CharDriverState));
2048 if (!chr)
2049 return NULL;
2050 s = qemu_mallocz(sizeof(FDCharDriver));
2051 if (!s) {
2052 free(chr);
2053 return NULL;
2055 s->fd_in = fd_in;
2056 s->fd_out = fd_out;
2057 chr->opaque = s;
2058 chr->chr_write = fd_chr_write;
2059 chr->chr_update_read_handler = fd_chr_update_read_handler;
2061 qemu_chr_reset(chr);
2063 return chr;
2066 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2068 int fd_out;
2070 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2071 if (fd_out < 0)
2072 return NULL;
2073 return qemu_chr_open_fd(-1, fd_out);
2076 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2078 int fd_in, fd_out;
2079 char filename_in[256], filename_out[256];
2081 snprintf(filename_in, 256, "%s.in", filename);
2082 snprintf(filename_out, 256, "%s.out", filename);
2083 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2084 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2085 if (fd_in < 0 || fd_out < 0) {
2086 if (fd_in >= 0)
2087 close(fd_in);
2088 if (fd_out >= 0)
2089 close(fd_out);
2090 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2091 if (fd_in < 0)
2092 return NULL;
2094 return qemu_chr_open_fd(fd_in, fd_out);
2098 /* for STDIO, we handle the case where several clients use it
2099 (nographic mode) */
2101 #define TERM_FIFO_MAX_SIZE 1
2103 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2104 static int term_fifo_size;
2106 static int stdio_read_poll(void *opaque)
2108 CharDriverState *chr = opaque;
2110 /* try to flush the queue if needed */
2111 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2112 qemu_chr_read(chr, term_fifo, 1);
2113 term_fifo_size = 0;
2115 /* see if we can absorb more chars */
2116 if (term_fifo_size == 0)
2117 return 1;
2118 else
2119 return 0;
2122 static void stdio_read(void *opaque)
2124 int size;
2125 uint8_t buf[1];
2126 CharDriverState *chr = opaque;
2128 size = read(0, buf, 1);
2129 if (size == 0) {
2130 /* stdin has been closed. Remove it from the active list. */
2131 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2132 return;
2134 if (size > 0) {
2135 if (qemu_chr_can_read(chr) > 0) {
2136 qemu_chr_read(chr, buf, 1);
2137 } else if (term_fifo_size == 0) {
2138 term_fifo[term_fifo_size++] = buf[0];
2143 /* init terminal so that we can grab keys */
2144 static struct termios oldtty;
2145 static int old_fd0_flags;
2147 static void term_exit(void)
2149 tcsetattr (0, TCSANOW, &oldtty);
2150 fcntl(0, F_SETFL, old_fd0_flags);
2153 static void term_init(void)
2155 struct termios tty;
2157 tcgetattr (0, &tty);
2158 oldtty = tty;
2159 old_fd0_flags = fcntl(0, F_GETFL);
2161 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2162 |INLCR|IGNCR|ICRNL|IXON);
2163 tty.c_oflag |= OPOST;
2164 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2165 /* if graphical mode, we allow Ctrl-C handling */
2166 if (nographic)
2167 tty.c_lflag &= ~ISIG;
2168 tty.c_cflag &= ~(CSIZE|PARENB);
2169 tty.c_cflag |= CS8;
2170 tty.c_cc[VMIN] = 1;
2171 tty.c_cc[VTIME] = 0;
2173 tcsetattr (0, TCSANOW, &tty);
2175 atexit(term_exit);
2177 fcntl(0, F_SETFL, O_NONBLOCK);
2180 static CharDriverState *qemu_chr_open_stdio(void)
2182 CharDriverState *chr;
2184 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2185 return NULL;
2186 chr = qemu_chr_open_fd(0, 1);
2187 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2188 stdio_nb_clients++;
2189 term_init();
2191 return chr;
2194 #if defined(__linux__) || defined(__sun__)
2195 static CharDriverState *qemu_chr_open_pty(void)
2197 struct termios tty;
2198 char slave_name[1024];
2199 int master_fd, slave_fd;
2201 #if defined(__linux__)
2202 /* Not satisfying */
2203 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2204 return NULL;
2206 #endif
2208 /* Disabling local echo and line-buffered output */
2209 tcgetattr (master_fd, &tty);
2210 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2211 tty.c_cc[VMIN] = 1;
2212 tty.c_cc[VTIME] = 0;
2213 tcsetattr (master_fd, TCSAFLUSH, &tty);
2215 fprintf(stderr, "char device redirected to %s\n", slave_name);
2216 return qemu_chr_open_fd(master_fd, master_fd);
2219 static void tty_serial_init(int fd, int speed,
2220 int parity, int data_bits, int stop_bits)
2222 struct termios tty;
2223 speed_t spd;
2225 #if 0
2226 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2227 speed, parity, data_bits, stop_bits);
2228 #endif
2229 tcgetattr (fd, &tty);
2231 switch(speed) {
2232 case 50:
2233 spd = B50;
2234 break;
2235 case 75:
2236 spd = B75;
2237 break;
2238 case 300:
2239 spd = B300;
2240 break;
2241 case 600:
2242 spd = B600;
2243 break;
2244 case 1200:
2245 spd = B1200;
2246 break;
2247 case 2400:
2248 spd = B2400;
2249 break;
2250 case 4800:
2251 spd = B4800;
2252 break;
2253 case 9600:
2254 spd = B9600;
2255 break;
2256 case 19200:
2257 spd = B19200;
2258 break;
2259 case 38400:
2260 spd = B38400;
2261 break;
2262 case 57600:
2263 spd = B57600;
2264 break;
2265 default:
2266 case 115200:
2267 spd = B115200;
2268 break;
2271 cfsetispeed(&tty, spd);
2272 cfsetospeed(&tty, spd);
2274 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2275 |INLCR|IGNCR|ICRNL|IXON);
2276 tty.c_oflag |= OPOST;
2277 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2278 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2279 switch(data_bits) {
2280 default:
2281 case 8:
2282 tty.c_cflag |= CS8;
2283 break;
2284 case 7:
2285 tty.c_cflag |= CS7;
2286 break;
2287 case 6:
2288 tty.c_cflag |= CS6;
2289 break;
2290 case 5:
2291 tty.c_cflag |= CS5;
2292 break;
2294 switch(parity) {
2295 default:
2296 case 'N':
2297 break;
2298 case 'E':
2299 tty.c_cflag |= PARENB;
2300 break;
2301 case 'O':
2302 tty.c_cflag |= PARENB | PARODD;
2303 break;
2305 if (stop_bits == 2)
2306 tty.c_cflag |= CSTOPB;
2308 tcsetattr (fd, TCSANOW, &tty);
2311 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2313 FDCharDriver *s = chr->opaque;
2315 switch(cmd) {
2316 case CHR_IOCTL_SERIAL_SET_PARAMS:
2318 QEMUSerialSetParams *ssp = arg;
2319 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2320 ssp->data_bits, ssp->stop_bits);
2322 break;
2323 case CHR_IOCTL_SERIAL_SET_BREAK:
2325 int enable = *(int *)arg;
2326 if (enable)
2327 tcsendbreak(s->fd_in, 1);
2329 break;
2330 default:
2331 return -ENOTSUP;
2333 return 0;
2336 static CharDriverState *qemu_chr_open_tty(const char *filename)
2338 CharDriverState *chr;
2339 int fd;
2341 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2342 fcntl(fd, F_SETFL, O_NONBLOCK);
2343 tty_serial_init(fd, 115200, 'N', 8, 1);
2344 chr = qemu_chr_open_fd(fd, fd);
2345 if (!chr) {
2346 close(fd);
2347 return NULL;
2349 chr->chr_ioctl = tty_serial_ioctl;
2350 qemu_chr_reset(chr);
2351 return chr;
2353 #else /* ! __linux__ && ! __sun__ */
2354 static CharDriverState *qemu_chr_open_pty(void)
2356 return NULL;
2358 #endif /* __linux__ || __sun__ */
2360 #if defined(__linux__)
2361 typedef struct {
2362 int fd;
2363 int mode;
2364 } ParallelCharDriver;
2366 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2368 if (s->mode != mode) {
2369 int m = mode;
2370 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2371 return 0;
2372 s->mode = mode;
2374 return 1;
2377 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2379 ParallelCharDriver *drv = chr->opaque;
2380 int fd = drv->fd;
2381 uint8_t b;
2383 switch(cmd) {
2384 case CHR_IOCTL_PP_READ_DATA:
2385 if (ioctl(fd, PPRDATA, &b) < 0)
2386 return -ENOTSUP;
2387 *(uint8_t *)arg = b;
2388 break;
2389 case CHR_IOCTL_PP_WRITE_DATA:
2390 b = *(uint8_t *)arg;
2391 if (ioctl(fd, PPWDATA, &b) < 0)
2392 return -ENOTSUP;
2393 break;
2394 case CHR_IOCTL_PP_READ_CONTROL:
2395 if (ioctl(fd, PPRCONTROL, &b) < 0)
2396 return -ENOTSUP;
2397 /* Linux gives only the lowest bits, and no way to know data
2398 direction! For better compatibility set the fixed upper
2399 bits. */
2400 *(uint8_t *)arg = b | 0xc0;
2401 break;
2402 case CHR_IOCTL_PP_WRITE_CONTROL:
2403 b = *(uint8_t *)arg;
2404 if (ioctl(fd, PPWCONTROL, &b) < 0)
2405 return -ENOTSUP;
2406 break;
2407 case CHR_IOCTL_PP_READ_STATUS:
2408 if (ioctl(fd, PPRSTATUS, &b) < 0)
2409 return -ENOTSUP;
2410 *(uint8_t *)arg = b;
2411 break;
2412 case CHR_IOCTL_PP_EPP_READ_ADDR:
2413 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2414 struct ParallelIOArg *parg = arg;
2415 int n = read(fd, parg->buffer, parg->count);
2416 if (n != parg->count) {
2417 return -EIO;
2420 break;
2421 case CHR_IOCTL_PP_EPP_READ:
2422 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2423 struct ParallelIOArg *parg = arg;
2424 int n = read(fd, parg->buffer, parg->count);
2425 if (n != parg->count) {
2426 return -EIO;
2429 break;
2430 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2431 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2432 struct ParallelIOArg *parg = arg;
2433 int n = write(fd, parg->buffer, parg->count);
2434 if (n != parg->count) {
2435 return -EIO;
2438 break;
2439 case CHR_IOCTL_PP_EPP_WRITE:
2440 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2441 struct ParallelIOArg *parg = arg;
2442 int n = write(fd, parg->buffer, parg->count);
2443 if (n != parg->count) {
2444 return -EIO;
2447 break;
2448 default:
2449 return -ENOTSUP;
2451 return 0;
2454 static void pp_close(CharDriverState *chr)
2456 ParallelCharDriver *drv = chr->opaque;
2457 int fd = drv->fd;
2459 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2460 ioctl(fd, PPRELEASE);
2461 close(fd);
2462 qemu_free(drv);
2465 static CharDriverState *qemu_chr_open_pp(const char *filename)
2467 CharDriverState *chr;
2468 ParallelCharDriver *drv;
2469 int fd;
2471 TFR(fd = open(filename, O_RDWR));
2472 if (fd < 0)
2473 return NULL;
2475 if (ioctl(fd, PPCLAIM) < 0) {
2476 close(fd);
2477 return NULL;
2480 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2481 if (!drv) {
2482 close(fd);
2483 return NULL;
2485 drv->fd = fd;
2486 drv->mode = IEEE1284_MODE_COMPAT;
2488 chr = qemu_mallocz(sizeof(CharDriverState));
2489 if (!chr) {
2490 qemu_free(drv);
2491 close(fd);
2492 return NULL;
2494 chr->chr_write = null_chr_write;
2495 chr->chr_ioctl = pp_ioctl;
2496 chr->chr_close = pp_close;
2497 chr->opaque = drv;
2499 qemu_chr_reset(chr);
2501 return chr;
2503 #endif /* __linux__ */
2505 #else /* _WIN32 */
2507 typedef struct {
2508 int max_size;
2509 HANDLE hcom, hrecv, hsend;
2510 OVERLAPPED orecv, osend;
2511 BOOL fpipe;
2512 DWORD len;
2513 } WinCharState;
2515 #define NSENDBUF 2048
2516 #define NRECVBUF 2048
2517 #define MAXCONNECT 1
2518 #define NTIMEOUT 5000
2520 static int win_chr_poll(void *opaque);
2521 static int win_chr_pipe_poll(void *opaque);
2523 static void win_chr_close(CharDriverState *chr)
2525 WinCharState *s = chr->opaque;
2527 if (s->hsend) {
2528 CloseHandle(s->hsend);
2529 s->hsend = NULL;
2531 if (s->hrecv) {
2532 CloseHandle(s->hrecv);
2533 s->hrecv = NULL;
2535 if (s->hcom) {
2536 CloseHandle(s->hcom);
2537 s->hcom = NULL;
2539 if (s->fpipe)
2540 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2541 else
2542 qemu_del_polling_cb(win_chr_poll, chr);
2545 static int win_chr_init(CharDriverState *chr, const char *filename)
2547 WinCharState *s = chr->opaque;
2548 COMMCONFIG comcfg;
2549 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2550 COMSTAT comstat;
2551 DWORD size;
2552 DWORD err;
2554 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2555 if (!s->hsend) {
2556 fprintf(stderr, "Failed CreateEvent\n");
2557 goto fail;
2559 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2560 if (!s->hrecv) {
2561 fprintf(stderr, "Failed CreateEvent\n");
2562 goto fail;
2565 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2566 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2567 if (s->hcom == INVALID_HANDLE_VALUE) {
2568 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2569 s->hcom = NULL;
2570 goto fail;
2573 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2574 fprintf(stderr, "Failed SetupComm\n");
2575 goto fail;
2578 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2579 size = sizeof(COMMCONFIG);
2580 GetDefaultCommConfig(filename, &comcfg, &size);
2581 comcfg.dcb.DCBlength = sizeof(DCB);
2582 CommConfigDialog(filename, NULL, &comcfg);
2584 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2585 fprintf(stderr, "Failed SetCommState\n");
2586 goto fail;
2589 if (!SetCommMask(s->hcom, EV_ERR)) {
2590 fprintf(stderr, "Failed SetCommMask\n");
2591 goto fail;
2594 cto.ReadIntervalTimeout = MAXDWORD;
2595 if (!SetCommTimeouts(s->hcom, &cto)) {
2596 fprintf(stderr, "Failed SetCommTimeouts\n");
2597 goto fail;
2600 if (!ClearCommError(s->hcom, &err, &comstat)) {
2601 fprintf(stderr, "Failed ClearCommError\n");
2602 goto fail;
2604 qemu_add_polling_cb(win_chr_poll, chr);
2605 return 0;
2607 fail:
2608 win_chr_close(chr);
2609 return -1;
2612 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2614 WinCharState *s = chr->opaque;
2615 DWORD len, ret, size, err;
2617 len = len1;
2618 ZeroMemory(&s->osend, sizeof(s->osend));
2619 s->osend.hEvent = s->hsend;
2620 while (len > 0) {
2621 if (s->hsend)
2622 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2623 else
2624 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2625 if (!ret) {
2626 err = GetLastError();
2627 if (err == ERROR_IO_PENDING) {
2628 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2629 if (ret) {
2630 buf += size;
2631 len -= size;
2632 } else {
2633 break;
2635 } else {
2636 break;
2638 } else {
2639 buf += size;
2640 len -= size;
2643 return len1 - len;
2646 static int win_chr_read_poll(CharDriverState *chr)
2648 WinCharState *s = chr->opaque;
2650 s->max_size = qemu_chr_can_read(chr);
2651 return s->max_size;
2654 static void win_chr_readfile(CharDriverState *chr)
2656 WinCharState *s = chr->opaque;
2657 int ret, err;
2658 uint8_t buf[1024];
2659 DWORD size;
2661 ZeroMemory(&s->orecv, sizeof(s->orecv));
2662 s->orecv.hEvent = s->hrecv;
2663 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2664 if (!ret) {
2665 err = GetLastError();
2666 if (err == ERROR_IO_PENDING) {
2667 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2671 if (size > 0) {
2672 qemu_chr_read(chr, buf, size);
2676 static void win_chr_read(CharDriverState *chr)
2678 WinCharState *s = chr->opaque;
2680 if (s->len > s->max_size)
2681 s->len = s->max_size;
2682 if (s->len == 0)
2683 return;
2685 win_chr_readfile(chr);
2688 static int win_chr_poll(void *opaque)
2690 CharDriverState *chr = opaque;
2691 WinCharState *s = chr->opaque;
2692 COMSTAT status;
2693 DWORD comerr;
2695 ClearCommError(s->hcom, &comerr, &status);
2696 if (status.cbInQue > 0) {
2697 s->len = status.cbInQue;
2698 win_chr_read_poll(chr);
2699 win_chr_read(chr);
2700 return 1;
2702 return 0;
2705 static CharDriverState *qemu_chr_open_win(const char *filename)
2707 CharDriverState *chr;
2708 WinCharState *s;
2710 chr = qemu_mallocz(sizeof(CharDriverState));
2711 if (!chr)
2712 return NULL;
2713 s = qemu_mallocz(sizeof(WinCharState));
2714 if (!s) {
2715 free(chr);
2716 return NULL;
2718 chr->opaque = s;
2719 chr->chr_write = win_chr_write;
2720 chr->chr_close = win_chr_close;
2722 if (win_chr_init(chr, filename) < 0) {
2723 free(s);
2724 free(chr);
2725 return NULL;
2727 qemu_chr_reset(chr);
2728 return chr;
2731 static int win_chr_pipe_poll(void *opaque)
2733 CharDriverState *chr = opaque;
2734 WinCharState *s = chr->opaque;
2735 DWORD size;
2737 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2738 if (size > 0) {
2739 s->len = size;
2740 win_chr_read_poll(chr);
2741 win_chr_read(chr);
2742 return 1;
2744 return 0;
2747 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2749 WinCharState *s = chr->opaque;
2750 OVERLAPPED ov;
2751 int ret;
2752 DWORD size;
2753 char openname[256];
2755 s->fpipe = TRUE;
2757 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2758 if (!s->hsend) {
2759 fprintf(stderr, "Failed CreateEvent\n");
2760 goto fail;
2762 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2763 if (!s->hrecv) {
2764 fprintf(stderr, "Failed CreateEvent\n");
2765 goto fail;
2768 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2769 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2770 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2771 PIPE_WAIT,
2772 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2773 if (s->hcom == INVALID_HANDLE_VALUE) {
2774 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2775 s->hcom = NULL;
2776 goto fail;
2779 ZeroMemory(&ov, sizeof(ov));
2780 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2781 ret = ConnectNamedPipe(s->hcom, &ov);
2782 if (ret) {
2783 fprintf(stderr, "Failed ConnectNamedPipe\n");
2784 goto fail;
2787 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2788 if (!ret) {
2789 fprintf(stderr, "Failed GetOverlappedResult\n");
2790 if (ov.hEvent) {
2791 CloseHandle(ov.hEvent);
2792 ov.hEvent = NULL;
2794 goto fail;
2797 if (ov.hEvent) {
2798 CloseHandle(ov.hEvent);
2799 ov.hEvent = NULL;
2801 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2802 return 0;
2804 fail:
2805 win_chr_close(chr);
2806 return -1;
2810 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2812 CharDriverState *chr;
2813 WinCharState *s;
2815 chr = qemu_mallocz(sizeof(CharDriverState));
2816 if (!chr)
2817 return NULL;
2818 s = qemu_mallocz(sizeof(WinCharState));
2819 if (!s) {
2820 free(chr);
2821 return NULL;
2823 chr->opaque = s;
2824 chr->chr_write = win_chr_write;
2825 chr->chr_close = win_chr_close;
2827 if (win_chr_pipe_init(chr, filename) < 0) {
2828 free(s);
2829 free(chr);
2830 return NULL;
2832 qemu_chr_reset(chr);
2833 return chr;
2836 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2838 CharDriverState *chr;
2839 WinCharState *s;
2841 chr = qemu_mallocz(sizeof(CharDriverState));
2842 if (!chr)
2843 return NULL;
2844 s = qemu_mallocz(sizeof(WinCharState));
2845 if (!s) {
2846 free(chr);
2847 return NULL;
2849 s->hcom = fd_out;
2850 chr->opaque = s;
2851 chr->chr_write = win_chr_write;
2852 qemu_chr_reset(chr);
2853 return chr;
2856 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2858 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2861 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2863 HANDLE fd_out;
2865 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2866 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2867 if (fd_out == INVALID_HANDLE_VALUE)
2868 return NULL;
2870 return qemu_chr_open_win_file(fd_out);
2872 #endif /* !_WIN32 */
2874 /***********************************************************/
2875 /* UDP Net console */
2877 typedef struct {
2878 int fd;
2879 struct sockaddr_in daddr;
2880 uint8_t buf[1024];
2881 int bufcnt;
2882 int bufptr;
2883 int max_size;
2884 } NetCharDriver;
2886 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2888 NetCharDriver *s = chr->opaque;
2890 return sendto(s->fd, buf, len, 0,
2891 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2894 static int udp_chr_read_poll(void *opaque)
2896 CharDriverState *chr = opaque;
2897 NetCharDriver *s = chr->opaque;
2899 s->max_size = qemu_chr_can_read(chr);
2901 /* If there were any stray characters in the queue process them
2902 * first
2904 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2905 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2906 s->bufptr++;
2907 s->max_size = qemu_chr_can_read(chr);
2909 return s->max_size;
2912 static void udp_chr_read(void *opaque)
2914 CharDriverState *chr = opaque;
2915 NetCharDriver *s = chr->opaque;
2917 if (s->max_size == 0)
2918 return;
2919 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2920 s->bufptr = s->bufcnt;
2921 if (s->bufcnt <= 0)
2922 return;
2924 s->bufptr = 0;
2925 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2926 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2927 s->bufptr++;
2928 s->max_size = qemu_chr_can_read(chr);
2932 static void udp_chr_update_read_handler(CharDriverState *chr)
2934 NetCharDriver *s = chr->opaque;
2936 if (s->fd >= 0) {
2937 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2938 udp_chr_read, NULL, chr);
2942 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2943 #ifndef _WIN32
2944 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2945 #endif
2946 int parse_host_src_port(struct sockaddr_in *haddr,
2947 struct sockaddr_in *saddr,
2948 const char *str);
2950 static CharDriverState *qemu_chr_open_udp(const char *def)
2952 CharDriverState *chr = NULL;
2953 NetCharDriver *s = NULL;
2954 int fd = -1;
2955 struct sockaddr_in saddr;
2957 chr = qemu_mallocz(sizeof(CharDriverState));
2958 if (!chr)
2959 goto return_err;
2960 s = qemu_mallocz(sizeof(NetCharDriver));
2961 if (!s)
2962 goto return_err;
2964 fd = socket(PF_INET, SOCK_DGRAM, 0);
2965 if (fd < 0) {
2966 perror("socket(PF_INET, SOCK_DGRAM)");
2967 goto return_err;
2970 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2971 printf("Could not parse: %s\n", def);
2972 goto return_err;
2975 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2977 perror("bind");
2978 goto return_err;
2981 s->fd = fd;
2982 s->bufcnt = 0;
2983 s->bufptr = 0;
2984 chr->opaque = s;
2985 chr->chr_write = udp_chr_write;
2986 chr->chr_update_read_handler = udp_chr_update_read_handler;
2987 return chr;
2989 return_err:
2990 if (chr)
2991 free(chr);
2992 if (s)
2993 free(s);
2994 if (fd >= 0)
2995 closesocket(fd);
2996 return NULL;
2999 /***********************************************************/
3000 /* TCP Net console */
3002 typedef struct {
3003 int fd, listen_fd;
3004 int connected;
3005 int max_size;
3006 int do_telnetopt;
3007 int do_nodelay;
3008 int is_unix;
3009 } TCPCharDriver;
3011 static void tcp_chr_accept(void *opaque);
3013 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3015 TCPCharDriver *s = chr->opaque;
3016 if (s->connected) {
3017 return send_all(s->fd, buf, len);
3018 } else {
3019 /* XXX: indicate an error ? */
3020 return len;
3024 static int tcp_chr_read_poll(void *opaque)
3026 CharDriverState *chr = opaque;
3027 TCPCharDriver *s = chr->opaque;
3028 if (!s->connected)
3029 return 0;
3030 s->max_size = qemu_chr_can_read(chr);
3031 return s->max_size;
3034 #define IAC 255
3035 #define IAC_BREAK 243
3036 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3037 TCPCharDriver *s,
3038 uint8_t *buf, int *size)
3040 /* Handle any telnet client's basic IAC options to satisfy char by
3041 * char mode with no echo. All IAC options will be removed from
3042 * the buf and the do_telnetopt variable will be used to track the
3043 * state of the width of the IAC information.
3045 * IAC commands come in sets of 3 bytes with the exception of the
3046 * "IAC BREAK" command and the double IAC.
3049 int i;
3050 int j = 0;
3052 for (i = 0; i < *size; i++) {
3053 if (s->do_telnetopt > 1) {
3054 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3055 /* Double IAC means send an IAC */
3056 if (j != i)
3057 buf[j] = buf[i];
3058 j++;
3059 s->do_telnetopt = 1;
3060 } else {
3061 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3062 /* Handle IAC break commands by sending a serial break */
3063 qemu_chr_event(chr, CHR_EVENT_BREAK);
3064 s->do_telnetopt++;
3066 s->do_telnetopt++;
3068 if (s->do_telnetopt >= 4) {
3069 s->do_telnetopt = 1;
3071 } else {
3072 if ((unsigned char)buf[i] == IAC) {
3073 s->do_telnetopt = 2;
3074 } else {
3075 if (j != i)
3076 buf[j] = buf[i];
3077 j++;
3081 *size = j;
3084 static void tcp_chr_read(void *opaque)
3086 CharDriverState *chr = opaque;
3087 TCPCharDriver *s = chr->opaque;
3088 uint8_t buf[1024];
3089 int len, size;
3091 if (!s->connected || s->max_size <= 0)
3092 return;
3093 len = sizeof(buf);
3094 if (len > s->max_size)
3095 len = s->max_size;
3096 size = recv(s->fd, buf, len, 0);
3097 if (size == 0) {
3098 /* connection closed */
3099 s->connected = 0;
3100 if (s->listen_fd >= 0) {
3101 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3103 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3104 closesocket(s->fd);
3105 s->fd = -1;
3106 } else if (size > 0) {
3107 if (s->do_telnetopt)
3108 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3109 if (size > 0)
3110 qemu_chr_read(chr, buf, size);
3114 static void tcp_chr_connect(void *opaque)
3116 CharDriverState *chr = opaque;
3117 TCPCharDriver *s = chr->opaque;
3119 s->connected = 1;
3120 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3121 tcp_chr_read, NULL, chr);
3122 qemu_chr_reset(chr);
3125 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3126 static void tcp_chr_telnet_init(int fd)
3128 char buf[3];
3129 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3130 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3131 send(fd, (char *)buf, 3, 0);
3132 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3133 send(fd, (char *)buf, 3, 0);
3134 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3135 send(fd, (char *)buf, 3, 0);
3136 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3137 send(fd, (char *)buf, 3, 0);
3140 static void socket_set_nodelay(int fd)
3142 int val = 1;
3143 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3146 static void tcp_chr_accept(void *opaque)
3148 CharDriverState *chr = opaque;
3149 TCPCharDriver *s = chr->opaque;
3150 struct sockaddr_in saddr;
3151 #ifndef _WIN32
3152 struct sockaddr_un uaddr;
3153 #endif
3154 struct sockaddr *addr;
3155 socklen_t len;
3156 int fd;
3158 for(;;) {
3159 #ifndef _WIN32
3160 if (s->is_unix) {
3161 len = sizeof(uaddr);
3162 addr = (struct sockaddr *)&uaddr;
3163 } else
3164 #endif
3166 len = sizeof(saddr);
3167 addr = (struct sockaddr *)&saddr;
3169 fd = accept(s->listen_fd, addr, &len);
3170 if (fd < 0 && errno != EINTR) {
3171 return;
3172 } else if (fd >= 0) {
3173 if (s->do_telnetopt)
3174 tcp_chr_telnet_init(fd);
3175 break;
3178 socket_set_nonblock(fd);
3179 if (s->do_nodelay)
3180 socket_set_nodelay(fd);
3181 s->fd = fd;
3182 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3183 tcp_chr_connect(chr);
3186 static void tcp_chr_close(CharDriverState *chr)
3188 TCPCharDriver *s = chr->opaque;
3189 if (s->fd >= 0)
3190 closesocket(s->fd);
3191 if (s->listen_fd >= 0)
3192 closesocket(s->listen_fd);
3193 qemu_free(s);
3196 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3197 int is_telnet,
3198 int is_unix)
3200 CharDriverState *chr = NULL;
3201 TCPCharDriver *s = NULL;
3202 int fd = -1, ret, err, val;
3203 int is_listen = 0;
3204 int is_waitconnect = 1;
3205 int do_nodelay = 0;
3206 const char *ptr;
3207 struct sockaddr_in saddr;
3208 #ifndef _WIN32
3209 struct sockaddr_un uaddr;
3210 #endif
3211 struct sockaddr *addr;
3212 socklen_t addrlen;
3214 #ifndef _WIN32
3215 if (is_unix) {
3216 addr = (struct sockaddr *)&uaddr;
3217 addrlen = sizeof(uaddr);
3218 if (parse_unix_path(&uaddr, host_str) < 0)
3219 goto fail;
3220 } else
3221 #endif
3223 addr = (struct sockaddr *)&saddr;
3224 addrlen = sizeof(saddr);
3225 if (parse_host_port(&saddr, host_str) < 0)
3226 goto fail;
3229 ptr = host_str;
3230 while((ptr = strchr(ptr,','))) {
3231 ptr++;
3232 if (!strncmp(ptr,"server",6)) {
3233 is_listen = 1;
3234 } else if (!strncmp(ptr,"nowait",6)) {
3235 is_waitconnect = 0;
3236 } else if (!strncmp(ptr,"nodelay",6)) {
3237 do_nodelay = 1;
3238 } else {
3239 printf("Unknown option: %s\n", ptr);
3240 goto fail;
3243 if (!is_listen)
3244 is_waitconnect = 0;
3246 chr = qemu_mallocz(sizeof(CharDriverState));
3247 if (!chr)
3248 goto fail;
3249 s = qemu_mallocz(sizeof(TCPCharDriver));
3250 if (!s)
3251 goto fail;
3253 #ifndef _WIN32
3254 if (is_unix)
3255 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3256 else
3257 #endif
3258 fd = socket(PF_INET, SOCK_STREAM, 0);
3260 if (fd < 0)
3261 goto fail;
3263 if (!is_waitconnect)
3264 socket_set_nonblock(fd);
3266 s->connected = 0;
3267 s->fd = -1;
3268 s->listen_fd = -1;
3269 s->is_unix = is_unix;
3270 s->do_nodelay = do_nodelay && !is_unix;
3272 chr->opaque = s;
3273 chr->chr_write = tcp_chr_write;
3274 chr->chr_close = tcp_chr_close;
3276 if (is_listen) {
3277 /* allow fast reuse */
3278 #ifndef _WIN32
3279 if (is_unix) {
3280 char path[109];
3281 strncpy(path, uaddr.sun_path, 108);
3282 path[108] = 0;
3283 unlink(path);
3284 } else
3285 #endif
3287 val = 1;
3288 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3291 ret = bind(fd, addr, addrlen);
3292 if (ret < 0)
3293 goto fail;
3295 ret = listen(fd, 0);
3296 if (ret < 0)
3297 goto fail;
3299 s->listen_fd = fd;
3300 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3301 if (is_telnet)
3302 s->do_telnetopt = 1;
3303 } else {
3304 for(;;) {
3305 ret = connect(fd, addr, addrlen);
3306 if (ret < 0) {
3307 err = socket_error();
3308 if (err == EINTR || err == EWOULDBLOCK) {
3309 } else if (err == EINPROGRESS) {
3310 break;
3311 #ifdef _WIN32
3312 } else if (err == WSAEALREADY) {
3313 break;
3314 #endif
3315 } else {
3316 goto fail;
3318 } else {
3319 s->connected = 1;
3320 break;
3323 s->fd = fd;
3324 socket_set_nodelay(fd);
3325 if (s->connected)
3326 tcp_chr_connect(chr);
3327 else
3328 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3331 if (is_listen && is_waitconnect) {
3332 printf("QEMU waiting for connection on: %s\n", host_str);
3333 tcp_chr_accept(chr);
3334 socket_set_nonblock(s->listen_fd);
3337 return chr;
3338 fail:
3339 if (fd >= 0)
3340 closesocket(fd);
3341 qemu_free(s);
3342 qemu_free(chr);
3343 return NULL;
3346 CharDriverState *qemu_chr_open(const char *filename)
3348 const char *p;
3350 if (!strcmp(filename, "vc")) {
3351 return text_console_init(&display_state, 0);
3352 } else if (strstart(filename, "vc:", &p)) {
3353 return text_console_init(&display_state, p);
3354 } else if (!strcmp(filename, "null")) {
3355 return qemu_chr_open_null();
3356 } else
3357 if (strstart(filename, "tcp:", &p)) {
3358 return qemu_chr_open_tcp(p, 0, 0);
3359 } else
3360 if (strstart(filename, "telnet:", &p)) {
3361 return qemu_chr_open_tcp(p, 1, 0);
3362 } else
3363 if (strstart(filename, "udp:", &p)) {
3364 return qemu_chr_open_udp(p);
3365 } else
3366 if (strstart(filename, "mon:", &p)) {
3367 CharDriverState *drv = qemu_chr_open(p);
3368 if (drv) {
3369 drv = qemu_chr_open_mux(drv);
3370 monitor_init(drv, !nographic);
3371 return drv;
3373 printf("Unable to open driver: %s\n", p);
3374 return 0;
3375 } else
3376 #ifndef _WIN32
3377 if (strstart(filename, "unix:", &p)) {
3378 return qemu_chr_open_tcp(p, 0, 1);
3379 } else if (strstart(filename, "file:", &p)) {
3380 return qemu_chr_open_file_out(p);
3381 } else if (strstart(filename, "pipe:", &p)) {
3382 return qemu_chr_open_pipe(p);
3383 } else if (!strcmp(filename, "pty")) {
3384 return qemu_chr_open_pty();
3385 } else if (!strcmp(filename, "stdio")) {
3386 return qemu_chr_open_stdio();
3387 } else
3388 #if defined(__linux__)
3389 if (strstart(filename, "/dev/parport", NULL)) {
3390 return qemu_chr_open_pp(filename);
3391 } else
3392 #endif
3393 #if defined(__linux__) || defined(__sun__)
3394 if (strstart(filename, "/dev/", NULL)) {
3395 return qemu_chr_open_tty(filename);
3396 } else
3397 #endif
3398 #else /* !_WIN32 */
3399 if (strstart(filename, "COM", NULL)) {
3400 return qemu_chr_open_win(filename);
3401 } else
3402 if (strstart(filename, "pipe:", &p)) {
3403 return qemu_chr_open_win_pipe(p);
3404 } else
3405 if (strstart(filename, "con:", NULL)) {
3406 return qemu_chr_open_win_con(filename);
3407 } else
3408 if (strstart(filename, "file:", &p)) {
3409 return qemu_chr_open_win_file_out(p);
3411 #endif
3413 return NULL;
3417 void qemu_chr_close(CharDriverState *chr)
3419 if (chr->chr_close)
3420 chr->chr_close(chr);
3423 /***********************************************************/
3424 /* network device redirectors */
3426 __attribute__ (( unused ))
3427 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3429 int len, i, j, c;
3431 for(i=0;i<size;i+=16) {
3432 len = size - i;
3433 if (len > 16)
3434 len = 16;
3435 fprintf(f, "%08x ", i);
3436 for(j=0;j<16;j++) {
3437 if (j < len)
3438 fprintf(f, " %02x", buf[i+j]);
3439 else
3440 fprintf(f, " ");
3442 fprintf(f, " ");
3443 for(j=0;j<len;j++) {
3444 c = buf[i+j];
3445 if (c < ' ' || c > '~')
3446 c = '.';
3447 fprintf(f, "%c", c);
3449 fprintf(f, "\n");
3453 static int parse_macaddr(uint8_t *macaddr, const char *p)
3455 int i;
3456 for(i = 0; i < 6; i++) {
3457 macaddr[i] = strtol(p, (char **)&p, 16);
3458 if (i == 5) {
3459 if (*p != '\0')
3460 return -1;
3461 } else {
3462 if (*p != ':')
3463 return -1;
3464 p++;
3467 return 0;
3470 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3472 const char *p, *p1;
3473 int len;
3474 p = *pp;
3475 p1 = strchr(p, sep);
3476 if (!p1)
3477 return -1;
3478 len = p1 - p;
3479 p1++;
3480 if (buf_size > 0) {
3481 if (len > buf_size - 1)
3482 len = buf_size - 1;
3483 memcpy(buf, p, len);
3484 buf[len] = '\0';
3486 *pp = p1;
3487 return 0;
3490 int parse_host_src_port(struct sockaddr_in *haddr,
3491 struct sockaddr_in *saddr,
3492 const char *input_str)
3494 char *str = strdup(input_str);
3495 char *host_str = str;
3496 char *src_str;
3497 char *ptr;
3500 * Chop off any extra arguments at the end of the string which
3501 * would start with a comma, then fill in the src port information
3502 * if it was provided else use the "any address" and "any port".
3504 if ((ptr = strchr(str,',')))
3505 *ptr = '\0';
3507 if ((src_str = strchr(input_str,'@'))) {
3508 *src_str = '\0';
3509 src_str++;
3512 if (parse_host_port(haddr, host_str) < 0)
3513 goto fail;
3515 if (!src_str || *src_str == '\0')
3516 src_str = ":0";
3518 if (parse_host_port(saddr, src_str) < 0)
3519 goto fail;
3521 free(str);
3522 return(0);
3524 fail:
3525 free(str);
3526 return -1;
3529 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3531 char buf[512];
3532 struct hostent *he;
3533 const char *p, *r;
3534 int port;
3536 p = str;
3537 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3538 return -1;
3539 saddr->sin_family = AF_INET;
3540 if (buf[0] == '\0') {
3541 saddr->sin_addr.s_addr = 0;
3542 } else {
3543 if (isdigit(buf[0])) {
3544 if (!inet_aton(buf, &saddr->sin_addr))
3545 return -1;
3546 } else {
3547 if ((he = gethostbyname(buf)) == NULL)
3548 return - 1;
3549 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3552 port = strtol(p, (char **)&r, 0);
3553 if (r == p)
3554 return -1;
3555 saddr->sin_port = htons(port);
3556 return 0;
3559 #ifndef _WIN32
3560 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3562 const char *p;
3563 int len;
3565 len = MIN(108, strlen(str));
3566 p = strchr(str, ',');
3567 if (p)
3568 len = MIN(len, p - str);
3570 memset(uaddr, 0, sizeof(*uaddr));
3572 uaddr->sun_family = AF_UNIX;
3573 memcpy(uaddr->sun_path, str, len);
3575 return 0;
3577 #endif
3579 /* find or alloc a new VLAN */
3580 VLANState *qemu_find_vlan(int id)
3582 VLANState **pvlan, *vlan;
3583 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3584 if (vlan->id == id)
3585 return vlan;
3587 vlan = qemu_mallocz(sizeof(VLANState));
3588 if (!vlan)
3589 return NULL;
3590 vlan->id = id;
3591 vlan->next = NULL;
3592 pvlan = &first_vlan;
3593 while (*pvlan != NULL)
3594 pvlan = &(*pvlan)->next;
3595 *pvlan = vlan;
3596 return vlan;
3599 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3600 IOReadHandler *fd_read,
3601 IOCanRWHandler *fd_can_read,
3602 void *opaque)
3604 VLANClientState *vc, **pvc;
3605 vc = qemu_mallocz(sizeof(VLANClientState));
3606 if (!vc)
3607 return NULL;
3608 vc->fd_read = fd_read;
3609 vc->fd_can_read = fd_can_read;
3610 vc->opaque = opaque;
3611 vc->vlan = vlan;
3613 vc->next = NULL;
3614 pvc = &vlan->first_client;
3615 while (*pvc != NULL)
3616 pvc = &(*pvc)->next;
3617 *pvc = vc;
3618 return vc;
3621 int qemu_can_send_packet(VLANClientState *vc1)
3623 VLANState *vlan = vc1->vlan;
3624 VLANClientState *vc;
3626 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3627 if (vc != vc1) {
3628 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3629 return 1;
3632 return 0;
3635 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3637 VLANState *vlan = vc1->vlan;
3638 VLANClientState *vc;
3640 #if 0
3641 printf("vlan %d send:\n", vlan->id);
3642 hex_dump(stdout, buf, size);
3643 #endif
3644 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3645 if (vc != vc1) {
3646 vc->fd_read(vc->opaque, buf, size);
3651 #if defined(CONFIG_SLIRP)
3653 /* slirp network adapter */
3655 static int slirp_inited;
3656 static VLANClientState *slirp_vc;
3658 int slirp_can_output(void)
3660 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3663 void slirp_output(const uint8_t *pkt, int pkt_len)
3665 #if 0
3666 printf("slirp output:\n");
3667 hex_dump(stdout, pkt, pkt_len);
3668 #endif
3669 if (!slirp_vc)
3670 return;
3671 qemu_send_packet(slirp_vc, pkt, pkt_len);
3674 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3676 #if 0
3677 printf("slirp input:\n");
3678 hex_dump(stdout, buf, size);
3679 #endif
3680 slirp_input(buf, size);
3683 static int net_slirp_init(VLANState *vlan)
3685 if (!slirp_inited) {
3686 slirp_inited = 1;
3687 slirp_init();
3689 slirp_vc = qemu_new_vlan_client(vlan,
3690 slirp_receive, NULL, NULL);
3691 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3692 return 0;
3695 static void net_slirp_redir(const char *redir_str)
3697 int is_udp;
3698 char buf[256], *r;
3699 const char *p;
3700 struct in_addr guest_addr;
3701 int host_port, guest_port;
3703 if (!slirp_inited) {
3704 slirp_inited = 1;
3705 slirp_init();
3708 p = redir_str;
3709 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3710 goto fail;
3711 if (!strcmp(buf, "tcp")) {
3712 is_udp = 0;
3713 } else if (!strcmp(buf, "udp")) {
3714 is_udp = 1;
3715 } else {
3716 goto fail;
3719 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3720 goto fail;
3721 host_port = strtol(buf, &r, 0);
3722 if (r == buf)
3723 goto fail;
3725 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3726 goto fail;
3727 if (buf[0] == '\0') {
3728 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3730 if (!inet_aton(buf, &guest_addr))
3731 goto fail;
3733 guest_port = strtol(p, &r, 0);
3734 if (r == p)
3735 goto fail;
3737 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3738 fprintf(stderr, "qemu: could not set up redirection\n");
3739 exit(1);
3741 return;
3742 fail:
3743 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3744 exit(1);
3747 #ifndef _WIN32
3749 char smb_dir[1024];
3751 static void smb_exit(void)
3753 DIR *d;
3754 struct dirent *de;
3755 char filename[1024];
3757 /* erase all the files in the directory */
3758 d = opendir(smb_dir);
3759 for(;;) {
3760 de = readdir(d);
3761 if (!de)
3762 break;
3763 if (strcmp(de->d_name, ".") != 0 &&
3764 strcmp(de->d_name, "..") != 0) {
3765 snprintf(filename, sizeof(filename), "%s/%s",
3766 smb_dir, de->d_name);
3767 unlink(filename);
3770 closedir(d);
3771 rmdir(smb_dir);
3774 /* automatic user mode samba server configuration */
3775 static void net_slirp_smb(const char *exported_dir)
3777 char smb_conf[1024];
3778 char smb_cmdline[1024];
3779 FILE *f;
3781 if (!slirp_inited) {
3782 slirp_inited = 1;
3783 slirp_init();
3786 /* XXX: better tmp dir construction */
3787 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3788 if (mkdir(smb_dir, 0700) < 0) {
3789 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3790 exit(1);
3792 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3794 f = fopen(smb_conf, "w");
3795 if (!f) {
3796 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3797 exit(1);
3799 fprintf(f,
3800 "[global]\n"
3801 "private dir=%s\n"
3802 "smb ports=0\n"
3803 "socket address=127.0.0.1\n"
3804 "pid directory=%s\n"
3805 "lock directory=%s\n"
3806 "log file=%s/log.smbd\n"
3807 "smb passwd file=%s/smbpasswd\n"
3808 "security = share\n"
3809 "[qemu]\n"
3810 "path=%s\n"
3811 "read only=no\n"
3812 "guest ok=yes\n",
3813 smb_dir,
3814 smb_dir,
3815 smb_dir,
3816 smb_dir,
3817 smb_dir,
3818 exported_dir
3820 fclose(f);
3821 atexit(smb_exit);
3823 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3824 SMBD_COMMAND, smb_conf);
3826 slirp_add_exec(0, smb_cmdline, 4, 139);
3829 #endif /* !defined(_WIN32) */
3830 void do_info_slirp(void)
3832 slirp_stats();
3835 #endif /* CONFIG_SLIRP */
3837 #if !defined(_WIN32)
3839 typedef struct TAPState {
3840 VLANClientState *vc;
3841 int fd;
3842 char down_script[1024];
3843 } TAPState;
3845 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3847 TAPState *s = opaque;
3848 int ret;
3849 for(;;) {
3850 ret = write(s->fd, buf, size);
3851 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3852 } else {
3853 break;
3858 static void tap_send(void *opaque)
3860 TAPState *s = opaque;
3861 uint8_t buf[4096];
3862 int size;
3864 #ifdef __sun__
3865 struct strbuf sbuf;
3866 int f = 0;
3867 sbuf.maxlen = sizeof(buf);
3868 sbuf.buf = buf;
3869 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3870 #else
3871 size = read(s->fd, buf, sizeof(buf));
3872 #endif
3873 if (size > 0) {
3874 qemu_send_packet(s->vc, buf, size);
3878 /* fd support */
3880 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3882 TAPState *s;
3884 s = qemu_mallocz(sizeof(TAPState));
3885 if (!s)
3886 return NULL;
3887 s->fd = fd;
3888 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3889 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3890 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3891 return s;
3894 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3895 static int tap_open(char *ifname, int ifname_size)
3897 int fd;
3898 char *dev;
3899 struct stat s;
3901 TFR(fd = open("/dev/tap", O_RDWR));
3902 if (fd < 0) {
3903 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3904 return -1;
3907 fstat(fd, &s);
3908 dev = devname(s.st_rdev, S_IFCHR);
3909 pstrcpy(ifname, ifname_size, dev);
3911 fcntl(fd, F_SETFL, O_NONBLOCK);
3912 return fd;
3914 #elif defined(__sun__)
3915 #define TUNNEWPPA (('T'<<16) | 0x0001)
3917 * Allocate TAP device, returns opened fd.
3918 * Stores dev name in the first arg(must be large enough).
3920 int tap_alloc(char *dev)
3922 int tap_fd, if_fd, ppa = -1;
3923 static int ip_fd = 0;
3924 char *ptr;
3926 static int arp_fd = 0;
3927 int ip_muxid, arp_muxid;
3928 struct strioctl strioc_if, strioc_ppa;
3929 int link_type = I_PLINK;;
3930 struct lifreq ifr;
3931 char actual_name[32] = "";
3933 memset(&ifr, 0x0, sizeof(ifr));
3935 if( *dev ){
3936 ptr = dev;
3937 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3938 ppa = atoi(ptr);
3941 /* Check if IP device was opened */
3942 if( ip_fd )
3943 close(ip_fd);
3945 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3946 if (ip_fd < 0) {
3947 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3948 return -1;
3951 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3952 if (tap_fd < 0) {
3953 syslog(LOG_ERR, "Can't open /dev/tap");
3954 return -1;
3957 /* Assign a new PPA and get its unit number. */
3958 strioc_ppa.ic_cmd = TUNNEWPPA;
3959 strioc_ppa.ic_timout = 0;
3960 strioc_ppa.ic_len = sizeof(ppa);
3961 strioc_ppa.ic_dp = (char *)&ppa;
3962 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3963 syslog (LOG_ERR, "Can't assign new interface");
3965 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3966 if (if_fd < 0) {
3967 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3968 return -1;
3970 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3971 syslog(LOG_ERR, "Can't push IP module");
3972 return -1;
3975 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3976 syslog(LOG_ERR, "Can't get flags\n");
3978 snprintf (actual_name, 32, "tap%d", ppa);
3979 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3981 ifr.lifr_ppa = ppa;
3982 /* Assign ppa according to the unit number returned by tun device */
3984 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3985 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3986 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3987 syslog (LOG_ERR, "Can't get flags\n");
3988 /* Push arp module to if_fd */
3989 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3990 syslog (LOG_ERR, "Can't push ARP module (2)");
3992 /* Push arp module to ip_fd */
3993 if (ioctl (ip_fd, I_POP, NULL) < 0)
3994 syslog (LOG_ERR, "I_POP failed\n");
3995 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3996 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3997 /* Open arp_fd */
3998 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3999 if (arp_fd < 0)
4000 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4002 /* Set ifname to arp */
4003 strioc_if.ic_cmd = SIOCSLIFNAME;
4004 strioc_if.ic_timout = 0;
4005 strioc_if.ic_len = sizeof(ifr);
4006 strioc_if.ic_dp = (char *)&ifr;
4007 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4008 syslog (LOG_ERR, "Can't set ifname to arp\n");
4011 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4012 syslog(LOG_ERR, "Can't link TAP device to IP");
4013 return -1;
4016 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4017 syslog (LOG_ERR, "Can't link TAP device to ARP");
4019 close (if_fd);
4021 memset(&ifr, 0x0, sizeof(ifr));
4022 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4023 ifr.lifr_ip_muxid = ip_muxid;
4024 ifr.lifr_arp_muxid = arp_muxid;
4026 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4028 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4029 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4030 syslog (LOG_ERR, "Can't set multiplexor id");
4033 sprintf(dev, "tap%d", ppa);
4034 return tap_fd;
4037 static int tap_open(char *ifname, int ifname_size)
4039 char dev[10]="";
4040 int fd;
4041 if( (fd = tap_alloc(dev)) < 0 ){
4042 fprintf(stderr, "Cannot allocate TAP device\n");
4043 return -1;
4045 pstrcpy(ifname, ifname_size, dev);
4046 fcntl(fd, F_SETFL, O_NONBLOCK);
4047 return fd;
4049 #else
4050 static int tap_open(char *ifname, int ifname_size)
4052 struct ifreq ifr;
4053 int fd, ret;
4055 TFR(fd = open("/dev/net/tun", O_RDWR));
4056 if (fd < 0) {
4057 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4058 return -1;
4060 memset(&ifr, 0, sizeof(ifr));
4061 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4062 if (ifname[0] != '\0')
4063 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4064 else
4065 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4066 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4067 if (ret != 0) {
4068 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4069 close(fd);
4070 return -1;
4072 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4073 fcntl(fd, F_SETFL, O_NONBLOCK);
4074 return fd;
4076 #endif
4078 static int launch_script(const char *setup_script, const char *ifname, int fd)
4080 int pid, status;
4081 char *args[3];
4082 char **parg;
4084 /* try to launch network script */
4085 pid = fork();
4086 if (pid >= 0) {
4087 if (pid == 0) {
4088 int open_max = sysconf (_SC_OPEN_MAX), i;
4089 for (i = 0; i < open_max; i++)
4090 if (i != STDIN_FILENO &&
4091 i != STDOUT_FILENO &&
4092 i != STDERR_FILENO &&
4093 i != fd)
4094 close(i);
4096 parg = args;
4097 *parg++ = (char *)setup_script;
4098 *parg++ = (char *)ifname;
4099 *parg++ = NULL;
4100 execv(setup_script, args);
4101 _exit(1);
4103 while (waitpid(pid, &status, 0) != pid);
4104 if (!WIFEXITED(status) ||
4105 WEXITSTATUS(status) != 0) {
4106 fprintf(stderr, "%s: could not launch network script\n",
4107 setup_script);
4108 return -1;
4111 return 0;
4114 static int net_tap_init(VLANState *vlan, const char *ifname1,
4115 const char *setup_script, const char *down_script)
4117 TAPState *s;
4118 int fd;
4119 char ifname[128];
4121 if (ifname1 != NULL)
4122 pstrcpy(ifname, sizeof(ifname), ifname1);
4123 else
4124 ifname[0] = '\0';
4125 TFR(fd = tap_open(ifname, sizeof(ifname)));
4126 if (fd < 0)
4127 return -1;
4129 if (!setup_script || !strcmp(setup_script, "no"))
4130 setup_script = "";
4131 if (setup_script[0] != '\0') {
4132 if (launch_script(setup_script, ifname, fd))
4133 return -1;
4135 s = net_tap_fd_init(vlan, fd);
4136 if (!s)
4137 return -1;
4138 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4139 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4140 if (down_script && strcmp(down_script, "no"))
4141 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4142 return 0;
4145 #endif /* !_WIN32 */
4147 /* network connection */
4148 typedef struct NetSocketState {
4149 VLANClientState *vc;
4150 int fd;
4151 int state; /* 0 = getting length, 1 = getting data */
4152 int index;
4153 int packet_len;
4154 uint8_t buf[4096];
4155 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4156 } NetSocketState;
4158 typedef struct NetSocketListenState {
4159 VLANState *vlan;
4160 int fd;
4161 } NetSocketListenState;
4163 /* XXX: we consider we can send the whole packet without blocking */
4164 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4166 NetSocketState *s = opaque;
4167 uint32_t len;
4168 len = htonl(size);
4170 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4171 send_all(s->fd, buf, size);
4174 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4176 NetSocketState *s = opaque;
4177 sendto(s->fd, buf, size, 0,
4178 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4181 static void net_socket_send(void *opaque)
4183 NetSocketState *s = opaque;
4184 int l, size, err;
4185 uint8_t buf1[4096];
4186 const uint8_t *buf;
4188 size = recv(s->fd, buf1, sizeof(buf1), 0);
4189 if (size < 0) {
4190 err = socket_error();
4191 if (err != EWOULDBLOCK)
4192 goto eoc;
4193 } else if (size == 0) {
4194 /* end of connection */
4195 eoc:
4196 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4197 closesocket(s->fd);
4198 return;
4200 buf = buf1;
4201 while (size > 0) {
4202 /* reassemble a packet from the network */
4203 switch(s->state) {
4204 case 0:
4205 l = 4 - s->index;
4206 if (l > size)
4207 l = size;
4208 memcpy(s->buf + s->index, buf, l);
4209 buf += l;
4210 size -= l;
4211 s->index += l;
4212 if (s->index == 4) {
4213 /* got length */
4214 s->packet_len = ntohl(*(uint32_t *)s->buf);
4215 s->index = 0;
4216 s->state = 1;
4218 break;
4219 case 1:
4220 l = s->packet_len - s->index;
4221 if (l > size)
4222 l = size;
4223 memcpy(s->buf + s->index, buf, l);
4224 s->index += l;
4225 buf += l;
4226 size -= l;
4227 if (s->index >= s->packet_len) {
4228 qemu_send_packet(s->vc, s->buf, s->packet_len);
4229 s->index = 0;
4230 s->state = 0;
4232 break;
4237 static void net_socket_send_dgram(void *opaque)
4239 NetSocketState *s = opaque;
4240 int size;
4242 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4243 if (size < 0)
4244 return;
4245 if (size == 0) {
4246 /* end of connection */
4247 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4248 return;
4250 qemu_send_packet(s->vc, s->buf, size);
4253 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4255 struct ip_mreq imr;
4256 int fd;
4257 int val, ret;
4258 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4259 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4260 inet_ntoa(mcastaddr->sin_addr),
4261 (int)ntohl(mcastaddr->sin_addr.s_addr));
4262 return -1;
4265 fd = socket(PF_INET, SOCK_DGRAM, 0);
4266 if (fd < 0) {
4267 perror("socket(PF_INET, SOCK_DGRAM)");
4268 return -1;
4271 val = 1;
4272 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4273 (const char *)&val, sizeof(val));
4274 if (ret < 0) {
4275 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4276 goto fail;
4279 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4280 if (ret < 0) {
4281 perror("bind");
4282 goto fail;
4285 /* Add host to multicast group */
4286 imr.imr_multiaddr = mcastaddr->sin_addr;
4287 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4289 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4290 (const char *)&imr, sizeof(struct ip_mreq));
4291 if (ret < 0) {
4292 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4293 goto fail;
4296 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4297 val = 1;
4298 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4299 (const char *)&val, sizeof(val));
4300 if (ret < 0) {
4301 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4302 goto fail;
4305 socket_set_nonblock(fd);
4306 return fd;
4307 fail:
4308 if (fd >= 0)
4309 closesocket(fd);
4310 return -1;
4313 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4314 int is_connected)
4316 struct sockaddr_in saddr;
4317 int newfd;
4318 socklen_t saddr_len;
4319 NetSocketState *s;
4321 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4322 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4323 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4326 if (is_connected) {
4327 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4328 /* must be bound */
4329 if (saddr.sin_addr.s_addr==0) {
4330 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4331 fd);
4332 return NULL;
4334 /* clone dgram socket */
4335 newfd = net_socket_mcast_create(&saddr);
4336 if (newfd < 0) {
4337 /* error already reported by net_socket_mcast_create() */
4338 close(fd);
4339 return NULL;
4341 /* clone newfd to fd, close newfd */
4342 dup2(newfd, fd);
4343 close(newfd);
4345 } else {
4346 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4347 fd, strerror(errno));
4348 return NULL;
4352 s = qemu_mallocz(sizeof(NetSocketState));
4353 if (!s)
4354 return NULL;
4355 s->fd = fd;
4357 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4358 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4360 /* mcast: save bound address as dst */
4361 if (is_connected) s->dgram_dst=saddr;
4363 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4364 "socket: fd=%d (%s mcast=%s:%d)",
4365 fd, is_connected? "cloned" : "",
4366 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4367 return s;
4370 static void net_socket_connect(void *opaque)
4372 NetSocketState *s = opaque;
4373 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4376 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4377 int is_connected)
4379 NetSocketState *s;
4380 s = qemu_mallocz(sizeof(NetSocketState));
4381 if (!s)
4382 return NULL;
4383 s->fd = fd;
4384 s->vc = qemu_new_vlan_client(vlan,
4385 net_socket_receive, NULL, s);
4386 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4387 "socket: fd=%d", fd);
4388 if (is_connected) {
4389 net_socket_connect(s);
4390 } else {
4391 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4393 return s;
4396 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4397 int is_connected)
4399 int so_type=-1, optlen=sizeof(so_type);
4401 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4402 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4403 return NULL;
4405 switch(so_type) {
4406 case SOCK_DGRAM:
4407 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4408 case SOCK_STREAM:
4409 return net_socket_fd_init_stream(vlan, fd, is_connected);
4410 default:
4411 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4412 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4413 return net_socket_fd_init_stream(vlan, fd, is_connected);
4415 return NULL;
4418 static void net_socket_accept(void *opaque)
4420 NetSocketListenState *s = opaque;
4421 NetSocketState *s1;
4422 struct sockaddr_in saddr;
4423 socklen_t len;
4424 int fd;
4426 for(;;) {
4427 len = sizeof(saddr);
4428 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4429 if (fd < 0 && errno != EINTR) {
4430 return;
4431 } else if (fd >= 0) {
4432 break;
4435 s1 = net_socket_fd_init(s->vlan, fd, 1);
4436 if (!s1) {
4437 closesocket(fd);
4438 } else {
4439 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4440 "socket: connection from %s:%d",
4441 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4445 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4447 NetSocketListenState *s;
4448 int fd, val, ret;
4449 struct sockaddr_in saddr;
4451 if (parse_host_port(&saddr, host_str) < 0)
4452 return -1;
4454 s = qemu_mallocz(sizeof(NetSocketListenState));
4455 if (!s)
4456 return -1;
4458 fd = socket(PF_INET, SOCK_STREAM, 0);
4459 if (fd < 0) {
4460 perror("socket");
4461 return -1;
4463 socket_set_nonblock(fd);
4465 /* allow fast reuse */
4466 val = 1;
4467 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4469 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4470 if (ret < 0) {
4471 perror("bind");
4472 return -1;
4474 ret = listen(fd, 0);
4475 if (ret < 0) {
4476 perror("listen");
4477 return -1;
4479 s->vlan = vlan;
4480 s->fd = fd;
4481 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4482 return 0;
4485 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4487 NetSocketState *s;
4488 int fd, connected, ret, err;
4489 struct sockaddr_in saddr;
4491 if (parse_host_port(&saddr, host_str) < 0)
4492 return -1;
4494 fd = socket(PF_INET, SOCK_STREAM, 0);
4495 if (fd < 0) {
4496 perror("socket");
4497 return -1;
4499 socket_set_nonblock(fd);
4501 connected = 0;
4502 for(;;) {
4503 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4504 if (ret < 0) {
4505 err = socket_error();
4506 if (err == EINTR || err == EWOULDBLOCK) {
4507 } else if (err == EINPROGRESS) {
4508 break;
4509 #ifdef _WIN32
4510 } else if (err == WSAEALREADY) {
4511 break;
4512 #endif
4513 } else {
4514 perror("connect");
4515 closesocket(fd);
4516 return -1;
4518 } else {
4519 connected = 1;
4520 break;
4523 s = net_socket_fd_init(vlan, fd, connected);
4524 if (!s)
4525 return -1;
4526 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4527 "socket: connect to %s:%d",
4528 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4529 return 0;
4532 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4534 NetSocketState *s;
4535 int fd;
4536 struct sockaddr_in saddr;
4538 if (parse_host_port(&saddr, host_str) < 0)
4539 return -1;
4542 fd = net_socket_mcast_create(&saddr);
4543 if (fd < 0)
4544 return -1;
4546 s = net_socket_fd_init(vlan, fd, 0);
4547 if (!s)
4548 return -1;
4550 s->dgram_dst = saddr;
4552 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4553 "socket: mcast=%s:%d",
4554 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4555 return 0;
4559 static const char *get_word(char *buf, int buf_size, const char *p)
4561 char *q;
4562 int substring;
4564 substring = 0;
4565 q = buf;
4566 while (*p != '\0') {
4567 if (*p == '\\') {
4568 p++;
4569 if (*p == '\0')
4570 break;
4571 } else if (*p == '\"') {
4572 substring = !substring;
4573 p++;
4574 continue;
4575 } else if (!substring && (*p == ',' || *p == '='))
4576 break;
4577 if (q && (q - buf) < buf_size - 1)
4578 *q++ = *p;
4579 p++;
4581 if (q)
4582 *q = '\0';
4584 return p;
4587 static int get_param_value(char *buf, int buf_size,
4588 const char *tag, const char *str)
4590 const char *p;
4591 char option[128];
4593 p = str;
4594 for(;;) {
4595 p = get_word(option, sizeof(option), p);
4596 if (*p != '=')
4597 break;
4598 p++;
4599 if (!strcmp(tag, option)) {
4600 (void)get_word(buf, buf_size, p);
4601 return strlen(buf);
4602 } else {
4603 p = get_word(NULL, 0, p);
4605 if (*p != ',')
4606 break;
4607 p++;
4609 return 0;
4612 static int check_params(char *buf, int buf_size,
4613 char **params, const char *str)
4615 const char *p;
4616 int i;
4618 p = str;
4619 for(;;) {
4620 p = get_word(buf, buf_size, p);
4621 if (*p != '=')
4622 return -1;
4623 p++;
4624 for(i = 0; params[i] != NULL; i++)
4625 if (!strcmp(params[i], buf))
4626 break;
4627 if (params[i] == NULL)
4628 return -1;
4629 p = get_word(NULL, 0, p);
4630 if (*p != ',')
4631 break;
4632 p++;
4634 return 0;
4638 static int net_client_init(const char *str)
4640 const char *p;
4641 char *q;
4642 char device[64];
4643 char buf[1024];
4644 int vlan_id, ret;
4645 VLANState *vlan;
4647 p = str;
4648 q = device;
4649 while (*p != '\0' && *p != ',') {
4650 if ((q - device) < sizeof(device) - 1)
4651 *q++ = *p;
4652 p++;
4654 *q = '\0';
4655 if (*p == ',')
4656 p++;
4657 vlan_id = 0;
4658 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4659 vlan_id = strtol(buf, NULL, 0);
4661 vlan = qemu_find_vlan(vlan_id);
4662 if (!vlan) {
4663 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4664 return -1;
4666 if (!strcmp(device, "nic")) {
4667 NICInfo *nd;
4668 uint8_t *macaddr;
4670 if (nb_nics >= MAX_NICS) {
4671 fprintf(stderr, "Too Many NICs\n");
4672 return -1;
4674 nd = &nd_table[nb_nics];
4675 macaddr = nd->macaddr;
4676 macaddr[0] = 0x52;
4677 macaddr[1] = 0x54;
4678 macaddr[2] = 0x00;
4679 macaddr[3] = 0x12;
4680 macaddr[4] = 0x34;
4681 macaddr[5] = 0x56 + nb_nics;
4683 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4684 if (parse_macaddr(macaddr, buf) < 0) {
4685 fprintf(stderr, "invalid syntax for ethernet address\n");
4686 return -1;
4689 if (get_param_value(buf, sizeof(buf), "model", p)) {
4690 nd->model = strdup(buf);
4692 nd->vlan = vlan;
4693 nb_nics++;
4694 vlan->nb_guest_devs++;
4695 ret = 0;
4696 } else
4697 if (!strcmp(device, "none")) {
4698 /* does nothing. It is needed to signal that no network cards
4699 are wanted */
4700 ret = 0;
4701 } else
4702 #ifdef CONFIG_SLIRP
4703 if (!strcmp(device, "user")) {
4704 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4705 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4707 vlan->nb_host_devs++;
4708 ret = net_slirp_init(vlan);
4709 } else
4710 #endif
4711 #ifdef _WIN32
4712 if (!strcmp(device, "tap")) {
4713 char ifname[64];
4714 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4715 fprintf(stderr, "tap: no interface name\n");
4716 return -1;
4718 vlan->nb_host_devs++;
4719 ret = tap_win32_init(vlan, ifname);
4720 } else
4721 #else
4722 if (!strcmp(device, "tap")) {
4723 char ifname[64];
4724 char setup_script[1024], down_script[1024];
4725 int fd;
4726 vlan->nb_host_devs++;
4727 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4728 fd = strtol(buf, NULL, 0);
4729 ret = -1;
4730 if (net_tap_fd_init(vlan, fd))
4731 ret = 0;
4732 } else {
4733 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4734 ifname[0] = '\0';
4736 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4737 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4739 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4740 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4742 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4744 } else
4745 #endif
4746 if (!strcmp(device, "socket")) {
4747 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4748 int fd;
4749 fd = strtol(buf, NULL, 0);
4750 ret = -1;
4751 if (net_socket_fd_init(vlan, fd, 1))
4752 ret = 0;
4753 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4754 ret = net_socket_listen_init(vlan, buf);
4755 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4756 ret = net_socket_connect_init(vlan, buf);
4757 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4758 ret = net_socket_mcast_init(vlan, buf);
4759 } else {
4760 fprintf(stderr, "Unknown socket options: %s\n", p);
4761 return -1;
4763 vlan->nb_host_devs++;
4764 } else
4766 fprintf(stderr, "Unknown network device: %s\n", device);
4767 return -1;
4769 if (ret < 0) {
4770 fprintf(stderr, "Could not initialize device '%s'\n", device);
4773 return ret;
4776 void do_info_network(void)
4778 VLANState *vlan;
4779 VLANClientState *vc;
4781 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4782 term_printf("VLAN %d devices:\n", vlan->id);
4783 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4784 term_printf(" %s\n", vc->info_str);
4788 #define HD_ALIAS "file=\"%s\",index=%d,media=disk"
4789 #ifdef TARGET_PPC
4790 #define CDROM_ALIAS "index=1,media=cdrom"
4791 #else
4792 #define CDROM_ALIAS "index=2,media=cdrom"
4793 #endif
4794 #define FD_ALIAS "index=%d,if=floppy"
4795 #define PFLASH_ALIAS "file=\"%s\",if=pflash"
4796 #define MTD_ALIAS "file=\"%s\",if=mtd"
4797 #define SD_ALIAS "index=0,if=sd"
4799 static int drive_add(const char *fmt, ...)
4801 va_list ap;
4803 if (nb_drives_opt >= MAX_DRIVES) {
4804 fprintf(stderr, "qemu: too many drives\n");
4805 exit(1);
4808 va_start(ap, fmt);
4809 vsnprintf(drives_opt[nb_drives_opt], sizeof(drives_opt[0]), fmt, ap);
4810 va_end(ap);
4812 return nb_drives_opt++;
4815 int drive_get_index(BlockInterfaceType interface, int bus, int unit)
4817 int index;
4819 /* seek interface, bus and unit */
4821 for (index = 0; index < nb_drives; index++)
4822 if (drives_table[index].interface == interface &&
4823 drives_table[index].bus == bus &&
4824 drives_table[index].unit == unit)
4825 return index;
4827 return -1;
4830 int drive_get_max_bus(BlockInterfaceType interface)
4832 int max_bus;
4833 int index;
4835 max_bus = -1;
4836 for (index = 0; index < nb_drives; index++) {
4837 if(drives_table[index].interface == interface &&
4838 drives_table[index].bus > max_bus)
4839 max_bus = drives_table[index].bus;
4841 return max_bus;
4844 static int drive_init(const char *str, int snapshot, QEMUMachine *machine)
4846 char buf[128];
4847 char file[1024];
4848 char devname[128];
4849 const char *mediastr = "";
4850 BlockInterfaceType interface;
4851 enum { MEDIA_DISK, MEDIA_CDROM } media;
4852 int bus_id, unit_id;
4853 int cyls, heads, secs, translation;
4854 BlockDriverState *bdrv;
4855 int max_devs;
4856 int index;
4857 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4858 "secs", "trans", "media", "snapshot", "file", NULL };
4860 if (check_params(buf, sizeof(buf), params, str) < 0) {
4861 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4862 buf, str);
4863 return -1;
4866 file[0] = 0;
4867 cyls = heads = secs = 0;
4868 bus_id = 0;
4869 unit_id = -1;
4870 translation = BIOS_ATA_TRANSLATION_AUTO;
4871 index = -1;
4873 if (!strcmp(machine->name, "realview") ||
4874 !strcmp(machine->name, "SS-5") ||
4875 !strcmp(machine->name, "SS-10") ||
4876 !strcmp(machine->name, "SS-600MP") ||
4877 !strcmp(machine->name, "versatilepb") ||
4878 !strcmp(machine->name, "versatileab")) {
4879 interface = IF_SCSI;
4880 max_devs = MAX_SCSI_DEVS;
4881 strcpy(devname, "scsi");
4882 } else {
4883 interface = IF_IDE;
4884 max_devs = MAX_IDE_DEVS;
4885 strcpy(devname, "ide");
4887 media = MEDIA_DISK;
4889 /* extract parameters */
4891 if (get_param_value(buf, sizeof(buf), "bus", str)) {
4892 bus_id = strtol(buf, NULL, 0);
4893 if (bus_id < 0) {
4894 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4895 return -1;
4899 if (get_param_value(buf, sizeof(buf), "unit", str)) {
4900 unit_id = strtol(buf, NULL, 0);
4901 if (unit_id < 0) {
4902 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4903 return -1;
4907 if (get_param_value(buf, sizeof(buf), "if", str)) {
4908 strncpy(devname, buf, sizeof(devname));
4909 if (!strcmp(buf, "ide")) {
4910 interface = IF_IDE;
4911 max_devs = MAX_IDE_DEVS;
4912 } else if (!strcmp(buf, "scsi")) {
4913 interface = IF_SCSI;
4914 max_devs = MAX_SCSI_DEVS;
4915 } else if (!strcmp(buf, "floppy")) {
4916 interface = IF_FLOPPY;
4917 max_devs = 0;
4918 } else if (!strcmp(buf, "pflash")) {
4919 interface = IF_PFLASH;
4920 max_devs = 0;
4921 } else if (!strcmp(buf, "mtd")) {
4922 interface = IF_MTD;
4923 max_devs = 0;
4924 } else if (!strcmp(buf, "sd")) {
4925 interface = IF_SD;
4926 max_devs = 0;
4927 } else {
4928 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
4929 return -1;
4933 if (get_param_value(buf, sizeof(buf), "index", str)) {
4934 index = strtol(buf, NULL, 0);
4935 if (index < 0) {
4936 fprintf(stderr, "qemu: '%s' invalid index\n", str);
4937 return -1;
4941 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
4942 cyls = strtol(buf, NULL, 0);
4945 if (get_param_value(buf, sizeof(buf), "heads", str)) {
4946 heads = strtol(buf, NULL, 0);
4949 if (get_param_value(buf, sizeof(buf), "secs", str)) {
4950 secs = strtol(buf, NULL, 0);
4953 if (cyls || heads || secs) {
4954 if (cyls < 1 || cyls > 16383) {
4955 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
4956 return -1;
4958 if (heads < 1 || heads > 16) {
4959 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
4960 return -1;
4962 if (secs < 1 || secs > 63) {
4963 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
4964 return -1;
4968 if (get_param_value(buf, sizeof(buf), "trans", str)) {
4969 if (!cyls) {
4970 fprintf(stderr,
4971 "qemu: '%s' trans must be used with cyls,heads and secs\n",
4972 str);
4973 return -1;
4975 if (!strcmp(buf, "none"))
4976 translation = BIOS_ATA_TRANSLATION_NONE;
4977 else if (!strcmp(buf, "lba"))
4978 translation = BIOS_ATA_TRANSLATION_LBA;
4979 else if (!strcmp(buf, "auto"))
4980 translation = BIOS_ATA_TRANSLATION_AUTO;
4981 else {
4982 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
4983 return -1;
4987 if (get_param_value(buf, sizeof(buf), "media", str)) {
4988 if (!strcmp(buf, "disk")) {
4989 media = MEDIA_DISK;
4990 } else if (!strcmp(buf, "cdrom")) {
4991 if (cyls || secs || heads) {
4992 fprintf(stderr,
4993 "qemu: '%s' invalid physical CHS format\n", str);
4994 return -1;
4996 media = MEDIA_CDROM;
4997 } else {
4998 fprintf(stderr, "qemu: '%s' invalid media\n", str);
4999 return -1;
5003 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5004 if (!strcmp(buf, "on"))
5005 snapshot = 1;
5006 else if (!strcmp(buf, "off"))
5007 snapshot = 0;
5008 else {
5009 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5010 return -1;
5014 get_param_value(file, sizeof(file), "file", str);
5016 /* compute bus and unit according index */
5018 if (index != -1) {
5019 if (bus_id != 0 || unit_id != -1) {
5020 fprintf(stderr,
5021 "qemu: '%s' index cannot be used with bus and unit\n", str);
5022 return -1;
5024 if (max_devs == 0)
5026 unit_id = index;
5027 bus_id = 0;
5028 } else {
5029 unit_id = index % max_devs;
5030 bus_id = index / max_devs;
5034 /* if user doesn't specify a unit_id,
5035 * try to find the first free
5038 if (unit_id == -1) {
5039 unit_id = 0;
5040 while (drive_get_index(interface, bus_id, unit_id) != -1) {
5041 unit_id++;
5042 if (max_devs && unit_id >= max_devs) {
5043 unit_id -= max_devs;
5044 bus_id++;
5049 /* check unit id */
5051 if (max_devs && unit_id >= max_devs) {
5052 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5053 str, unit_id, max_devs - 1);
5054 return -1;
5058 * ignore multiple definitions
5061 if (drive_get_index(interface, bus_id, unit_id) != -1)
5062 return 0;
5064 /* init */
5066 if (interface == IF_IDE || interface == IF_SCSI)
5067 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5068 snprintf(buf, sizeof(buf), max_devs ? "%1$s%4$i%2$s%3$i" : "%s%s%i",
5069 devname, mediastr, unit_id, bus_id);
5070 bdrv = bdrv_new(buf);
5071 drives_table[nb_drives].bdrv = bdrv;
5072 drives_table[nb_drives].interface = interface;
5073 drives_table[nb_drives].bus = bus_id;
5074 drives_table[nb_drives].unit = unit_id;
5075 nb_drives++;
5077 switch(interface) {
5078 case IF_IDE:
5079 case IF_SCSI:
5080 switch(media) {
5081 case MEDIA_DISK:
5082 if (cyls != 0) {
5083 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5084 bdrv_set_translation_hint(bdrv, translation);
5086 break;
5087 case MEDIA_CDROM:
5088 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5089 break;
5091 break;
5092 case IF_SD:
5093 /* FIXME: This isn't really a floppy, but it's a reasonable
5094 approximation. */
5095 case IF_FLOPPY:
5096 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5097 break;
5098 case IF_PFLASH:
5099 case IF_MTD:
5100 break;
5102 if (!file[0])
5103 return 0;
5104 if (bdrv_open(bdrv, file, snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
5105 qemu_key_check(bdrv, file)) {
5106 fprintf(stderr, "qemu: could not open disk image %s\n",
5107 file);
5108 return -1;
5110 return 0;
5113 /***********************************************************/
5114 /* USB devices */
5116 static USBPort *used_usb_ports;
5117 static USBPort *free_usb_ports;
5119 /* ??? Maybe change this to register a hub to keep track of the topology. */
5120 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5121 usb_attachfn attach)
5123 port->opaque = opaque;
5124 port->index = index;
5125 port->attach = attach;
5126 port->next = free_usb_ports;
5127 free_usb_ports = port;
5130 static int usb_device_add(const char *devname)
5132 const char *p;
5133 USBDevice *dev;
5134 USBPort *port;
5136 if (!free_usb_ports)
5137 return -1;
5139 if (strstart(devname, "host:", &p)) {
5140 dev = usb_host_device_open(p);
5141 } else if (!strcmp(devname, "mouse")) {
5142 dev = usb_mouse_init();
5143 } else if (!strcmp(devname, "tablet")) {
5144 dev = usb_tablet_init();
5145 } else if (!strcmp(devname, "keyboard")) {
5146 dev = usb_keyboard_init();
5147 } else if (strstart(devname, "disk:", &p)) {
5148 dev = usb_msd_init(p);
5149 } else if (!strcmp(devname, "wacom-tablet")) {
5150 dev = usb_wacom_init();
5151 } else {
5152 return -1;
5154 if (!dev)
5155 return -1;
5157 /* Find a USB port to add the device to. */
5158 port = free_usb_ports;
5159 if (!port->next) {
5160 USBDevice *hub;
5162 /* Create a new hub and chain it on. */
5163 free_usb_ports = NULL;
5164 port->next = used_usb_ports;
5165 used_usb_ports = port;
5167 hub = usb_hub_init(VM_USB_HUB_SIZE);
5168 usb_attach(port, hub);
5169 port = free_usb_ports;
5172 free_usb_ports = port->next;
5173 port->next = used_usb_ports;
5174 used_usb_ports = port;
5175 usb_attach(port, dev);
5176 return 0;
5179 static int usb_device_del(const char *devname)
5181 USBPort *port;
5182 USBPort **lastp;
5183 USBDevice *dev;
5184 int bus_num, addr;
5185 const char *p;
5187 if (!used_usb_ports)
5188 return -1;
5190 p = strchr(devname, '.');
5191 if (!p)
5192 return -1;
5193 bus_num = strtoul(devname, NULL, 0);
5194 addr = strtoul(p + 1, NULL, 0);
5195 if (bus_num != 0)
5196 return -1;
5198 lastp = &used_usb_ports;
5199 port = used_usb_ports;
5200 while (port && port->dev->addr != addr) {
5201 lastp = &port->next;
5202 port = port->next;
5205 if (!port)
5206 return -1;
5208 dev = port->dev;
5209 *lastp = port->next;
5210 usb_attach(port, NULL);
5211 dev->handle_destroy(dev);
5212 port->next = free_usb_ports;
5213 free_usb_ports = port;
5214 return 0;
5217 void do_usb_add(const char *devname)
5219 int ret;
5220 ret = usb_device_add(devname);
5221 if (ret < 0)
5222 term_printf("Could not add USB device '%s'\n", devname);
5225 void do_usb_del(const char *devname)
5227 int ret;
5228 ret = usb_device_del(devname);
5229 if (ret < 0)
5230 term_printf("Could not remove USB device '%s'\n", devname);
5233 void usb_info(void)
5235 USBDevice *dev;
5236 USBPort *port;
5237 const char *speed_str;
5239 if (!usb_enabled) {
5240 term_printf("USB support not enabled\n");
5241 return;
5244 for (port = used_usb_ports; port; port = port->next) {
5245 dev = port->dev;
5246 if (!dev)
5247 continue;
5248 switch(dev->speed) {
5249 case USB_SPEED_LOW:
5250 speed_str = "1.5";
5251 break;
5252 case USB_SPEED_FULL:
5253 speed_str = "12";
5254 break;
5255 case USB_SPEED_HIGH:
5256 speed_str = "480";
5257 break;
5258 default:
5259 speed_str = "?";
5260 break;
5262 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5263 0, dev->addr, speed_str, dev->devname);
5267 /***********************************************************/
5268 /* PCMCIA/Cardbus */
5270 static struct pcmcia_socket_entry_s {
5271 struct pcmcia_socket_s *socket;
5272 struct pcmcia_socket_entry_s *next;
5273 } *pcmcia_sockets = 0;
5275 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5277 struct pcmcia_socket_entry_s *entry;
5279 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5280 entry->socket = socket;
5281 entry->next = pcmcia_sockets;
5282 pcmcia_sockets = entry;
5285 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5287 struct pcmcia_socket_entry_s *entry, **ptr;
5289 ptr = &pcmcia_sockets;
5290 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5291 if (entry->socket == socket) {
5292 *ptr = entry->next;
5293 qemu_free(entry);
5297 void pcmcia_info(void)
5299 struct pcmcia_socket_entry_s *iter;
5300 if (!pcmcia_sockets)
5301 term_printf("No PCMCIA sockets\n");
5303 for (iter = pcmcia_sockets; iter; iter = iter->next)
5304 term_printf("%s: %s\n", iter->socket->slot_string,
5305 iter->socket->attached ? iter->socket->card_string :
5306 "Empty");
5309 /***********************************************************/
5310 /* dumb display */
5312 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5316 static void dumb_resize(DisplayState *ds, int w, int h)
5320 static void dumb_refresh(DisplayState *ds)
5322 #if defined(CONFIG_SDL)
5323 vga_hw_update();
5324 #endif
5327 static void dumb_display_init(DisplayState *ds)
5329 ds->data = NULL;
5330 ds->linesize = 0;
5331 ds->depth = 0;
5332 ds->dpy_update = dumb_update;
5333 ds->dpy_resize = dumb_resize;
5334 ds->dpy_refresh = dumb_refresh;
5337 /***********************************************************/
5338 /* I/O handling */
5340 #define MAX_IO_HANDLERS 64
5342 typedef struct IOHandlerRecord {
5343 int fd;
5344 IOCanRWHandler *fd_read_poll;
5345 IOHandler *fd_read;
5346 IOHandler *fd_write;
5347 int deleted;
5348 void *opaque;
5349 /* temporary data */
5350 struct pollfd *ufd;
5351 struct IOHandlerRecord *next;
5352 } IOHandlerRecord;
5354 static IOHandlerRecord *first_io_handler;
5356 /* XXX: fd_read_poll should be suppressed, but an API change is
5357 necessary in the character devices to suppress fd_can_read(). */
5358 int qemu_set_fd_handler2(int fd,
5359 IOCanRWHandler *fd_read_poll,
5360 IOHandler *fd_read,
5361 IOHandler *fd_write,
5362 void *opaque)
5364 IOHandlerRecord **pioh, *ioh;
5366 if (!fd_read && !fd_write) {
5367 pioh = &first_io_handler;
5368 for(;;) {
5369 ioh = *pioh;
5370 if (ioh == NULL)
5371 break;
5372 if (ioh->fd == fd) {
5373 ioh->deleted = 1;
5374 break;
5376 pioh = &ioh->next;
5378 } else {
5379 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5380 if (ioh->fd == fd)
5381 goto found;
5383 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5384 if (!ioh)
5385 return -1;
5386 ioh->next = first_io_handler;
5387 first_io_handler = ioh;
5388 found:
5389 ioh->fd = fd;
5390 ioh->fd_read_poll = fd_read_poll;
5391 ioh->fd_read = fd_read;
5392 ioh->fd_write = fd_write;
5393 ioh->opaque = opaque;
5394 ioh->deleted = 0;
5396 return 0;
5399 int qemu_set_fd_handler(int fd,
5400 IOHandler *fd_read,
5401 IOHandler *fd_write,
5402 void *opaque)
5404 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5407 /***********************************************************/
5408 /* Polling handling */
5410 typedef struct PollingEntry {
5411 PollingFunc *func;
5412 void *opaque;
5413 struct PollingEntry *next;
5414 } PollingEntry;
5416 static PollingEntry *first_polling_entry;
5418 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5420 PollingEntry **ppe, *pe;
5421 pe = qemu_mallocz(sizeof(PollingEntry));
5422 if (!pe)
5423 return -1;
5424 pe->func = func;
5425 pe->opaque = opaque;
5426 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5427 *ppe = pe;
5428 return 0;
5431 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5433 PollingEntry **ppe, *pe;
5434 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5435 pe = *ppe;
5436 if (pe->func == func && pe->opaque == opaque) {
5437 *ppe = pe->next;
5438 qemu_free(pe);
5439 break;
5444 #ifdef _WIN32
5445 /***********************************************************/
5446 /* Wait objects support */
5447 typedef struct WaitObjects {
5448 int num;
5449 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5450 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5451 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5452 } WaitObjects;
5454 static WaitObjects wait_objects = {0};
5456 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5458 WaitObjects *w = &wait_objects;
5460 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5461 return -1;
5462 w->events[w->num] = handle;
5463 w->func[w->num] = func;
5464 w->opaque[w->num] = opaque;
5465 w->num++;
5466 return 0;
5469 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5471 int i, found;
5472 WaitObjects *w = &wait_objects;
5474 found = 0;
5475 for (i = 0; i < w->num; i++) {
5476 if (w->events[i] == handle)
5477 found = 1;
5478 if (found) {
5479 w->events[i] = w->events[i + 1];
5480 w->func[i] = w->func[i + 1];
5481 w->opaque[i] = w->opaque[i + 1];
5484 if (found)
5485 w->num--;
5487 #endif
5489 /***********************************************************/
5490 /* savevm/loadvm support */
5492 #define IO_BUF_SIZE 32768
5494 struct QEMUFile {
5495 FILE *outfile;
5496 BlockDriverState *bs;
5497 int is_file;
5498 int is_writable;
5499 int64_t base_offset;
5500 int64_t buf_offset; /* start of buffer when writing, end of buffer
5501 when reading */
5502 int buf_index;
5503 int buf_size; /* 0 when writing */
5504 uint8_t buf[IO_BUF_SIZE];
5507 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5509 QEMUFile *f;
5511 f = qemu_mallocz(sizeof(QEMUFile));
5512 if (!f)
5513 return NULL;
5514 if (!strcmp(mode, "wb")) {
5515 f->is_writable = 1;
5516 } else if (!strcmp(mode, "rb")) {
5517 f->is_writable = 0;
5518 } else {
5519 goto fail;
5521 f->outfile = fopen(filename, mode);
5522 if (!f->outfile)
5523 goto fail;
5524 f->is_file = 1;
5525 return f;
5526 fail:
5527 if (f->outfile)
5528 fclose(f->outfile);
5529 qemu_free(f);
5530 return NULL;
5533 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5535 QEMUFile *f;
5537 f = qemu_mallocz(sizeof(QEMUFile));
5538 if (!f)
5539 return NULL;
5540 f->is_file = 0;
5541 f->bs = bs;
5542 f->is_writable = is_writable;
5543 f->base_offset = offset;
5544 return f;
5547 void qemu_fflush(QEMUFile *f)
5549 if (!f->is_writable)
5550 return;
5551 if (f->buf_index > 0) {
5552 if (f->is_file) {
5553 fseek(f->outfile, f->buf_offset, SEEK_SET);
5554 fwrite(f->buf, 1, f->buf_index, f->outfile);
5555 } else {
5556 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5557 f->buf, f->buf_index);
5559 f->buf_offset += f->buf_index;
5560 f->buf_index = 0;
5564 static void qemu_fill_buffer(QEMUFile *f)
5566 int len;
5568 if (f->is_writable)
5569 return;
5570 if (f->is_file) {
5571 fseek(f->outfile, f->buf_offset, SEEK_SET);
5572 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5573 if (len < 0)
5574 len = 0;
5575 } else {
5576 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5577 f->buf, IO_BUF_SIZE);
5578 if (len < 0)
5579 len = 0;
5581 f->buf_index = 0;
5582 f->buf_size = len;
5583 f->buf_offset += len;
5586 void qemu_fclose(QEMUFile *f)
5588 if (f->is_writable)
5589 qemu_fflush(f);
5590 if (f->is_file) {
5591 fclose(f->outfile);
5593 qemu_free(f);
5596 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5598 int l;
5599 while (size > 0) {
5600 l = IO_BUF_SIZE - f->buf_index;
5601 if (l > size)
5602 l = size;
5603 memcpy(f->buf + f->buf_index, buf, l);
5604 f->buf_index += l;
5605 buf += l;
5606 size -= l;
5607 if (f->buf_index >= IO_BUF_SIZE)
5608 qemu_fflush(f);
5612 void qemu_put_byte(QEMUFile *f, int v)
5614 f->buf[f->buf_index++] = v;
5615 if (f->buf_index >= IO_BUF_SIZE)
5616 qemu_fflush(f);
5619 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5621 int size, l;
5623 size = size1;
5624 while (size > 0) {
5625 l = f->buf_size - f->buf_index;
5626 if (l == 0) {
5627 qemu_fill_buffer(f);
5628 l = f->buf_size - f->buf_index;
5629 if (l == 0)
5630 break;
5632 if (l > size)
5633 l = size;
5634 memcpy(buf, f->buf + f->buf_index, l);
5635 f->buf_index += l;
5636 buf += l;
5637 size -= l;
5639 return size1 - size;
5642 int qemu_get_byte(QEMUFile *f)
5644 if (f->buf_index >= f->buf_size) {
5645 qemu_fill_buffer(f);
5646 if (f->buf_index >= f->buf_size)
5647 return 0;
5649 return f->buf[f->buf_index++];
5652 int64_t qemu_ftell(QEMUFile *f)
5654 return f->buf_offset - f->buf_size + f->buf_index;
5657 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5659 if (whence == SEEK_SET) {
5660 /* nothing to do */
5661 } else if (whence == SEEK_CUR) {
5662 pos += qemu_ftell(f);
5663 } else {
5664 /* SEEK_END not supported */
5665 return -1;
5667 if (f->is_writable) {
5668 qemu_fflush(f);
5669 f->buf_offset = pos;
5670 } else {
5671 f->buf_offset = pos;
5672 f->buf_index = 0;
5673 f->buf_size = 0;
5675 return pos;
5678 void qemu_put_be16(QEMUFile *f, unsigned int v)
5680 qemu_put_byte(f, v >> 8);
5681 qemu_put_byte(f, v);
5684 void qemu_put_be32(QEMUFile *f, unsigned int v)
5686 qemu_put_byte(f, v >> 24);
5687 qemu_put_byte(f, v >> 16);
5688 qemu_put_byte(f, v >> 8);
5689 qemu_put_byte(f, v);
5692 void qemu_put_be64(QEMUFile *f, uint64_t v)
5694 qemu_put_be32(f, v >> 32);
5695 qemu_put_be32(f, v);
5698 unsigned int qemu_get_be16(QEMUFile *f)
5700 unsigned int v;
5701 v = qemu_get_byte(f) << 8;
5702 v |= qemu_get_byte(f);
5703 return v;
5706 unsigned int qemu_get_be32(QEMUFile *f)
5708 unsigned int v;
5709 v = qemu_get_byte(f) << 24;
5710 v |= qemu_get_byte(f) << 16;
5711 v |= qemu_get_byte(f) << 8;
5712 v |= qemu_get_byte(f);
5713 return v;
5716 uint64_t qemu_get_be64(QEMUFile *f)
5718 uint64_t v;
5719 v = (uint64_t)qemu_get_be32(f) << 32;
5720 v |= qemu_get_be32(f);
5721 return v;
5724 typedef struct SaveStateEntry {
5725 char idstr[256];
5726 int instance_id;
5727 int version_id;
5728 SaveStateHandler *save_state;
5729 LoadStateHandler *load_state;
5730 void *opaque;
5731 struct SaveStateEntry *next;
5732 } SaveStateEntry;
5734 static SaveStateEntry *first_se;
5736 int register_savevm(const char *idstr,
5737 int instance_id,
5738 int version_id,
5739 SaveStateHandler *save_state,
5740 LoadStateHandler *load_state,
5741 void *opaque)
5743 SaveStateEntry *se, **pse;
5745 se = qemu_malloc(sizeof(SaveStateEntry));
5746 if (!se)
5747 return -1;
5748 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5749 se->instance_id = instance_id;
5750 se->version_id = version_id;
5751 se->save_state = save_state;
5752 se->load_state = load_state;
5753 se->opaque = opaque;
5754 se->next = NULL;
5756 /* add at the end of list */
5757 pse = &first_se;
5758 while (*pse != NULL)
5759 pse = &(*pse)->next;
5760 *pse = se;
5761 return 0;
5764 #define QEMU_VM_FILE_MAGIC 0x5145564d
5765 #define QEMU_VM_FILE_VERSION 0x00000002
5767 static int qemu_savevm_state(QEMUFile *f)
5769 SaveStateEntry *se;
5770 int len, ret;
5771 int64_t cur_pos, len_pos, total_len_pos;
5773 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5774 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5775 total_len_pos = qemu_ftell(f);
5776 qemu_put_be64(f, 0); /* total size */
5778 for(se = first_se; se != NULL; se = se->next) {
5779 /* ID string */
5780 len = strlen(se->idstr);
5781 qemu_put_byte(f, len);
5782 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5784 qemu_put_be32(f, se->instance_id);
5785 qemu_put_be32(f, se->version_id);
5787 /* record size: filled later */
5788 len_pos = qemu_ftell(f);
5789 qemu_put_be32(f, 0);
5790 se->save_state(f, se->opaque);
5792 /* fill record size */
5793 cur_pos = qemu_ftell(f);
5794 len = cur_pos - len_pos - 4;
5795 qemu_fseek(f, len_pos, SEEK_SET);
5796 qemu_put_be32(f, len);
5797 qemu_fseek(f, cur_pos, SEEK_SET);
5799 cur_pos = qemu_ftell(f);
5800 qemu_fseek(f, total_len_pos, SEEK_SET);
5801 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5802 qemu_fseek(f, cur_pos, SEEK_SET);
5804 ret = 0;
5805 return ret;
5808 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5810 SaveStateEntry *se;
5812 for(se = first_se; se != NULL; se = se->next) {
5813 if (!strcmp(se->idstr, idstr) &&
5814 instance_id == se->instance_id)
5815 return se;
5817 return NULL;
5820 static int qemu_loadvm_state(QEMUFile *f)
5822 SaveStateEntry *se;
5823 int len, ret, instance_id, record_len, version_id;
5824 int64_t total_len, end_pos, cur_pos;
5825 unsigned int v;
5826 char idstr[256];
5828 v = qemu_get_be32(f);
5829 if (v != QEMU_VM_FILE_MAGIC)
5830 goto fail;
5831 v = qemu_get_be32(f);
5832 if (v != QEMU_VM_FILE_VERSION) {
5833 fail:
5834 ret = -1;
5835 goto the_end;
5837 total_len = qemu_get_be64(f);
5838 end_pos = total_len + qemu_ftell(f);
5839 for(;;) {
5840 if (qemu_ftell(f) >= end_pos)
5841 break;
5842 len = qemu_get_byte(f);
5843 qemu_get_buffer(f, (uint8_t *)idstr, len);
5844 idstr[len] = '\0';
5845 instance_id = qemu_get_be32(f);
5846 version_id = qemu_get_be32(f);
5847 record_len = qemu_get_be32(f);
5848 #if 0
5849 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5850 idstr, instance_id, version_id, record_len);
5851 #endif
5852 cur_pos = qemu_ftell(f);
5853 se = find_se(idstr, instance_id);
5854 if (!se) {
5855 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5856 instance_id, idstr);
5857 } else {
5858 ret = se->load_state(f, se->opaque, version_id);
5859 if (ret < 0) {
5860 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5861 instance_id, idstr);
5864 /* always seek to exact end of record */
5865 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5867 ret = 0;
5868 the_end:
5869 return ret;
5872 /* device can contain snapshots */
5873 static int bdrv_can_snapshot(BlockDriverState *bs)
5875 return (bs &&
5876 !bdrv_is_removable(bs) &&
5877 !bdrv_is_read_only(bs));
5880 /* device must be snapshots in order to have a reliable snapshot */
5881 static int bdrv_has_snapshot(BlockDriverState *bs)
5883 return (bs &&
5884 !bdrv_is_removable(bs) &&
5885 !bdrv_is_read_only(bs));
5888 static BlockDriverState *get_bs_snapshots(void)
5890 BlockDriverState *bs;
5891 int i;
5893 if (bs_snapshots)
5894 return bs_snapshots;
5895 for(i = 0; i <= nb_drives; i++) {
5896 bs = drives_table[i].bdrv;
5897 if (bdrv_can_snapshot(bs))
5898 goto ok;
5900 return NULL;
5902 bs_snapshots = bs;
5903 return bs;
5906 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5907 const char *name)
5909 QEMUSnapshotInfo *sn_tab, *sn;
5910 int nb_sns, i, ret;
5912 ret = -ENOENT;
5913 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5914 if (nb_sns < 0)
5915 return ret;
5916 for(i = 0; i < nb_sns; i++) {
5917 sn = &sn_tab[i];
5918 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5919 *sn_info = *sn;
5920 ret = 0;
5921 break;
5924 qemu_free(sn_tab);
5925 return ret;
5928 void do_savevm(const char *name)
5930 BlockDriverState *bs, *bs1;
5931 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5932 int must_delete, ret, i;
5933 BlockDriverInfo bdi1, *bdi = &bdi1;
5934 QEMUFile *f;
5935 int saved_vm_running;
5936 #ifdef _WIN32
5937 struct _timeb tb;
5938 #else
5939 struct timeval tv;
5940 #endif
5942 bs = get_bs_snapshots();
5943 if (!bs) {
5944 term_printf("No block device can accept snapshots\n");
5945 return;
5948 /* ??? Should this occur after vm_stop? */
5949 qemu_aio_flush();
5951 saved_vm_running = vm_running;
5952 vm_stop(0);
5954 must_delete = 0;
5955 if (name) {
5956 ret = bdrv_snapshot_find(bs, old_sn, name);
5957 if (ret >= 0) {
5958 must_delete = 1;
5961 memset(sn, 0, sizeof(*sn));
5962 if (must_delete) {
5963 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5964 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5965 } else {
5966 if (name)
5967 pstrcpy(sn->name, sizeof(sn->name), name);
5970 /* fill auxiliary fields */
5971 #ifdef _WIN32
5972 _ftime(&tb);
5973 sn->date_sec = tb.time;
5974 sn->date_nsec = tb.millitm * 1000000;
5975 #else
5976 gettimeofday(&tv, NULL);
5977 sn->date_sec = tv.tv_sec;
5978 sn->date_nsec = tv.tv_usec * 1000;
5979 #endif
5980 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5982 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5983 term_printf("Device %s does not support VM state snapshots\n",
5984 bdrv_get_device_name(bs));
5985 goto the_end;
5988 /* save the VM state */
5989 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5990 if (!f) {
5991 term_printf("Could not open VM state file\n");
5992 goto the_end;
5994 ret = qemu_savevm_state(f);
5995 sn->vm_state_size = qemu_ftell(f);
5996 qemu_fclose(f);
5997 if (ret < 0) {
5998 term_printf("Error %d while writing VM\n", ret);
5999 goto the_end;
6002 /* create the snapshots */
6004 for(i = 0; i < nb_drives; i++) {
6005 bs1 = drives_table[i].bdrv;
6006 if (bdrv_has_snapshot(bs1)) {
6007 if (must_delete) {
6008 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6009 if (ret < 0) {
6010 term_printf("Error while deleting snapshot on '%s'\n",
6011 bdrv_get_device_name(bs1));
6014 ret = bdrv_snapshot_create(bs1, sn);
6015 if (ret < 0) {
6016 term_printf("Error while creating snapshot on '%s'\n",
6017 bdrv_get_device_name(bs1));
6022 the_end:
6023 if (saved_vm_running)
6024 vm_start();
6027 void do_loadvm(const char *name)
6029 BlockDriverState *bs, *bs1;
6030 BlockDriverInfo bdi1, *bdi = &bdi1;
6031 QEMUFile *f;
6032 int i, ret;
6033 int saved_vm_running;
6035 bs = get_bs_snapshots();
6036 if (!bs) {
6037 term_printf("No block device supports snapshots\n");
6038 return;
6041 /* Flush all IO requests so they don't interfere with the new state. */
6042 qemu_aio_flush();
6044 saved_vm_running = vm_running;
6045 vm_stop(0);
6047 for(i = 0; i <= nb_drives; i++) {
6048 bs1 = drives_table[i].bdrv;
6049 if (bdrv_has_snapshot(bs1)) {
6050 ret = bdrv_snapshot_goto(bs1, name);
6051 if (ret < 0) {
6052 if (bs != bs1)
6053 term_printf("Warning: ");
6054 switch(ret) {
6055 case -ENOTSUP:
6056 term_printf("Snapshots not supported on device '%s'\n",
6057 bdrv_get_device_name(bs1));
6058 break;
6059 case -ENOENT:
6060 term_printf("Could not find snapshot '%s' on device '%s'\n",
6061 name, bdrv_get_device_name(bs1));
6062 break;
6063 default:
6064 term_printf("Error %d while activating snapshot on '%s'\n",
6065 ret, bdrv_get_device_name(bs1));
6066 break;
6068 /* fatal on snapshot block device */
6069 if (bs == bs1)
6070 goto the_end;
6075 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6076 term_printf("Device %s does not support VM state snapshots\n",
6077 bdrv_get_device_name(bs));
6078 return;
6081 /* restore the VM state */
6082 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6083 if (!f) {
6084 term_printf("Could not open VM state file\n");
6085 goto the_end;
6087 ret = qemu_loadvm_state(f);
6088 qemu_fclose(f);
6089 if (ret < 0) {
6090 term_printf("Error %d while loading VM state\n", ret);
6092 the_end:
6093 if (saved_vm_running)
6094 vm_start();
6097 void do_delvm(const char *name)
6099 BlockDriverState *bs, *bs1;
6100 int i, ret;
6102 bs = get_bs_snapshots();
6103 if (!bs) {
6104 term_printf("No block device supports snapshots\n");
6105 return;
6108 for(i = 0; i <= nb_drives; i++) {
6109 bs1 = drives_table[i].bdrv;
6110 if (bdrv_has_snapshot(bs1)) {
6111 ret = bdrv_snapshot_delete(bs1, name);
6112 if (ret < 0) {
6113 if (ret == -ENOTSUP)
6114 term_printf("Snapshots not supported on device '%s'\n",
6115 bdrv_get_device_name(bs1));
6116 else
6117 term_printf("Error %d while deleting snapshot on '%s'\n",
6118 ret, bdrv_get_device_name(bs1));
6124 void do_info_snapshots(void)
6126 BlockDriverState *bs, *bs1;
6127 QEMUSnapshotInfo *sn_tab, *sn;
6128 int nb_sns, i;
6129 char buf[256];
6131 bs = get_bs_snapshots();
6132 if (!bs) {
6133 term_printf("No available block device supports snapshots\n");
6134 return;
6136 term_printf("Snapshot devices:");
6137 for(i = 0; i <= nb_drives; i++) {
6138 bs1 = drives_table[i].bdrv;
6139 if (bdrv_has_snapshot(bs1)) {
6140 if (bs == bs1)
6141 term_printf(" %s", bdrv_get_device_name(bs1));
6144 term_printf("\n");
6146 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6147 if (nb_sns < 0) {
6148 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6149 return;
6151 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6152 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6153 for(i = 0; i < nb_sns; i++) {
6154 sn = &sn_tab[i];
6155 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6157 qemu_free(sn_tab);
6160 /***********************************************************/
6161 /* cpu save/restore */
6163 #if defined(TARGET_I386)
6165 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6167 qemu_put_be32(f, dt->selector);
6168 qemu_put_betl(f, dt->base);
6169 qemu_put_be32(f, dt->limit);
6170 qemu_put_be32(f, dt->flags);
6173 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6175 dt->selector = qemu_get_be32(f);
6176 dt->base = qemu_get_betl(f);
6177 dt->limit = qemu_get_be32(f);
6178 dt->flags = qemu_get_be32(f);
6181 void cpu_save(QEMUFile *f, void *opaque)
6183 CPUState *env = opaque;
6184 uint16_t fptag, fpus, fpuc, fpregs_format;
6185 uint32_t hflags;
6186 int i;
6188 for(i = 0; i < CPU_NB_REGS; i++)
6189 qemu_put_betls(f, &env->regs[i]);
6190 qemu_put_betls(f, &env->eip);
6191 qemu_put_betls(f, &env->eflags);
6192 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6193 qemu_put_be32s(f, &hflags);
6195 /* FPU */
6196 fpuc = env->fpuc;
6197 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6198 fptag = 0;
6199 for(i = 0; i < 8; i++) {
6200 fptag |= ((!env->fptags[i]) << i);
6203 qemu_put_be16s(f, &fpuc);
6204 qemu_put_be16s(f, &fpus);
6205 qemu_put_be16s(f, &fptag);
6207 #ifdef USE_X86LDOUBLE
6208 fpregs_format = 0;
6209 #else
6210 fpregs_format = 1;
6211 #endif
6212 qemu_put_be16s(f, &fpregs_format);
6214 for(i = 0; i < 8; i++) {
6215 #ifdef USE_X86LDOUBLE
6217 uint64_t mant;
6218 uint16_t exp;
6219 /* we save the real CPU data (in case of MMX usage only 'mant'
6220 contains the MMX register */
6221 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6222 qemu_put_be64(f, mant);
6223 qemu_put_be16(f, exp);
6225 #else
6226 /* if we use doubles for float emulation, we save the doubles to
6227 avoid losing information in case of MMX usage. It can give
6228 problems if the image is restored on a CPU where long
6229 doubles are used instead. */
6230 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6231 #endif
6234 for(i = 0; i < 6; i++)
6235 cpu_put_seg(f, &env->segs[i]);
6236 cpu_put_seg(f, &env->ldt);
6237 cpu_put_seg(f, &env->tr);
6238 cpu_put_seg(f, &env->gdt);
6239 cpu_put_seg(f, &env->idt);
6241 qemu_put_be32s(f, &env->sysenter_cs);
6242 qemu_put_be32s(f, &env->sysenter_esp);
6243 qemu_put_be32s(f, &env->sysenter_eip);
6245 qemu_put_betls(f, &env->cr[0]);
6246 qemu_put_betls(f, &env->cr[2]);
6247 qemu_put_betls(f, &env->cr[3]);
6248 qemu_put_betls(f, &env->cr[4]);
6250 for(i = 0; i < 8; i++)
6251 qemu_put_betls(f, &env->dr[i]);
6253 /* MMU */
6254 qemu_put_be32s(f, &env->a20_mask);
6256 /* XMM */
6257 qemu_put_be32s(f, &env->mxcsr);
6258 for(i = 0; i < CPU_NB_REGS; i++) {
6259 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6260 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6263 #ifdef TARGET_X86_64
6264 qemu_put_be64s(f, &env->efer);
6265 qemu_put_be64s(f, &env->star);
6266 qemu_put_be64s(f, &env->lstar);
6267 qemu_put_be64s(f, &env->cstar);
6268 qemu_put_be64s(f, &env->fmask);
6269 qemu_put_be64s(f, &env->kernelgsbase);
6270 #endif
6271 qemu_put_be32s(f, &env->smbase);
6274 #ifdef USE_X86LDOUBLE
6275 /* XXX: add that in a FPU generic layer */
6276 union x86_longdouble {
6277 uint64_t mant;
6278 uint16_t exp;
6281 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6282 #define EXPBIAS1 1023
6283 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6284 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6286 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6288 int e;
6289 /* mantissa */
6290 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6291 /* exponent + sign */
6292 e = EXPD1(temp) - EXPBIAS1 + 16383;
6293 e |= SIGND1(temp) >> 16;
6294 p->exp = e;
6296 #endif
6298 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6300 CPUState *env = opaque;
6301 int i, guess_mmx;
6302 uint32_t hflags;
6303 uint16_t fpus, fpuc, fptag, fpregs_format;
6305 if (version_id != 3 && version_id != 4)
6306 return -EINVAL;
6307 for(i = 0; i < CPU_NB_REGS; i++)
6308 qemu_get_betls(f, &env->regs[i]);
6309 qemu_get_betls(f, &env->eip);
6310 qemu_get_betls(f, &env->eflags);
6311 qemu_get_be32s(f, &hflags);
6313 qemu_get_be16s(f, &fpuc);
6314 qemu_get_be16s(f, &fpus);
6315 qemu_get_be16s(f, &fptag);
6316 qemu_get_be16s(f, &fpregs_format);
6318 /* NOTE: we cannot always restore the FPU state if the image come
6319 from a host with a different 'USE_X86LDOUBLE' define. We guess
6320 if we are in an MMX state to restore correctly in that case. */
6321 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6322 for(i = 0; i < 8; i++) {
6323 uint64_t mant;
6324 uint16_t exp;
6326 switch(fpregs_format) {
6327 case 0:
6328 mant = qemu_get_be64(f);
6329 exp = qemu_get_be16(f);
6330 #ifdef USE_X86LDOUBLE
6331 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6332 #else
6333 /* difficult case */
6334 if (guess_mmx)
6335 env->fpregs[i].mmx.MMX_Q(0) = mant;
6336 else
6337 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6338 #endif
6339 break;
6340 case 1:
6341 mant = qemu_get_be64(f);
6342 #ifdef USE_X86LDOUBLE
6344 union x86_longdouble *p;
6345 /* difficult case */
6346 p = (void *)&env->fpregs[i];
6347 if (guess_mmx) {
6348 p->mant = mant;
6349 p->exp = 0xffff;
6350 } else {
6351 fp64_to_fp80(p, mant);
6354 #else
6355 env->fpregs[i].mmx.MMX_Q(0) = mant;
6356 #endif
6357 break;
6358 default:
6359 return -EINVAL;
6363 env->fpuc = fpuc;
6364 /* XXX: restore FPU round state */
6365 env->fpstt = (fpus >> 11) & 7;
6366 env->fpus = fpus & ~0x3800;
6367 fptag ^= 0xff;
6368 for(i = 0; i < 8; i++) {
6369 env->fptags[i] = (fptag >> i) & 1;
6372 for(i = 0; i < 6; i++)
6373 cpu_get_seg(f, &env->segs[i]);
6374 cpu_get_seg(f, &env->ldt);
6375 cpu_get_seg(f, &env->tr);
6376 cpu_get_seg(f, &env->gdt);
6377 cpu_get_seg(f, &env->idt);
6379 qemu_get_be32s(f, &env->sysenter_cs);
6380 qemu_get_be32s(f, &env->sysenter_esp);
6381 qemu_get_be32s(f, &env->sysenter_eip);
6383 qemu_get_betls(f, &env->cr[0]);
6384 qemu_get_betls(f, &env->cr[2]);
6385 qemu_get_betls(f, &env->cr[3]);
6386 qemu_get_betls(f, &env->cr[4]);
6388 for(i = 0; i < 8; i++)
6389 qemu_get_betls(f, &env->dr[i]);
6391 /* MMU */
6392 qemu_get_be32s(f, &env->a20_mask);
6394 qemu_get_be32s(f, &env->mxcsr);
6395 for(i = 0; i < CPU_NB_REGS; i++) {
6396 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6397 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6400 #ifdef TARGET_X86_64
6401 qemu_get_be64s(f, &env->efer);
6402 qemu_get_be64s(f, &env->star);
6403 qemu_get_be64s(f, &env->lstar);
6404 qemu_get_be64s(f, &env->cstar);
6405 qemu_get_be64s(f, &env->fmask);
6406 qemu_get_be64s(f, &env->kernelgsbase);
6407 #endif
6408 if (version_id >= 4)
6409 qemu_get_be32s(f, &env->smbase);
6411 /* XXX: compute hflags from scratch, except for CPL and IIF */
6412 env->hflags = hflags;
6413 tlb_flush(env, 1);
6414 return 0;
6417 #elif defined(TARGET_PPC)
6418 void cpu_save(QEMUFile *f, void *opaque)
6422 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6424 return 0;
6427 #elif defined(TARGET_MIPS)
6428 void cpu_save(QEMUFile *f, void *opaque)
6432 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6434 return 0;
6437 #elif defined(TARGET_SPARC)
6438 void cpu_save(QEMUFile *f, void *opaque)
6440 CPUState *env = opaque;
6441 int i;
6442 uint32_t tmp;
6444 for(i = 0; i < 8; i++)
6445 qemu_put_betls(f, &env->gregs[i]);
6446 for(i = 0; i < NWINDOWS * 16; i++)
6447 qemu_put_betls(f, &env->regbase[i]);
6449 /* FPU */
6450 for(i = 0; i < TARGET_FPREGS; i++) {
6451 union {
6452 float32 f;
6453 uint32_t i;
6454 } u;
6455 u.f = env->fpr[i];
6456 qemu_put_be32(f, u.i);
6459 qemu_put_betls(f, &env->pc);
6460 qemu_put_betls(f, &env->npc);
6461 qemu_put_betls(f, &env->y);
6462 tmp = GET_PSR(env);
6463 qemu_put_be32(f, tmp);
6464 qemu_put_betls(f, &env->fsr);
6465 qemu_put_betls(f, &env->tbr);
6466 #ifndef TARGET_SPARC64
6467 qemu_put_be32s(f, &env->wim);
6468 /* MMU */
6469 for(i = 0; i < 16; i++)
6470 qemu_put_be32s(f, &env->mmuregs[i]);
6471 #endif
6474 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6476 CPUState *env = opaque;
6477 int i;
6478 uint32_t tmp;
6480 for(i = 0; i < 8; i++)
6481 qemu_get_betls(f, &env->gregs[i]);
6482 for(i = 0; i < NWINDOWS * 16; i++)
6483 qemu_get_betls(f, &env->regbase[i]);
6485 /* FPU */
6486 for(i = 0; i < TARGET_FPREGS; i++) {
6487 union {
6488 float32 f;
6489 uint32_t i;
6490 } u;
6491 u.i = qemu_get_be32(f);
6492 env->fpr[i] = u.f;
6495 qemu_get_betls(f, &env->pc);
6496 qemu_get_betls(f, &env->npc);
6497 qemu_get_betls(f, &env->y);
6498 tmp = qemu_get_be32(f);
6499 env->cwp = 0; /* needed to ensure that the wrapping registers are
6500 correctly updated */
6501 PUT_PSR(env, tmp);
6502 qemu_get_betls(f, &env->fsr);
6503 qemu_get_betls(f, &env->tbr);
6504 #ifndef TARGET_SPARC64
6505 qemu_get_be32s(f, &env->wim);
6506 /* MMU */
6507 for(i = 0; i < 16; i++)
6508 qemu_get_be32s(f, &env->mmuregs[i]);
6509 #endif
6510 tlb_flush(env, 1);
6511 return 0;
6514 #elif defined(TARGET_ARM)
6516 void cpu_save(QEMUFile *f, void *opaque)
6518 int i;
6519 CPUARMState *env = (CPUARMState *)opaque;
6521 for (i = 0; i < 16; i++) {
6522 qemu_put_be32(f, env->regs[i]);
6524 qemu_put_be32(f, cpsr_read(env));
6525 qemu_put_be32(f, env->spsr);
6526 for (i = 0; i < 6; i++) {
6527 qemu_put_be32(f, env->banked_spsr[i]);
6528 qemu_put_be32(f, env->banked_r13[i]);
6529 qemu_put_be32(f, env->banked_r14[i]);
6531 for (i = 0; i < 5; i++) {
6532 qemu_put_be32(f, env->usr_regs[i]);
6533 qemu_put_be32(f, env->fiq_regs[i]);
6535 qemu_put_be32(f, env->cp15.c0_cpuid);
6536 qemu_put_be32(f, env->cp15.c0_cachetype);
6537 qemu_put_be32(f, env->cp15.c1_sys);
6538 qemu_put_be32(f, env->cp15.c1_coproc);
6539 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6540 qemu_put_be32(f, env->cp15.c2_base0);
6541 qemu_put_be32(f, env->cp15.c2_base1);
6542 qemu_put_be32(f, env->cp15.c2_mask);
6543 qemu_put_be32(f, env->cp15.c2_data);
6544 qemu_put_be32(f, env->cp15.c2_insn);
6545 qemu_put_be32(f, env->cp15.c3);
6546 qemu_put_be32(f, env->cp15.c5_insn);
6547 qemu_put_be32(f, env->cp15.c5_data);
6548 for (i = 0; i < 8; i++) {
6549 qemu_put_be32(f, env->cp15.c6_region[i]);
6551 qemu_put_be32(f, env->cp15.c6_insn);
6552 qemu_put_be32(f, env->cp15.c6_data);
6553 qemu_put_be32(f, env->cp15.c9_insn);
6554 qemu_put_be32(f, env->cp15.c9_data);
6555 qemu_put_be32(f, env->cp15.c13_fcse);
6556 qemu_put_be32(f, env->cp15.c13_context);
6557 qemu_put_be32(f, env->cp15.c13_tls1);
6558 qemu_put_be32(f, env->cp15.c13_tls2);
6559 qemu_put_be32(f, env->cp15.c13_tls3);
6560 qemu_put_be32(f, env->cp15.c15_cpar);
6562 qemu_put_be32(f, env->features);
6564 if (arm_feature(env, ARM_FEATURE_VFP)) {
6565 for (i = 0; i < 16; i++) {
6566 CPU_DoubleU u;
6567 u.d = env->vfp.regs[i];
6568 qemu_put_be32(f, u.l.upper);
6569 qemu_put_be32(f, u.l.lower);
6571 for (i = 0; i < 16; i++) {
6572 qemu_put_be32(f, env->vfp.xregs[i]);
6575 /* TODO: Should use proper FPSCR access functions. */
6576 qemu_put_be32(f, env->vfp.vec_len);
6577 qemu_put_be32(f, env->vfp.vec_stride);
6579 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6580 for (i = 16; i < 32; i++) {
6581 CPU_DoubleU u;
6582 u.d = env->vfp.regs[i];
6583 qemu_put_be32(f, u.l.upper);
6584 qemu_put_be32(f, u.l.lower);
6589 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6590 for (i = 0; i < 16; i++) {
6591 qemu_put_be64(f, env->iwmmxt.regs[i]);
6593 for (i = 0; i < 16; i++) {
6594 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6598 if (arm_feature(env, ARM_FEATURE_M)) {
6599 qemu_put_be32(f, env->v7m.other_sp);
6600 qemu_put_be32(f, env->v7m.vecbase);
6601 qemu_put_be32(f, env->v7m.basepri);
6602 qemu_put_be32(f, env->v7m.control);
6603 qemu_put_be32(f, env->v7m.current_sp);
6604 qemu_put_be32(f, env->v7m.exception);
6608 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6610 CPUARMState *env = (CPUARMState *)opaque;
6611 int i;
6613 if (version_id != ARM_CPU_SAVE_VERSION)
6614 return -EINVAL;
6616 for (i = 0; i < 16; i++) {
6617 env->regs[i] = qemu_get_be32(f);
6619 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6620 env->spsr = qemu_get_be32(f);
6621 for (i = 0; i < 6; i++) {
6622 env->banked_spsr[i] = qemu_get_be32(f);
6623 env->banked_r13[i] = qemu_get_be32(f);
6624 env->banked_r14[i] = qemu_get_be32(f);
6626 for (i = 0; i < 5; i++) {
6627 env->usr_regs[i] = qemu_get_be32(f);
6628 env->fiq_regs[i] = qemu_get_be32(f);
6630 env->cp15.c0_cpuid = qemu_get_be32(f);
6631 env->cp15.c0_cachetype = qemu_get_be32(f);
6632 env->cp15.c1_sys = qemu_get_be32(f);
6633 env->cp15.c1_coproc = qemu_get_be32(f);
6634 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6635 env->cp15.c2_base0 = qemu_get_be32(f);
6636 env->cp15.c2_base1 = qemu_get_be32(f);
6637 env->cp15.c2_mask = qemu_get_be32(f);
6638 env->cp15.c2_data = qemu_get_be32(f);
6639 env->cp15.c2_insn = qemu_get_be32(f);
6640 env->cp15.c3 = qemu_get_be32(f);
6641 env->cp15.c5_insn = qemu_get_be32(f);
6642 env->cp15.c5_data = qemu_get_be32(f);
6643 for (i = 0; i < 8; i++) {
6644 env->cp15.c6_region[i] = qemu_get_be32(f);
6646 env->cp15.c6_insn = qemu_get_be32(f);
6647 env->cp15.c6_data = qemu_get_be32(f);
6648 env->cp15.c9_insn = qemu_get_be32(f);
6649 env->cp15.c9_data = qemu_get_be32(f);
6650 env->cp15.c13_fcse = qemu_get_be32(f);
6651 env->cp15.c13_context = qemu_get_be32(f);
6652 env->cp15.c13_tls1 = qemu_get_be32(f);
6653 env->cp15.c13_tls2 = qemu_get_be32(f);
6654 env->cp15.c13_tls3 = qemu_get_be32(f);
6655 env->cp15.c15_cpar = qemu_get_be32(f);
6657 env->features = qemu_get_be32(f);
6659 if (arm_feature(env, ARM_FEATURE_VFP)) {
6660 for (i = 0; i < 16; i++) {
6661 CPU_DoubleU u;
6662 u.l.upper = qemu_get_be32(f);
6663 u.l.lower = qemu_get_be32(f);
6664 env->vfp.regs[i] = u.d;
6666 for (i = 0; i < 16; i++) {
6667 env->vfp.xregs[i] = qemu_get_be32(f);
6670 /* TODO: Should use proper FPSCR access functions. */
6671 env->vfp.vec_len = qemu_get_be32(f);
6672 env->vfp.vec_stride = qemu_get_be32(f);
6674 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6675 for (i = 0; i < 16; i++) {
6676 CPU_DoubleU u;
6677 u.l.upper = qemu_get_be32(f);
6678 u.l.lower = qemu_get_be32(f);
6679 env->vfp.regs[i] = u.d;
6684 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6685 for (i = 0; i < 16; i++) {
6686 env->iwmmxt.regs[i] = qemu_get_be64(f);
6688 for (i = 0; i < 16; i++) {
6689 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6693 if (arm_feature(env, ARM_FEATURE_M)) {
6694 env->v7m.other_sp = qemu_get_be32(f);
6695 env->v7m.vecbase = qemu_get_be32(f);
6696 env->v7m.basepri = qemu_get_be32(f);
6697 env->v7m.control = qemu_get_be32(f);
6698 env->v7m.current_sp = qemu_get_be32(f);
6699 env->v7m.exception = qemu_get_be32(f);
6702 return 0;
6705 #else
6707 //#warning No CPU save/restore functions
6709 #endif
6711 /***********************************************************/
6712 /* ram save/restore */
6714 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6716 int v;
6718 v = qemu_get_byte(f);
6719 switch(v) {
6720 case 0:
6721 if (qemu_get_buffer(f, buf, len) != len)
6722 return -EIO;
6723 break;
6724 case 1:
6725 v = qemu_get_byte(f);
6726 memset(buf, v, len);
6727 break;
6728 default:
6729 return -EINVAL;
6731 return 0;
6734 static int ram_load_v1(QEMUFile *f, void *opaque)
6736 int i, ret;
6738 if (qemu_get_be32(f) != phys_ram_size)
6739 return -EINVAL;
6740 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6741 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6742 if (ret)
6743 return ret;
6745 return 0;
6748 #define BDRV_HASH_BLOCK_SIZE 1024
6749 #define IOBUF_SIZE 4096
6750 #define RAM_CBLOCK_MAGIC 0xfabe
6752 typedef struct RamCompressState {
6753 z_stream zstream;
6754 QEMUFile *f;
6755 uint8_t buf[IOBUF_SIZE];
6756 } RamCompressState;
6758 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6760 int ret;
6761 memset(s, 0, sizeof(*s));
6762 s->f = f;
6763 ret = deflateInit2(&s->zstream, 1,
6764 Z_DEFLATED, 15,
6765 9, Z_DEFAULT_STRATEGY);
6766 if (ret != Z_OK)
6767 return -1;
6768 s->zstream.avail_out = IOBUF_SIZE;
6769 s->zstream.next_out = s->buf;
6770 return 0;
6773 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6775 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6776 qemu_put_be16(s->f, len);
6777 qemu_put_buffer(s->f, buf, len);
6780 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6782 int ret;
6784 s->zstream.avail_in = len;
6785 s->zstream.next_in = (uint8_t *)buf;
6786 while (s->zstream.avail_in > 0) {
6787 ret = deflate(&s->zstream, Z_NO_FLUSH);
6788 if (ret != Z_OK)
6789 return -1;
6790 if (s->zstream.avail_out == 0) {
6791 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6792 s->zstream.avail_out = IOBUF_SIZE;
6793 s->zstream.next_out = s->buf;
6796 return 0;
6799 static void ram_compress_close(RamCompressState *s)
6801 int len, ret;
6803 /* compress last bytes */
6804 for(;;) {
6805 ret = deflate(&s->zstream, Z_FINISH);
6806 if (ret == Z_OK || ret == Z_STREAM_END) {
6807 len = IOBUF_SIZE - s->zstream.avail_out;
6808 if (len > 0) {
6809 ram_put_cblock(s, s->buf, len);
6811 s->zstream.avail_out = IOBUF_SIZE;
6812 s->zstream.next_out = s->buf;
6813 if (ret == Z_STREAM_END)
6814 break;
6815 } else {
6816 goto fail;
6819 fail:
6820 deflateEnd(&s->zstream);
6823 typedef struct RamDecompressState {
6824 z_stream zstream;
6825 QEMUFile *f;
6826 uint8_t buf[IOBUF_SIZE];
6827 } RamDecompressState;
6829 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6831 int ret;
6832 memset(s, 0, sizeof(*s));
6833 s->f = f;
6834 ret = inflateInit(&s->zstream);
6835 if (ret != Z_OK)
6836 return -1;
6837 return 0;
6840 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6842 int ret, clen;
6844 s->zstream.avail_out = len;
6845 s->zstream.next_out = buf;
6846 while (s->zstream.avail_out > 0) {
6847 if (s->zstream.avail_in == 0) {
6848 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6849 return -1;
6850 clen = qemu_get_be16(s->f);
6851 if (clen > IOBUF_SIZE)
6852 return -1;
6853 qemu_get_buffer(s->f, s->buf, clen);
6854 s->zstream.avail_in = clen;
6855 s->zstream.next_in = s->buf;
6857 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6858 if (ret != Z_OK && ret != Z_STREAM_END) {
6859 return -1;
6862 return 0;
6865 static void ram_decompress_close(RamDecompressState *s)
6867 inflateEnd(&s->zstream);
6870 static void ram_save(QEMUFile *f, void *opaque)
6872 int i;
6873 RamCompressState s1, *s = &s1;
6874 uint8_t buf[10];
6876 qemu_put_be32(f, phys_ram_size);
6877 if (ram_compress_open(s, f) < 0)
6878 return;
6879 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6880 #if 0
6881 if (tight_savevm_enabled) {
6882 int64_t sector_num;
6883 int j;
6885 /* find if the memory block is available on a virtual
6886 block device */
6887 sector_num = -1;
6888 for(j = 0; j < nb_drives; j++) {
6889 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6890 phys_ram_base + i,
6891 BDRV_HASH_BLOCK_SIZE);
6892 if (sector_num >= 0)
6893 break;
6895 if (j == nb_drives)
6896 goto normal_compress;
6897 buf[0] = 1;
6898 buf[1] = j;
6899 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6900 ram_compress_buf(s, buf, 10);
6901 } else
6902 #endif
6904 // normal_compress:
6905 buf[0] = 0;
6906 ram_compress_buf(s, buf, 1);
6907 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6910 ram_compress_close(s);
6913 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6915 RamDecompressState s1, *s = &s1;
6916 uint8_t buf[10];
6917 int i;
6919 if (version_id == 1)
6920 return ram_load_v1(f, opaque);
6921 if (version_id != 2)
6922 return -EINVAL;
6923 if (qemu_get_be32(f) != phys_ram_size)
6924 return -EINVAL;
6925 if (ram_decompress_open(s, f) < 0)
6926 return -EINVAL;
6927 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6928 if (ram_decompress_buf(s, buf, 1) < 0) {
6929 fprintf(stderr, "Error while reading ram block header\n");
6930 goto error;
6932 if (buf[0] == 0) {
6933 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6934 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6935 goto error;
6937 } else
6938 #if 0
6939 if (buf[0] == 1) {
6940 int bs_index;
6941 int64_t sector_num;
6943 ram_decompress_buf(s, buf + 1, 9);
6944 bs_index = buf[1];
6945 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6946 if (bs_index >= nb_drives) {
6947 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6948 goto error;
6950 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6951 phys_ram_base + i,
6952 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6953 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6954 bs_index, sector_num);
6955 goto error;
6957 } else
6958 #endif
6960 error:
6961 printf("Error block header\n");
6962 return -EINVAL;
6965 ram_decompress_close(s);
6966 return 0;
6969 /***********************************************************/
6970 /* bottom halves (can be seen as timers which expire ASAP) */
6972 struct QEMUBH {
6973 QEMUBHFunc *cb;
6974 void *opaque;
6975 int scheduled;
6976 QEMUBH *next;
6979 static QEMUBH *first_bh = NULL;
6981 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6983 QEMUBH *bh;
6984 bh = qemu_mallocz(sizeof(QEMUBH));
6985 if (!bh)
6986 return NULL;
6987 bh->cb = cb;
6988 bh->opaque = opaque;
6989 return bh;
6992 int qemu_bh_poll(void)
6994 QEMUBH *bh, **pbh;
6995 int ret;
6997 ret = 0;
6998 for(;;) {
6999 pbh = &first_bh;
7000 bh = *pbh;
7001 if (!bh)
7002 break;
7003 ret = 1;
7004 *pbh = bh->next;
7005 bh->scheduled = 0;
7006 bh->cb(bh->opaque);
7008 return ret;
7011 void qemu_bh_schedule(QEMUBH *bh)
7013 CPUState *env = cpu_single_env;
7014 if (bh->scheduled)
7015 return;
7016 bh->scheduled = 1;
7017 bh->next = first_bh;
7018 first_bh = bh;
7020 /* stop the currently executing CPU to execute the BH ASAP */
7021 if (env) {
7022 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7026 void qemu_bh_cancel(QEMUBH *bh)
7028 QEMUBH **pbh;
7029 if (bh->scheduled) {
7030 pbh = &first_bh;
7031 while (*pbh != bh)
7032 pbh = &(*pbh)->next;
7033 *pbh = bh->next;
7034 bh->scheduled = 0;
7038 void qemu_bh_delete(QEMUBH *bh)
7040 qemu_bh_cancel(bh);
7041 qemu_free(bh);
7044 /***********************************************************/
7045 /* machine registration */
7047 QEMUMachine *first_machine = NULL;
7049 int qemu_register_machine(QEMUMachine *m)
7051 QEMUMachine **pm;
7052 pm = &first_machine;
7053 while (*pm != NULL)
7054 pm = &(*pm)->next;
7055 m->next = NULL;
7056 *pm = m;
7057 return 0;
7060 static QEMUMachine *find_machine(const char *name)
7062 QEMUMachine *m;
7064 for(m = first_machine; m != NULL; m = m->next) {
7065 if (!strcmp(m->name, name))
7066 return m;
7068 return NULL;
7071 /***********************************************************/
7072 /* main execution loop */
7074 static void gui_update(void *opaque)
7076 DisplayState *ds = opaque;
7077 ds->dpy_refresh(ds);
7078 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7081 struct vm_change_state_entry {
7082 VMChangeStateHandler *cb;
7083 void *opaque;
7084 LIST_ENTRY (vm_change_state_entry) entries;
7087 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7089 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7090 void *opaque)
7092 VMChangeStateEntry *e;
7094 e = qemu_mallocz(sizeof (*e));
7095 if (!e)
7096 return NULL;
7098 e->cb = cb;
7099 e->opaque = opaque;
7100 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7101 return e;
7104 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7106 LIST_REMOVE (e, entries);
7107 qemu_free (e);
7110 static void vm_state_notify(int running)
7112 VMChangeStateEntry *e;
7114 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7115 e->cb(e->opaque, running);
7119 /* XXX: support several handlers */
7120 static VMStopHandler *vm_stop_cb;
7121 static void *vm_stop_opaque;
7123 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7125 vm_stop_cb = cb;
7126 vm_stop_opaque = opaque;
7127 return 0;
7130 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7132 vm_stop_cb = NULL;
7135 void vm_start(void)
7137 if (!vm_running) {
7138 cpu_enable_ticks();
7139 vm_running = 1;
7140 vm_state_notify(1);
7141 qemu_rearm_alarm_timer(alarm_timer);
7145 void vm_stop(int reason)
7147 if (vm_running) {
7148 cpu_disable_ticks();
7149 vm_running = 0;
7150 if (reason != 0) {
7151 if (vm_stop_cb) {
7152 vm_stop_cb(vm_stop_opaque, reason);
7155 vm_state_notify(0);
7159 /* reset/shutdown handler */
7161 typedef struct QEMUResetEntry {
7162 QEMUResetHandler *func;
7163 void *opaque;
7164 struct QEMUResetEntry *next;
7165 } QEMUResetEntry;
7167 static QEMUResetEntry *first_reset_entry;
7168 static int reset_requested;
7169 static int shutdown_requested;
7170 static int powerdown_requested;
7172 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7174 QEMUResetEntry **pre, *re;
7176 pre = &first_reset_entry;
7177 while (*pre != NULL)
7178 pre = &(*pre)->next;
7179 re = qemu_mallocz(sizeof(QEMUResetEntry));
7180 re->func = func;
7181 re->opaque = opaque;
7182 re->next = NULL;
7183 *pre = re;
7186 static void qemu_system_reset(void)
7188 QEMUResetEntry *re;
7190 /* reset all devices */
7191 for(re = first_reset_entry; re != NULL; re = re->next) {
7192 re->func(re->opaque);
7196 void qemu_system_reset_request(void)
7198 if (no_reboot) {
7199 shutdown_requested = 1;
7200 } else {
7201 reset_requested = 1;
7203 if (cpu_single_env)
7204 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7207 void qemu_system_shutdown_request(void)
7209 shutdown_requested = 1;
7210 if (cpu_single_env)
7211 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7214 void qemu_system_powerdown_request(void)
7216 powerdown_requested = 1;
7217 if (cpu_single_env)
7218 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7221 void main_loop_wait(int timeout)
7223 IOHandlerRecord *ioh;
7224 fd_set rfds, wfds, xfds;
7225 int ret, nfds;
7226 #ifdef _WIN32
7227 int ret2, i;
7228 #endif
7229 struct timeval tv;
7230 PollingEntry *pe;
7233 /* XXX: need to suppress polling by better using win32 events */
7234 ret = 0;
7235 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7236 ret |= pe->func(pe->opaque);
7238 #ifdef _WIN32
7239 if (ret == 0) {
7240 int err;
7241 WaitObjects *w = &wait_objects;
7243 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7244 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7245 if (w->func[ret - WAIT_OBJECT_0])
7246 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7248 /* Check for additional signaled events */
7249 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7251 /* Check if event is signaled */
7252 ret2 = WaitForSingleObject(w->events[i], 0);
7253 if(ret2 == WAIT_OBJECT_0) {
7254 if (w->func[i])
7255 w->func[i](w->opaque[i]);
7256 } else if (ret2 == WAIT_TIMEOUT) {
7257 } else {
7258 err = GetLastError();
7259 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7262 } else if (ret == WAIT_TIMEOUT) {
7263 } else {
7264 err = GetLastError();
7265 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7268 #endif
7269 /* poll any events */
7270 /* XXX: separate device handlers from system ones */
7271 nfds = -1;
7272 FD_ZERO(&rfds);
7273 FD_ZERO(&wfds);
7274 FD_ZERO(&xfds);
7275 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7276 if (ioh->deleted)
7277 continue;
7278 if (ioh->fd_read &&
7279 (!ioh->fd_read_poll ||
7280 ioh->fd_read_poll(ioh->opaque) != 0)) {
7281 FD_SET(ioh->fd, &rfds);
7282 if (ioh->fd > nfds)
7283 nfds = ioh->fd;
7285 if (ioh->fd_write) {
7286 FD_SET(ioh->fd, &wfds);
7287 if (ioh->fd > nfds)
7288 nfds = ioh->fd;
7292 tv.tv_sec = 0;
7293 #ifdef _WIN32
7294 tv.tv_usec = 0;
7295 #else
7296 tv.tv_usec = timeout * 1000;
7297 #endif
7298 #if defined(CONFIG_SLIRP)
7299 if (slirp_inited) {
7300 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7302 #endif
7303 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7304 if (ret > 0) {
7305 IOHandlerRecord **pioh;
7307 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7308 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7309 ioh->fd_read(ioh->opaque);
7311 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7312 ioh->fd_write(ioh->opaque);
7316 /* remove deleted IO handlers */
7317 pioh = &first_io_handler;
7318 while (*pioh) {
7319 ioh = *pioh;
7320 if (ioh->deleted) {
7321 *pioh = ioh->next;
7322 qemu_free(ioh);
7323 } else
7324 pioh = &ioh->next;
7327 #if defined(CONFIG_SLIRP)
7328 if (slirp_inited) {
7329 if (ret < 0) {
7330 FD_ZERO(&rfds);
7331 FD_ZERO(&wfds);
7332 FD_ZERO(&xfds);
7334 slirp_select_poll(&rfds, &wfds, &xfds);
7336 #endif
7337 qemu_aio_poll();
7339 if (vm_running) {
7340 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7341 qemu_get_clock(vm_clock));
7342 /* run dma transfers, if any */
7343 DMA_run();
7346 /* real time timers */
7347 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7348 qemu_get_clock(rt_clock));
7350 /* Check bottom-halves last in case any of the earlier events triggered
7351 them. */
7352 qemu_bh_poll();
7356 static int main_loop(void)
7358 int ret, timeout;
7359 #ifdef CONFIG_PROFILER
7360 int64_t ti;
7361 #endif
7362 CPUState *env;
7364 cur_cpu = first_cpu;
7365 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7366 for(;;) {
7367 if (vm_running) {
7369 for(;;) {
7370 /* get next cpu */
7371 env = next_cpu;
7372 #ifdef CONFIG_PROFILER
7373 ti = profile_getclock();
7374 #endif
7375 ret = cpu_exec(env);
7376 #ifdef CONFIG_PROFILER
7377 qemu_time += profile_getclock() - ti;
7378 #endif
7379 next_cpu = env->next_cpu ?: first_cpu;
7380 if (event_pending) {
7381 ret = EXCP_INTERRUPT;
7382 event_pending = 0;
7383 break;
7385 if (ret == EXCP_HLT) {
7386 /* Give the next CPU a chance to run. */
7387 cur_cpu = env;
7388 continue;
7390 if (ret != EXCP_HALTED)
7391 break;
7392 /* all CPUs are halted ? */
7393 if (env == cur_cpu)
7394 break;
7396 cur_cpu = env;
7398 if (shutdown_requested) {
7399 ret = EXCP_INTERRUPT;
7400 break;
7402 if (reset_requested) {
7403 reset_requested = 0;
7404 qemu_system_reset();
7405 ret = EXCP_INTERRUPT;
7407 if (powerdown_requested) {
7408 powerdown_requested = 0;
7409 qemu_system_powerdown();
7410 ret = EXCP_INTERRUPT;
7412 if (ret == EXCP_DEBUG) {
7413 vm_stop(EXCP_DEBUG);
7415 /* If all cpus are halted then wait until the next IRQ */
7416 /* XXX: use timeout computed from timers */
7417 if (ret == EXCP_HALTED)
7418 timeout = 10;
7419 else
7420 timeout = 0;
7421 } else {
7422 timeout = 10;
7424 #ifdef CONFIG_PROFILER
7425 ti = profile_getclock();
7426 #endif
7427 main_loop_wait(timeout);
7428 #ifdef CONFIG_PROFILER
7429 dev_time += profile_getclock() - ti;
7430 #endif
7432 cpu_disable_ticks();
7433 return ret;
7436 static void help(int exitcode)
7438 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7439 "usage: %s [options] [disk_image]\n"
7440 "\n"
7441 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7442 "\n"
7443 "Standard options:\n"
7444 "-M machine select emulated machine (-M ? for list)\n"
7445 "-cpu cpu select CPU (-cpu ? for list)\n"
7446 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7447 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7448 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7449 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7450 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7451 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7452 " use 'file' as a drive image\n"
7453 "-mtdblock file use 'file' as on-board Flash memory image\n"
7454 "-sd file use 'file' as SecureDigital card image\n"
7455 "-pflash file use 'file' as a parallel flash image\n"
7456 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7457 "-snapshot write to temporary files instead of disk image files\n"
7458 #ifdef CONFIG_SDL
7459 "-no-frame open SDL window without a frame and window decorations\n"
7460 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7461 "-no-quit disable SDL window close capability\n"
7462 #endif
7463 #ifdef TARGET_I386
7464 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7465 #endif
7466 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7467 "-smp n set the number of CPUs to 'n' [default=1]\n"
7468 "-nographic disable graphical output and redirect serial I/Os to console\n"
7469 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7470 #ifndef _WIN32
7471 "-k language use keyboard layout (for example \"fr\" for French)\n"
7472 #endif
7473 #ifdef HAS_AUDIO
7474 "-audio-help print list of audio drivers and their options\n"
7475 "-soundhw c1,... enable audio support\n"
7476 " and only specified sound cards (comma separated list)\n"
7477 " use -soundhw ? to get the list of supported cards\n"
7478 " use -soundhw all to enable all of them\n"
7479 #endif
7480 "-localtime set the real time clock to local time [default=utc]\n"
7481 "-full-screen start in full screen\n"
7482 #ifdef TARGET_I386
7483 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7484 #endif
7485 "-usb enable the USB driver (will be the default soon)\n"
7486 "-usbdevice name add the host or guest USB device 'name'\n"
7487 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7488 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7489 #endif
7490 "-name string set the name of the guest\n"
7491 "\n"
7492 "Network options:\n"
7493 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7494 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7495 #ifdef CONFIG_SLIRP
7496 "-net user[,vlan=n][,hostname=host]\n"
7497 " connect the user mode network stack to VLAN 'n' and send\n"
7498 " hostname 'host' to DHCP clients\n"
7499 #endif
7500 #ifdef _WIN32
7501 "-net tap[,vlan=n],ifname=name\n"
7502 " connect the host TAP network interface to VLAN 'n'\n"
7503 #else
7504 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7505 " connect the host TAP network interface to VLAN 'n' and use the\n"
7506 " network scripts 'file' (default=%s)\n"
7507 " and 'dfile' (default=%s);\n"
7508 " use '[down]script=no' to disable script execution;\n"
7509 " use 'fd=h' to connect to an already opened TAP interface\n"
7510 #endif
7511 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7512 " connect the vlan 'n' to another VLAN using a socket connection\n"
7513 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7514 " connect the vlan 'n' to multicast maddr and port\n"
7515 "-net none use it alone to have zero network devices; if no -net option\n"
7516 " is provided, the default is '-net nic -net user'\n"
7517 "\n"
7518 #ifdef CONFIG_SLIRP
7519 "-tftp dir allow tftp access to files in dir [-net user]\n"
7520 "-bootp file advertise file in BOOTP replies\n"
7521 #ifndef _WIN32
7522 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7523 #endif
7524 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7525 " redirect TCP or UDP connections from host to guest [-net user]\n"
7526 #endif
7527 "\n"
7528 "Linux boot specific:\n"
7529 "-kernel bzImage use 'bzImage' as kernel image\n"
7530 "-append cmdline use 'cmdline' as kernel command line\n"
7531 "-initrd file use 'file' as initial ram disk\n"
7532 "\n"
7533 "Debug/Expert options:\n"
7534 "-monitor dev redirect the monitor to char device 'dev'\n"
7535 "-serial dev redirect the serial port to char device 'dev'\n"
7536 "-parallel dev redirect the parallel port to char device 'dev'\n"
7537 "-pidfile file Write PID to 'file'\n"
7538 "-S freeze CPU at startup (use 'c' to start execution)\n"
7539 "-s wait gdb connection to port\n"
7540 "-p port set gdb connection port [default=%s]\n"
7541 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7542 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7543 " translation (t=none or lba) (usually qemu can guess them)\n"
7544 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7545 #ifdef USE_KQEMU
7546 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7547 "-no-kqemu disable KQEMU kernel module usage\n"
7548 #endif
7549 #ifdef TARGET_I386
7550 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7551 " (default is CL-GD5446 PCI VGA)\n"
7552 "-no-acpi disable ACPI\n"
7553 #endif
7554 "-no-reboot exit instead of rebooting\n"
7555 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7556 "-vnc display start a VNC server on display\n"
7557 #ifndef _WIN32
7558 "-daemonize daemonize QEMU after initializing\n"
7559 #endif
7560 "-option-rom rom load a file, rom, into the option ROM space\n"
7561 #ifdef TARGET_SPARC
7562 "-prom-env variable=value set OpenBIOS nvram variables\n"
7563 #endif
7564 "-clock force the use of the given methods for timer alarm.\n"
7565 " To see what timers are available use -clock help\n"
7566 "\n"
7567 "During emulation, the following keys are useful:\n"
7568 "ctrl-alt-f toggle full screen\n"
7569 "ctrl-alt-n switch to virtual console 'n'\n"
7570 "ctrl-alt toggle mouse and keyboard grab\n"
7571 "\n"
7572 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7574 "qemu",
7575 DEFAULT_RAM_SIZE,
7576 #ifndef _WIN32
7577 DEFAULT_NETWORK_SCRIPT,
7578 DEFAULT_NETWORK_DOWN_SCRIPT,
7579 #endif
7580 DEFAULT_GDBSTUB_PORT,
7581 "/tmp/qemu.log");
7582 exit(exitcode);
7585 #define HAS_ARG 0x0001
7587 enum {
7588 QEMU_OPTION_h,
7590 QEMU_OPTION_M,
7591 QEMU_OPTION_cpu,
7592 QEMU_OPTION_fda,
7593 QEMU_OPTION_fdb,
7594 QEMU_OPTION_hda,
7595 QEMU_OPTION_hdb,
7596 QEMU_OPTION_hdc,
7597 QEMU_OPTION_hdd,
7598 QEMU_OPTION_drive,
7599 QEMU_OPTION_cdrom,
7600 QEMU_OPTION_mtdblock,
7601 QEMU_OPTION_sd,
7602 QEMU_OPTION_pflash,
7603 QEMU_OPTION_boot,
7604 QEMU_OPTION_snapshot,
7605 #ifdef TARGET_I386
7606 QEMU_OPTION_no_fd_bootchk,
7607 #endif
7608 QEMU_OPTION_m,
7609 QEMU_OPTION_nographic,
7610 QEMU_OPTION_portrait,
7611 #ifdef HAS_AUDIO
7612 QEMU_OPTION_audio_help,
7613 QEMU_OPTION_soundhw,
7614 #endif
7616 QEMU_OPTION_net,
7617 QEMU_OPTION_tftp,
7618 QEMU_OPTION_bootp,
7619 QEMU_OPTION_smb,
7620 QEMU_OPTION_redir,
7622 QEMU_OPTION_kernel,
7623 QEMU_OPTION_append,
7624 QEMU_OPTION_initrd,
7626 QEMU_OPTION_S,
7627 QEMU_OPTION_s,
7628 QEMU_OPTION_p,
7629 QEMU_OPTION_d,
7630 QEMU_OPTION_hdachs,
7631 QEMU_OPTION_L,
7632 QEMU_OPTION_bios,
7633 QEMU_OPTION_no_code_copy,
7634 QEMU_OPTION_k,
7635 QEMU_OPTION_localtime,
7636 QEMU_OPTION_cirrusvga,
7637 QEMU_OPTION_vmsvga,
7638 QEMU_OPTION_g,
7639 QEMU_OPTION_std_vga,
7640 QEMU_OPTION_echr,
7641 QEMU_OPTION_monitor,
7642 QEMU_OPTION_serial,
7643 QEMU_OPTION_parallel,
7644 QEMU_OPTION_loadvm,
7645 QEMU_OPTION_full_screen,
7646 QEMU_OPTION_no_frame,
7647 QEMU_OPTION_alt_grab,
7648 QEMU_OPTION_no_quit,
7649 QEMU_OPTION_pidfile,
7650 QEMU_OPTION_no_kqemu,
7651 QEMU_OPTION_kernel_kqemu,
7652 QEMU_OPTION_win2k_hack,
7653 QEMU_OPTION_usb,
7654 QEMU_OPTION_usbdevice,
7655 QEMU_OPTION_smp,
7656 QEMU_OPTION_vnc,
7657 QEMU_OPTION_no_acpi,
7658 QEMU_OPTION_no_reboot,
7659 QEMU_OPTION_show_cursor,
7660 QEMU_OPTION_daemonize,
7661 QEMU_OPTION_option_rom,
7662 QEMU_OPTION_semihosting,
7663 QEMU_OPTION_name,
7664 QEMU_OPTION_prom_env,
7665 QEMU_OPTION_old_param,
7666 QEMU_OPTION_clock,
7667 QEMU_OPTION_startdate,
7670 typedef struct QEMUOption {
7671 const char *name;
7672 int flags;
7673 int index;
7674 } QEMUOption;
7676 const QEMUOption qemu_options[] = {
7677 { "h", 0, QEMU_OPTION_h },
7678 { "help", 0, QEMU_OPTION_h },
7680 { "M", HAS_ARG, QEMU_OPTION_M },
7681 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7682 { "fda", HAS_ARG, QEMU_OPTION_fda },
7683 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7684 { "hda", HAS_ARG, QEMU_OPTION_hda },
7685 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7686 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7687 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7688 { "drive", HAS_ARG, QEMU_OPTION_drive },
7689 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7690 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7691 { "sd", HAS_ARG, QEMU_OPTION_sd },
7692 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7693 { "boot", HAS_ARG, QEMU_OPTION_boot },
7694 { "snapshot", 0, QEMU_OPTION_snapshot },
7695 #ifdef TARGET_I386
7696 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7697 #endif
7698 { "m", HAS_ARG, QEMU_OPTION_m },
7699 { "nographic", 0, QEMU_OPTION_nographic },
7700 { "portrait", 0, QEMU_OPTION_portrait },
7701 { "k", HAS_ARG, QEMU_OPTION_k },
7702 #ifdef HAS_AUDIO
7703 { "audio-help", 0, QEMU_OPTION_audio_help },
7704 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7705 #endif
7707 { "net", HAS_ARG, QEMU_OPTION_net},
7708 #ifdef CONFIG_SLIRP
7709 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7710 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7711 #ifndef _WIN32
7712 { "smb", HAS_ARG, QEMU_OPTION_smb },
7713 #endif
7714 { "redir", HAS_ARG, QEMU_OPTION_redir },
7715 #endif
7717 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7718 { "append", HAS_ARG, QEMU_OPTION_append },
7719 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7721 { "S", 0, QEMU_OPTION_S },
7722 { "s", 0, QEMU_OPTION_s },
7723 { "p", HAS_ARG, QEMU_OPTION_p },
7724 { "d", HAS_ARG, QEMU_OPTION_d },
7725 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7726 { "L", HAS_ARG, QEMU_OPTION_L },
7727 { "bios", HAS_ARG, QEMU_OPTION_bios },
7728 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7729 #ifdef USE_KQEMU
7730 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7731 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7732 #endif
7733 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7734 { "g", 1, QEMU_OPTION_g },
7735 #endif
7736 { "localtime", 0, QEMU_OPTION_localtime },
7737 { "std-vga", 0, QEMU_OPTION_std_vga },
7738 { "echr", HAS_ARG, QEMU_OPTION_echr },
7739 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7740 { "serial", HAS_ARG, QEMU_OPTION_serial },
7741 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7742 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7743 { "full-screen", 0, QEMU_OPTION_full_screen },
7744 #ifdef CONFIG_SDL
7745 { "no-frame", 0, QEMU_OPTION_no_frame },
7746 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7747 { "no-quit", 0, QEMU_OPTION_no_quit },
7748 #endif
7749 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7750 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7751 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7752 { "smp", HAS_ARG, QEMU_OPTION_smp },
7753 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7755 /* temporary options */
7756 { "usb", 0, QEMU_OPTION_usb },
7757 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7758 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7759 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7760 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7761 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7762 { "daemonize", 0, QEMU_OPTION_daemonize },
7763 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7764 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7765 { "semihosting", 0, QEMU_OPTION_semihosting },
7766 #endif
7767 { "name", HAS_ARG, QEMU_OPTION_name },
7768 #if defined(TARGET_SPARC)
7769 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7770 #endif
7771 #if defined(TARGET_ARM)
7772 { "old-param", 0, QEMU_OPTION_old_param },
7773 #endif
7774 { "clock", HAS_ARG, QEMU_OPTION_clock },
7775 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7776 { NULL },
7779 /* password input */
7781 int qemu_key_check(BlockDriverState *bs, const char *name)
7783 char password[256];
7784 int i;
7786 if (!bdrv_is_encrypted(bs))
7787 return 0;
7789 term_printf("%s is encrypted.\n", name);
7790 for(i = 0; i < 3; i++) {
7791 monitor_readline("Password: ", 1, password, sizeof(password));
7792 if (bdrv_set_key(bs, password) == 0)
7793 return 0;
7794 term_printf("invalid password\n");
7796 return -EPERM;
7799 static BlockDriverState *get_bdrv(int index)
7801 if (index > nb_drives)
7802 return NULL;
7803 return drives_table[index].bdrv;
7806 static void read_passwords(void)
7808 BlockDriverState *bs;
7809 int i;
7811 for(i = 0; i < 6; i++) {
7812 bs = get_bdrv(i);
7813 if (bs)
7814 qemu_key_check(bs, bdrv_get_device_name(bs));
7818 /* XXX: currently we cannot use simultaneously different CPUs */
7819 static void register_machines(void)
7821 #if defined(TARGET_I386)
7822 qemu_register_machine(&pc_machine);
7823 qemu_register_machine(&isapc_machine);
7824 #elif defined(TARGET_PPC)
7825 qemu_register_machine(&heathrow_machine);
7826 qemu_register_machine(&core99_machine);
7827 qemu_register_machine(&prep_machine);
7828 qemu_register_machine(&ref405ep_machine);
7829 qemu_register_machine(&taihu_machine);
7830 #elif defined(TARGET_MIPS)
7831 qemu_register_machine(&mips_machine);
7832 qemu_register_machine(&mips_malta_machine);
7833 qemu_register_machine(&mips_pica61_machine);
7834 qemu_register_machine(&mips_mipssim_machine);
7835 #elif defined(TARGET_SPARC)
7836 #ifdef TARGET_SPARC64
7837 qemu_register_machine(&sun4u_machine);
7838 #else
7839 qemu_register_machine(&ss5_machine);
7840 qemu_register_machine(&ss10_machine);
7841 qemu_register_machine(&ss600mp_machine);
7842 qemu_register_machine(&ss20_machine);
7843 #endif
7844 #elif defined(TARGET_ARM)
7845 qemu_register_machine(&integratorcp_machine);
7846 qemu_register_machine(&versatilepb_machine);
7847 qemu_register_machine(&versatileab_machine);
7848 qemu_register_machine(&realview_machine);
7849 qemu_register_machine(&akitapda_machine);
7850 qemu_register_machine(&spitzpda_machine);
7851 qemu_register_machine(&borzoipda_machine);
7852 qemu_register_machine(&terrierpda_machine);
7853 qemu_register_machine(&palmte_machine);
7854 qemu_register_machine(&lm3s811evb_machine);
7855 qemu_register_machine(&lm3s6965evb_machine);
7856 qemu_register_machine(&connex_machine);
7857 qemu_register_machine(&verdex_machine);
7858 qemu_register_machine(&mainstone2_machine);
7859 #elif defined(TARGET_SH4)
7860 qemu_register_machine(&shix_machine);
7861 qemu_register_machine(&r2d_machine);
7862 #elif defined(TARGET_ALPHA)
7863 /* XXX: TODO */
7864 #elif defined(TARGET_M68K)
7865 qemu_register_machine(&mcf5208evb_machine);
7866 qemu_register_machine(&an5206_machine);
7867 qemu_register_machine(&dummy_m68k_machine);
7868 #elif defined(TARGET_CRIS)
7869 qemu_register_machine(&bareetraxfs_machine);
7870 #else
7871 #error unsupported CPU
7872 #endif
7875 #ifdef HAS_AUDIO
7876 struct soundhw soundhw[] = {
7877 #ifdef HAS_AUDIO_CHOICE
7878 #ifdef TARGET_I386
7880 "pcspk",
7881 "PC speaker",
7884 { .init_isa = pcspk_audio_init }
7886 #endif
7888 "sb16",
7889 "Creative Sound Blaster 16",
7892 { .init_isa = SB16_init }
7895 #ifdef CONFIG_ADLIB
7897 "adlib",
7898 #ifdef HAS_YMF262
7899 "Yamaha YMF262 (OPL3)",
7900 #else
7901 "Yamaha YM3812 (OPL2)",
7902 #endif
7905 { .init_isa = Adlib_init }
7907 #endif
7909 #ifdef CONFIG_GUS
7911 "gus",
7912 "Gravis Ultrasound GF1",
7915 { .init_isa = GUS_init }
7917 #endif
7920 "es1370",
7921 "ENSONIQ AudioPCI ES1370",
7924 { .init_pci = es1370_init }
7926 #endif
7928 { NULL, NULL, 0, 0, { NULL } }
7931 static void select_soundhw (const char *optarg)
7933 struct soundhw *c;
7935 if (*optarg == '?') {
7936 show_valid_cards:
7938 printf ("Valid sound card names (comma separated):\n");
7939 for (c = soundhw; c->name; ++c) {
7940 printf ("%-11s %s\n", c->name, c->descr);
7942 printf ("\n-soundhw all will enable all of the above\n");
7943 exit (*optarg != '?');
7945 else {
7946 size_t l;
7947 const char *p;
7948 char *e;
7949 int bad_card = 0;
7951 if (!strcmp (optarg, "all")) {
7952 for (c = soundhw; c->name; ++c) {
7953 c->enabled = 1;
7955 return;
7958 p = optarg;
7959 while (*p) {
7960 e = strchr (p, ',');
7961 l = !e ? strlen (p) : (size_t) (e - p);
7963 for (c = soundhw; c->name; ++c) {
7964 if (!strncmp (c->name, p, l)) {
7965 c->enabled = 1;
7966 break;
7970 if (!c->name) {
7971 if (l > 80) {
7972 fprintf (stderr,
7973 "Unknown sound card name (too big to show)\n");
7975 else {
7976 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7977 (int) l, p);
7979 bad_card = 1;
7981 p += l + (e != NULL);
7984 if (bad_card)
7985 goto show_valid_cards;
7988 #endif
7990 #ifdef _WIN32
7991 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7993 exit(STATUS_CONTROL_C_EXIT);
7994 return TRUE;
7996 #endif
7998 #define MAX_NET_CLIENTS 32
8000 int main(int argc, char **argv)
8002 #ifdef CONFIG_GDBSTUB
8003 int use_gdbstub;
8004 const char *gdbstub_port;
8005 #endif
8006 uint32_t boot_devices_bitmap = 0;
8007 int i;
8008 int snapshot, linux_boot, net_boot;
8009 const char *initrd_filename;
8010 const char *kernel_filename, *kernel_cmdline;
8011 const char *boot_devices = "";
8012 DisplayState *ds = &display_state;
8013 int cyls, heads, secs, translation;
8014 char net_clients[MAX_NET_CLIENTS][256];
8015 int nb_net_clients;
8016 int hda_index;
8017 int optind;
8018 const char *r, *optarg;
8019 CharDriverState *monitor_hd;
8020 char monitor_device[128];
8021 char serial_devices[MAX_SERIAL_PORTS][128];
8022 int serial_device_index;
8023 char parallel_devices[MAX_PARALLEL_PORTS][128];
8024 int parallel_device_index;
8025 const char *loadvm = NULL;
8026 QEMUMachine *machine;
8027 const char *cpu_model;
8028 char usb_devices[MAX_USB_CMDLINE][128];
8029 int usb_devices_index;
8030 int fds[2];
8031 const char *pid_file = NULL;
8032 VLANState *vlan;
8034 LIST_INIT (&vm_change_state_head);
8035 #ifndef _WIN32
8037 struct sigaction act;
8038 sigfillset(&act.sa_mask);
8039 act.sa_flags = 0;
8040 act.sa_handler = SIG_IGN;
8041 sigaction(SIGPIPE, &act, NULL);
8043 #else
8044 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8045 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8046 QEMU to run on a single CPU */
8048 HANDLE h;
8049 DWORD mask, smask;
8050 int i;
8051 h = GetCurrentProcess();
8052 if (GetProcessAffinityMask(h, &mask, &smask)) {
8053 for(i = 0; i < 32; i++) {
8054 if (mask & (1 << i))
8055 break;
8057 if (i != 32) {
8058 mask = 1 << i;
8059 SetProcessAffinityMask(h, mask);
8063 #endif
8065 register_machines();
8066 machine = first_machine;
8067 cpu_model = NULL;
8068 initrd_filename = NULL;
8069 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8070 vga_ram_size = VGA_RAM_SIZE;
8071 #ifdef CONFIG_GDBSTUB
8072 use_gdbstub = 0;
8073 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8074 #endif
8075 snapshot = 0;
8076 nographic = 0;
8077 kernel_filename = NULL;
8078 kernel_cmdline = "";
8079 cyls = heads = secs = 0;
8080 translation = BIOS_ATA_TRANSLATION_AUTO;
8081 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8083 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8084 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8085 serial_devices[i][0] = '\0';
8086 serial_device_index = 0;
8088 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8089 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8090 parallel_devices[i][0] = '\0';
8091 parallel_device_index = 0;
8093 usb_devices_index = 0;
8095 nb_net_clients = 0;
8096 nb_drives = 0;
8097 nb_drives_opt = 0;
8098 hda_index = -1;
8100 nb_nics = 0;
8101 /* default mac address of the first network interface */
8103 optind = 1;
8104 for(;;) {
8105 if (optind >= argc)
8106 break;
8107 r = argv[optind];
8108 if (r[0] != '-') {
8109 hda_index = drive_add(HD_ALIAS, argv[optind++], 0);
8110 } else {
8111 const QEMUOption *popt;
8113 optind++;
8114 /* Treat --foo the same as -foo. */
8115 if (r[1] == '-')
8116 r++;
8117 popt = qemu_options;
8118 for(;;) {
8119 if (!popt->name) {
8120 fprintf(stderr, "%s: invalid option -- '%s'\n",
8121 argv[0], r);
8122 exit(1);
8124 if (!strcmp(popt->name, r + 1))
8125 break;
8126 popt++;
8128 if (popt->flags & HAS_ARG) {
8129 if (optind >= argc) {
8130 fprintf(stderr, "%s: option '%s' requires an argument\n",
8131 argv[0], r);
8132 exit(1);
8134 optarg = argv[optind++];
8135 } else {
8136 optarg = NULL;
8139 switch(popt->index) {
8140 case QEMU_OPTION_M:
8141 machine = find_machine(optarg);
8142 if (!machine) {
8143 QEMUMachine *m;
8144 printf("Supported machines are:\n");
8145 for(m = first_machine; m != NULL; m = m->next) {
8146 printf("%-10s %s%s\n",
8147 m->name, m->desc,
8148 m == first_machine ? " (default)" : "");
8150 exit(*optarg != '?');
8152 break;
8153 case QEMU_OPTION_cpu:
8154 /* hw initialization will check this */
8155 if (*optarg == '?') {
8156 /* XXX: implement xxx_cpu_list for targets that still miss it */
8157 #if defined(cpu_list)
8158 cpu_list(stdout, &fprintf);
8159 #endif
8160 exit(0);
8161 } else {
8162 cpu_model = optarg;
8164 break;
8165 case QEMU_OPTION_initrd:
8166 initrd_filename = optarg;
8167 break;
8168 case QEMU_OPTION_hda:
8169 if (cyls == 0)
8170 hda_index = drive_add(HD_ALIAS, optarg, 0);
8171 else
8172 hda_index = drive_add(HD_ALIAS
8173 ",cyls=%d,heads=%d,secs=%d%s",
8174 optarg, 0, cyls, heads, secs,
8175 translation == BIOS_ATA_TRANSLATION_LBA ?
8176 ",trans=lba" :
8177 translation == BIOS_ATA_TRANSLATION_NONE ?
8178 ",trans=none" : "");
8179 break;
8180 case QEMU_OPTION_hdb:
8181 case QEMU_OPTION_hdc:
8182 case QEMU_OPTION_hdd:
8183 drive_add(HD_ALIAS, optarg, popt->index - QEMU_OPTION_hda);
8184 break;
8185 case QEMU_OPTION_drive:
8186 drive_add("%s", optarg);
8187 break;
8188 case QEMU_OPTION_mtdblock:
8189 drive_add(MTD_ALIAS, optarg);
8190 break;
8191 case QEMU_OPTION_sd:
8192 drive_add("file=\"%s\"," SD_ALIAS, optarg);
8193 break;
8194 case QEMU_OPTION_pflash:
8195 drive_add(PFLASH_ALIAS, optarg);
8196 break;
8197 case QEMU_OPTION_snapshot:
8198 snapshot = 1;
8199 break;
8200 case QEMU_OPTION_hdachs:
8202 const char *p;
8203 p = optarg;
8204 cyls = strtol(p, (char **)&p, 0);
8205 if (cyls < 1 || cyls > 16383)
8206 goto chs_fail;
8207 if (*p != ',')
8208 goto chs_fail;
8209 p++;
8210 heads = strtol(p, (char **)&p, 0);
8211 if (heads < 1 || heads > 16)
8212 goto chs_fail;
8213 if (*p != ',')
8214 goto chs_fail;
8215 p++;
8216 secs = strtol(p, (char **)&p, 0);
8217 if (secs < 1 || secs > 63)
8218 goto chs_fail;
8219 if (*p == ',') {
8220 p++;
8221 if (!strcmp(p, "none"))
8222 translation = BIOS_ATA_TRANSLATION_NONE;
8223 else if (!strcmp(p, "lba"))
8224 translation = BIOS_ATA_TRANSLATION_LBA;
8225 else if (!strcmp(p, "auto"))
8226 translation = BIOS_ATA_TRANSLATION_AUTO;
8227 else
8228 goto chs_fail;
8229 } else if (*p != '\0') {
8230 chs_fail:
8231 fprintf(stderr, "qemu: invalid physical CHS format\n");
8232 exit(1);
8234 if (hda_index != -1)
8235 snprintf(drives_opt[hda_index] +
8236 strlen(drives_opt[hda_index]),
8237 sizeof(drives_opt[0]) -
8238 strlen(drives_opt[hda_index]),
8239 ",cyls=%d,heads=%d,secs=%d%s",
8240 cyls, heads, secs,
8241 translation == BIOS_ATA_TRANSLATION_LBA ?
8242 ",trans=lba" :
8243 translation == BIOS_ATA_TRANSLATION_NONE ?
8244 ",trans=none" : "");
8246 break;
8247 case QEMU_OPTION_nographic:
8248 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8249 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8250 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8251 nographic = 1;
8252 break;
8253 case QEMU_OPTION_portrait:
8254 graphic_rotate = 1;
8255 break;
8256 case QEMU_OPTION_kernel:
8257 kernel_filename = optarg;
8258 break;
8259 case QEMU_OPTION_append:
8260 kernel_cmdline = optarg;
8261 break;
8262 case QEMU_OPTION_cdrom:
8263 drive_add("file=\"%s\"," CDROM_ALIAS, optarg);
8264 break;
8265 case QEMU_OPTION_boot:
8266 boot_devices = optarg;
8267 /* We just do some generic consistency checks */
8269 /* Could easily be extended to 64 devices if needed */
8270 const char *p;
8272 boot_devices_bitmap = 0;
8273 for (p = boot_devices; *p != '\0'; p++) {
8274 /* Allowed boot devices are:
8275 * a b : floppy disk drives
8276 * c ... f : IDE disk drives
8277 * g ... m : machine implementation dependant drives
8278 * n ... p : network devices
8279 * It's up to each machine implementation to check
8280 * if the given boot devices match the actual hardware
8281 * implementation and firmware features.
8283 if (*p < 'a' || *p > 'q') {
8284 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8285 exit(1);
8287 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8288 fprintf(stderr,
8289 "Boot device '%c' was given twice\n",*p);
8290 exit(1);
8292 boot_devices_bitmap |= 1 << (*p - 'a');
8295 break;
8296 case QEMU_OPTION_fda:
8297 case QEMU_OPTION_fdb:
8298 drive_add("file=\"%s\"," FD_ALIAS, optarg,
8299 popt->index - QEMU_OPTION_fda);
8300 break;
8301 #ifdef TARGET_I386
8302 case QEMU_OPTION_no_fd_bootchk:
8303 fd_bootchk = 0;
8304 break;
8305 #endif
8306 case QEMU_OPTION_no_code_copy:
8307 code_copy_enabled = 0;
8308 break;
8309 case QEMU_OPTION_net:
8310 if (nb_net_clients >= MAX_NET_CLIENTS) {
8311 fprintf(stderr, "qemu: too many network clients\n");
8312 exit(1);
8314 pstrcpy(net_clients[nb_net_clients],
8315 sizeof(net_clients[0]),
8316 optarg);
8317 nb_net_clients++;
8318 break;
8319 #ifdef CONFIG_SLIRP
8320 case QEMU_OPTION_tftp:
8321 tftp_prefix = optarg;
8322 break;
8323 case QEMU_OPTION_bootp:
8324 bootp_filename = optarg;
8325 break;
8326 #ifndef _WIN32
8327 case QEMU_OPTION_smb:
8328 net_slirp_smb(optarg);
8329 break;
8330 #endif
8331 case QEMU_OPTION_redir:
8332 net_slirp_redir(optarg);
8333 break;
8334 #endif
8335 #ifdef HAS_AUDIO
8336 case QEMU_OPTION_audio_help:
8337 AUD_help ();
8338 exit (0);
8339 break;
8340 case QEMU_OPTION_soundhw:
8341 select_soundhw (optarg);
8342 break;
8343 #endif
8344 case QEMU_OPTION_h:
8345 help(0);
8346 break;
8347 case QEMU_OPTION_m:
8348 ram_size = atoi(optarg) * 1024 * 1024;
8349 if (ram_size <= 0)
8350 help(1);
8351 if (ram_size > PHYS_RAM_MAX_SIZE) {
8352 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8353 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8354 exit(1);
8356 break;
8357 case QEMU_OPTION_d:
8359 int mask;
8360 CPULogItem *item;
8362 mask = cpu_str_to_log_mask(optarg);
8363 if (!mask) {
8364 printf("Log items (comma separated):\n");
8365 for(item = cpu_log_items; item->mask != 0; item++) {
8366 printf("%-10s %s\n", item->name, item->help);
8368 exit(1);
8370 cpu_set_log(mask);
8372 break;
8373 #ifdef CONFIG_GDBSTUB
8374 case QEMU_OPTION_s:
8375 use_gdbstub = 1;
8376 break;
8377 case QEMU_OPTION_p:
8378 gdbstub_port = optarg;
8379 break;
8380 #endif
8381 case QEMU_OPTION_L:
8382 bios_dir = optarg;
8383 break;
8384 case QEMU_OPTION_bios:
8385 bios_name = optarg;
8386 break;
8387 case QEMU_OPTION_S:
8388 autostart = 0;
8389 break;
8390 case QEMU_OPTION_k:
8391 keyboard_layout = optarg;
8392 break;
8393 case QEMU_OPTION_localtime:
8394 rtc_utc = 0;
8395 break;
8396 case QEMU_OPTION_cirrusvga:
8397 cirrus_vga_enabled = 1;
8398 vmsvga_enabled = 0;
8399 break;
8400 case QEMU_OPTION_vmsvga:
8401 cirrus_vga_enabled = 0;
8402 vmsvga_enabled = 1;
8403 break;
8404 case QEMU_OPTION_std_vga:
8405 cirrus_vga_enabled = 0;
8406 vmsvga_enabled = 0;
8407 break;
8408 case QEMU_OPTION_g:
8410 const char *p;
8411 int w, h, depth;
8412 p = optarg;
8413 w = strtol(p, (char **)&p, 10);
8414 if (w <= 0) {
8415 graphic_error:
8416 fprintf(stderr, "qemu: invalid resolution or depth\n");
8417 exit(1);
8419 if (*p != 'x')
8420 goto graphic_error;
8421 p++;
8422 h = strtol(p, (char **)&p, 10);
8423 if (h <= 0)
8424 goto graphic_error;
8425 if (*p == 'x') {
8426 p++;
8427 depth = strtol(p, (char **)&p, 10);
8428 if (depth != 8 && depth != 15 && depth != 16 &&
8429 depth != 24 && depth != 32)
8430 goto graphic_error;
8431 } else if (*p == '\0') {
8432 depth = graphic_depth;
8433 } else {
8434 goto graphic_error;
8437 graphic_width = w;
8438 graphic_height = h;
8439 graphic_depth = depth;
8441 break;
8442 case QEMU_OPTION_echr:
8444 char *r;
8445 term_escape_char = strtol(optarg, &r, 0);
8446 if (r == optarg)
8447 printf("Bad argument to echr\n");
8448 break;
8450 case QEMU_OPTION_monitor:
8451 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8452 break;
8453 case QEMU_OPTION_serial:
8454 if (serial_device_index >= MAX_SERIAL_PORTS) {
8455 fprintf(stderr, "qemu: too many serial ports\n");
8456 exit(1);
8458 pstrcpy(serial_devices[serial_device_index],
8459 sizeof(serial_devices[0]), optarg);
8460 serial_device_index++;
8461 break;
8462 case QEMU_OPTION_parallel:
8463 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8464 fprintf(stderr, "qemu: too many parallel ports\n");
8465 exit(1);
8467 pstrcpy(parallel_devices[parallel_device_index],
8468 sizeof(parallel_devices[0]), optarg);
8469 parallel_device_index++;
8470 break;
8471 case QEMU_OPTION_loadvm:
8472 loadvm = optarg;
8473 break;
8474 case QEMU_OPTION_full_screen:
8475 full_screen = 1;
8476 break;
8477 #ifdef CONFIG_SDL
8478 case QEMU_OPTION_no_frame:
8479 no_frame = 1;
8480 break;
8481 case QEMU_OPTION_alt_grab:
8482 alt_grab = 1;
8483 break;
8484 case QEMU_OPTION_no_quit:
8485 no_quit = 1;
8486 break;
8487 #endif
8488 case QEMU_OPTION_pidfile:
8489 pid_file = optarg;
8490 break;
8491 #ifdef TARGET_I386
8492 case QEMU_OPTION_win2k_hack:
8493 win2k_install_hack = 1;
8494 break;
8495 #endif
8496 #ifdef USE_KQEMU
8497 case QEMU_OPTION_no_kqemu:
8498 kqemu_allowed = 0;
8499 break;
8500 case QEMU_OPTION_kernel_kqemu:
8501 kqemu_allowed = 2;
8502 break;
8503 #endif
8504 case QEMU_OPTION_usb:
8505 usb_enabled = 1;
8506 break;
8507 case QEMU_OPTION_usbdevice:
8508 usb_enabled = 1;
8509 if (usb_devices_index >= MAX_USB_CMDLINE) {
8510 fprintf(stderr, "Too many USB devices\n");
8511 exit(1);
8513 pstrcpy(usb_devices[usb_devices_index],
8514 sizeof(usb_devices[usb_devices_index]),
8515 optarg);
8516 usb_devices_index++;
8517 break;
8518 case QEMU_OPTION_smp:
8519 smp_cpus = atoi(optarg);
8520 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8521 fprintf(stderr, "Invalid number of CPUs\n");
8522 exit(1);
8524 break;
8525 case QEMU_OPTION_vnc:
8526 vnc_display = optarg;
8527 break;
8528 case QEMU_OPTION_no_acpi:
8529 acpi_enabled = 0;
8530 break;
8531 case QEMU_OPTION_no_reboot:
8532 no_reboot = 1;
8533 break;
8534 case QEMU_OPTION_show_cursor:
8535 cursor_hide = 0;
8536 break;
8537 case QEMU_OPTION_daemonize:
8538 daemonize = 1;
8539 break;
8540 case QEMU_OPTION_option_rom:
8541 if (nb_option_roms >= MAX_OPTION_ROMS) {
8542 fprintf(stderr, "Too many option ROMs\n");
8543 exit(1);
8545 option_rom[nb_option_roms] = optarg;
8546 nb_option_roms++;
8547 break;
8548 case QEMU_OPTION_semihosting:
8549 semihosting_enabled = 1;
8550 break;
8551 case QEMU_OPTION_name:
8552 qemu_name = optarg;
8553 break;
8554 #ifdef TARGET_SPARC
8555 case QEMU_OPTION_prom_env:
8556 if (nb_prom_envs >= MAX_PROM_ENVS) {
8557 fprintf(stderr, "Too many prom variables\n");
8558 exit(1);
8560 prom_envs[nb_prom_envs] = optarg;
8561 nb_prom_envs++;
8562 break;
8563 #endif
8564 #ifdef TARGET_ARM
8565 case QEMU_OPTION_old_param:
8566 old_param = 1;
8567 #endif
8568 case QEMU_OPTION_clock:
8569 configure_alarms(optarg);
8570 break;
8571 case QEMU_OPTION_startdate:
8573 struct tm tm;
8574 if (!strcmp(optarg, "now")) {
8575 rtc_start_date = -1;
8576 } else {
8577 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8578 &tm.tm_year,
8579 &tm.tm_mon,
8580 &tm.tm_mday,
8581 &tm.tm_hour,
8582 &tm.tm_min,
8583 &tm.tm_sec) == 6) {
8584 /* OK */
8585 } else if (sscanf(optarg, "%d-%d-%d",
8586 &tm.tm_year,
8587 &tm.tm_mon,
8588 &tm.tm_mday) == 3) {
8589 tm.tm_hour = 0;
8590 tm.tm_min = 0;
8591 tm.tm_sec = 0;
8592 } else {
8593 goto date_fail;
8595 tm.tm_year -= 1900;
8596 tm.tm_mon--;
8597 rtc_start_date = mktimegm(&tm);
8598 if (rtc_start_date == -1) {
8599 date_fail:
8600 fprintf(stderr, "Invalid date format. Valid format are:\n"
8601 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8602 exit(1);
8606 break;
8611 #ifndef _WIN32
8612 if (daemonize && !nographic && vnc_display == NULL) {
8613 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8614 daemonize = 0;
8617 if (daemonize) {
8618 pid_t pid;
8620 if (pipe(fds) == -1)
8621 exit(1);
8623 pid = fork();
8624 if (pid > 0) {
8625 uint8_t status;
8626 ssize_t len;
8628 close(fds[1]);
8630 again:
8631 len = read(fds[0], &status, 1);
8632 if (len == -1 && (errno == EINTR))
8633 goto again;
8635 if (len != 1)
8636 exit(1);
8637 else if (status == 1) {
8638 fprintf(stderr, "Could not acquire pidfile\n");
8639 exit(1);
8640 } else
8641 exit(0);
8642 } else if (pid < 0)
8643 exit(1);
8645 setsid();
8647 pid = fork();
8648 if (pid > 0)
8649 exit(0);
8650 else if (pid < 0)
8651 exit(1);
8653 umask(027);
8654 chdir("/");
8656 signal(SIGTSTP, SIG_IGN);
8657 signal(SIGTTOU, SIG_IGN);
8658 signal(SIGTTIN, SIG_IGN);
8660 #endif
8662 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8663 if (daemonize) {
8664 uint8_t status = 1;
8665 write(fds[1], &status, 1);
8666 } else
8667 fprintf(stderr, "Could not acquire pid file\n");
8668 exit(1);
8671 #ifdef USE_KQEMU
8672 if (smp_cpus > 1)
8673 kqemu_allowed = 0;
8674 #endif
8675 linux_boot = (kernel_filename != NULL);
8676 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8678 /* XXX: this should not be: some embedded targets just have flash */
8679 if (!linux_boot && net_boot == 0 &&
8680 nb_drives_opt == 0)
8681 help(1);
8683 /* boot to floppy or the default cd if no hard disk defined yet */
8684 if (!boot_devices[0]) {
8685 boot_devices = "cad";
8687 setvbuf(stdout, NULL, _IOLBF, 0);
8689 init_timers();
8690 init_timer_alarm();
8691 qemu_aio_init();
8693 #ifdef _WIN32
8694 socket_init();
8695 #endif
8697 /* init network clients */
8698 if (nb_net_clients == 0) {
8699 /* if no clients, we use a default config */
8700 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8701 "nic");
8702 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8703 "user");
8704 nb_net_clients = 2;
8707 for(i = 0;i < nb_net_clients; i++) {
8708 if (net_client_init(net_clients[i]) < 0)
8709 exit(1);
8711 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8712 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8713 continue;
8714 if (vlan->nb_guest_devs == 0) {
8715 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8716 exit(1);
8718 if (vlan->nb_host_devs == 0)
8719 fprintf(stderr,
8720 "Warning: vlan %d is not connected to host network\n",
8721 vlan->id);
8724 #ifdef TARGET_I386
8725 /* XXX: this should be moved in the PC machine instantiation code */
8726 if (net_boot != 0) {
8727 int netroms = 0;
8728 for (i = 0; i < nb_nics && i < 4; i++) {
8729 const char *model = nd_table[i].model;
8730 char buf[1024];
8731 if (net_boot & (1 << i)) {
8732 if (model == NULL)
8733 model = "ne2k_pci";
8734 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8735 if (get_image_size(buf) > 0) {
8736 if (nb_option_roms >= MAX_OPTION_ROMS) {
8737 fprintf(stderr, "Too many option ROMs\n");
8738 exit(1);
8740 option_rom[nb_option_roms] = strdup(buf);
8741 nb_option_roms++;
8742 netroms++;
8746 if (netroms == 0) {
8747 fprintf(stderr, "No valid PXE rom found for network device\n");
8748 exit(1);
8751 #endif
8753 /* init the memory */
8754 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8756 phys_ram_base = qemu_vmalloc(phys_ram_size);
8757 if (!phys_ram_base) {
8758 fprintf(stderr, "Could not allocate physical memory\n");
8759 exit(1);
8762 bdrv_init();
8764 /* we always create the cdrom drive, even if no disk is there */
8766 if (nb_drives_opt < MAX_DRIVES)
8767 drive_add(CDROM_ALIAS);
8769 /* we always create at least one floppy */
8771 if (nb_drives_opt < MAX_DRIVES)
8772 drive_add(FD_ALIAS, 0);
8774 /* we always create one sd slot, even if no card is in it */
8776 if (nb_drives_opt < MAX_DRIVES)
8777 drive_add(SD_ALIAS);
8779 /* open the virtual block devices */
8781 for(i = 0; i < nb_drives_opt; i++)
8782 if (drive_init(drives_opt[i], snapshot, machine) == -1)
8783 exit(1);
8785 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8786 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8788 init_ioports();
8790 /* terminal init */
8791 memset(&display_state, 0, sizeof(display_state));
8792 if (nographic) {
8793 /* nearly nothing to do */
8794 dumb_display_init(ds);
8795 } else if (vnc_display != NULL) {
8796 vnc_display_init(ds);
8797 if (vnc_display_open(ds, vnc_display) < 0)
8798 exit(1);
8799 } else {
8800 #if defined(CONFIG_SDL)
8801 sdl_display_init(ds, full_screen, no_frame);
8802 #elif defined(CONFIG_COCOA)
8803 cocoa_display_init(ds, full_screen);
8804 #else
8805 dumb_display_init(ds);
8806 #endif
8809 /* Maintain compatibility with multiple stdio monitors */
8810 if (!strcmp(monitor_device,"stdio")) {
8811 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8812 if (!strcmp(serial_devices[i],"mon:stdio")) {
8813 monitor_device[0] = '\0';
8814 break;
8815 } else if (!strcmp(serial_devices[i],"stdio")) {
8816 monitor_device[0] = '\0';
8817 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8818 break;
8822 if (monitor_device[0] != '\0') {
8823 monitor_hd = qemu_chr_open(monitor_device);
8824 if (!monitor_hd) {
8825 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8826 exit(1);
8828 monitor_init(monitor_hd, !nographic);
8831 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8832 const char *devname = serial_devices[i];
8833 if (devname[0] != '\0' && strcmp(devname, "none")) {
8834 serial_hds[i] = qemu_chr_open(devname);
8835 if (!serial_hds[i]) {
8836 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8837 devname);
8838 exit(1);
8840 if (strstart(devname, "vc", 0))
8841 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8845 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8846 const char *devname = parallel_devices[i];
8847 if (devname[0] != '\0' && strcmp(devname, "none")) {
8848 parallel_hds[i] = qemu_chr_open(devname);
8849 if (!parallel_hds[i]) {
8850 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8851 devname);
8852 exit(1);
8854 if (strstart(devname, "vc", 0))
8855 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8859 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8860 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8862 /* init USB devices */
8863 if (usb_enabled) {
8864 for(i = 0; i < usb_devices_index; i++) {
8865 if (usb_device_add(usb_devices[i]) < 0) {
8866 fprintf(stderr, "Warning: could not add USB device %s\n",
8867 usb_devices[i]);
8872 if (display_state.dpy_refresh) {
8873 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8874 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8877 #ifdef CONFIG_GDBSTUB
8878 if (use_gdbstub) {
8879 /* XXX: use standard host:port notation and modify options
8880 accordingly. */
8881 if (gdbserver_start(gdbstub_port) < 0) {
8882 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8883 gdbstub_port);
8884 exit(1);
8887 #endif
8889 if (loadvm)
8890 do_loadvm(loadvm);
8893 /* XXX: simplify init */
8894 read_passwords();
8895 if (autostart) {
8896 vm_start();
8900 if (daemonize) {
8901 uint8_t status = 0;
8902 ssize_t len;
8903 int fd;
8905 again1:
8906 len = write(fds[1], &status, 1);
8907 if (len == -1 && (errno == EINTR))
8908 goto again1;
8910 if (len != 1)
8911 exit(1);
8913 TFR(fd = open("/dev/null", O_RDWR));
8914 if (fd == -1)
8915 exit(1);
8917 dup2(fd, 0);
8918 dup2(fd, 1);
8919 dup2(fd, 2);
8921 close(fd);
8924 main_loop();
8925 quit_timers();
8927 #if !defined(_WIN32)
8928 /* close network clients */
8929 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8930 VLANClientState *vc;
8932 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8933 if (vc->fd_read == tap_receive) {
8934 char ifname[64];
8935 TAPState *s = vc->opaque;
8937 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8938 s->down_script[0])
8939 launch_script(s->down_script, ifname, s->fd);
8943 #endif
8944 return 0;