Support alternative formats for MAC addresses, by Balazs Attila-Mihaly.
[qemu/mini2440.git] / vl.c
bloba4592f7bd0ee14b45cd9bfb1a07e7cbc0785424b
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 = 1;
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 char *last_char;
3457 long int offset;
3459 errno = 0;
3460 offset = strtol(p, &last_char, 0);
3461 if (0 == errno && '\0' == *last_char &&
3462 offset >= 0 && offset <= 0xFFFFFF) {
3463 macaddr[3] = (offset & 0xFF0000) >> 16;
3464 macaddr[4] = (offset & 0xFF00) >> 8;
3465 macaddr[5] = offset & 0xFF;
3466 return 0;
3467 } else {
3468 for(i = 0; i < 6; i++) {
3469 macaddr[i] = strtol(p, (char **)&p, 16);
3470 if (i == 5) {
3471 if (*p != '\0')
3472 return -1;
3473 } else {
3474 if (*p != ':' && *p != '-')
3475 return -1;
3476 p++;
3479 return 0;
3482 return -1;
3485 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3487 const char *p, *p1;
3488 int len;
3489 p = *pp;
3490 p1 = strchr(p, sep);
3491 if (!p1)
3492 return -1;
3493 len = p1 - p;
3494 p1++;
3495 if (buf_size > 0) {
3496 if (len > buf_size - 1)
3497 len = buf_size - 1;
3498 memcpy(buf, p, len);
3499 buf[len] = '\0';
3501 *pp = p1;
3502 return 0;
3505 int parse_host_src_port(struct sockaddr_in *haddr,
3506 struct sockaddr_in *saddr,
3507 const char *input_str)
3509 char *str = strdup(input_str);
3510 char *host_str = str;
3511 char *src_str;
3512 char *ptr;
3515 * Chop off any extra arguments at the end of the string which
3516 * would start with a comma, then fill in the src port information
3517 * if it was provided else use the "any address" and "any port".
3519 if ((ptr = strchr(str,',')))
3520 *ptr = '\0';
3522 if ((src_str = strchr(input_str,'@'))) {
3523 *src_str = '\0';
3524 src_str++;
3527 if (parse_host_port(haddr, host_str) < 0)
3528 goto fail;
3530 if (!src_str || *src_str == '\0')
3531 src_str = ":0";
3533 if (parse_host_port(saddr, src_str) < 0)
3534 goto fail;
3536 free(str);
3537 return(0);
3539 fail:
3540 free(str);
3541 return -1;
3544 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3546 char buf[512];
3547 struct hostent *he;
3548 const char *p, *r;
3549 int port;
3551 p = str;
3552 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3553 return -1;
3554 saddr->sin_family = AF_INET;
3555 if (buf[0] == '\0') {
3556 saddr->sin_addr.s_addr = 0;
3557 } else {
3558 if (isdigit(buf[0])) {
3559 if (!inet_aton(buf, &saddr->sin_addr))
3560 return -1;
3561 } else {
3562 if ((he = gethostbyname(buf)) == NULL)
3563 return - 1;
3564 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3567 port = strtol(p, (char **)&r, 0);
3568 if (r == p)
3569 return -1;
3570 saddr->sin_port = htons(port);
3571 return 0;
3574 #ifndef _WIN32
3575 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3577 const char *p;
3578 int len;
3580 len = MIN(108, strlen(str));
3581 p = strchr(str, ',');
3582 if (p)
3583 len = MIN(len, p - str);
3585 memset(uaddr, 0, sizeof(*uaddr));
3587 uaddr->sun_family = AF_UNIX;
3588 memcpy(uaddr->sun_path, str, len);
3590 return 0;
3592 #endif
3594 /* find or alloc a new VLAN */
3595 VLANState *qemu_find_vlan(int id)
3597 VLANState **pvlan, *vlan;
3598 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3599 if (vlan->id == id)
3600 return vlan;
3602 vlan = qemu_mallocz(sizeof(VLANState));
3603 if (!vlan)
3604 return NULL;
3605 vlan->id = id;
3606 vlan->next = NULL;
3607 pvlan = &first_vlan;
3608 while (*pvlan != NULL)
3609 pvlan = &(*pvlan)->next;
3610 *pvlan = vlan;
3611 return vlan;
3614 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3615 IOReadHandler *fd_read,
3616 IOCanRWHandler *fd_can_read,
3617 void *opaque)
3619 VLANClientState *vc, **pvc;
3620 vc = qemu_mallocz(sizeof(VLANClientState));
3621 if (!vc)
3622 return NULL;
3623 vc->fd_read = fd_read;
3624 vc->fd_can_read = fd_can_read;
3625 vc->opaque = opaque;
3626 vc->vlan = vlan;
3628 vc->next = NULL;
3629 pvc = &vlan->first_client;
3630 while (*pvc != NULL)
3631 pvc = &(*pvc)->next;
3632 *pvc = vc;
3633 return vc;
3636 int qemu_can_send_packet(VLANClientState *vc1)
3638 VLANState *vlan = vc1->vlan;
3639 VLANClientState *vc;
3641 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3642 if (vc != vc1) {
3643 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3644 return 1;
3647 return 0;
3650 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3652 VLANState *vlan = vc1->vlan;
3653 VLANClientState *vc;
3655 #if 0
3656 printf("vlan %d send:\n", vlan->id);
3657 hex_dump(stdout, buf, size);
3658 #endif
3659 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3660 if (vc != vc1) {
3661 vc->fd_read(vc->opaque, buf, size);
3666 #if defined(CONFIG_SLIRP)
3668 /* slirp network adapter */
3670 static int slirp_inited;
3671 static VLANClientState *slirp_vc;
3673 int slirp_can_output(void)
3675 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3678 void slirp_output(const uint8_t *pkt, int pkt_len)
3680 #if 0
3681 printf("slirp output:\n");
3682 hex_dump(stdout, pkt, pkt_len);
3683 #endif
3684 if (!slirp_vc)
3685 return;
3686 qemu_send_packet(slirp_vc, pkt, pkt_len);
3689 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3691 #if 0
3692 printf("slirp input:\n");
3693 hex_dump(stdout, buf, size);
3694 #endif
3695 slirp_input(buf, size);
3698 static int net_slirp_init(VLANState *vlan)
3700 if (!slirp_inited) {
3701 slirp_inited = 1;
3702 slirp_init();
3704 slirp_vc = qemu_new_vlan_client(vlan,
3705 slirp_receive, NULL, NULL);
3706 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3707 return 0;
3710 static void net_slirp_redir(const char *redir_str)
3712 int is_udp;
3713 char buf[256], *r;
3714 const char *p;
3715 struct in_addr guest_addr;
3716 int host_port, guest_port;
3718 if (!slirp_inited) {
3719 slirp_inited = 1;
3720 slirp_init();
3723 p = redir_str;
3724 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3725 goto fail;
3726 if (!strcmp(buf, "tcp")) {
3727 is_udp = 0;
3728 } else if (!strcmp(buf, "udp")) {
3729 is_udp = 1;
3730 } else {
3731 goto fail;
3734 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3735 goto fail;
3736 host_port = strtol(buf, &r, 0);
3737 if (r == buf)
3738 goto fail;
3740 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3741 goto fail;
3742 if (buf[0] == '\0') {
3743 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3745 if (!inet_aton(buf, &guest_addr))
3746 goto fail;
3748 guest_port = strtol(p, &r, 0);
3749 if (r == p)
3750 goto fail;
3752 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3753 fprintf(stderr, "qemu: could not set up redirection\n");
3754 exit(1);
3756 return;
3757 fail:
3758 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3759 exit(1);
3762 #ifndef _WIN32
3764 char smb_dir[1024];
3766 static void smb_exit(void)
3768 DIR *d;
3769 struct dirent *de;
3770 char filename[1024];
3772 /* erase all the files in the directory */
3773 d = opendir(smb_dir);
3774 for(;;) {
3775 de = readdir(d);
3776 if (!de)
3777 break;
3778 if (strcmp(de->d_name, ".") != 0 &&
3779 strcmp(de->d_name, "..") != 0) {
3780 snprintf(filename, sizeof(filename), "%s/%s",
3781 smb_dir, de->d_name);
3782 unlink(filename);
3785 closedir(d);
3786 rmdir(smb_dir);
3789 /* automatic user mode samba server configuration */
3790 static void net_slirp_smb(const char *exported_dir)
3792 char smb_conf[1024];
3793 char smb_cmdline[1024];
3794 FILE *f;
3796 if (!slirp_inited) {
3797 slirp_inited = 1;
3798 slirp_init();
3801 /* XXX: better tmp dir construction */
3802 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3803 if (mkdir(smb_dir, 0700) < 0) {
3804 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3805 exit(1);
3807 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3809 f = fopen(smb_conf, "w");
3810 if (!f) {
3811 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3812 exit(1);
3814 fprintf(f,
3815 "[global]\n"
3816 "private dir=%s\n"
3817 "smb ports=0\n"
3818 "socket address=127.0.0.1\n"
3819 "pid directory=%s\n"
3820 "lock directory=%s\n"
3821 "log file=%s/log.smbd\n"
3822 "smb passwd file=%s/smbpasswd\n"
3823 "security = share\n"
3824 "[qemu]\n"
3825 "path=%s\n"
3826 "read only=no\n"
3827 "guest ok=yes\n",
3828 smb_dir,
3829 smb_dir,
3830 smb_dir,
3831 smb_dir,
3832 smb_dir,
3833 exported_dir
3835 fclose(f);
3836 atexit(smb_exit);
3838 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3839 SMBD_COMMAND, smb_conf);
3841 slirp_add_exec(0, smb_cmdline, 4, 139);
3844 #endif /* !defined(_WIN32) */
3845 void do_info_slirp(void)
3847 slirp_stats();
3850 #endif /* CONFIG_SLIRP */
3852 #if !defined(_WIN32)
3854 typedef struct TAPState {
3855 VLANClientState *vc;
3856 int fd;
3857 char down_script[1024];
3858 } TAPState;
3860 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3862 TAPState *s = opaque;
3863 int ret;
3864 for(;;) {
3865 ret = write(s->fd, buf, size);
3866 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3867 } else {
3868 break;
3873 static void tap_send(void *opaque)
3875 TAPState *s = opaque;
3876 uint8_t buf[4096];
3877 int size;
3879 #ifdef __sun__
3880 struct strbuf sbuf;
3881 int f = 0;
3882 sbuf.maxlen = sizeof(buf);
3883 sbuf.buf = buf;
3884 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3885 #else
3886 size = read(s->fd, buf, sizeof(buf));
3887 #endif
3888 if (size > 0) {
3889 qemu_send_packet(s->vc, buf, size);
3893 /* fd support */
3895 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3897 TAPState *s;
3899 s = qemu_mallocz(sizeof(TAPState));
3900 if (!s)
3901 return NULL;
3902 s->fd = fd;
3903 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3904 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3905 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3906 return s;
3909 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3910 static int tap_open(char *ifname, int ifname_size)
3912 int fd;
3913 char *dev;
3914 struct stat s;
3916 TFR(fd = open("/dev/tap", O_RDWR));
3917 if (fd < 0) {
3918 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3919 return -1;
3922 fstat(fd, &s);
3923 dev = devname(s.st_rdev, S_IFCHR);
3924 pstrcpy(ifname, ifname_size, dev);
3926 fcntl(fd, F_SETFL, O_NONBLOCK);
3927 return fd;
3929 #elif defined(__sun__)
3930 #define TUNNEWPPA (('T'<<16) | 0x0001)
3932 * Allocate TAP device, returns opened fd.
3933 * Stores dev name in the first arg(must be large enough).
3935 int tap_alloc(char *dev)
3937 int tap_fd, if_fd, ppa = -1;
3938 static int ip_fd = 0;
3939 char *ptr;
3941 static int arp_fd = 0;
3942 int ip_muxid, arp_muxid;
3943 struct strioctl strioc_if, strioc_ppa;
3944 int link_type = I_PLINK;;
3945 struct lifreq ifr;
3946 char actual_name[32] = "";
3948 memset(&ifr, 0x0, sizeof(ifr));
3950 if( *dev ){
3951 ptr = dev;
3952 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3953 ppa = atoi(ptr);
3956 /* Check if IP device was opened */
3957 if( ip_fd )
3958 close(ip_fd);
3960 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3961 if (ip_fd < 0) {
3962 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3963 return -1;
3966 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3967 if (tap_fd < 0) {
3968 syslog(LOG_ERR, "Can't open /dev/tap");
3969 return -1;
3972 /* Assign a new PPA and get its unit number. */
3973 strioc_ppa.ic_cmd = TUNNEWPPA;
3974 strioc_ppa.ic_timout = 0;
3975 strioc_ppa.ic_len = sizeof(ppa);
3976 strioc_ppa.ic_dp = (char *)&ppa;
3977 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3978 syslog (LOG_ERR, "Can't assign new interface");
3980 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3981 if (if_fd < 0) {
3982 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3983 return -1;
3985 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3986 syslog(LOG_ERR, "Can't push IP module");
3987 return -1;
3990 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3991 syslog(LOG_ERR, "Can't get flags\n");
3993 snprintf (actual_name, 32, "tap%d", ppa);
3994 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3996 ifr.lifr_ppa = ppa;
3997 /* Assign ppa according to the unit number returned by tun device */
3999 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4000 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4001 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4002 syslog (LOG_ERR, "Can't get flags\n");
4003 /* Push arp module to if_fd */
4004 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4005 syslog (LOG_ERR, "Can't push ARP module (2)");
4007 /* Push arp module to ip_fd */
4008 if (ioctl (ip_fd, I_POP, NULL) < 0)
4009 syslog (LOG_ERR, "I_POP failed\n");
4010 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4011 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4012 /* Open arp_fd */
4013 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4014 if (arp_fd < 0)
4015 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4017 /* Set ifname to arp */
4018 strioc_if.ic_cmd = SIOCSLIFNAME;
4019 strioc_if.ic_timout = 0;
4020 strioc_if.ic_len = sizeof(ifr);
4021 strioc_if.ic_dp = (char *)&ifr;
4022 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4023 syslog (LOG_ERR, "Can't set ifname to arp\n");
4026 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4027 syslog(LOG_ERR, "Can't link TAP device to IP");
4028 return -1;
4031 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4032 syslog (LOG_ERR, "Can't link TAP device to ARP");
4034 close (if_fd);
4036 memset(&ifr, 0x0, sizeof(ifr));
4037 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4038 ifr.lifr_ip_muxid = ip_muxid;
4039 ifr.lifr_arp_muxid = arp_muxid;
4041 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4043 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4044 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4045 syslog (LOG_ERR, "Can't set multiplexor id");
4048 sprintf(dev, "tap%d", ppa);
4049 return tap_fd;
4052 static int tap_open(char *ifname, int ifname_size)
4054 char dev[10]="";
4055 int fd;
4056 if( (fd = tap_alloc(dev)) < 0 ){
4057 fprintf(stderr, "Cannot allocate TAP device\n");
4058 return -1;
4060 pstrcpy(ifname, ifname_size, dev);
4061 fcntl(fd, F_SETFL, O_NONBLOCK);
4062 return fd;
4064 #else
4065 static int tap_open(char *ifname, int ifname_size)
4067 struct ifreq ifr;
4068 int fd, ret;
4070 TFR(fd = open("/dev/net/tun", O_RDWR));
4071 if (fd < 0) {
4072 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4073 return -1;
4075 memset(&ifr, 0, sizeof(ifr));
4076 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4077 if (ifname[0] != '\0')
4078 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4079 else
4080 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4081 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4082 if (ret != 0) {
4083 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4084 close(fd);
4085 return -1;
4087 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4088 fcntl(fd, F_SETFL, O_NONBLOCK);
4089 return fd;
4091 #endif
4093 static int launch_script(const char *setup_script, const char *ifname, int fd)
4095 int pid, status;
4096 char *args[3];
4097 char **parg;
4099 /* try to launch network script */
4100 pid = fork();
4101 if (pid >= 0) {
4102 if (pid == 0) {
4103 int open_max = sysconf (_SC_OPEN_MAX), i;
4104 for (i = 0; i < open_max; i++)
4105 if (i != STDIN_FILENO &&
4106 i != STDOUT_FILENO &&
4107 i != STDERR_FILENO &&
4108 i != fd)
4109 close(i);
4111 parg = args;
4112 *parg++ = (char *)setup_script;
4113 *parg++ = (char *)ifname;
4114 *parg++ = NULL;
4115 execv(setup_script, args);
4116 _exit(1);
4118 while (waitpid(pid, &status, 0) != pid);
4119 if (!WIFEXITED(status) ||
4120 WEXITSTATUS(status) != 0) {
4121 fprintf(stderr, "%s: could not launch network script\n",
4122 setup_script);
4123 return -1;
4126 return 0;
4129 static int net_tap_init(VLANState *vlan, const char *ifname1,
4130 const char *setup_script, const char *down_script)
4132 TAPState *s;
4133 int fd;
4134 char ifname[128];
4136 if (ifname1 != NULL)
4137 pstrcpy(ifname, sizeof(ifname), ifname1);
4138 else
4139 ifname[0] = '\0';
4140 TFR(fd = tap_open(ifname, sizeof(ifname)));
4141 if (fd < 0)
4142 return -1;
4144 if (!setup_script || !strcmp(setup_script, "no"))
4145 setup_script = "";
4146 if (setup_script[0] != '\0') {
4147 if (launch_script(setup_script, ifname, fd))
4148 return -1;
4150 s = net_tap_fd_init(vlan, fd);
4151 if (!s)
4152 return -1;
4153 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4154 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4155 if (down_script && strcmp(down_script, "no"))
4156 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4157 return 0;
4160 #endif /* !_WIN32 */
4162 /* network connection */
4163 typedef struct NetSocketState {
4164 VLANClientState *vc;
4165 int fd;
4166 int state; /* 0 = getting length, 1 = getting data */
4167 int index;
4168 int packet_len;
4169 uint8_t buf[4096];
4170 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4171 } NetSocketState;
4173 typedef struct NetSocketListenState {
4174 VLANState *vlan;
4175 int fd;
4176 } NetSocketListenState;
4178 /* XXX: we consider we can send the whole packet without blocking */
4179 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4181 NetSocketState *s = opaque;
4182 uint32_t len;
4183 len = htonl(size);
4185 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4186 send_all(s->fd, buf, size);
4189 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4191 NetSocketState *s = opaque;
4192 sendto(s->fd, buf, size, 0,
4193 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4196 static void net_socket_send(void *opaque)
4198 NetSocketState *s = opaque;
4199 int l, size, err;
4200 uint8_t buf1[4096];
4201 const uint8_t *buf;
4203 size = recv(s->fd, buf1, sizeof(buf1), 0);
4204 if (size < 0) {
4205 err = socket_error();
4206 if (err != EWOULDBLOCK)
4207 goto eoc;
4208 } else if (size == 0) {
4209 /* end of connection */
4210 eoc:
4211 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4212 closesocket(s->fd);
4213 return;
4215 buf = buf1;
4216 while (size > 0) {
4217 /* reassemble a packet from the network */
4218 switch(s->state) {
4219 case 0:
4220 l = 4 - s->index;
4221 if (l > size)
4222 l = size;
4223 memcpy(s->buf + s->index, buf, l);
4224 buf += l;
4225 size -= l;
4226 s->index += l;
4227 if (s->index == 4) {
4228 /* got length */
4229 s->packet_len = ntohl(*(uint32_t *)s->buf);
4230 s->index = 0;
4231 s->state = 1;
4233 break;
4234 case 1:
4235 l = s->packet_len - s->index;
4236 if (l > size)
4237 l = size;
4238 memcpy(s->buf + s->index, buf, l);
4239 s->index += l;
4240 buf += l;
4241 size -= l;
4242 if (s->index >= s->packet_len) {
4243 qemu_send_packet(s->vc, s->buf, s->packet_len);
4244 s->index = 0;
4245 s->state = 0;
4247 break;
4252 static void net_socket_send_dgram(void *opaque)
4254 NetSocketState *s = opaque;
4255 int size;
4257 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4258 if (size < 0)
4259 return;
4260 if (size == 0) {
4261 /* end of connection */
4262 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4263 return;
4265 qemu_send_packet(s->vc, s->buf, size);
4268 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4270 struct ip_mreq imr;
4271 int fd;
4272 int val, ret;
4273 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4274 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4275 inet_ntoa(mcastaddr->sin_addr),
4276 (int)ntohl(mcastaddr->sin_addr.s_addr));
4277 return -1;
4280 fd = socket(PF_INET, SOCK_DGRAM, 0);
4281 if (fd < 0) {
4282 perror("socket(PF_INET, SOCK_DGRAM)");
4283 return -1;
4286 val = 1;
4287 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4288 (const char *)&val, sizeof(val));
4289 if (ret < 0) {
4290 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4291 goto fail;
4294 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4295 if (ret < 0) {
4296 perror("bind");
4297 goto fail;
4300 /* Add host to multicast group */
4301 imr.imr_multiaddr = mcastaddr->sin_addr;
4302 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4304 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4305 (const char *)&imr, sizeof(struct ip_mreq));
4306 if (ret < 0) {
4307 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4308 goto fail;
4311 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4312 val = 1;
4313 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4314 (const char *)&val, sizeof(val));
4315 if (ret < 0) {
4316 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4317 goto fail;
4320 socket_set_nonblock(fd);
4321 return fd;
4322 fail:
4323 if (fd >= 0)
4324 closesocket(fd);
4325 return -1;
4328 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4329 int is_connected)
4331 struct sockaddr_in saddr;
4332 int newfd;
4333 socklen_t saddr_len;
4334 NetSocketState *s;
4336 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4337 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4338 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4341 if (is_connected) {
4342 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4343 /* must be bound */
4344 if (saddr.sin_addr.s_addr==0) {
4345 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4346 fd);
4347 return NULL;
4349 /* clone dgram socket */
4350 newfd = net_socket_mcast_create(&saddr);
4351 if (newfd < 0) {
4352 /* error already reported by net_socket_mcast_create() */
4353 close(fd);
4354 return NULL;
4356 /* clone newfd to fd, close newfd */
4357 dup2(newfd, fd);
4358 close(newfd);
4360 } else {
4361 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4362 fd, strerror(errno));
4363 return NULL;
4367 s = qemu_mallocz(sizeof(NetSocketState));
4368 if (!s)
4369 return NULL;
4370 s->fd = fd;
4372 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4373 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4375 /* mcast: save bound address as dst */
4376 if (is_connected) s->dgram_dst=saddr;
4378 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4379 "socket: fd=%d (%s mcast=%s:%d)",
4380 fd, is_connected? "cloned" : "",
4381 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4382 return s;
4385 static void net_socket_connect(void *opaque)
4387 NetSocketState *s = opaque;
4388 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4391 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4392 int is_connected)
4394 NetSocketState *s;
4395 s = qemu_mallocz(sizeof(NetSocketState));
4396 if (!s)
4397 return NULL;
4398 s->fd = fd;
4399 s->vc = qemu_new_vlan_client(vlan,
4400 net_socket_receive, NULL, s);
4401 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4402 "socket: fd=%d", fd);
4403 if (is_connected) {
4404 net_socket_connect(s);
4405 } else {
4406 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4408 return s;
4411 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4412 int is_connected)
4414 int so_type=-1, optlen=sizeof(so_type);
4416 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4417 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4418 return NULL;
4420 switch(so_type) {
4421 case SOCK_DGRAM:
4422 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4423 case SOCK_STREAM:
4424 return net_socket_fd_init_stream(vlan, fd, is_connected);
4425 default:
4426 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4427 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4428 return net_socket_fd_init_stream(vlan, fd, is_connected);
4430 return NULL;
4433 static void net_socket_accept(void *opaque)
4435 NetSocketListenState *s = opaque;
4436 NetSocketState *s1;
4437 struct sockaddr_in saddr;
4438 socklen_t len;
4439 int fd;
4441 for(;;) {
4442 len = sizeof(saddr);
4443 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4444 if (fd < 0 && errno != EINTR) {
4445 return;
4446 } else if (fd >= 0) {
4447 break;
4450 s1 = net_socket_fd_init(s->vlan, fd, 1);
4451 if (!s1) {
4452 closesocket(fd);
4453 } else {
4454 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4455 "socket: connection from %s:%d",
4456 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4460 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4462 NetSocketListenState *s;
4463 int fd, val, ret;
4464 struct sockaddr_in saddr;
4466 if (parse_host_port(&saddr, host_str) < 0)
4467 return -1;
4469 s = qemu_mallocz(sizeof(NetSocketListenState));
4470 if (!s)
4471 return -1;
4473 fd = socket(PF_INET, SOCK_STREAM, 0);
4474 if (fd < 0) {
4475 perror("socket");
4476 return -1;
4478 socket_set_nonblock(fd);
4480 /* allow fast reuse */
4481 val = 1;
4482 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4484 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4485 if (ret < 0) {
4486 perror("bind");
4487 return -1;
4489 ret = listen(fd, 0);
4490 if (ret < 0) {
4491 perror("listen");
4492 return -1;
4494 s->vlan = vlan;
4495 s->fd = fd;
4496 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4497 return 0;
4500 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4502 NetSocketState *s;
4503 int fd, connected, ret, err;
4504 struct sockaddr_in saddr;
4506 if (parse_host_port(&saddr, host_str) < 0)
4507 return -1;
4509 fd = socket(PF_INET, SOCK_STREAM, 0);
4510 if (fd < 0) {
4511 perror("socket");
4512 return -1;
4514 socket_set_nonblock(fd);
4516 connected = 0;
4517 for(;;) {
4518 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4519 if (ret < 0) {
4520 err = socket_error();
4521 if (err == EINTR || err == EWOULDBLOCK) {
4522 } else if (err == EINPROGRESS) {
4523 break;
4524 #ifdef _WIN32
4525 } else if (err == WSAEALREADY) {
4526 break;
4527 #endif
4528 } else {
4529 perror("connect");
4530 closesocket(fd);
4531 return -1;
4533 } else {
4534 connected = 1;
4535 break;
4538 s = net_socket_fd_init(vlan, fd, connected);
4539 if (!s)
4540 return -1;
4541 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4542 "socket: connect to %s:%d",
4543 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4544 return 0;
4547 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4549 NetSocketState *s;
4550 int fd;
4551 struct sockaddr_in saddr;
4553 if (parse_host_port(&saddr, host_str) < 0)
4554 return -1;
4557 fd = net_socket_mcast_create(&saddr);
4558 if (fd < 0)
4559 return -1;
4561 s = net_socket_fd_init(vlan, fd, 0);
4562 if (!s)
4563 return -1;
4565 s->dgram_dst = saddr;
4567 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4568 "socket: mcast=%s:%d",
4569 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4570 return 0;
4574 static const char *get_word(char *buf, int buf_size, const char *p)
4576 char *q;
4577 int substring;
4579 substring = 0;
4580 q = buf;
4581 while (*p != '\0') {
4582 if (*p == '\\') {
4583 p++;
4584 if (*p == '\0')
4585 break;
4586 } else if (*p == '\"') {
4587 substring = !substring;
4588 p++;
4589 continue;
4590 } else if (!substring && (*p == ',' || *p == '='))
4591 break;
4592 if (q && (q - buf) < buf_size - 1)
4593 *q++ = *p;
4594 p++;
4596 if (q)
4597 *q = '\0';
4599 return p;
4602 static int get_param_value(char *buf, int buf_size,
4603 const char *tag, const char *str)
4605 const char *p;
4606 char option[128];
4608 p = str;
4609 for(;;) {
4610 p = get_word(option, sizeof(option), p);
4611 if (*p != '=')
4612 break;
4613 p++;
4614 if (!strcmp(tag, option)) {
4615 (void)get_word(buf, buf_size, p);
4616 return strlen(buf);
4617 } else {
4618 p = get_word(NULL, 0, p);
4620 if (*p != ',')
4621 break;
4622 p++;
4624 return 0;
4627 static int check_params(char *buf, int buf_size,
4628 char **params, const char *str)
4630 const char *p;
4631 int i;
4633 p = str;
4634 for(;;) {
4635 p = get_word(buf, buf_size, p);
4636 if (*p != '=')
4637 return -1;
4638 p++;
4639 for(i = 0; params[i] != NULL; i++)
4640 if (!strcmp(params[i], buf))
4641 break;
4642 if (params[i] == NULL)
4643 return -1;
4644 p = get_word(NULL, 0, p);
4645 if (*p != ',')
4646 break;
4647 p++;
4649 return 0;
4653 static int net_client_init(const char *str)
4655 const char *p;
4656 char *q;
4657 char device[64];
4658 char buf[1024];
4659 int vlan_id, ret;
4660 VLANState *vlan;
4662 p = str;
4663 q = device;
4664 while (*p != '\0' && *p != ',') {
4665 if ((q - device) < sizeof(device) - 1)
4666 *q++ = *p;
4667 p++;
4669 *q = '\0';
4670 if (*p == ',')
4671 p++;
4672 vlan_id = 0;
4673 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4674 vlan_id = strtol(buf, NULL, 0);
4676 vlan = qemu_find_vlan(vlan_id);
4677 if (!vlan) {
4678 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4679 return -1;
4681 if (!strcmp(device, "nic")) {
4682 NICInfo *nd;
4683 uint8_t *macaddr;
4685 if (nb_nics >= MAX_NICS) {
4686 fprintf(stderr, "Too Many NICs\n");
4687 return -1;
4689 nd = &nd_table[nb_nics];
4690 macaddr = nd->macaddr;
4691 macaddr[0] = 0x52;
4692 macaddr[1] = 0x54;
4693 macaddr[2] = 0x00;
4694 macaddr[3] = 0x12;
4695 macaddr[4] = 0x34;
4696 macaddr[5] = 0x56 + nb_nics;
4698 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4699 if (parse_macaddr(macaddr, buf) < 0) {
4700 fprintf(stderr, "invalid syntax for ethernet address\n");
4701 return -1;
4704 if (get_param_value(buf, sizeof(buf), "model", p)) {
4705 nd->model = strdup(buf);
4707 nd->vlan = vlan;
4708 nb_nics++;
4709 vlan->nb_guest_devs++;
4710 ret = 0;
4711 } else
4712 if (!strcmp(device, "none")) {
4713 /* does nothing. It is needed to signal that no network cards
4714 are wanted */
4715 ret = 0;
4716 } else
4717 #ifdef CONFIG_SLIRP
4718 if (!strcmp(device, "user")) {
4719 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4720 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4722 vlan->nb_host_devs++;
4723 ret = net_slirp_init(vlan);
4724 } else
4725 #endif
4726 #ifdef _WIN32
4727 if (!strcmp(device, "tap")) {
4728 char ifname[64];
4729 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4730 fprintf(stderr, "tap: no interface name\n");
4731 return -1;
4733 vlan->nb_host_devs++;
4734 ret = tap_win32_init(vlan, ifname);
4735 } else
4736 #else
4737 if (!strcmp(device, "tap")) {
4738 char ifname[64];
4739 char setup_script[1024], down_script[1024];
4740 int fd;
4741 vlan->nb_host_devs++;
4742 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4743 fd = strtol(buf, NULL, 0);
4744 ret = -1;
4745 if (net_tap_fd_init(vlan, fd))
4746 ret = 0;
4747 } else {
4748 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4749 ifname[0] = '\0';
4751 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4752 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4754 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4755 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4757 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4759 } else
4760 #endif
4761 if (!strcmp(device, "socket")) {
4762 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4763 int fd;
4764 fd = strtol(buf, NULL, 0);
4765 ret = -1;
4766 if (net_socket_fd_init(vlan, fd, 1))
4767 ret = 0;
4768 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4769 ret = net_socket_listen_init(vlan, buf);
4770 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4771 ret = net_socket_connect_init(vlan, buf);
4772 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4773 ret = net_socket_mcast_init(vlan, buf);
4774 } else {
4775 fprintf(stderr, "Unknown socket options: %s\n", p);
4776 return -1;
4778 vlan->nb_host_devs++;
4779 } else
4781 fprintf(stderr, "Unknown network device: %s\n", device);
4782 return -1;
4784 if (ret < 0) {
4785 fprintf(stderr, "Could not initialize device '%s'\n", device);
4788 return ret;
4791 void do_info_network(void)
4793 VLANState *vlan;
4794 VLANClientState *vc;
4796 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4797 term_printf("VLAN %d devices:\n", vlan->id);
4798 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4799 term_printf(" %s\n", vc->info_str);
4803 #define HD_ALIAS "file=\"%s\",index=%d,media=disk"
4804 #ifdef TARGET_PPC
4805 #define CDROM_ALIAS "index=1,media=cdrom"
4806 #else
4807 #define CDROM_ALIAS "index=2,media=cdrom"
4808 #endif
4809 #define FD_ALIAS "index=%d,if=floppy"
4810 #define PFLASH_ALIAS "file=\"%s\",if=pflash"
4811 #define MTD_ALIAS "file=\"%s\",if=mtd"
4812 #define SD_ALIAS "index=0,if=sd"
4814 static int drive_add(const char *fmt, ...)
4816 va_list ap;
4818 if (nb_drives_opt >= MAX_DRIVES) {
4819 fprintf(stderr, "qemu: too many drives\n");
4820 exit(1);
4823 va_start(ap, fmt);
4824 vsnprintf(drives_opt[nb_drives_opt], sizeof(drives_opt[0]), fmt, ap);
4825 va_end(ap);
4827 return nb_drives_opt++;
4830 int drive_get_index(BlockInterfaceType interface, int bus, int unit)
4832 int index;
4834 /* seek interface, bus and unit */
4836 for (index = 0; index < nb_drives; index++)
4837 if (drives_table[index].interface == interface &&
4838 drives_table[index].bus == bus &&
4839 drives_table[index].unit == unit)
4840 return index;
4842 return -1;
4845 int drive_get_max_bus(BlockInterfaceType interface)
4847 int max_bus;
4848 int index;
4850 max_bus = -1;
4851 for (index = 0; index < nb_drives; index++) {
4852 if(drives_table[index].interface == interface &&
4853 drives_table[index].bus > max_bus)
4854 max_bus = drives_table[index].bus;
4856 return max_bus;
4859 static int drive_init(const char *str, int snapshot, QEMUMachine *machine)
4861 char buf[128];
4862 char file[1024];
4863 char devname[128];
4864 const char *mediastr = "";
4865 BlockInterfaceType interface;
4866 enum { MEDIA_DISK, MEDIA_CDROM } media;
4867 int bus_id, unit_id;
4868 int cyls, heads, secs, translation;
4869 BlockDriverState *bdrv;
4870 int max_devs;
4871 int index;
4872 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4873 "secs", "trans", "media", "snapshot", "file", NULL };
4875 if (check_params(buf, sizeof(buf), params, str) < 0) {
4876 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4877 buf, str);
4878 return -1;
4881 file[0] = 0;
4882 cyls = heads = secs = 0;
4883 bus_id = 0;
4884 unit_id = -1;
4885 translation = BIOS_ATA_TRANSLATION_AUTO;
4886 index = -1;
4888 if (!strcmp(machine->name, "realview") ||
4889 !strcmp(machine->name, "SS-5") ||
4890 !strcmp(machine->name, "SS-10") ||
4891 !strcmp(machine->name, "SS-600MP") ||
4892 !strcmp(machine->name, "versatilepb") ||
4893 !strcmp(machine->name, "versatileab")) {
4894 interface = IF_SCSI;
4895 max_devs = MAX_SCSI_DEVS;
4896 strcpy(devname, "scsi");
4897 } else {
4898 interface = IF_IDE;
4899 max_devs = MAX_IDE_DEVS;
4900 strcpy(devname, "ide");
4902 media = MEDIA_DISK;
4904 /* extract parameters */
4906 if (get_param_value(buf, sizeof(buf), "bus", str)) {
4907 bus_id = strtol(buf, NULL, 0);
4908 if (bus_id < 0) {
4909 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4910 return -1;
4914 if (get_param_value(buf, sizeof(buf), "unit", str)) {
4915 unit_id = strtol(buf, NULL, 0);
4916 if (unit_id < 0) {
4917 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4918 return -1;
4922 if (get_param_value(buf, sizeof(buf), "if", str)) {
4923 strncpy(devname, buf, sizeof(devname));
4924 if (!strcmp(buf, "ide")) {
4925 interface = IF_IDE;
4926 max_devs = MAX_IDE_DEVS;
4927 } else if (!strcmp(buf, "scsi")) {
4928 interface = IF_SCSI;
4929 max_devs = MAX_SCSI_DEVS;
4930 } else if (!strcmp(buf, "floppy")) {
4931 interface = IF_FLOPPY;
4932 max_devs = 0;
4933 } else if (!strcmp(buf, "pflash")) {
4934 interface = IF_PFLASH;
4935 max_devs = 0;
4936 } else if (!strcmp(buf, "mtd")) {
4937 interface = IF_MTD;
4938 max_devs = 0;
4939 } else if (!strcmp(buf, "sd")) {
4940 interface = IF_SD;
4941 max_devs = 0;
4942 } else {
4943 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
4944 return -1;
4948 if (get_param_value(buf, sizeof(buf), "index", str)) {
4949 index = strtol(buf, NULL, 0);
4950 if (index < 0) {
4951 fprintf(stderr, "qemu: '%s' invalid index\n", str);
4952 return -1;
4956 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
4957 cyls = strtol(buf, NULL, 0);
4960 if (get_param_value(buf, sizeof(buf), "heads", str)) {
4961 heads = strtol(buf, NULL, 0);
4964 if (get_param_value(buf, sizeof(buf), "secs", str)) {
4965 secs = strtol(buf, NULL, 0);
4968 if (cyls || heads || secs) {
4969 if (cyls < 1 || cyls > 16383) {
4970 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
4971 return -1;
4973 if (heads < 1 || heads > 16) {
4974 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
4975 return -1;
4977 if (secs < 1 || secs > 63) {
4978 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
4979 return -1;
4983 if (get_param_value(buf, sizeof(buf), "trans", str)) {
4984 if (!cyls) {
4985 fprintf(stderr,
4986 "qemu: '%s' trans must be used with cyls,heads and secs\n",
4987 str);
4988 return -1;
4990 if (!strcmp(buf, "none"))
4991 translation = BIOS_ATA_TRANSLATION_NONE;
4992 else if (!strcmp(buf, "lba"))
4993 translation = BIOS_ATA_TRANSLATION_LBA;
4994 else if (!strcmp(buf, "auto"))
4995 translation = BIOS_ATA_TRANSLATION_AUTO;
4996 else {
4997 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
4998 return -1;
5002 if (get_param_value(buf, sizeof(buf), "media", str)) {
5003 if (!strcmp(buf, "disk")) {
5004 media = MEDIA_DISK;
5005 } else if (!strcmp(buf, "cdrom")) {
5006 if (cyls || secs || heads) {
5007 fprintf(stderr,
5008 "qemu: '%s' invalid physical CHS format\n", str);
5009 return -1;
5011 media = MEDIA_CDROM;
5012 } else {
5013 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5014 return -1;
5018 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5019 if (!strcmp(buf, "on"))
5020 snapshot = 1;
5021 else if (!strcmp(buf, "off"))
5022 snapshot = 0;
5023 else {
5024 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5025 return -1;
5029 get_param_value(file, sizeof(file), "file", str);
5031 /* compute bus and unit according index */
5033 if (index != -1) {
5034 if (bus_id != 0 || unit_id != -1) {
5035 fprintf(stderr,
5036 "qemu: '%s' index cannot be used with bus and unit\n", str);
5037 return -1;
5039 if (max_devs == 0)
5041 unit_id = index;
5042 bus_id = 0;
5043 } else {
5044 unit_id = index % max_devs;
5045 bus_id = index / max_devs;
5049 /* if user doesn't specify a unit_id,
5050 * try to find the first free
5053 if (unit_id == -1) {
5054 unit_id = 0;
5055 while (drive_get_index(interface, bus_id, unit_id) != -1) {
5056 unit_id++;
5057 if (max_devs && unit_id >= max_devs) {
5058 unit_id -= max_devs;
5059 bus_id++;
5064 /* check unit id */
5066 if (max_devs && unit_id >= max_devs) {
5067 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5068 str, unit_id, max_devs - 1);
5069 return -1;
5073 * ignore multiple definitions
5076 if (drive_get_index(interface, bus_id, unit_id) != -1)
5077 return 0;
5079 /* init */
5081 if (interface == IF_IDE || interface == IF_SCSI)
5082 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5083 snprintf(buf, sizeof(buf), max_devs ? "%1$s%4$i%2$s%3$i" : "%s%s%i",
5084 devname, mediastr, unit_id, bus_id);
5085 bdrv = bdrv_new(buf);
5086 drives_table[nb_drives].bdrv = bdrv;
5087 drives_table[nb_drives].interface = interface;
5088 drives_table[nb_drives].bus = bus_id;
5089 drives_table[nb_drives].unit = unit_id;
5090 nb_drives++;
5092 switch(interface) {
5093 case IF_IDE:
5094 case IF_SCSI:
5095 switch(media) {
5096 case MEDIA_DISK:
5097 if (cyls != 0) {
5098 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5099 bdrv_set_translation_hint(bdrv, translation);
5101 break;
5102 case MEDIA_CDROM:
5103 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5104 break;
5106 break;
5107 case IF_SD:
5108 /* FIXME: This isn't really a floppy, but it's a reasonable
5109 approximation. */
5110 case IF_FLOPPY:
5111 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5112 break;
5113 case IF_PFLASH:
5114 case IF_MTD:
5115 break;
5117 if (!file[0])
5118 return 0;
5119 if (bdrv_open(bdrv, file, snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
5120 qemu_key_check(bdrv, file)) {
5121 fprintf(stderr, "qemu: could not open disk image %s\n",
5122 file);
5123 return -1;
5125 return 0;
5128 /***********************************************************/
5129 /* USB devices */
5131 static USBPort *used_usb_ports;
5132 static USBPort *free_usb_ports;
5134 /* ??? Maybe change this to register a hub to keep track of the topology. */
5135 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5136 usb_attachfn attach)
5138 port->opaque = opaque;
5139 port->index = index;
5140 port->attach = attach;
5141 port->next = free_usb_ports;
5142 free_usb_ports = port;
5145 static int usb_device_add(const char *devname)
5147 const char *p;
5148 USBDevice *dev;
5149 USBPort *port;
5151 if (!free_usb_ports)
5152 return -1;
5154 if (strstart(devname, "host:", &p)) {
5155 dev = usb_host_device_open(p);
5156 } else if (!strcmp(devname, "mouse")) {
5157 dev = usb_mouse_init();
5158 } else if (!strcmp(devname, "tablet")) {
5159 dev = usb_tablet_init();
5160 } else if (!strcmp(devname, "keyboard")) {
5161 dev = usb_keyboard_init();
5162 } else if (strstart(devname, "disk:", &p)) {
5163 dev = usb_msd_init(p);
5164 } else if (!strcmp(devname, "wacom-tablet")) {
5165 dev = usb_wacom_init();
5166 } else {
5167 return -1;
5169 if (!dev)
5170 return -1;
5172 /* Find a USB port to add the device to. */
5173 port = free_usb_ports;
5174 if (!port->next) {
5175 USBDevice *hub;
5177 /* Create a new hub and chain it on. */
5178 free_usb_ports = NULL;
5179 port->next = used_usb_ports;
5180 used_usb_ports = port;
5182 hub = usb_hub_init(VM_USB_HUB_SIZE);
5183 usb_attach(port, hub);
5184 port = free_usb_ports;
5187 free_usb_ports = port->next;
5188 port->next = used_usb_ports;
5189 used_usb_ports = port;
5190 usb_attach(port, dev);
5191 return 0;
5194 static int usb_device_del(const char *devname)
5196 USBPort *port;
5197 USBPort **lastp;
5198 USBDevice *dev;
5199 int bus_num, addr;
5200 const char *p;
5202 if (!used_usb_ports)
5203 return -1;
5205 p = strchr(devname, '.');
5206 if (!p)
5207 return -1;
5208 bus_num = strtoul(devname, NULL, 0);
5209 addr = strtoul(p + 1, NULL, 0);
5210 if (bus_num != 0)
5211 return -1;
5213 lastp = &used_usb_ports;
5214 port = used_usb_ports;
5215 while (port && port->dev->addr != addr) {
5216 lastp = &port->next;
5217 port = port->next;
5220 if (!port)
5221 return -1;
5223 dev = port->dev;
5224 *lastp = port->next;
5225 usb_attach(port, NULL);
5226 dev->handle_destroy(dev);
5227 port->next = free_usb_ports;
5228 free_usb_ports = port;
5229 return 0;
5232 void do_usb_add(const char *devname)
5234 int ret;
5235 ret = usb_device_add(devname);
5236 if (ret < 0)
5237 term_printf("Could not add USB device '%s'\n", devname);
5240 void do_usb_del(const char *devname)
5242 int ret;
5243 ret = usb_device_del(devname);
5244 if (ret < 0)
5245 term_printf("Could not remove USB device '%s'\n", devname);
5248 void usb_info(void)
5250 USBDevice *dev;
5251 USBPort *port;
5252 const char *speed_str;
5254 if (!usb_enabled) {
5255 term_printf("USB support not enabled\n");
5256 return;
5259 for (port = used_usb_ports; port; port = port->next) {
5260 dev = port->dev;
5261 if (!dev)
5262 continue;
5263 switch(dev->speed) {
5264 case USB_SPEED_LOW:
5265 speed_str = "1.5";
5266 break;
5267 case USB_SPEED_FULL:
5268 speed_str = "12";
5269 break;
5270 case USB_SPEED_HIGH:
5271 speed_str = "480";
5272 break;
5273 default:
5274 speed_str = "?";
5275 break;
5277 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5278 0, dev->addr, speed_str, dev->devname);
5282 /***********************************************************/
5283 /* PCMCIA/Cardbus */
5285 static struct pcmcia_socket_entry_s {
5286 struct pcmcia_socket_s *socket;
5287 struct pcmcia_socket_entry_s *next;
5288 } *pcmcia_sockets = 0;
5290 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5292 struct pcmcia_socket_entry_s *entry;
5294 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5295 entry->socket = socket;
5296 entry->next = pcmcia_sockets;
5297 pcmcia_sockets = entry;
5300 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5302 struct pcmcia_socket_entry_s *entry, **ptr;
5304 ptr = &pcmcia_sockets;
5305 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5306 if (entry->socket == socket) {
5307 *ptr = entry->next;
5308 qemu_free(entry);
5312 void pcmcia_info(void)
5314 struct pcmcia_socket_entry_s *iter;
5315 if (!pcmcia_sockets)
5316 term_printf("No PCMCIA sockets\n");
5318 for (iter = pcmcia_sockets; iter; iter = iter->next)
5319 term_printf("%s: %s\n", iter->socket->slot_string,
5320 iter->socket->attached ? iter->socket->card_string :
5321 "Empty");
5324 /***********************************************************/
5325 /* dumb display */
5327 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5331 static void dumb_resize(DisplayState *ds, int w, int h)
5335 static void dumb_refresh(DisplayState *ds)
5337 #if defined(CONFIG_SDL)
5338 vga_hw_update();
5339 #endif
5342 static void dumb_display_init(DisplayState *ds)
5344 ds->data = NULL;
5345 ds->linesize = 0;
5346 ds->depth = 0;
5347 ds->dpy_update = dumb_update;
5348 ds->dpy_resize = dumb_resize;
5349 ds->dpy_refresh = dumb_refresh;
5352 /***********************************************************/
5353 /* I/O handling */
5355 #define MAX_IO_HANDLERS 64
5357 typedef struct IOHandlerRecord {
5358 int fd;
5359 IOCanRWHandler *fd_read_poll;
5360 IOHandler *fd_read;
5361 IOHandler *fd_write;
5362 int deleted;
5363 void *opaque;
5364 /* temporary data */
5365 struct pollfd *ufd;
5366 struct IOHandlerRecord *next;
5367 } IOHandlerRecord;
5369 static IOHandlerRecord *first_io_handler;
5371 /* XXX: fd_read_poll should be suppressed, but an API change is
5372 necessary in the character devices to suppress fd_can_read(). */
5373 int qemu_set_fd_handler2(int fd,
5374 IOCanRWHandler *fd_read_poll,
5375 IOHandler *fd_read,
5376 IOHandler *fd_write,
5377 void *opaque)
5379 IOHandlerRecord **pioh, *ioh;
5381 if (!fd_read && !fd_write) {
5382 pioh = &first_io_handler;
5383 for(;;) {
5384 ioh = *pioh;
5385 if (ioh == NULL)
5386 break;
5387 if (ioh->fd == fd) {
5388 ioh->deleted = 1;
5389 break;
5391 pioh = &ioh->next;
5393 } else {
5394 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5395 if (ioh->fd == fd)
5396 goto found;
5398 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5399 if (!ioh)
5400 return -1;
5401 ioh->next = first_io_handler;
5402 first_io_handler = ioh;
5403 found:
5404 ioh->fd = fd;
5405 ioh->fd_read_poll = fd_read_poll;
5406 ioh->fd_read = fd_read;
5407 ioh->fd_write = fd_write;
5408 ioh->opaque = opaque;
5409 ioh->deleted = 0;
5411 return 0;
5414 int qemu_set_fd_handler(int fd,
5415 IOHandler *fd_read,
5416 IOHandler *fd_write,
5417 void *opaque)
5419 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5422 /***********************************************************/
5423 /* Polling handling */
5425 typedef struct PollingEntry {
5426 PollingFunc *func;
5427 void *opaque;
5428 struct PollingEntry *next;
5429 } PollingEntry;
5431 static PollingEntry *first_polling_entry;
5433 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5435 PollingEntry **ppe, *pe;
5436 pe = qemu_mallocz(sizeof(PollingEntry));
5437 if (!pe)
5438 return -1;
5439 pe->func = func;
5440 pe->opaque = opaque;
5441 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5442 *ppe = pe;
5443 return 0;
5446 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5448 PollingEntry **ppe, *pe;
5449 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5450 pe = *ppe;
5451 if (pe->func == func && pe->opaque == opaque) {
5452 *ppe = pe->next;
5453 qemu_free(pe);
5454 break;
5459 #ifdef _WIN32
5460 /***********************************************************/
5461 /* Wait objects support */
5462 typedef struct WaitObjects {
5463 int num;
5464 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5465 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5466 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5467 } WaitObjects;
5469 static WaitObjects wait_objects = {0};
5471 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5473 WaitObjects *w = &wait_objects;
5475 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5476 return -1;
5477 w->events[w->num] = handle;
5478 w->func[w->num] = func;
5479 w->opaque[w->num] = opaque;
5480 w->num++;
5481 return 0;
5484 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5486 int i, found;
5487 WaitObjects *w = &wait_objects;
5489 found = 0;
5490 for (i = 0; i < w->num; i++) {
5491 if (w->events[i] == handle)
5492 found = 1;
5493 if (found) {
5494 w->events[i] = w->events[i + 1];
5495 w->func[i] = w->func[i + 1];
5496 w->opaque[i] = w->opaque[i + 1];
5499 if (found)
5500 w->num--;
5502 #endif
5504 /***********************************************************/
5505 /* savevm/loadvm support */
5507 #define IO_BUF_SIZE 32768
5509 struct QEMUFile {
5510 FILE *outfile;
5511 BlockDriverState *bs;
5512 int is_file;
5513 int is_writable;
5514 int64_t base_offset;
5515 int64_t buf_offset; /* start of buffer when writing, end of buffer
5516 when reading */
5517 int buf_index;
5518 int buf_size; /* 0 when writing */
5519 uint8_t buf[IO_BUF_SIZE];
5522 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5524 QEMUFile *f;
5526 f = qemu_mallocz(sizeof(QEMUFile));
5527 if (!f)
5528 return NULL;
5529 if (!strcmp(mode, "wb")) {
5530 f->is_writable = 1;
5531 } else if (!strcmp(mode, "rb")) {
5532 f->is_writable = 0;
5533 } else {
5534 goto fail;
5536 f->outfile = fopen(filename, mode);
5537 if (!f->outfile)
5538 goto fail;
5539 f->is_file = 1;
5540 return f;
5541 fail:
5542 if (f->outfile)
5543 fclose(f->outfile);
5544 qemu_free(f);
5545 return NULL;
5548 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5550 QEMUFile *f;
5552 f = qemu_mallocz(sizeof(QEMUFile));
5553 if (!f)
5554 return NULL;
5555 f->is_file = 0;
5556 f->bs = bs;
5557 f->is_writable = is_writable;
5558 f->base_offset = offset;
5559 return f;
5562 void qemu_fflush(QEMUFile *f)
5564 if (!f->is_writable)
5565 return;
5566 if (f->buf_index > 0) {
5567 if (f->is_file) {
5568 fseek(f->outfile, f->buf_offset, SEEK_SET);
5569 fwrite(f->buf, 1, f->buf_index, f->outfile);
5570 } else {
5571 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5572 f->buf, f->buf_index);
5574 f->buf_offset += f->buf_index;
5575 f->buf_index = 0;
5579 static void qemu_fill_buffer(QEMUFile *f)
5581 int len;
5583 if (f->is_writable)
5584 return;
5585 if (f->is_file) {
5586 fseek(f->outfile, f->buf_offset, SEEK_SET);
5587 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5588 if (len < 0)
5589 len = 0;
5590 } else {
5591 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5592 f->buf, IO_BUF_SIZE);
5593 if (len < 0)
5594 len = 0;
5596 f->buf_index = 0;
5597 f->buf_size = len;
5598 f->buf_offset += len;
5601 void qemu_fclose(QEMUFile *f)
5603 if (f->is_writable)
5604 qemu_fflush(f);
5605 if (f->is_file) {
5606 fclose(f->outfile);
5608 qemu_free(f);
5611 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5613 int l;
5614 while (size > 0) {
5615 l = IO_BUF_SIZE - f->buf_index;
5616 if (l > size)
5617 l = size;
5618 memcpy(f->buf + f->buf_index, buf, l);
5619 f->buf_index += l;
5620 buf += l;
5621 size -= l;
5622 if (f->buf_index >= IO_BUF_SIZE)
5623 qemu_fflush(f);
5627 void qemu_put_byte(QEMUFile *f, int v)
5629 f->buf[f->buf_index++] = v;
5630 if (f->buf_index >= IO_BUF_SIZE)
5631 qemu_fflush(f);
5634 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5636 int size, l;
5638 size = size1;
5639 while (size > 0) {
5640 l = f->buf_size - f->buf_index;
5641 if (l == 0) {
5642 qemu_fill_buffer(f);
5643 l = f->buf_size - f->buf_index;
5644 if (l == 0)
5645 break;
5647 if (l > size)
5648 l = size;
5649 memcpy(buf, f->buf + f->buf_index, l);
5650 f->buf_index += l;
5651 buf += l;
5652 size -= l;
5654 return size1 - size;
5657 int qemu_get_byte(QEMUFile *f)
5659 if (f->buf_index >= f->buf_size) {
5660 qemu_fill_buffer(f);
5661 if (f->buf_index >= f->buf_size)
5662 return 0;
5664 return f->buf[f->buf_index++];
5667 int64_t qemu_ftell(QEMUFile *f)
5669 return f->buf_offset - f->buf_size + f->buf_index;
5672 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5674 if (whence == SEEK_SET) {
5675 /* nothing to do */
5676 } else if (whence == SEEK_CUR) {
5677 pos += qemu_ftell(f);
5678 } else {
5679 /* SEEK_END not supported */
5680 return -1;
5682 if (f->is_writable) {
5683 qemu_fflush(f);
5684 f->buf_offset = pos;
5685 } else {
5686 f->buf_offset = pos;
5687 f->buf_index = 0;
5688 f->buf_size = 0;
5690 return pos;
5693 void qemu_put_be16(QEMUFile *f, unsigned int v)
5695 qemu_put_byte(f, v >> 8);
5696 qemu_put_byte(f, v);
5699 void qemu_put_be32(QEMUFile *f, unsigned int v)
5701 qemu_put_byte(f, v >> 24);
5702 qemu_put_byte(f, v >> 16);
5703 qemu_put_byte(f, v >> 8);
5704 qemu_put_byte(f, v);
5707 void qemu_put_be64(QEMUFile *f, uint64_t v)
5709 qemu_put_be32(f, v >> 32);
5710 qemu_put_be32(f, v);
5713 unsigned int qemu_get_be16(QEMUFile *f)
5715 unsigned int v;
5716 v = qemu_get_byte(f) << 8;
5717 v |= qemu_get_byte(f);
5718 return v;
5721 unsigned int qemu_get_be32(QEMUFile *f)
5723 unsigned int v;
5724 v = qemu_get_byte(f) << 24;
5725 v |= qemu_get_byte(f) << 16;
5726 v |= qemu_get_byte(f) << 8;
5727 v |= qemu_get_byte(f);
5728 return v;
5731 uint64_t qemu_get_be64(QEMUFile *f)
5733 uint64_t v;
5734 v = (uint64_t)qemu_get_be32(f) << 32;
5735 v |= qemu_get_be32(f);
5736 return v;
5739 typedef struct SaveStateEntry {
5740 char idstr[256];
5741 int instance_id;
5742 int version_id;
5743 SaveStateHandler *save_state;
5744 LoadStateHandler *load_state;
5745 void *opaque;
5746 struct SaveStateEntry *next;
5747 } SaveStateEntry;
5749 static SaveStateEntry *first_se;
5751 int register_savevm(const char *idstr,
5752 int instance_id,
5753 int version_id,
5754 SaveStateHandler *save_state,
5755 LoadStateHandler *load_state,
5756 void *opaque)
5758 SaveStateEntry *se, **pse;
5760 se = qemu_malloc(sizeof(SaveStateEntry));
5761 if (!se)
5762 return -1;
5763 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5764 se->instance_id = instance_id;
5765 se->version_id = version_id;
5766 se->save_state = save_state;
5767 se->load_state = load_state;
5768 se->opaque = opaque;
5769 se->next = NULL;
5771 /* add at the end of list */
5772 pse = &first_se;
5773 while (*pse != NULL)
5774 pse = &(*pse)->next;
5775 *pse = se;
5776 return 0;
5779 #define QEMU_VM_FILE_MAGIC 0x5145564d
5780 #define QEMU_VM_FILE_VERSION 0x00000002
5782 static int qemu_savevm_state(QEMUFile *f)
5784 SaveStateEntry *se;
5785 int len, ret;
5786 int64_t cur_pos, len_pos, total_len_pos;
5788 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5789 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5790 total_len_pos = qemu_ftell(f);
5791 qemu_put_be64(f, 0); /* total size */
5793 for(se = first_se; se != NULL; se = se->next) {
5794 /* ID string */
5795 len = strlen(se->idstr);
5796 qemu_put_byte(f, len);
5797 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5799 qemu_put_be32(f, se->instance_id);
5800 qemu_put_be32(f, se->version_id);
5802 /* record size: filled later */
5803 len_pos = qemu_ftell(f);
5804 qemu_put_be32(f, 0);
5805 se->save_state(f, se->opaque);
5807 /* fill record size */
5808 cur_pos = qemu_ftell(f);
5809 len = cur_pos - len_pos - 4;
5810 qemu_fseek(f, len_pos, SEEK_SET);
5811 qemu_put_be32(f, len);
5812 qemu_fseek(f, cur_pos, SEEK_SET);
5814 cur_pos = qemu_ftell(f);
5815 qemu_fseek(f, total_len_pos, SEEK_SET);
5816 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5817 qemu_fseek(f, cur_pos, SEEK_SET);
5819 ret = 0;
5820 return ret;
5823 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5825 SaveStateEntry *se;
5827 for(se = first_se; se != NULL; se = se->next) {
5828 if (!strcmp(se->idstr, idstr) &&
5829 instance_id == se->instance_id)
5830 return se;
5832 return NULL;
5835 static int qemu_loadvm_state(QEMUFile *f)
5837 SaveStateEntry *se;
5838 int len, ret, instance_id, record_len, version_id;
5839 int64_t total_len, end_pos, cur_pos;
5840 unsigned int v;
5841 char idstr[256];
5843 v = qemu_get_be32(f);
5844 if (v != QEMU_VM_FILE_MAGIC)
5845 goto fail;
5846 v = qemu_get_be32(f);
5847 if (v != QEMU_VM_FILE_VERSION) {
5848 fail:
5849 ret = -1;
5850 goto the_end;
5852 total_len = qemu_get_be64(f);
5853 end_pos = total_len + qemu_ftell(f);
5854 for(;;) {
5855 if (qemu_ftell(f) >= end_pos)
5856 break;
5857 len = qemu_get_byte(f);
5858 qemu_get_buffer(f, (uint8_t *)idstr, len);
5859 idstr[len] = '\0';
5860 instance_id = qemu_get_be32(f);
5861 version_id = qemu_get_be32(f);
5862 record_len = qemu_get_be32(f);
5863 #if 0
5864 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5865 idstr, instance_id, version_id, record_len);
5866 #endif
5867 cur_pos = qemu_ftell(f);
5868 se = find_se(idstr, instance_id);
5869 if (!se) {
5870 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5871 instance_id, idstr);
5872 } else {
5873 ret = se->load_state(f, se->opaque, version_id);
5874 if (ret < 0) {
5875 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5876 instance_id, idstr);
5879 /* always seek to exact end of record */
5880 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5882 ret = 0;
5883 the_end:
5884 return ret;
5887 /* device can contain snapshots */
5888 static int bdrv_can_snapshot(BlockDriverState *bs)
5890 return (bs &&
5891 !bdrv_is_removable(bs) &&
5892 !bdrv_is_read_only(bs));
5895 /* device must be snapshots in order to have a reliable snapshot */
5896 static int bdrv_has_snapshot(BlockDriverState *bs)
5898 return (bs &&
5899 !bdrv_is_removable(bs) &&
5900 !bdrv_is_read_only(bs));
5903 static BlockDriverState *get_bs_snapshots(void)
5905 BlockDriverState *bs;
5906 int i;
5908 if (bs_snapshots)
5909 return bs_snapshots;
5910 for(i = 0; i <= nb_drives; i++) {
5911 bs = drives_table[i].bdrv;
5912 if (bdrv_can_snapshot(bs))
5913 goto ok;
5915 return NULL;
5917 bs_snapshots = bs;
5918 return bs;
5921 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5922 const char *name)
5924 QEMUSnapshotInfo *sn_tab, *sn;
5925 int nb_sns, i, ret;
5927 ret = -ENOENT;
5928 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5929 if (nb_sns < 0)
5930 return ret;
5931 for(i = 0; i < nb_sns; i++) {
5932 sn = &sn_tab[i];
5933 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5934 *sn_info = *sn;
5935 ret = 0;
5936 break;
5939 qemu_free(sn_tab);
5940 return ret;
5943 void do_savevm(const char *name)
5945 BlockDriverState *bs, *bs1;
5946 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5947 int must_delete, ret, i;
5948 BlockDriverInfo bdi1, *bdi = &bdi1;
5949 QEMUFile *f;
5950 int saved_vm_running;
5951 #ifdef _WIN32
5952 struct _timeb tb;
5953 #else
5954 struct timeval tv;
5955 #endif
5957 bs = get_bs_snapshots();
5958 if (!bs) {
5959 term_printf("No block device can accept snapshots\n");
5960 return;
5963 /* ??? Should this occur after vm_stop? */
5964 qemu_aio_flush();
5966 saved_vm_running = vm_running;
5967 vm_stop(0);
5969 must_delete = 0;
5970 if (name) {
5971 ret = bdrv_snapshot_find(bs, old_sn, name);
5972 if (ret >= 0) {
5973 must_delete = 1;
5976 memset(sn, 0, sizeof(*sn));
5977 if (must_delete) {
5978 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5979 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5980 } else {
5981 if (name)
5982 pstrcpy(sn->name, sizeof(sn->name), name);
5985 /* fill auxiliary fields */
5986 #ifdef _WIN32
5987 _ftime(&tb);
5988 sn->date_sec = tb.time;
5989 sn->date_nsec = tb.millitm * 1000000;
5990 #else
5991 gettimeofday(&tv, NULL);
5992 sn->date_sec = tv.tv_sec;
5993 sn->date_nsec = tv.tv_usec * 1000;
5994 #endif
5995 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5997 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5998 term_printf("Device %s does not support VM state snapshots\n",
5999 bdrv_get_device_name(bs));
6000 goto the_end;
6003 /* save the VM state */
6004 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6005 if (!f) {
6006 term_printf("Could not open VM state file\n");
6007 goto the_end;
6009 ret = qemu_savevm_state(f);
6010 sn->vm_state_size = qemu_ftell(f);
6011 qemu_fclose(f);
6012 if (ret < 0) {
6013 term_printf("Error %d while writing VM\n", ret);
6014 goto the_end;
6017 /* create the snapshots */
6019 for(i = 0; i < nb_drives; i++) {
6020 bs1 = drives_table[i].bdrv;
6021 if (bdrv_has_snapshot(bs1)) {
6022 if (must_delete) {
6023 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6024 if (ret < 0) {
6025 term_printf("Error while deleting snapshot on '%s'\n",
6026 bdrv_get_device_name(bs1));
6029 ret = bdrv_snapshot_create(bs1, sn);
6030 if (ret < 0) {
6031 term_printf("Error while creating snapshot on '%s'\n",
6032 bdrv_get_device_name(bs1));
6037 the_end:
6038 if (saved_vm_running)
6039 vm_start();
6042 void do_loadvm(const char *name)
6044 BlockDriverState *bs, *bs1;
6045 BlockDriverInfo bdi1, *bdi = &bdi1;
6046 QEMUFile *f;
6047 int i, ret;
6048 int saved_vm_running;
6050 bs = get_bs_snapshots();
6051 if (!bs) {
6052 term_printf("No block device supports snapshots\n");
6053 return;
6056 /* Flush all IO requests so they don't interfere with the new state. */
6057 qemu_aio_flush();
6059 saved_vm_running = vm_running;
6060 vm_stop(0);
6062 for(i = 0; i <= nb_drives; i++) {
6063 bs1 = drives_table[i].bdrv;
6064 if (bdrv_has_snapshot(bs1)) {
6065 ret = bdrv_snapshot_goto(bs1, name);
6066 if (ret < 0) {
6067 if (bs != bs1)
6068 term_printf("Warning: ");
6069 switch(ret) {
6070 case -ENOTSUP:
6071 term_printf("Snapshots not supported on device '%s'\n",
6072 bdrv_get_device_name(bs1));
6073 break;
6074 case -ENOENT:
6075 term_printf("Could not find snapshot '%s' on device '%s'\n",
6076 name, bdrv_get_device_name(bs1));
6077 break;
6078 default:
6079 term_printf("Error %d while activating snapshot on '%s'\n",
6080 ret, bdrv_get_device_name(bs1));
6081 break;
6083 /* fatal on snapshot block device */
6084 if (bs == bs1)
6085 goto the_end;
6090 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6091 term_printf("Device %s does not support VM state snapshots\n",
6092 bdrv_get_device_name(bs));
6093 return;
6096 /* restore the VM state */
6097 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6098 if (!f) {
6099 term_printf("Could not open VM state file\n");
6100 goto the_end;
6102 ret = qemu_loadvm_state(f);
6103 qemu_fclose(f);
6104 if (ret < 0) {
6105 term_printf("Error %d while loading VM state\n", ret);
6107 the_end:
6108 if (saved_vm_running)
6109 vm_start();
6112 void do_delvm(const char *name)
6114 BlockDriverState *bs, *bs1;
6115 int i, ret;
6117 bs = get_bs_snapshots();
6118 if (!bs) {
6119 term_printf("No block device supports snapshots\n");
6120 return;
6123 for(i = 0; i <= nb_drives; i++) {
6124 bs1 = drives_table[i].bdrv;
6125 if (bdrv_has_snapshot(bs1)) {
6126 ret = bdrv_snapshot_delete(bs1, name);
6127 if (ret < 0) {
6128 if (ret == -ENOTSUP)
6129 term_printf("Snapshots not supported on device '%s'\n",
6130 bdrv_get_device_name(bs1));
6131 else
6132 term_printf("Error %d while deleting snapshot on '%s'\n",
6133 ret, bdrv_get_device_name(bs1));
6139 void do_info_snapshots(void)
6141 BlockDriverState *bs, *bs1;
6142 QEMUSnapshotInfo *sn_tab, *sn;
6143 int nb_sns, i;
6144 char buf[256];
6146 bs = get_bs_snapshots();
6147 if (!bs) {
6148 term_printf("No available block device supports snapshots\n");
6149 return;
6151 term_printf("Snapshot devices:");
6152 for(i = 0; i <= nb_drives; i++) {
6153 bs1 = drives_table[i].bdrv;
6154 if (bdrv_has_snapshot(bs1)) {
6155 if (bs == bs1)
6156 term_printf(" %s", bdrv_get_device_name(bs1));
6159 term_printf("\n");
6161 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6162 if (nb_sns < 0) {
6163 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6164 return;
6166 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6167 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6168 for(i = 0; i < nb_sns; i++) {
6169 sn = &sn_tab[i];
6170 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6172 qemu_free(sn_tab);
6175 /***********************************************************/
6176 /* cpu save/restore */
6178 #if defined(TARGET_I386)
6180 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6182 qemu_put_be32(f, dt->selector);
6183 qemu_put_betl(f, dt->base);
6184 qemu_put_be32(f, dt->limit);
6185 qemu_put_be32(f, dt->flags);
6188 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6190 dt->selector = qemu_get_be32(f);
6191 dt->base = qemu_get_betl(f);
6192 dt->limit = qemu_get_be32(f);
6193 dt->flags = qemu_get_be32(f);
6196 void cpu_save(QEMUFile *f, void *opaque)
6198 CPUState *env = opaque;
6199 uint16_t fptag, fpus, fpuc, fpregs_format;
6200 uint32_t hflags;
6201 int i;
6203 for(i = 0; i < CPU_NB_REGS; i++)
6204 qemu_put_betls(f, &env->regs[i]);
6205 qemu_put_betls(f, &env->eip);
6206 qemu_put_betls(f, &env->eflags);
6207 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6208 qemu_put_be32s(f, &hflags);
6210 /* FPU */
6211 fpuc = env->fpuc;
6212 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6213 fptag = 0;
6214 for(i = 0; i < 8; i++) {
6215 fptag |= ((!env->fptags[i]) << i);
6218 qemu_put_be16s(f, &fpuc);
6219 qemu_put_be16s(f, &fpus);
6220 qemu_put_be16s(f, &fptag);
6222 #ifdef USE_X86LDOUBLE
6223 fpregs_format = 0;
6224 #else
6225 fpregs_format = 1;
6226 #endif
6227 qemu_put_be16s(f, &fpregs_format);
6229 for(i = 0; i < 8; i++) {
6230 #ifdef USE_X86LDOUBLE
6232 uint64_t mant;
6233 uint16_t exp;
6234 /* we save the real CPU data (in case of MMX usage only 'mant'
6235 contains the MMX register */
6236 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6237 qemu_put_be64(f, mant);
6238 qemu_put_be16(f, exp);
6240 #else
6241 /* if we use doubles for float emulation, we save the doubles to
6242 avoid losing information in case of MMX usage. It can give
6243 problems if the image is restored on a CPU where long
6244 doubles are used instead. */
6245 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6246 #endif
6249 for(i = 0; i < 6; i++)
6250 cpu_put_seg(f, &env->segs[i]);
6251 cpu_put_seg(f, &env->ldt);
6252 cpu_put_seg(f, &env->tr);
6253 cpu_put_seg(f, &env->gdt);
6254 cpu_put_seg(f, &env->idt);
6256 qemu_put_be32s(f, &env->sysenter_cs);
6257 qemu_put_be32s(f, &env->sysenter_esp);
6258 qemu_put_be32s(f, &env->sysenter_eip);
6260 qemu_put_betls(f, &env->cr[0]);
6261 qemu_put_betls(f, &env->cr[2]);
6262 qemu_put_betls(f, &env->cr[3]);
6263 qemu_put_betls(f, &env->cr[4]);
6265 for(i = 0; i < 8; i++)
6266 qemu_put_betls(f, &env->dr[i]);
6268 /* MMU */
6269 qemu_put_be32s(f, &env->a20_mask);
6271 /* XMM */
6272 qemu_put_be32s(f, &env->mxcsr);
6273 for(i = 0; i < CPU_NB_REGS; i++) {
6274 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6275 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6278 #ifdef TARGET_X86_64
6279 qemu_put_be64s(f, &env->efer);
6280 qemu_put_be64s(f, &env->star);
6281 qemu_put_be64s(f, &env->lstar);
6282 qemu_put_be64s(f, &env->cstar);
6283 qemu_put_be64s(f, &env->fmask);
6284 qemu_put_be64s(f, &env->kernelgsbase);
6285 #endif
6286 qemu_put_be32s(f, &env->smbase);
6289 #ifdef USE_X86LDOUBLE
6290 /* XXX: add that in a FPU generic layer */
6291 union x86_longdouble {
6292 uint64_t mant;
6293 uint16_t exp;
6296 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6297 #define EXPBIAS1 1023
6298 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6299 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6301 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6303 int e;
6304 /* mantissa */
6305 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6306 /* exponent + sign */
6307 e = EXPD1(temp) - EXPBIAS1 + 16383;
6308 e |= SIGND1(temp) >> 16;
6309 p->exp = e;
6311 #endif
6313 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6315 CPUState *env = opaque;
6316 int i, guess_mmx;
6317 uint32_t hflags;
6318 uint16_t fpus, fpuc, fptag, fpregs_format;
6320 if (version_id != 3 && version_id != 4)
6321 return -EINVAL;
6322 for(i = 0; i < CPU_NB_REGS; i++)
6323 qemu_get_betls(f, &env->regs[i]);
6324 qemu_get_betls(f, &env->eip);
6325 qemu_get_betls(f, &env->eflags);
6326 qemu_get_be32s(f, &hflags);
6328 qemu_get_be16s(f, &fpuc);
6329 qemu_get_be16s(f, &fpus);
6330 qemu_get_be16s(f, &fptag);
6331 qemu_get_be16s(f, &fpregs_format);
6333 /* NOTE: we cannot always restore the FPU state if the image come
6334 from a host with a different 'USE_X86LDOUBLE' define. We guess
6335 if we are in an MMX state to restore correctly in that case. */
6336 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6337 for(i = 0; i < 8; i++) {
6338 uint64_t mant;
6339 uint16_t exp;
6341 switch(fpregs_format) {
6342 case 0:
6343 mant = qemu_get_be64(f);
6344 exp = qemu_get_be16(f);
6345 #ifdef USE_X86LDOUBLE
6346 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6347 #else
6348 /* difficult case */
6349 if (guess_mmx)
6350 env->fpregs[i].mmx.MMX_Q(0) = mant;
6351 else
6352 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6353 #endif
6354 break;
6355 case 1:
6356 mant = qemu_get_be64(f);
6357 #ifdef USE_X86LDOUBLE
6359 union x86_longdouble *p;
6360 /* difficult case */
6361 p = (void *)&env->fpregs[i];
6362 if (guess_mmx) {
6363 p->mant = mant;
6364 p->exp = 0xffff;
6365 } else {
6366 fp64_to_fp80(p, mant);
6369 #else
6370 env->fpregs[i].mmx.MMX_Q(0) = mant;
6371 #endif
6372 break;
6373 default:
6374 return -EINVAL;
6378 env->fpuc = fpuc;
6379 /* XXX: restore FPU round state */
6380 env->fpstt = (fpus >> 11) & 7;
6381 env->fpus = fpus & ~0x3800;
6382 fptag ^= 0xff;
6383 for(i = 0; i < 8; i++) {
6384 env->fptags[i] = (fptag >> i) & 1;
6387 for(i = 0; i < 6; i++)
6388 cpu_get_seg(f, &env->segs[i]);
6389 cpu_get_seg(f, &env->ldt);
6390 cpu_get_seg(f, &env->tr);
6391 cpu_get_seg(f, &env->gdt);
6392 cpu_get_seg(f, &env->idt);
6394 qemu_get_be32s(f, &env->sysenter_cs);
6395 qemu_get_be32s(f, &env->sysenter_esp);
6396 qemu_get_be32s(f, &env->sysenter_eip);
6398 qemu_get_betls(f, &env->cr[0]);
6399 qemu_get_betls(f, &env->cr[2]);
6400 qemu_get_betls(f, &env->cr[3]);
6401 qemu_get_betls(f, &env->cr[4]);
6403 for(i = 0; i < 8; i++)
6404 qemu_get_betls(f, &env->dr[i]);
6406 /* MMU */
6407 qemu_get_be32s(f, &env->a20_mask);
6409 qemu_get_be32s(f, &env->mxcsr);
6410 for(i = 0; i < CPU_NB_REGS; i++) {
6411 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6412 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6415 #ifdef TARGET_X86_64
6416 qemu_get_be64s(f, &env->efer);
6417 qemu_get_be64s(f, &env->star);
6418 qemu_get_be64s(f, &env->lstar);
6419 qemu_get_be64s(f, &env->cstar);
6420 qemu_get_be64s(f, &env->fmask);
6421 qemu_get_be64s(f, &env->kernelgsbase);
6422 #endif
6423 if (version_id >= 4)
6424 qemu_get_be32s(f, &env->smbase);
6426 /* XXX: compute hflags from scratch, except for CPL and IIF */
6427 env->hflags = hflags;
6428 tlb_flush(env, 1);
6429 return 0;
6432 #elif defined(TARGET_PPC)
6433 void cpu_save(QEMUFile *f, void *opaque)
6437 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6439 return 0;
6442 #elif defined(TARGET_MIPS)
6443 void cpu_save(QEMUFile *f, void *opaque)
6447 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6449 return 0;
6452 #elif defined(TARGET_SPARC)
6453 void cpu_save(QEMUFile *f, void *opaque)
6455 CPUState *env = opaque;
6456 int i;
6457 uint32_t tmp;
6459 for(i = 0; i < 8; i++)
6460 qemu_put_betls(f, &env->gregs[i]);
6461 for(i = 0; i < NWINDOWS * 16; i++)
6462 qemu_put_betls(f, &env->regbase[i]);
6464 /* FPU */
6465 for(i = 0; i < TARGET_FPREGS; i++) {
6466 union {
6467 float32 f;
6468 uint32_t i;
6469 } u;
6470 u.f = env->fpr[i];
6471 qemu_put_be32(f, u.i);
6474 qemu_put_betls(f, &env->pc);
6475 qemu_put_betls(f, &env->npc);
6476 qemu_put_betls(f, &env->y);
6477 tmp = GET_PSR(env);
6478 qemu_put_be32(f, tmp);
6479 qemu_put_betls(f, &env->fsr);
6480 qemu_put_betls(f, &env->tbr);
6481 #ifndef TARGET_SPARC64
6482 qemu_put_be32s(f, &env->wim);
6483 /* MMU */
6484 for(i = 0; i < 16; i++)
6485 qemu_put_be32s(f, &env->mmuregs[i]);
6486 #endif
6489 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6491 CPUState *env = opaque;
6492 int i;
6493 uint32_t tmp;
6495 for(i = 0; i < 8; i++)
6496 qemu_get_betls(f, &env->gregs[i]);
6497 for(i = 0; i < NWINDOWS * 16; i++)
6498 qemu_get_betls(f, &env->regbase[i]);
6500 /* FPU */
6501 for(i = 0; i < TARGET_FPREGS; i++) {
6502 union {
6503 float32 f;
6504 uint32_t i;
6505 } u;
6506 u.i = qemu_get_be32(f);
6507 env->fpr[i] = u.f;
6510 qemu_get_betls(f, &env->pc);
6511 qemu_get_betls(f, &env->npc);
6512 qemu_get_betls(f, &env->y);
6513 tmp = qemu_get_be32(f);
6514 env->cwp = 0; /* needed to ensure that the wrapping registers are
6515 correctly updated */
6516 PUT_PSR(env, tmp);
6517 qemu_get_betls(f, &env->fsr);
6518 qemu_get_betls(f, &env->tbr);
6519 #ifndef TARGET_SPARC64
6520 qemu_get_be32s(f, &env->wim);
6521 /* MMU */
6522 for(i = 0; i < 16; i++)
6523 qemu_get_be32s(f, &env->mmuregs[i]);
6524 #endif
6525 tlb_flush(env, 1);
6526 return 0;
6529 #elif defined(TARGET_ARM)
6531 void cpu_save(QEMUFile *f, void *opaque)
6533 int i;
6534 CPUARMState *env = (CPUARMState *)opaque;
6536 for (i = 0; i < 16; i++) {
6537 qemu_put_be32(f, env->regs[i]);
6539 qemu_put_be32(f, cpsr_read(env));
6540 qemu_put_be32(f, env->spsr);
6541 for (i = 0; i < 6; i++) {
6542 qemu_put_be32(f, env->banked_spsr[i]);
6543 qemu_put_be32(f, env->banked_r13[i]);
6544 qemu_put_be32(f, env->banked_r14[i]);
6546 for (i = 0; i < 5; i++) {
6547 qemu_put_be32(f, env->usr_regs[i]);
6548 qemu_put_be32(f, env->fiq_regs[i]);
6550 qemu_put_be32(f, env->cp15.c0_cpuid);
6551 qemu_put_be32(f, env->cp15.c0_cachetype);
6552 qemu_put_be32(f, env->cp15.c1_sys);
6553 qemu_put_be32(f, env->cp15.c1_coproc);
6554 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6555 qemu_put_be32(f, env->cp15.c2_base0);
6556 qemu_put_be32(f, env->cp15.c2_base1);
6557 qemu_put_be32(f, env->cp15.c2_mask);
6558 qemu_put_be32(f, env->cp15.c2_data);
6559 qemu_put_be32(f, env->cp15.c2_insn);
6560 qemu_put_be32(f, env->cp15.c3);
6561 qemu_put_be32(f, env->cp15.c5_insn);
6562 qemu_put_be32(f, env->cp15.c5_data);
6563 for (i = 0; i < 8; i++) {
6564 qemu_put_be32(f, env->cp15.c6_region[i]);
6566 qemu_put_be32(f, env->cp15.c6_insn);
6567 qemu_put_be32(f, env->cp15.c6_data);
6568 qemu_put_be32(f, env->cp15.c9_insn);
6569 qemu_put_be32(f, env->cp15.c9_data);
6570 qemu_put_be32(f, env->cp15.c13_fcse);
6571 qemu_put_be32(f, env->cp15.c13_context);
6572 qemu_put_be32(f, env->cp15.c13_tls1);
6573 qemu_put_be32(f, env->cp15.c13_tls2);
6574 qemu_put_be32(f, env->cp15.c13_tls3);
6575 qemu_put_be32(f, env->cp15.c15_cpar);
6577 qemu_put_be32(f, env->features);
6579 if (arm_feature(env, ARM_FEATURE_VFP)) {
6580 for (i = 0; i < 16; 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);
6586 for (i = 0; i < 16; i++) {
6587 qemu_put_be32(f, env->vfp.xregs[i]);
6590 /* TODO: Should use proper FPSCR access functions. */
6591 qemu_put_be32(f, env->vfp.vec_len);
6592 qemu_put_be32(f, env->vfp.vec_stride);
6594 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6595 for (i = 16; i < 32; i++) {
6596 CPU_DoubleU u;
6597 u.d = env->vfp.regs[i];
6598 qemu_put_be32(f, u.l.upper);
6599 qemu_put_be32(f, u.l.lower);
6604 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6605 for (i = 0; i < 16; i++) {
6606 qemu_put_be64(f, env->iwmmxt.regs[i]);
6608 for (i = 0; i < 16; i++) {
6609 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6613 if (arm_feature(env, ARM_FEATURE_M)) {
6614 qemu_put_be32(f, env->v7m.other_sp);
6615 qemu_put_be32(f, env->v7m.vecbase);
6616 qemu_put_be32(f, env->v7m.basepri);
6617 qemu_put_be32(f, env->v7m.control);
6618 qemu_put_be32(f, env->v7m.current_sp);
6619 qemu_put_be32(f, env->v7m.exception);
6623 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6625 CPUARMState *env = (CPUARMState *)opaque;
6626 int i;
6628 if (version_id != ARM_CPU_SAVE_VERSION)
6629 return -EINVAL;
6631 for (i = 0; i < 16; i++) {
6632 env->regs[i] = qemu_get_be32(f);
6634 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6635 env->spsr = qemu_get_be32(f);
6636 for (i = 0; i < 6; i++) {
6637 env->banked_spsr[i] = qemu_get_be32(f);
6638 env->banked_r13[i] = qemu_get_be32(f);
6639 env->banked_r14[i] = qemu_get_be32(f);
6641 for (i = 0; i < 5; i++) {
6642 env->usr_regs[i] = qemu_get_be32(f);
6643 env->fiq_regs[i] = qemu_get_be32(f);
6645 env->cp15.c0_cpuid = qemu_get_be32(f);
6646 env->cp15.c0_cachetype = qemu_get_be32(f);
6647 env->cp15.c1_sys = qemu_get_be32(f);
6648 env->cp15.c1_coproc = qemu_get_be32(f);
6649 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6650 env->cp15.c2_base0 = qemu_get_be32(f);
6651 env->cp15.c2_base1 = qemu_get_be32(f);
6652 env->cp15.c2_mask = qemu_get_be32(f);
6653 env->cp15.c2_data = qemu_get_be32(f);
6654 env->cp15.c2_insn = qemu_get_be32(f);
6655 env->cp15.c3 = qemu_get_be32(f);
6656 env->cp15.c5_insn = qemu_get_be32(f);
6657 env->cp15.c5_data = qemu_get_be32(f);
6658 for (i = 0; i < 8; i++) {
6659 env->cp15.c6_region[i] = qemu_get_be32(f);
6661 env->cp15.c6_insn = qemu_get_be32(f);
6662 env->cp15.c6_data = qemu_get_be32(f);
6663 env->cp15.c9_insn = qemu_get_be32(f);
6664 env->cp15.c9_data = qemu_get_be32(f);
6665 env->cp15.c13_fcse = qemu_get_be32(f);
6666 env->cp15.c13_context = qemu_get_be32(f);
6667 env->cp15.c13_tls1 = qemu_get_be32(f);
6668 env->cp15.c13_tls2 = qemu_get_be32(f);
6669 env->cp15.c13_tls3 = qemu_get_be32(f);
6670 env->cp15.c15_cpar = qemu_get_be32(f);
6672 env->features = qemu_get_be32(f);
6674 if (arm_feature(env, ARM_FEATURE_VFP)) {
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;
6681 for (i = 0; i < 16; i++) {
6682 env->vfp.xregs[i] = qemu_get_be32(f);
6685 /* TODO: Should use proper FPSCR access functions. */
6686 env->vfp.vec_len = qemu_get_be32(f);
6687 env->vfp.vec_stride = qemu_get_be32(f);
6689 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6690 for (i = 0; i < 16; i++) {
6691 CPU_DoubleU u;
6692 u.l.upper = qemu_get_be32(f);
6693 u.l.lower = qemu_get_be32(f);
6694 env->vfp.regs[i] = u.d;
6699 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6700 for (i = 0; i < 16; i++) {
6701 env->iwmmxt.regs[i] = qemu_get_be64(f);
6703 for (i = 0; i < 16; i++) {
6704 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6708 if (arm_feature(env, ARM_FEATURE_M)) {
6709 env->v7m.other_sp = qemu_get_be32(f);
6710 env->v7m.vecbase = qemu_get_be32(f);
6711 env->v7m.basepri = qemu_get_be32(f);
6712 env->v7m.control = qemu_get_be32(f);
6713 env->v7m.current_sp = qemu_get_be32(f);
6714 env->v7m.exception = qemu_get_be32(f);
6717 return 0;
6720 #else
6722 //#warning No CPU save/restore functions
6724 #endif
6726 /***********************************************************/
6727 /* ram save/restore */
6729 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6731 int v;
6733 v = qemu_get_byte(f);
6734 switch(v) {
6735 case 0:
6736 if (qemu_get_buffer(f, buf, len) != len)
6737 return -EIO;
6738 break;
6739 case 1:
6740 v = qemu_get_byte(f);
6741 memset(buf, v, len);
6742 break;
6743 default:
6744 return -EINVAL;
6746 return 0;
6749 static int ram_load_v1(QEMUFile *f, void *opaque)
6751 int i, ret;
6753 if (qemu_get_be32(f) != phys_ram_size)
6754 return -EINVAL;
6755 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6756 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6757 if (ret)
6758 return ret;
6760 return 0;
6763 #define BDRV_HASH_BLOCK_SIZE 1024
6764 #define IOBUF_SIZE 4096
6765 #define RAM_CBLOCK_MAGIC 0xfabe
6767 typedef struct RamCompressState {
6768 z_stream zstream;
6769 QEMUFile *f;
6770 uint8_t buf[IOBUF_SIZE];
6771 } RamCompressState;
6773 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6775 int ret;
6776 memset(s, 0, sizeof(*s));
6777 s->f = f;
6778 ret = deflateInit2(&s->zstream, 1,
6779 Z_DEFLATED, 15,
6780 9, Z_DEFAULT_STRATEGY);
6781 if (ret != Z_OK)
6782 return -1;
6783 s->zstream.avail_out = IOBUF_SIZE;
6784 s->zstream.next_out = s->buf;
6785 return 0;
6788 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6790 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6791 qemu_put_be16(s->f, len);
6792 qemu_put_buffer(s->f, buf, len);
6795 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6797 int ret;
6799 s->zstream.avail_in = len;
6800 s->zstream.next_in = (uint8_t *)buf;
6801 while (s->zstream.avail_in > 0) {
6802 ret = deflate(&s->zstream, Z_NO_FLUSH);
6803 if (ret != Z_OK)
6804 return -1;
6805 if (s->zstream.avail_out == 0) {
6806 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6807 s->zstream.avail_out = IOBUF_SIZE;
6808 s->zstream.next_out = s->buf;
6811 return 0;
6814 static void ram_compress_close(RamCompressState *s)
6816 int len, ret;
6818 /* compress last bytes */
6819 for(;;) {
6820 ret = deflate(&s->zstream, Z_FINISH);
6821 if (ret == Z_OK || ret == Z_STREAM_END) {
6822 len = IOBUF_SIZE - s->zstream.avail_out;
6823 if (len > 0) {
6824 ram_put_cblock(s, s->buf, len);
6826 s->zstream.avail_out = IOBUF_SIZE;
6827 s->zstream.next_out = s->buf;
6828 if (ret == Z_STREAM_END)
6829 break;
6830 } else {
6831 goto fail;
6834 fail:
6835 deflateEnd(&s->zstream);
6838 typedef struct RamDecompressState {
6839 z_stream zstream;
6840 QEMUFile *f;
6841 uint8_t buf[IOBUF_SIZE];
6842 } RamDecompressState;
6844 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6846 int ret;
6847 memset(s, 0, sizeof(*s));
6848 s->f = f;
6849 ret = inflateInit(&s->zstream);
6850 if (ret != Z_OK)
6851 return -1;
6852 return 0;
6855 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6857 int ret, clen;
6859 s->zstream.avail_out = len;
6860 s->zstream.next_out = buf;
6861 while (s->zstream.avail_out > 0) {
6862 if (s->zstream.avail_in == 0) {
6863 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6864 return -1;
6865 clen = qemu_get_be16(s->f);
6866 if (clen > IOBUF_SIZE)
6867 return -1;
6868 qemu_get_buffer(s->f, s->buf, clen);
6869 s->zstream.avail_in = clen;
6870 s->zstream.next_in = s->buf;
6872 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6873 if (ret != Z_OK && ret != Z_STREAM_END) {
6874 return -1;
6877 return 0;
6880 static void ram_decompress_close(RamDecompressState *s)
6882 inflateEnd(&s->zstream);
6885 static void ram_save(QEMUFile *f, void *opaque)
6887 int i;
6888 RamCompressState s1, *s = &s1;
6889 uint8_t buf[10];
6891 qemu_put_be32(f, phys_ram_size);
6892 if (ram_compress_open(s, f) < 0)
6893 return;
6894 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6895 #if 0
6896 if (tight_savevm_enabled) {
6897 int64_t sector_num;
6898 int j;
6900 /* find if the memory block is available on a virtual
6901 block device */
6902 sector_num = -1;
6903 for(j = 0; j < nb_drives; j++) {
6904 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6905 phys_ram_base + i,
6906 BDRV_HASH_BLOCK_SIZE);
6907 if (sector_num >= 0)
6908 break;
6910 if (j == nb_drives)
6911 goto normal_compress;
6912 buf[0] = 1;
6913 buf[1] = j;
6914 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6915 ram_compress_buf(s, buf, 10);
6916 } else
6917 #endif
6919 // normal_compress:
6920 buf[0] = 0;
6921 ram_compress_buf(s, buf, 1);
6922 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6925 ram_compress_close(s);
6928 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6930 RamDecompressState s1, *s = &s1;
6931 uint8_t buf[10];
6932 int i;
6934 if (version_id == 1)
6935 return ram_load_v1(f, opaque);
6936 if (version_id != 2)
6937 return -EINVAL;
6938 if (qemu_get_be32(f) != phys_ram_size)
6939 return -EINVAL;
6940 if (ram_decompress_open(s, f) < 0)
6941 return -EINVAL;
6942 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6943 if (ram_decompress_buf(s, buf, 1) < 0) {
6944 fprintf(stderr, "Error while reading ram block header\n");
6945 goto error;
6947 if (buf[0] == 0) {
6948 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6949 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6950 goto error;
6952 } else
6953 #if 0
6954 if (buf[0] == 1) {
6955 int bs_index;
6956 int64_t sector_num;
6958 ram_decompress_buf(s, buf + 1, 9);
6959 bs_index = buf[1];
6960 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6961 if (bs_index >= nb_drives) {
6962 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6963 goto error;
6965 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6966 phys_ram_base + i,
6967 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6968 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6969 bs_index, sector_num);
6970 goto error;
6972 } else
6973 #endif
6975 error:
6976 printf("Error block header\n");
6977 return -EINVAL;
6980 ram_decompress_close(s);
6981 return 0;
6984 /***********************************************************/
6985 /* bottom halves (can be seen as timers which expire ASAP) */
6987 struct QEMUBH {
6988 QEMUBHFunc *cb;
6989 void *opaque;
6990 int scheduled;
6991 QEMUBH *next;
6994 static QEMUBH *first_bh = NULL;
6996 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6998 QEMUBH *bh;
6999 bh = qemu_mallocz(sizeof(QEMUBH));
7000 if (!bh)
7001 return NULL;
7002 bh->cb = cb;
7003 bh->opaque = opaque;
7004 return bh;
7007 int qemu_bh_poll(void)
7009 QEMUBH *bh, **pbh;
7010 int ret;
7012 ret = 0;
7013 for(;;) {
7014 pbh = &first_bh;
7015 bh = *pbh;
7016 if (!bh)
7017 break;
7018 ret = 1;
7019 *pbh = bh->next;
7020 bh->scheduled = 0;
7021 bh->cb(bh->opaque);
7023 return ret;
7026 void qemu_bh_schedule(QEMUBH *bh)
7028 CPUState *env = cpu_single_env;
7029 if (bh->scheduled)
7030 return;
7031 bh->scheduled = 1;
7032 bh->next = first_bh;
7033 first_bh = bh;
7035 /* stop the currently executing CPU to execute the BH ASAP */
7036 if (env) {
7037 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7041 void qemu_bh_cancel(QEMUBH *bh)
7043 QEMUBH **pbh;
7044 if (bh->scheduled) {
7045 pbh = &first_bh;
7046 while (*pbh != bh)
7047 pbh = &(*pbh)->next;
7048 *pbh = bh->next;
7049 bh->scheduled = 0;
7053 void qemu_bh_delete(QEMUBH *bh)
7055 qemu_bh_cancel(bh);
7056 qemu_free(bh);
7059 /***********************************************************/
7060 /* machine registration */
7062 QEMUMachine *first_machine = NULL;
7064 int qemu_register_machine(QEMUMachine *m)
7066 QEMUMachine **pm;
7067 pm = &first_machine;
7068 while (*pm != NULL)
7069 pm = &(*pm)->next;
7070 m->next = NULL;
7071 *pm = m;
7072 return 0;
7075 static QEMUMachine *find_machine(const char *name)
7077 QEMUMachine *m;
7079 for(m = first_machine; m != NULL; m = m->next) {
7080 if (!strcmp(m->name, name))
7081 return m;
7083 return NULL;
7086 /***********************************************************/
7087 /* main execution loop */
7089 static void gui_update(void *opaque)
7091 DisplayState *ds = opaque;
7092 ds->dpy_refresh(ds);
7093 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7096 struct vm_change_state_entry {
7097 VMChangeStateHandler *cb;
7098 void *opaque;
7099 LIST_ENTRY (vm_change_state_entry) entries;
7102 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7104 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7105 void *opaque)
7107 VMChangeStateEntry *e;
7109 e = qemu_mallocz(sizeof (*e));
7110 if (!e)
7111 return NULL;
7113 e->cb = cb;
7114 e->opaque = opaque;
7115 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7116 return e;
7119 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7121 LIST_REMOVE (e, entries);
7122 qemu_free (e);
7125 static void vm_state_notify(int running)
7127 VMChangeStateEntry *e;
7129 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7130 e->cb(e->opaque, running);
7134 /* XXX: support several handlers */
7135 static VMStopHandler *vm_stop_cb;
7136 static void *vm_stop_opaque;
7138 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7140 vm_stop_cb = cb;
7141 vm_stop_opaque = opaque;
7142 return 0;
7145 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7147 vm_stop_cb = NULL;
7150 void vm_start(void)
7152 if (!vm_running) {
7153 cpu_enable_ticks();
7154 vm_running = 1;
7155 vm_state_notify(1);
7156 qemu_rearm_alarm_timer(alarm_timer);
7160 void vm_stop(int reason)
7162 if (vm_running) {
7163 cpu_disable_ticks();
7164 vm_running = 0;
7165 if (reason != 0) {
7166 if (vm_stop_cb) {
7167 vm_stop_cb(vm_stop_opaque, reason);
7170 vm_state_notify(0);
7174 /* reset/shutdown handler */
7176 typedef struct QEMUResetEntry {
7177 QEMUResetHandler *func;
7178 void *opaque;
7179 struct QEMUResetEntry *next;
7180 } QEMUResetEntry;
7182 static QEMUResetEntry *first_reset_entry;
7183 static int reset_requested;
7184 static int shutdown_requested;
7185 static int powerdown_requested;
7187 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7189 QEMUResetEntry **pre, *re;
7191 pre = &first_reset_entry;
7192 while (*pre != NULL)
7193 pre = &(*pre)->next;
7194 re = qemu_mallocz(sizeof(QEMUResetEntry));
7195 re->func = func;
7196 re->opaque = opaque;
7197 re->next = NULL;
7198 *pre = re;
7201 static void qemu_system_reset(void)
7203 QEMUResetEntry *re;
7205 /* reset all devices */
7206 for(re = first_reset_entry; re != NULL; re = re->next) {
7207 re->func(re->opaque);
7211 void qemu_system_reset_request(void)
7213 if (no_reboot) {
7214 shutdown_requested = 1;
7215 } else {
7216 reset_requested = 1;
7218 if (cpu_single_env)
7219 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7222 void qemu_system_shutdown_request(void)
7224 shutdown_requested = 1;
7225 if (cpu_single_env)
7226 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7229 void qemu_system_powerdown_request(void)
7231 powerdown_requested = 1;
7232 if (cpu_single_env)
7233 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7236 void main_loop_wait(int timeout)
7238 IOHandlerRecord *ioh;
7239 fd_set rfds, wfds, xfds;
7240 int ret, nfds;
7241 #ifdef _WIN32
7242 int ret2, i;
7243 #endif
7244 struct timeval tv;
7245 PollingEntry *pe;
7248 /* XXX: need to suppress polling by better using win32 events */
7249 ret = 0;
7250 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7251 ret |= pe->func(pe->opaque);
7253 #ifdef _WIN32
7254 if (ret == 0) {
7255 int err;
7256 WaitObjects *w = &wait_objects;
7258 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7259 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7260 if (w->func[ret - WAIT_OBJECT_0])
7261 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7263 /* Check for additional signaled events */
7264 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7266 /* Check if event is signaled */
7267 ret2 = WaitForSingleObject(w->events[i], 0);
7268 if(ret2 == WAIT_OBJECT_0) {
7269 if (w->func[i])
7270 w->func[i](w->opaque[i]);
7271 } else if (ret2 == WAIT_TIMEOUT) {
7272 } else {
7273 err = GetLastError();
7274 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7277 } else if (ret == WAIT_TIMEOUT) {
7278 } else {
7279 err = GetLastError();
7280 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7283 #endif
7284 /* poll any events */
7285 /* XXX: separate device handlers from system ones */
7286 nfds = -1;
7287 FD_ZERO(&rfds);
7288 FD_ZERO(&wfds);
7289 FD_ZERO(&xfds);
7290 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7291 if (ioh->deleted)
7292 continue;
7293 if (ioh->fd_read &&
7294 (!ioh->fd_read_poll ||
7295 ioh->fd_read_poll(ioh->opaque) != 0)) {
7296 FD_SET(ioh->fd, &rfds);
7297 if (ioh->fd > nfds)
7298 nfds = ioh->fd;
7300 if (ioh->fd_write) {
7301 FD_SET(ioh->fd, &wfds);
7302 if (ioh->fd > nfds)
7303 nfds = ioh->fd;
7307 tv.tv_sec = 0;
7308 #ifdef _WIN32
7309 tv.tv_usec = 0;
7310 #else
7311 tv.tv_usec = timeout * 1000;
7312 #endif
7313 #if defined(CONFIG_SLIRP)
7314 if (slirp_inited) {
7315 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7317 #endif
7318 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7319 if (ret > 0) {
7320 IOHandlerRecord **pioh;
7322 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7323 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7324 ioh->fd_read(ioh->opaque);
7326 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7327 ioh->fd_write(ioh->opaque);
7331 /* remove deleted IO handlers */
7332 pioh = &first_io_handler;
7333 while (*pioh) {
7334 ioh = *pioh;
7335 if (ioh->deleted) {
7336 *pioh = ioh->next;
7337 qemu_free(ioh);
7338 } else
7339 pioh = &ioh->next;
7342 #if defined(CONFIG_SLIRP)
7343 if (slirp_inited) {
7344 if (ret < 0) {
7345 FD_ZERO(&rfds);
7346 FD_ZERO(&wfds);
7347 FD_ZERO(&xfds);
7349 slirp_select_poll(&rfds, &wfds, &xfds);
7351 #endif
7352 qemu_aio_poll();
7354 if (vm_running) {
7355 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7356 qemu_get_clock(vm_clock));
7357 /* run dma transfers, if any */
7358 DMA_run();
7361 /* real time timers */
7362 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7363 qemu_get_clock(rt_clock));
7365 /* Check bottom-halves last in case any of the earlier events triggered
7366 them. */
7367 qemu_bh_poll();
7371 static int main_loop(void)
7373 int ret, timeout;
7374 #ifdef CONFIG_PROFILER
7375 int64_t ti;
7376 #endif
7377 CPUState *env;
7379 cur_cpu = first_cpu;
7380 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7381 for(;;) {
7382 if (vm_running) {
7384 for(;;) {
7385 /* get next cpu */
7386 env = next_cpu;
7387 #ifdef CONFIG_PROFILER
7388 ti = profile_getclock();
7389 #endif
7390 ret = cpu_exec(env);
7391 #ifdef CONFIG_PROFILER
7392 qemu_time += profile_getclock() - ti;
7393 #endif
7394 next_cpu = env->next_cpu ?: first_cpu;
7395 if (event_pending) {
7396 ret = EXCP_INTERRUPT;
7397 event_pending = 0;
7398 break;
7400 if (ret == EXCP_HLT) {
7401 /* Give the next CPU a chance to run. */
7402 cur_cpu = env;
7403 continue;
7405 if (ret != EXCP_HALTED)
7406 break;
7407 /* all CPUs are halted ? */
7408 if (env == cur_cpu)
7409 break;
7411 cur_cpu = env;
7413 if (shutdown_requested) {
7414 ret = EXCP_INTERRUPT;
7415 break;
7417 if (reset_requested) {
7418 reset_requested = 0;
7419 qemu_system_reset();
7420 ret = EXCP_INTERRUPT;
7422 if (powerdown_requested) {
7423 powerdown_requested = 0;
7424 qemu_system_powerdown();
7425 ret = EXCP_INTERRUPT;
7427 if (ret == EXCP_DEBUG) {
7428 vm_stop(EXCP_DEBUG);
7430 /* If all cpus are halted then wait until the next IRQ */
7431 /* XXX: use timeout computed from timers */
7432 if (ret == EXCP_HALTED)
7433 timeout = 10;
7434 else
7435 timeout = 0;
7436 } else {
7437 timeout = 10;
7439 #ifdef CONFIG_PROFILER
7440 ti = profile_getclock();
7441 #endif
7442 main_loop_wait(timeout);
7443 #ifdef CONFIG_PROFILER
7444 dev_time += profile_getclock() - ti;
7445 #endif
7447 cpu_disable_ticks();
7448 return ret;
7451 static void help(int exitcode)
7453 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7454 "usage: %s [options] [disk_image]\n"
7455 "\n"
7456 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7457 "\n"
7458 "Standard options:\n"
7459 "-M machine select emulated machine (-M ? for list)\n"
7460 "-cpu cpu select CPU (-cpu ? for list)\n"
7461 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7462 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7463 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7464 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7465 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7466 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7467 " use 'file' as a drive image\n"
7468 "-mtdblock file use 'file' as on-board Flash memory image\n"
7469 "-sd file use 'file' as SecureDigital card image\n"
7470 "-pflash file use 'file' as a parallel flash image\n"
7471 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7472 "-snapshot write to temporary files instead of disk image files\n"
7473 #ifdef CONFIG_SDL
7474 "-no-frame open SDL window without a frame and window decorations\n"
7475 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7476 "-no-quit disable SDL window close capability\n"
7477 #endif
7478 #ifdef TARGET_I386
7479 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7480 #endif
7481 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7482 "-smp n set the number of CPUs to 'n' [default=1]\n"
7483 "-nographic disable graphical output and redirect serial I/Os to console\n"
7484 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7485 #ifndef _WIN32
7486 "-k language use keyboard layout (for example \"fr\" for French)\n"
7487 #endif
7488 #ifdef HAS_AUDIO
7489 "-audio-help print list of audio drivers and their options\n"
7490 "-soundhw c1,... enable audio support\n"
7491 " and only specified sound cards (comma separated list)\n"
7492 " use -soundhw ? to get the list of supported cards\n"
7493 " use -soundhw all to enable all of them\n"
7494 #endif
7495 "-localtime set the real time clock to local time [default=utc]\n"
7496 "-full-screen start in full screen\n"
7497 #ifdef TARGET_I386
7498 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7499 #endif
7500 "-usb enable the USB driver (will be the default soon)\n"
7501 "-usbdevice name add the host or guest USB device 'name'\n"
7502 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7503 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7504 #endif
7505 "-name string set the name of the guest\n"
7506 "\n"
7507 "Network options:\n"
7508 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7509 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7510 #ifdef CONFIG_SLIRP
7511 "-net user[,vlan=n][,hostname=host]\n"
7512 " connect the user mode network stack to VLAN 'n' and send\n"
7513 " hostname 'host' to DHCP clients\n"
7514 #endif
7515 #ifdef _WIN32
7516 "-net tap[,vlan=n],ifname=name\n"
7517 " connect the host TAP network interface to VLAN 'n'\n"
7518 #else
7519 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7520 " connect the host TAP network interface to VLAN 'n' and use the\n"
7521 " network scripts 'file' (default=%s)\n"
7522 " and 'dfile' (default=%s);\n"
7523 " use '[down]script=no' to disable script execution;\n"
7524 " use 'fd=h' to connect to an already opened TAP interface\n"
7525 #endif
7526 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7527 " connect the vlan 'n' to another VLAN using a socket connection\n"
7528 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7529 " connect the vlan 'n' to multicast maddr and port\n"
7530 "-net none use it alone to have zero network devices; if no -net option\n"
7531 " is provided, the default is '-net nic -net user'\n"
7532 "\n"
7533 #ifdef CONFIG_SLIRP
7534 "-tftp dir allow tftp access to files in dir [-net user]\n"
7535 "-bootp file advertise file in BOOTP replies\n"
7536 #ifndef _WIN32
7537 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7538 #endif
7539 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7540 " redirect TCP or UDP connections from host to guest [-net user]\n"
7541 #endif
7542 "\n"
7543 "Linux boot specific:\n"
7544 "-kernel bzImage use 'bzImage' as kernel image\n"
7545 "-append cmdline use 'cmdline' as kernel command line\n"
7546 "-initrd file use 'file' as initial ram disk\n"
7547 "\n"
7548 "Debug/Expert options:\n"
7549 "-monitor dev redirect the monitor to char device 'dev'\n"
7550 "-serial dev redirect the serial port to char device 'dev'\n"
7551 "-parallel dev redirect the parallel port to char device 'dev'\n"
7552 "-pidfile file Write PID to 'file'\n"
7553 "-S freeze CPU at startup (use 'c' to start execution)\n"
7554 "-s wait gdb connection to port\n"
7555 "-p port set gdb connection port [default=%s]\n"
7556 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7557 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7558 " translation (t=none or lba) (usually qemu can guess them)\n"
7559 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7560 #ifdef USE_KQEMU
7561 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7562 "-no-kqemu disable KQEMU kernel module usage\n"
7563 #endif
7564 #ifdef TARGET_I386
7565 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7566 " (default is CL-GD5446 PCI VGA)\n"
7567 "-no-acpi disable ACPI\n"
7568 #endif
7569 "-no-reboot exit instead of rebooting\n"
7570 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7571 "-vnc display start a VNC server on display\n"
7572 #ifndef _WIN32
7573 "-daemonize daemonize QEMU after initializing\n"
7574 #endif
7575 "-option-rom rom load a file, rom, into the option ROM space\n"
7576 #ifdef TARGET_SPARC
7577 "-prom-env variable=value set OpenBIOS nvram variables\n"
7578 #endif
7579 "-clock force the use of the given methods for timer alarm.\n"
7580 " To see what timers are available use -clock help\n"
7581 "\n"
7582 "During emulation, the following keys are useful:\n"
7583 "ctrl-alt-f toggle full screen\n"
7584 "ctrl-alt-n switch to virtual console 'n'\n"
7585 "ctrl-alt toggle mouse and keyboard grab\n"
7586 "\n"
7587 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7589 "qemu",
7590 DEFAULT_RAM_SIZE,
7591 #ifndef _WIN32
7592 DEFAULT_NETWORK_SCRIPT,
7593 DEFAULT_NETWORK_DOWN_SCRIPT,
7594 #endif
7595 DEFAULT_GDBSTUB_PORT,
7596 "/tmp/qemu.log");
7597 exit(exitcode);
7600 #define HAS_ARG 0x0001
7602 enum {
7603 QEMU_OPTION_h,
7605 QEMU_OPTION_M,
7606 QEMU_OPTION_cpu,
7607 QEMU_OPTION_fda,
7608 QEMU_OPTION_fdb,
7609 QEMU_OPTION_hda,
7610 QEMU_OPTION_hdb,
7611 QEMU_OPTION_hdc,
7612 QEMU_OPTION_hdd,
7613 QEMU_OPTION_drive,
7614 QEMU_OPTION_cdrom,
7615 QEMU_OPTION_mtdblock,
7616 QEMU_OPTION_sd,
7617 QEMU_OPTION_pflash,
7618 QEMU_OPTION_boot,
7619 QEMU_OPTION_snapshot,
7620 #ifdef TARGET_I386
7621 QEMU_OPTION_no_fd_bootchk,
7622 #endif
7623 QEMU_OPTION_m,
7624 QEMU_OPTION_nographic,
7625 QEMU_OPTION_portrait,
7626 #ifdef HAS_AUDIO
7627 QEMU_OPTION_audio_help,
7628 QEMU_OPTION_soundhw,
7629 #endif
7631 QEMU_OPTION_net,
7632 QEMU_OPTION_tftp,
7633 QEMU_OPTION_bootp,
7634 QEMU_OPTION_smb,
7635 QEMU_OPTION_redir,
7637 QEMU_OPTION_kernel,
7638 QEMU_OPTION_append,
7639 QEMU_OPTION_initrd,
7641 QEMU_OPTION_S,
7642 QEMU_OPTION_s,
7643 QEMU_OPTION_p,
7644 QEMU_OPTION_d,
7645 QEMU_OPTION_hdachs,
7646 QEMU_OPTION_L,
7647 QEMU_OPTION_bios,
7648 QEMU_OPTION_no_code_copy,
7649 QEMU_OPTION_k,
7650 QEMU_OPTION_localtime,
7651 QEMU_OPTION_cirrusvga,
7652 QEMU_OPTION_vmsvga,
7653 QEMU_OPTION_g,
7654 QEMU_OPTION_std_vga,
7655 QEMU_OPTION_echr,
7656 QEMU_OPTION_monitor,
7657 QEMU_OPTION_serial,
7658 QEMU_OPTION_parallel,
7659 QEMU_OPTION_loadvm,
7660 QEMU_OPTION_full_screen,
7661 QEMU_OPTION_no_frame,
7662 QEMU_OPTION_alt_grab,
7663 QEMU_OPTION_no_quit,
7664 QEMU_OPTION_pidfile,
7665 QEMU_OPTION_no_kqemu,
7666 QEMU_OPTION_kernel_kqemu,
7667 QEMU_OPTION_win2k_hack,
7668 QEMU_OPTION_usb,
7669 QEMU_OPTION_usbdevice,
7670 QEMU_OPTION_smp,
7671 QEMU_OPTION_vnc,
7672 QEMU_OPTION_no_acpi,
7673 QEMU_OPTION_no_reboot,
7674 QEMU_OPTION_show_cursor,
7675 QEMU_OPTION_daemonize,
7676 QEMU_OPTION_option_rom,
7677 QEMU_OPTION_semihosting,
7678 QEMU_OPTION_name,
7679 QEMU_OPTION_prom_env,
7680 QEMU_OPTION_old_param,
7681 QEMU_OPTION_clock,
7682 QEMU_OPTION_startdate,
7685 typedef struct QEMUOption {
7686 const char *name;
7687 int flags;
7688 int index;
7689 } QEMUOption;
7691 const QEMUOption qemu_options[] = {
7692 { "h", 0, QEMU_OPTION_h },
7693 { "help", 0, QEMU_OPTION_h },
7695 { "M", HAS_ARG, QEMU_OPTION_M },
7696 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7697 { "fda", HAS_ARG, QEMU_OPTION_fda },
7698 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7699 { "hda", HAS_ARG, QEMU_OPTION_hda },
7700 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7701 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7702 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7703 { "drive", HAS_ARG, QEMU_OPTION_drive },
7704 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7705 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7706 { "sd", HAS_ARG, QEMU_OPTION_sd },
7707 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7708 { "boot", HAS_ARG, QEMU_OPTION_boot },
7709 { "snapshot", 0, QEMU_OPTION_snapshot },
7710 #ifdef TARGET_I386
7711 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7712 #endif
7713 { "m", HAS_ARG, QEMU_OPTION_m },
7714 { "nographic", 0, QEMU_OPTION_nographic },
7715 { "portrait", 0, QEMU_OPTION_portrait },
7716 { "k", HAS_ARG, QEMU_OPTION_k },
7717 #ifdef HAS_AUDIO
7718 { "audio-help", 0, QEMU_OPTION_audio_help },
7719 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7720 #endif
7722 { "net", HAS_ARG, QEMU_OPTION_net},
7723 #ifdef CONFIG_SLIRP
7724 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7725 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7726 #ifndef _WIN32
7727 { "smb", HAS_ARG, QEMU_OPTION_smb },
7728 #endif
7729 { "redir", HAS_ARG, QEMU_OPTION_redir },
7730 #endif
7732 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7733 { "append", HAS_ARG, QEMU_OPTION_append },
7734 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7736 { "S", 0, QEMU_OPTION_S },
7737 { "s", 0, QEMU_OPTION_s },
7738 { "p", HAS_ARG, QEMU_OPTION_p },
7739 { "d", HAS_ARG, QEMU_OPTION_d },
7740 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7741 { "L", HAS_ARG, QEMU_OPTION_L },
7742 { "bios", HAS_ARG, QEMU_OPTION_bios },
7743 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7744 #ifdef USE_KQEMU
7745 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7746 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7747 #endif
7748 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7749 { "g", 1, QEMU_OPTION_g },
7750 #endif
7751 { "localtime", 0, QEMU_OPTION_localtime },
7752 { "std-vga", 0, QEMU_OPTION_std_vga },
7753 { "echr", HAS_ARG, QEMU_OPTION_echr },
7754 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7755 { "serial", HAS_ARG, QEMU_OPTION_serial },
7756 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7757 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7758 { "full-screen", 0, QEMU_OPTION_full_screen },
7759 #ifdef CONFIG_SDL
7760 { "no-frame", 0, QEMU_OPTION_no_frame },
7761 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7762 { "no-quit", 0, QEMU_OPTION_no_quit },
7763 #endif
7764 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7765 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7766 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7767 { "smp", HAS_ARG, QEMU_OPTION_smp },
7768 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7770 /* temporary options */
7771 { "usb", 0, QEMU_OPTION_usb },
7772 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7773 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7774 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7775 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7776 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7777 { "daemonize", 0, QEMU_OPTION_daemonize },
7778 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7779 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7780 { "semihosting", 0, QEMU_OPTION_semihosting },
7781 #endif
7782 { "name", HAS_ARG, QEMU_OPTION_name },
7783 #if defined(TARGET_SPARC)
7784 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7785 #endif
7786 #if defined(TARGET_ARM)
7787 { "old-param", 0, QEMU_OPTION_old_param },
7788 #endif
7789 { "clock", HAS_ARG, QEMU_OPTION_clock },
7790 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7791 { NULL },
7794 /* password input */
7796 int qemu_key_check(BlockDriverState *bs, const char *name)
7798 char password[256];
7799 int i;
7801 if (!bdrv_is_encrypted(bs))
7802 return 0;
7804 term_printf("%s is encrypted.\n", name);
7805 for(i = 0; i < 3; i++) {
7806 monitor_readline("Password: ", 1, password, sizeof(password));
7807 if (bdrv_set_key(bs, password) == 0)
7808 return 0;
7809 term_printf("invalid password\n");
7811 return -EPERM;
7814 static BlockDriverState *get_bdrv(int index)
7816 if (index > nb_drives)
7817 return NULL;
7818 return drives_table[index].bdrv;
7821 static void read_passwords(void)
7823 BlockDriverState *bs;
7824 int i;
7826 for(i = 0; i < 6; i++) {
7827 bs = get_bdrv(i);
7828 if (bs)
7829 qemu_key_check(bs, bdrv_get_device_name(bs));
7833 /* XXX: currently we cannot use simultaneously different CPUs */
7834 static void register_machines(void)
7836 #if defined(TARGET_I386)
7837 qemu_register_machine(&pc_machine);
7838 qemu_register_machine(&isapc_machine);
7839 #elif defined(TARGET_PPC)
7840 qemu_register_machine(&heathrow_machine);
7841 qemu_register_machine(&core99_machine);
7842 qemu_register_machine(&prep_machine);
7843 qemu_register_machine(&ref405ep_machine);
7844 qemu_register_machine(&taihu_machine);
7845 #elif defined(TARGET_MIPS)
7846 qemu_register_machine(&mips_machine);
7847 qemu_register_machine(&mips_malta_machine);
7848 qemu_register_machine(&mips_pica61_machine);
7849 qemu_register_machine(&mips_mipssim_machine);
7850 #elif defined(TARGET_SPARC)
7851 #ifdef TARGET_SPARC64
7852 qemu_register_machine(&sun4u_machine);
7853 #else
7854 qemu_register_machine(&ss5_machine);
7855 qemu_register_machine(&ss10_machine);
7856 qemu_register_machine(&ss600mp_machine);
7857 qemu_register_machine(&ss20_machine);
7858 #endif
7859 #elif defined(TARGET_ARM)
7860 qemu_register_machine(&integratorcp_machine);
7861 qemu_register_machine(&versatilepb_machine);
7862 qemu_register_machine(&versatileab_machine);
7863 qemu_register_machine(&realview_machine);
7864 qemu_register_machine(&akitapda_machine);
7865 qemu_register_machine(&spitzpda_machine);
7866 qemu_register_machine(&borzoipda_machine);
7867 qemu_register_machine(&terrierpda_machine);
7868 qemu_register_machine(&palmte_machine);
7869 qemu_register_machine(&lm3s811evb_machine);
7870 qemu_register_machine(&lm3s6965evb_machine);
7871 qemu_register_machine(&connex_machine);
7872 qemu_register_machine(&verdex_machine);
7873 qemu_register_machine(&mainstone2_machine);
7874 #elif defined(TARGET_SH4)
7875 qemu_register_machine(&shix_machine);
7876 qemu_register_machine(&r2d_machine);
7877 #elif defined(TARGET_ALPHA)
7878 /* XXX: TODO */
7879 #elif defined(TARGET_M68K)
7880 qemu_register_machine(&mcf5208evb_machine);
7881 qemu_register_machine(&an5206_machine);
7882 qemu_register_machine(&dummy_m68k_machine);
7883 #elif defined(TARGET_CRIS)
7884 qemu_register_machine(&bareetraxfs_machine);
7885 #else
7886 #error unsupported CPU
7887 #endif
7890 #ifdef HAS_AUDIO
7891 struct soundhw soundhw[] = {
7892 #ifdef HAS_AUDIO_CHOICE
7893 #ifdef TARGET_I386
7895 "pcspk",
7896 "PC speaker",
7899 { .init_isa = pcspk_audio_init }
7901 #endif
7903 "sb16",
7904 "Creative Sound Blaster 16",
7907 { .init_isa = SB16_init }
7910 #ifdef CONFIG_ADLIB
7912 "adlib",
7913 #ifdef HAS_YMF262
7914 "Yamaha YMF262 (OPL3)",
7915 #else
7916 "Yamaha YM3812 (OPL2)",
7917 #endif
7920 { .init_isa = Adlib_init }
7922 #endif
7924 #ifdef CONFIG_GUS
7926 "gus",
7927 "Gravis Ultrasound GF1",
7930 { .init_isa = GUS_init }
7932 #endif
7935 "es1370",
7936 "ENSONIQ AudioPCI ES1370",
7939 { .init_pci = es1370_init }
7941 #endif
7943 { NULL, NULL, 0, 0, { NULL } }
7946 static void select_soundhw (const char *optarg)
7948 struct soundhw *c;
7950 if (*optarg == '?') {
7951 show_valid_cards:
7953 printf ("Valid sound card names (comma separated):\n");
7954 for (c = soundhw; c->name; ++c) {
7955 printf ("%-11s %s\n", c->name, c->descr);
7957 printf ("\n-soundhw all will enable all of the above\n");
7958 exit (*optarg != '?');
7960 else {
7961 size_t l;
7962 const char *p;
7963 char *e;
7964 int bad_card = 0;
7966 if (!strcmp (optarg, "all")) {
7967 for (c = soundhw; c->name; ++c) {
7968 c->enabled = 1;
7970 return;
7973 p = optarg;
7974 while (*p) {
7975 e = strchr (p, ',');
7976 l = !e ? strlen (p) : (size_t) (e - p);
7978 for (c = soundhw; c->name; ++c) {
7979 if (!strncmp (c->name, p, l)) {
7980 c->enabled = 1;
7981 break;
7985 if (!c->name) {
7986 if (l > 80) {
7987 fprintf (stderr,
7988 "Unknown sound card name (too big to show)\n");
7990 else {
7991 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7992 (int) l, p);
7994 bad_card = 1;
7996 p += l + (e != NULL);
7999 if (bad_card)
8000 goto show_valid_cards;
8003 #endif
8005 #ifdef _WIN32
8006 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8008 exit(STATUS_CONTROL_C_EXIT);
8009 return TRUE;
8011 #endif
8013 #define MAX_NET_CLIENTS 32
8015 int main(int argc, char **argv)
8017 #ifdef CONFIG_GDBSTUB
8018 int use_gdbstub;
8019 const char *gdbstub_port;
8020 #endif
8021 uint32_t boot_devices_bitmap = 0;
8022 int i;
8023 int snapshot, linux_boot, net_boot;
8024 const char *initrd_filename;
8025 const char *kernel_filename, *kernel_cmdline;
8026 const char *boot_devices = "";
8027 DisplayState *ds = &display_state;
8028 int cyls, heads, secs, translation;
8029 char net_clients[MAX_NET_CLIENTS][256];
8030 int nb_net_clients;
8031 int hda_index;
8032 int optind;
8033 const char *r, *optarg;
8034 CharDriverState *monitor_hd;
8035 char monitor_device[128];
8036 char serial_devices[MAX_SERIAL_PORTS][128];
8037 int serial_device_index;
8038 char parallel_devices[MAX_PARALLEL_PORTS][128];
8039 int parallel_device_index;
8040 const char *loadvm = NULL;
8041 QEMUMachine *machine;
8042 const char *cpu_model;
8043 char usb_devices[MAX_USB_CMDLINE][128];
8044 int usb_devices_index;
8045 int fds[2];
8046 const char *pid_file = NULL;
8047 VLANState *vlan;
8049 LIST_INIT (&vm_change_state_head);
8050 #ifndef _WIN32
8052 struct sigaction act;
8053 sigfillset(&act.sa_mask);
8054 act.sa_flags = 0;
8055 act.sa_handler = SIG_IGN;
8056 sigaction(SIGPIPE, &act, NULL);
8058 #else
8059 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8060 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8061 QEMU to run on a single CPU */
8063 HANDLE h;
8064 DWORD mask, smask;
8065 int i;
8066 h = GetCurrentProcess();
8067 if (GetProcessAffinityMask(h, &mask, &smask)) {
8068 for(i = 0; i < 32; i++) {
8069 if (mask & (1 << i))
8070 break;
8072 if (i != 32) {
8073 mask = 1 << i;
8074 SetProcessAffinityMask(h, mask);
8078 #endif
8080 register_machines();
8081 machine = first_machine;
8082 cpu_model = NULL;
8083 initrd_filename = NULL;
8084 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8085 vga_ram_size = VGA_RAM_SIZE;
8086 #ifdef CONFIG_GDBSTUB
8087 use_gdbstub = 0;
8088 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8089 #endif
8090 snapshot = 0;
8091 nographic = 0;
8092 kernel_filename = NULL;
8093 kernel_cmdline = "";
8094 cyls = heads = secs = 0;
8095 translation = BIOS_ATA_TRANSLATION_AUTO;
8096 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8098 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8099 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8100 serial_devices[i][0] = '\0';
8101 serial_device_index = 0;
8103 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8104 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8105 parallel_devices[i][0] = '\0';
8106 parallel_device_index = 0;
8108 usb_devices_index = 0;
8110 nb_net_clients = 0;
8111 nb_drives = 0;
8112 nb_drives_opt = 0;
8113 hda_index = -1;
8115 nb_nics = 0;
8116 /* default mac address of the first network interface */
8118 optind = 1;
8119 for(;;) {
8120 if (optind >= argc)
8121 break;
8122 r = argv[optind];
8123 if (r[0] != '-') {
8124 hda_index = drive_add(HD_ALIAS, argv[optind++], 0);
8125 } else {
8126 const QEMUOption *popt;
8128 optind++;
8129 /* Treat --foo the same as -foo. */
8130 if (r[1] == '-')
8131 r++;
8132 popt = qemu_options;
8133 for(;;) {
8134 if (!popt->name) {
8135 fprintf(stderr, "%s: invalid option -- '%s'\n",
8136 argv[0], r);
8137 exit(1);
8139 if (!strcmp(popt->name, r + 1))
8140 break;
8141 popt++;
8143 if (popt->flags & HAS_ARG) {
8144 if (optind >= argc) {
8145 fprintf(stderr, "%s: option '%s' requires an argument\n",
8146 argv[0], r);
8147 exit(1);
8149 optarg = argv[optind++];
8150 } else {
8151 optarg = NULL;
8154 switch(popt->index) {
8155 case QEMU_OPTION_M:
8156 machine = find_machine(optarg);
8157 if (!machine) {
8158 QEMUMachine *m;
8159 printf("Supported machines are:\n");
8160 for(m = first_machine; m != NULL; m = m->next) {
8161 printf("%-10s %s%s\n",
8162 m->name, m->desc,
8163 m == first_machine ? " (default)" : "");
8165 exit(*optarg != '?');
8167 break;
8168 case QEMU_OPTION_cpu:
8169 /* hw initialization will check this */
8170 if (*optarg == '?') {
8171 /* XXX: implement xxx_cpu_list for targets that still miss it */
8172 #if defined(cpu_list)
8173 cpu_list(stdout, &fprintf);
8174 #endif
8175 exit(0);
8176 } else {
8177 cpu_model = optarg;
8179 break;
8180 case QEMU_OPTION_initrd:
8181 initrd_filename = optarg;
8182 break;
8183 case QEMU_OPTION_hda:
8184 if (cyls == 0)
8185 hda_index = drive_add(HD_ALIAS, optarg, 0);
8186 else
8187 hda_index = drive_add(HD_ALIAS
8188 ",cyls=%d,heads=%d,secs=%d%s",
8189 optarg, 0, cyls, heads, secs,
8190 translation == BIOS_ATA_TRANSLATION_LBA ?
8191 ",trans=lba" :
8192 translation == BIOS_ATA_TRANSLATION_NONE ?
8193 ",trans=none" : "");
8194 break;
8195 case QEMU_OPTION_hdb:
8196 case QEMU_OPTION_hdc:
8197 case QEMU_OPTION_hdd:
8198 drive_add(HD_ALIAS, optarg, popt->index - QEMU_OPTION_hda);
8199 break;
8200 case QEMU_OPTION_drive:
8201 drive_add("%s", optarg);
8202 break;
8203 case QEMU_OPTION_mtdblock:
8204 drive_add(MTD_ALIAS, optarg);
8205 break;
8206 case QEMU_OPTION_sd:
8207 drive_add("file=\"%s\"," SD_ALIAS, optarg);
8208 break;
8209 case QEMU_OPTION_pflash:
8210 drive_add(PFLASH_ALIAS, optarg);
8211 break;
8212 case QEMU_OPTION_snapshot:
8213 snapshot = 1;
8214 break;
8215 case QEMU_OPTION_hdachs:
8217 const char *p;
8218 p = optarg;
8219 cyls = strtol(p, (char **)&p, 0);
8220 if (cyls < 1 || cyls > 16383)
8221 goto chs_fail;
8222 if (*p != ',')
8223 goto chs_fail;
8224 p++;
8225 heads = strtol(p, (char **)&p, 0);
8226 if (heads < 1 || heads > 16)
8227 goto chs_fail;
8228 if (*p != ',')
8229 goto chs_fail;
8230 p++;
8231 secs = strtol(p, (char **)&p, 0);
8232 if (secs < 1 || secs > 63)
8233 goto chs_fail;
8234 if (*p == ',') {
8235 p++;
8236 if (!strcmp(p, "none"))
8237 translation = BIOS_ATA_TRANSLATION_NONE;
8238 else if (!strcmp(p, "lba"))
8239 translation = BIOS_ATA_TRANSLATION_LBA;
8240 else if (!strcmp(p, "auto"))
8241 translation = BIOS_ATA_TRANSLATION_AUTO;
8242 else
8243 goto chs_fail;
8244 } else if (*p != '\0') {
8245 chs_fail:
8246 fprintf(stderr, "qemu: invalid physical CHS format\n");
8247 exit(1);
8249 if (hda_index != -1)
8250 snprintf(drives_opt[hda_index] +
8251 strlen(drives_opt[hda_index]),
8252 sizeof(drives_opt[0]) -
8253 strlen(drives_opt[hda_index]),
8254 ",cyls=%d,heads=%d,secs=%d%s",
8255 cyls, heads, secs,
8256 translation == BIOS_ATA_TRANSLATION_LBA ?
8257 ",trans=lba" :
8258 translation == BIOS_ATA_TRANSLATION_NONE ?
8259 ",trans=none" : "");
8261 break;
8262 case QEMU_OPTION_nographic:
8263 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8264 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8265 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8266 nographic = 1;
8267 break;
8268 case QEMU_OPTION_portrait:
8269 graphic_rotate = 1;
8270 break;
8271 case QEMU_OPTION_kernel:
8272 kernel_filename = optarg;
8273 break;
8274 case QEMU_OPTION_append:
8275 kernel_cmdline = optarg;
8276 break;
8277 case QEMU_OPTION_cdrom:
8278 drive_add("file=\"%s\"," CDROM_ALIAS, optarg);
8279 break;
8280 case QEMU_OPTION_boot:
8281 boot_devices = optarg;
8282 /* We just do some generic consistency checks */
8284 /* Could easily be extended to 64 devices if needed */
8285 const char *p;
8287 boot_devices_bitmap = 0;
8288 for (p = boot_devices; *p != '\0'; p++) {
8289 /* Allowed boot devices are:
8290 * a b : floppy disk drives
8291 * c ... f : IDE disk drives
8292 * g ... m : machine implementation dependant drives
8293 * n ... p : network devices
8294 * It's up to each machine implementation to check
8295 * if the given boot devices match the actual hardware
8296 * implementation and firmware features.
8298 if (*p < 'a' || *p > 'q') {
8299 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8300 exit(1);
8302 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8303 fprintf(stderr,
8304 "Boot device '%c' was given twice\n",*p);
8305 exit(1);
8307 boot_devices_bitmap |= 1 << (*p - 'a');
8310 break;
8311 case QEMU_OPTION_fda:
8312 case QEMU_OPTION_fdb:
8313 drive_add("file=\"%s\"," FD_ALIAS, optarg,
8314 popt->index - QEMU_OPTION_fda);
8315 break;
8316 #ifdef TARGET_I386
8317 case QEMU_OPTION_no_fd_bootchk:
8318 fd_bootchk = 0;
8319 break;
8320 #endif
8321 case QEMU_OPTION_no_code_copy:
8322 code_copy_enabled = 0;
8323 break;
8324 case QEMU_OPTION_net:
8325 if (nb_net_clients >= MAX_NET_CLIENTS) {
8326 fprintf(stderr, "qemu: too many network clients\n");
8327 exit(1);
8329 pstrcpy(net_clients[nb_net_clients],
8330 sizeof(net_clients[0]),
8331 optarg);
8332 nb_net_clients++;
8333 break;
8334 #ifdef CONFIG_SLIRP
8335 case QEMU_OPTION_tftp:
8336 tftp_prefix = optarg;
8337 break;
8338 case QEMU_OPTION_bootp:
8339 bootp_filename = optarg;
8340 break;
8341 #ifndef _WIN32
8342 case QEMU_OPTION_smb:
8343 net_slirp_smb(optarg);
8344 break;
8345 #endif
8346 case QEMU_OPTION_redir:
8347 net_slirp_redir(optarg);
8348 break;
8349 #endif
8350 #ifdef HAS_AUDIO
8351 case QEMU_OPTION_audio_help:
8352 AUD_help ();
8353 exit (0);
8354 break;
8355 case QEMU_OPTION_soundhw:
8356 select_soundhw (optarg);
8357 break;
8358 #endif
8359 case QEMU_OPTION_h:
8360 help(0);
8361 break;
8362 case QEMU_OPTION_m:
8363 ram_size = atoi(optarg) * 1024 * 1024;
8364 if (ram_size <= 0)
8365 help(1);
8366 if (ram_size > PHYS_RAM_MAX_SIZE) {
8367 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8368 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8369 exit(1);
8371 break;
8372 case QEMU_OPTION_d:
8374 int mask;
8375 CPULogItem *item;
8377 mask = cpu_str_to_log_mask(optarg);
8378 if (!mask) {
8379 printf("Log items (comma separated):\n");
8380 for(item = cpu_log_items; item->mask != 0; item++) {
8381 printf("%-10s %s\n", item->name, item->help);
8383 exit(1);
8385 cpu_set_log(mask);
8387 break;
8388 #ifdef CONFIG_GDBSTUB
8389 case QEMU_OPTION_s:
8390 use_gdbstub = 1;
8391 break;
8392 case QEMU_OPTION_p:
8393 gdbstub_port = optarg;
8394 break;
8395 #endif
8396 case QEMU_OPTION_L:
8397 bios_dir = optarg;
8398 break;
8399 case QEMU_OPTION_bios:
8400 bios_name = optarg;
8401 break;
8402 case QEMU_OPTION_S:
8403 autostart = 0;
8404 break;
8405 case QEMU_OPTION_k:
8406 keyboard_layout = optarg;
8407 break;
8408 case QEMU_OPTION_localtime:
8409 rtc_utc = 0;
8410 break;
8411 case QEMU_OPTION_cirrusvga:
8412 cirrus_vga_enabled = 1;
8413 vmsvga_enabled = 0;
8414 break;
8415 case QEMU_OPTION_vmsvga:
8416 cirrus_vga_enabled = 0;
8417 vmsvga_enabled = 1;
8418 break;
8419 case QEMU_OPTION_std_vga:
8420 cirrus_vga_enabled = 0;
8421 vmsvga_enabled = 0;
8422 break;
8423 case QEMU_OPTION_g:
8425 const char *p;
8426 int w, h, depth;
8427 p = optarg;
8428 w = strtol(p, (char **)&p, 10);
8429 if (w <= 0) {
8430 graphic_error:
8431 fprintf(stderr, "qemu: invalid resolution or depth\n");
8432 exit(1);
8434 if (*p != 'x')
8435 goto graphic_error;
8436 p++;
8437 h = strtol(p, (char **)&p, 10);
8438 if (h <= 0)
8439 goto graphic_error;
8440 if (*p == 'x') {
8441 p++;
8442 depth = strtol(p, (char **)&p, 10);
8443 if (depth != 8 && depth != 15 && depth != 16 &&
8444 depth != 24 && depth != 32)
8445 goto graphic_error;
8446 } else if (*p == '\0') {
8447 depth = graphic_depth;
8448 } else {
8449 goto graphic_error;
8452 graphic_width = w;
8453 graphic_height = h;
8454 graphic_depth = depth;
8456 break;
8457 case QEMU_OPTION_echr:
8459 char *r;
8460 term_escape_char = strtol(optarg, &r, 0);
8461 if (r == optarg)
8462 printf("Bad argument to echr\n");
8463 break;
8465 case QEMU_OPTION_monitor:
8466 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8467 break;
8468 case QEMU_OPTION_serial:
8469 if (serial_device_index >= MAX_SERIAL_PORTS) {
8470 fprintf(stderr, "qemu: too many serial ports\n");
8471 exit(1);
8473 pstrcpy(serial_devices[serial_device_index],
8474 sizeof(serial_devices[0]), optarg);
8475 serial_device_index++;
8476 break;
8477 case QEMU_OPTION_parallel:
8478 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8479 fprintf(stderr, "qemu: too many parallel ports\n");
8480 exit(1);
8482 pstrcpy(parallel_devices[parallel_device_index],
8483 sizeof(parallel_devices[0]), optarg);
8484 parallel_device_index++;
8485 break;
8486 case QEMU_OPTION_loadvm:
8487 loadvm = optarg;
8488 break;
8489 case QEMU_OPTION_full_screen:
8490 full_screen = 1;
8491 break;
8492 #ifdef CONFIG_SDL
8493 case QEMU_OPTION_no_frame:
8494 no_frame = 1;
8495 break;
8496 case QEMU_OPTION_alt_grab:
8497 alt_grab = 1;
8498 break;
8499 case QEMU_OPTION_no_quit:
8500 no_quit = 1;
8501 break;
8502 #endif
8503 case QEMU_OPTION_pidfile:
8504 pid_file = optarg;
8505 break;
8506 #ifdef TARGET_I386
8507 case QEMU_OPTION_win2k_hack:
8508 win2k_install_hack = 1;
8509 break;
8510 #endif
8511 #ifdef USE_KQEMU
8512 case QEMU_OPTION_no_kqemu:
8513 kqemu_allowed = 0;
8514 break;
8515 case QEMU_OPTION_kernel_kqemu:
8516 kqemu_allowed = 2;
8517 break;
8518 #endif
8519 case QEMU_OPTION_usb:
8520 usb_enabled = 1;
8521 break;
8522 case QEMU_OPTION_usbdevice:
8523 usb_enabled = 1;
8524 if (usb_devices_index >= MAX_USB_CMDLINE) {
8525 fprintf(stderr, "Too many USB devices\n");
8526 exit(1);
8528 pstrcpy(usb_devices[usb_devices_index],
8529 sizeof(usb_devices[usb_devices_index]),
8530 optarg);
8531 usb_devices_index++;
8532 break;
8533 case QEMU_OPTION_smp:
8534 smp_cpus = atoi(optarg);
8535 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8536 fprintf(stderr, "Invalid number of CPUs\n");
8537 exit(1);
8539 break;
8540 case QEMU_OPTION_vnc:
8541 vnc_display = optarg;
8542 break;
8543 case QEMU_OPTION_no_acpi:
8544 acpi_enabled = 0;
8545 break;
8546 case QEMU_OPTION_no_reboot:
8547 no_reboot = 1;
8548 break;
8549 case QEMU_OPTION_show_cursor:
8550 cursor_hide = 0;
8551 break;
8552 case QEMU_OPTION_daemonize:
8553 daemonize = 1;
8554 break;
8555 case QEMU_OPTION_option_rom:
8556 if (nb_option_roms >= MAX_OPTION_ROMS) {
8557 fprintf(stderr, "Too many option ROMs\n");
8558 exit(1);
8560 option_rom[nb_option_roms] = optarg;
8561 nb_option_roms++;
8562 break;
8563 case QEMU_OPTION_semihosting:
8564 semihosting_enabled = 1;
8565 break;
8566 case QEMU_OPTION_name:
8567 qemu_name = optarg;
8568 break;
8569 #ifdef TARGET_SPARC
8570 case QEMU_OPTION_prom_env:
8571 if (nb_prom_envs >= MAX_PROM_ENVS) {
8572 fprintf(stderr, "Too many prom variables\n");
8573 exit(1);
8575 prom_envs[nb_prom_envs] = optarg;
8576 nb_prom_envs++;
8577 break;
8578 #endif
8579 #ifdef TARGET_ARM
8580 case QEMU_OPTION_old_param:
8581 old_param = 1;
8582 #endif
8583 case QEMU_OPTION_clock:
8584 configure_alarms(optarg);
8585 break;
8586 case QEMU_OPTION_startdate:
8588 struct tm tm;
8589 if (!strcmp(optarg, "now")) {
8590 rtc_start_date = -1;
8591 } else {
8592 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8593 &tm.tm_year,
8594 &tm.tm_mon,
8595 &tm.tm_mday,
8596 &tm.tm_hour,
8597 &tm.tm_min,
8598 &tm.tm_sec) == 6) {
8599 /* OK */
8600 } else if (sscanf(optarg, "%d-%d-%d",
8601 &tm.tm_year,
8602 &tm.tm_mon,
8603 &tm.tm_mday) == 3) {
8604 tm.tm_hour = 0;
8605 tm.tm_min = 0;
8606 tm.tm_sec = 0;
8607 } else {
8608 goto date_fail;
8610 tm.tm_year -= 1900;
8611 tm.tm_mon--;
8612 rtc_start_date = mktimegm(&tm);
8613 if (rtc_start_date == -1) {
8614 date_fail:
8615 fprintf(stderr, "Invalid date format. Valid format are:\n"
8616 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8617 exit(1);
8621 break;
8626 #ifndef _WIN32
8627 if (daemonize && !nographic && vnc_display == NULL) {
8628 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8629 daemonize = 0;
8632 if (daemonize) {
8633 pid_t pid;
8635 if (pipe(fds) == -1)
8636 exit(1);
8638 pid = fork();
8639 if (pid > 0) {
8640 uint8_t status;
8641 ssize_t len;
8643 close(fds[1]);
8645 again:
8646 len = read(fds[0], &status, 1);
8647 if (len == -1 && (errno == EINTR))
8648 goto again;
8650 if (len != 1)
8651 exit(1);
8652 else if (status == 1) {
8653 fprintf(stderr, "Could not acquire pidfile\n");
8654 exit(1);
8655 } else
8656 exit(0);
8657 } else if (pid < 0)
8658 exit(1);
8660 setsid();
8662 pid = fork();
8663 if (pid > 0)
8664 exit(0);
8665 else if (pid < 0)
8666 exit(1);
8668 umask(027);
8669 chdir("/");
8671 signal(SIGTSTP, SIG_IGN);
8672 signal(SIGTTOU, SIG_IGN);
8673 signal(SIGTTIN, SIG_IGN);
8675 #endif
8677 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8678 if (daemonize) {
8679 uint8_t status = 1;
8680 write(fds[1], &status, 1);
8681 } else
8682 fprintf(stderr, "Could not acquire pid file\n");
8683 exit(1);
8686 #ifdef USE_KQEMU
8687 if (smp_cpus > 1)
8688 kqemu_allowed = 0;
8689 #endif
8690 linux_boot = (kernel_filename != NULL);
8691 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8693 /* XXX: this should not be: some embedded targets just have flash */
8694 if (!linux_boot && net_boot == 0 &&
8695 nb_drives_opt == 0)
8696 help(1);
8698 /* boot to floppy or the default cd if no hard disk defined yet */
8699 if (!boot_devices[0]) {
8700 boot_devices = "cad";
8702 setvbuf(stdout, NULL, _IOLBF, 0);
8704 init_timers();
8705 init_timer_alarm();
8706 qemu_aio_init();
8708 #ifdef _WIN32
8709 socket_init();
8710 #endif
8712 /* init network clients */
8713 if (nb_net_clients == 0) {
8714 /* if no clients, we use a default config */
8715 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8716 "nic");
8717 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8718 "user");
8719 nb_net_clients = 2;
8722 for(i = 0;i < nb_net_clients; i++) {
8723 if (net_client_init(net_clients[i]) < 0)
8724 exit(1);
8726 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8727 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8728 continue;
8729 if (vlan->nb_guest_devs == 0) {
8730 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8731 exit(1);
8733 if (vlan->nb_host_devs == 0)
8734 fprintf(stderr,
8735 "Warning: vlan %d is not connected to host network\n",
8736 vlan->id);
8739 #ifdef TARGET_I386
8740 /* XXX: this should be moved in the PC machine instantiation code */
8741 if (net_boot != 0) {
8742 int netroms = 0;
8743 for (i = 0; i < nb_nics && i < 4; i++) {
8744 const char *model = nd_table[i].model;
8745 char buf[1024];
8746 if (net_boot & (1 << i)) {
8747 if (model == NULL)
8748 model = "ne2k_pci";
8749 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8750 if (get_image_size(buf) > 0) {
8751 if (nb_option_roms >= MAX_OPTION_ROMS) {
8752 fprintf(stderr, "Too many option ROMs\n");
8753 exit(1);
8755 option_rom[nb_option_roms] = strdup(buf);
8756 nb_option_roms++;
8757 netroms++;
8761 if (netroms == 0) {
8762 fprintf(stderr, "No valid PXE rom found for network device\n");
8763 exit(1);
8766 #endif
8768 /* init the memory */
8769 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8771 phys_ram_base = qemu_vmalloc(phys_ram_size);
8772 if (!phys_ram_base) {
8773 fprintf(stderr, "Could not allocate physical memory\n");
8774 exit(1);
8777 bdrv_init();
8779 /* we always create the cdrom drive, even if no disk is there */
8781 if (nb_drives_opt < MAX_DRIVES)
8782 drive_add(CDROM_ALIAS);
8784 /* we always create at least one floppy */
8786 if (nb_drives_opt < MAX_DRIVES)
8787 drive_add(FD_ALIAS, 0);
8789 /* we always create one sd slot, even if no card is in it */
8791 if (nb_drives_opt < MAX_DRIVES)
8792 drive_add(SD_ALIAS);
8794 /* open the virtual block devices */
8796 for(i = 0; i < nb_drives_opt; i++)
8797 if (drive_init(drives_opt[i], snapshot, machine) == -1)
8798 exit(1);
8800 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8801 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8803 init_ioports();
8805 /* terminal init */
8806 memset(&display_state, 0, sizeof(display_state));
8807 if (nographic) {
8808 /* nearly nothing to do */
8809 dumb_display_init(ds);
8810 } else if (vnc_display != NULL) {
8811 vnc_display_init(ds);
8812 if (vnc_display_open(ds, vnc_display) < 0)
8813 exit(1);
8814 } else {
8815 #if defined(CONFIG_SDL)
8816 sdl_display_init(ds, full_screen, no_frame);
8817 #elif defined(CONFIG_COCOA)
8818 cocoa_display_init(ds, full_screen);
8819 #else
8820 dumb_display_init(ds);
8821 #endif
8824 /* Maintain compatibility with multiple stdio monitors */
8825 if (!strcmp(monitor_device,"stdio")) {
8826 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8827 if (!strcmp(serial_devices[i],"mon:stdio")) {
8828 monitor_device[0] = '\0';
8829 break;
8830 } else if (!strcmp(serial_devices[i],"stdio")) {
8831 monitor_device[0] = '\0';
8832 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8833 break;
8837 if (monitor_device[0] != '\0') {
8838 monitor_hd = qemu_chr_open(monitor_device);
8839 if (!monitor_hd) {
8840 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8841 exit(1);
8843 monitor_init(monitor_hd, !nographic);
8846 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8847 const char *devname = serial_devices[i];
8848 if (devname[0] != '\0' && strcmp(devname, "none")) {
8849 serial_hds[i] = qemu_chr_open(devname);
8850 if (!serial_hds[i]) {
8851 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8852 devname);
8853 exit(1);
8855 if (strstart(devname, "vc", 0))
8856 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8860 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8861 const char *devname = parallel_devices[i];
8862 if (devname[0] != '\0' && strcmp(devname, "none")) {
8863 parallel_hds[i] = qemu_chr_open(devname);
8864 if (!parallel_hds[i]) {
8865 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8866 devname);
8867 exit(1);
8869 if (strstart(devname, "vc", 0))
8870 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8874 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8875 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8877 /* init USB devices */
8878 if (usb_enabled) {
8879 for(i = 0; i < usb_devices_index; i++) {
8880 if (usb_device_add(usb_devices[i]) < 0) {
8881 fprintf(stderr, "Warning: could not add USB device %s\n",
8882 usb_devices[i]);
8887 if (display_state.dpy_refresh) {
8888 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8889 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8892 #ifdef CONFIG_GDBSTUB
8893 if (use_gdbstub) {
8894 /* XXX: use standard host:port notation and modify options
8895 accordingly. */
8896 if (gdbserver_start(gdbstub_port) < 0) {
8897 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8898 gdbstub_port);
8899 exit(1);
8902 #endif
8904 if (loadvm)
8905 do_loadvm(loadvm);
8908 /* XXX: simplify init */
8909 read_passwords();
8910 if (autostart) {
8911 vm_start();
8915 if (daemonize) {
8916 uint8_t status = 0;
8917 ssize_t len;
8918 int fd;
8920 again1:
8921 len = write(fds[1], &status, 1);
8922 if (len == -1 && (errno == EINTR))
8923 goto again1;
8925 if (len != 1)
8926 exit(1);
8928 TFR(fd = open("/dev/null", O_RDWR));
8929 if (fd == -1)
8930 exit(1);
8932 dup2(fd, 0);
8933 dup2(fd, 1);
8934 dup2(fd, 2);
8936 close(fd);
8939 main_loop();
8940 quit_timers();
8942 #if !defined(_WIN32)
8943 /* close network clients */
8944 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8945 VLANClientState *vc;
8947 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8948 if (vc->fd_read == tap_receive) {
8949 char ifname[64];
8950 TAPState *s = vc->opaque;
8952 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8953 s->down_script[0])
8954 launch_script(s->down_script, ifname, s->fd);
8958 #endif
8959 return 0;