Fix typo which broke MIPS32R2 64-bit FPU support.
[qemu/qemu_0_9_1_stable.git] / vl.c
blob6d9c82297adebdb49d6e3b682683fed891074a4f
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 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 <mmsystem.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
825 #define ALARM_FLAG_EXPIRED 0x2
827 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
829 return t->flags & ALARM_FLAG_DYNTICKS;
832 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
834 if (!alarm_has_dynticks(t))
835 return;
837 t->rearm(t);
840 /* TODO: MIN_TIMER_REARM_US should be optimized */
841 #define MIN_TIMER_REARM_US 250
843 static struct qemu_alarm_timer *alarm_timer;
845 #ifdef _WIN32
847 struct qemu_alarm_win32 {
848 MMRESULT timerId;
849 HANDLE host_alarm;
850 unsigned int period;
851 } alarm_win32_data = {0, NULL, -1};
853 static int win32_start_timer(struct qemu_alarm_timer *t);
854 static void win32_stop_timer(struct qemu_alarm_timer *t);
855 static void win32_rearm_timer(struct qemu_alarm_timer *t);
857 #else
859 static int unix_start_timer(struct qemu_alarm_timer *t);
860 static void unix_stop_timer(struct qemu_alarm_timer *t);
862 #ifdef __linux__
864 static int dynticks_start_timer(struct qemu_alarm_timer *t);
865 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
866 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
868 static int hpet_start_timer(struct qemu_alarm_timer *t);
869 static void hpet_stop_timer(struct qemu_alarm_timer *t);
871 static int rtc_start_timer(struct qemu_alarm_timer *t);
872 static void rtc_stop_timer(struct qemu_alarm_timer *t);
874 #endif /* __linux__ */
876 #endif /* _WIN32 */
878 static struct qemu_alarm_timer alarm_timers[] = {
879 #ifndef _WIN32
880 #ifdef __linux__
881 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
882 dynticks_stop_timer, dynticks_rearm_timer, NULL},
883 /* HPET - if available - is preferred */
884 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
885 /* ...otherwise try RTC */
886 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
887 #endif
888 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
889 #else
890 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
891 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
892 {"win32", 0, win32_start_timer,
893 win32_stop_timer, NULL, &alarm_win32_data},
894 #endif
895 {NULL, }
898 static void show_available_alarms()
900 int i;
902 printf("Available alarm timers, in order of precedence:\n");
903 for (i = 0; alarm_timers[i].name; i++)
904 printf("%s\n", alarm_timers[i].name);
907 static void configure_alarms(char const *opt)
909 int i;
910 int cur = 0;
911 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
912 char *arg;
913 char *name;
915 if (!strcmp(opt, "help")) {
916 show_available_alarms();
917 exit(0);
920 arg = strdup(opt);
922 /* Reorder the array */
923 name = strtok(arg, ",");
924 while (name) {
925 struct qemu_alarm_timer tmp;
927 for (i = 0; i < count && alarm_timers[i].name; i++) {
928 if (!strcmp(alarm_timers[i].name, name))
929 break;
932 if (i == count) {
933 fprintf(stderr, "Unknown clock %s\n", name);
934 goto next;
937 if (i < cur)
938 /* Ignore */
939 goto next;
941 /* Swap */
942 tmp = alarm_timers[i];
943 alarm_timers[i] = alarm_timers[cur];
944 alarm_timers[cur] = tmp;
946 cur++;
947 next:
948 name = strtok(NULL, ",");
951 free(arg);
953 if (cur) {
954 /* Disable remaining timers */
955 for (i = cur; i < count; i++)
956 alarm_timers[i].name = NULL;
959 /* debug */
960 show_available_alarms();
963 QEMUClock *rt_clock;
964 QEMUClock *vm_clock;
966 static QEMUTimer *active_timers[2];
968 static QEMUClock *qemu_new_clock(int type)
970 QEMUClock *clock;
971 clock = qemu_mallocz(sizeof(QEMUClock));
972 if (!clock)
973 return NULL;
974 clock->type = type;
975 return clock;
978 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
980 QEMUTimer *ts;
982 ts = qemu_mallocz(sizeof(QEMUTimer));
983 ts->clock = clock;
984 ts->cb = cb;
985 ts->opaque = opaque;
986 return ts;
989 void qemu_free_timer(QEMUTimer *ts)
991 qemu_free(ts);
994 /* stop a timer, but do not dealloc it */
995 void qemu_del_timer(QEMUTimer *ts)
997 QEMUTimer **pt, *t;
999 /* NOTE: this code must be signal safe because
1000 qemu_timer_expired() can be called from a signal. */
1001 pt = &active_timers[ts->clock->type];
1002 for(;;) {
1003 t = *pt;
1004 if (!t)
1005 break;
1006 if (t == ts) {
1007 *pt = t->next;
1008 break;
1010 pt = &t->next;
1014 /* modify the current timer so that it will be fired when current_time
1015 >= expire_time. The corresponding callback will be called. */
1016 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1018 QEMUTimer **pt, *t;
1020 qemu_del_timer(ts);
1022 /* add the timer in the sorted list */
1023 /* NOTE: this code must be signal safe because
1024 qemu_timer_expired() can be called from a signal. */
1025 pt = &active_timers[ts->clock->type];
1026 for(;;) {
1027 t = *pt;
1028 if (!t)
1029 break;
1030 if (t->expire_time > expire_time)
1031 break;
1032 pt = &t->next;
1034 ts->expire_time = expire_time;
1035 ts->next = *pt;
1036 *pt = ts;
1038 /* Rearm if necessary */
1039 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1040 pt == &active_timers[ts->clock->type])
1041 qemu_rearm_alarm_timer(alarm_timer);
1044 int qemu_timer_pending(QEMUTimer *ts)
1046 QEMUTimer *t;
1047 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1048 if (t == ts)
1049 return 1;
1051 return 0;
1054 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1056 if (!timer_head)
1057 return 0;
1058 return (timer_head->expire_time <= current_time);
1061 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1063 QEMUTimer *ts;
1065 for(;;) {
1066 ts = *ptimer_head;
1067 if (!ts || ts->expire_time > current_time)
1068 break;
1069 /* remove timer from the list before calling the callback */
1070 *ptimer_head = ts->next;
1071 ts->next = NULL;
1073 /* run the callback (the timer list can be modified) */
1074 ts->cb(ts->opaque);
1078 int64_t qemu_get_clock(QEMUClock *clock)
1080 switch(clock->type) {
1081 case QEMU_TIMER_REALTIME:
1082 return get_clock() / 1000000;
1083 default:
1084 case QEMU_TIMER_VIRTUAL:
1085 return cpu_get_clock();
1089 static void init_timers(void)
1091 init_get_clock();
1092 ticks_per_sec = QEMU_TIMER_BASE;
1093 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1094 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1097 /* save a timer */
1098 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1100 uint64_t expire_time;
1102 if (qemu_timer_pending(ts)) {
1103 expire_time = ts->expire_time;
1104 } else {
1105 expire_time = -1;
1107 qemu_put_be64(f, expire_time);
1110 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1112 uint64_t expire_time;
1114 expire_time = qemu_get_be64(f);
1115 if (expire_time != -1) {
1116 qemu_mod_timer(ts, expire_time);
1117 } else {
1118 qemu_del_timer(ts);
1122 static void timer_save(QEMUFile *f, void *opaque)
1124 if (cpu_ticks_enabled) {
1125 hw_error("cannot save state if virtual timers are running");
1127 qemu_put_be64(f, cpu_ticks_offset);
1128 qemu_put_be64(f, ticks_per_sec);
1129 qemu_put_be64(f, cpu_clock_offset);
1132 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1134 if (version_id != 1 && version_id != 2)
1135 return -EINVAL;
1136 if (cpu_ticks_enabled) {
1137 return -EINVAL;
1139 cpu_ticks_offset=qemu_get_be64(f);
1140 ticks_per_sec=qemu_get_be64(f);
1141 if (version_id == 2) {
1142 cpu_clock_offset=qemu_get_be64(f);
1144 return 0;
1147 #ifdef _WIN32
1148 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1149 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1150 #else
1151 static void host_alarm_handler(int host_signum)
1152 #endif
1154 #if 0
1155 #define DISP_FREQ 1000
1157 static int64_t delta_min = INT64_MAX;
1158 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1159 static int count;
1160 ti = qemu_get_clock(vm_clock);
1161 if (last_clock != 0) {
1162 delta = ti - last_clock;
1163 if (delta < delta_min)
1164 delta_min = delta;
1165 if (delta > delta_max)
1166 delta_max = delta;
1167 delta_cum += delta;
1168 if (++count == DISP_FREQ) {
1169 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1170 muldiv64(delta_min, 1000000, ticks_per_sec),
1171 muldiv64(delta_max, 1000000, ticks_per_sec),
1172 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1173 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1174 count = 0;
1175 delta_min = INT64_MAX;
1176 delta_max = 0;
1177 delta_cum = 0;
1180 last_clock = ti;
1182 #endif
1183 if (alarm_has_dynticks(alarm_timer) ||
1184 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1185 qemu_get_clock(vm_clock)) ||
1186 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1187 qemu_get_clock(rt_clock))) {
1188 #ifdef _WIN32
1189 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1190 SetEvent(data->host_alarm);
1191 #endif
1192 CPUState *env = next_cpu;
1194 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1196 if (env) {
1197 /* stop the currently executing cpu because a timer occured */
1198 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1199 #ifdef USE_KQEMU
1200 if (env->kqemu_enabled) {
1201 kqemu_cpu_interrupt(env);
1203 #endif
1205 event_pending = 1;
1209 static uint64_t qemu_next_deadline(void)
1211 int64_t nearest_delta_us = INT64_MAX;
1212 int64_t vmdelta_us;
1214 if (active_timers[QEMU_TIMER_REALTIME])
1215 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1216 qemu_get_clock(rt_clock))*1000;
1218 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1219 /* round up */
1220 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1221 qemu_get_clock(vm_clock)+999)/1000;
1222 if (vmdelta_us < nearest_delta_us)
1223 nearest_delta_us = vmdelta_us;
1226 /* Avoid arming the timer to negative, zero, or too low values */
1227 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1228 nearest_delta_us = MIN_TIMER_REARM_US;
1230 return nearest_delta_us;
1233 #ifndef _WIN32
1235 #if defined(__linux__)
1237 #define RTC_FREQ 1024
1239 static void enable_sigio_timer(int fd)
1241 struct sigaction act;
1243 /* timer signal */
1244 sigfillset(&act.sa_mask);
1245 act.sa_flags = 0;
1246 act.sa_handler = host_alarm_handler;
1248 sigaction(SIGIO, &act, NULL);
1249 fcntl(fd, F_SETFL, O_ASYNC);
1250 fcntl(fd, F_SETOWN, getpid());
1253 static int hpet_start_timer(struct qemu_alarm_timer *t)
1255 struct hpet_info info;
1256 int r, fd;
1258 fd = open("/dev/hpet", O_RDONLY);
1259 if (fd < 0)
1260 return -1;
1262 /* Set frequency */
1263 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1264 if (r < 0) {
1265 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1266 "error, but for better emulation accuracy type:\n"
1267 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1268 goto fail;
1271 /* Check capabilities */
1272 r = ioctl(fd, HPET_INFO, &info);
1273 if (r < 0)
1274 goto fail;
1276 /* Enable periodic mode */
1277 r = ioctl(fd, HPET_EPI, 0);
1278 if (info.hi_flags && (r < 0))
1279 goto fail;
1281 /* Enable interrupt */
1282 r = ioctl(fd, HPET_IE_ON, 0);
1283 if (r < 0)
1284 goto fail;
1286 enable_sigio_timer(fd);
1287 t->priv = (void *)(long)fd;
1289 return 0;
1290 fail:
1291 close(fd);
1292 return -1;
1295 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1297 int fd = (long)t->priv;
1299 close(fd);
1302 static int rtc_start_timer(struct qemu_alarm_timer *t)
1304 int rtc_fd;
1306 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1307 if (rtc_fd < 0)
1308 return -1;
1309 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1310 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1311 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1312 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1313 goto fail;
1315 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1316 fail:
1317 close(rtc_fd);
1318 return -1;
1321 enable_sigio_timer(rtc_fd);
1323 t->priv = (void *)(long)rtc_fd;
1325 return 0;
1328 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1330 int rtc_fd = (long)t->priv;
1332 close(rtc_fd);
1335 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1337 struct sigevent ev;
1338 timer_t host_timer;
1339 struct sigaction act;
1341 sigfillset(&act.sa_mask);
1342 act.sa_flags = 0;
1343 act.sa_handler = host_alarm_handler;
1345 sigaction(SIGALRM, &act, NULL);
1347 ev.sigev_value.sival_int = 0;
1348 ev.sigev_notify = SIGEV_SIGNAL;
1349 ev.sigev_signo = SIGALRM;
1351 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1352 perror("timer_create");
1354 /* disable dynticks */
1355 fprintf(stderr, "Dynamic Ticks disabled\n");
1357 return -1;
1360 t->priv = (void *)host_timer;
1362 return 0;
1365 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1367 timer_t host_timer = (timer_t)t->priv;
1369 timer_delete(host_timer);
1372 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1374 timer_t host_timer = (timer_t)t->priv;
1375 struct itimerspec timeout;
1376 int64_t nearest_delta_us = INT64_MAX;
1377 int64_t current_us;
1379 if (!active_timers[QEMU_TIMER_REALTIME] &&
1380 !active_timers[QEMU_TIMER_VIRTUAL])
1381 return;
1383 nearest_delta_us = qemu_next_deadline();
1385 /* check whether a timer is already running */
1386 if (timer_gettime(host_timer, &timeout)) {
1387 perror("gettime");
1388 fprintf(stderr, "Internal timer error: aborting\n");
1389 exit(1);
1391 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1392 if (current_us && current_us <= nearest_delta_us)
1393 return;
1395 timeout.it_interval.tv_sec = 0;
1396 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1397 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1398 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1399 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1400 perror("settime");
1401 fprintf(stderr, "Internal timer error: aborting\n");
1402 exit(1);
1406 #endif /* defined(__linux__) */
1408 static int unix_start_timer(struct qemu_alarm_timer *t)
1410 struct sigaction act;
1411 struct itimerval itv;
1412 int err;
1414 /* timer signal */
1415 sigfillset(&act.sa_mask);
1416 act.sa_flags = 0;
1417 act.sa_handler = host_alarm_handler;
1419 sigaction(SIGALRM, &act, NULL);
1421 itv.it_interval.tv_sec = 0;
1422 /* for i386 kernel 2.6 to get 1 ms */
1423 itv.it_interval.tv_usec = 999;
1424 itv.it_value.tv_sec = 0;
1425 itv.it_value.tv_usec = 10 * 1000;
1427 err = setitimer(ITIMER_REAL, &itv, NULL);
1428 if (err)
1429 return -1;
1431 return 0;
1434 static void unix_stop_timer(struct qemu_alarm_timer *t)
1436 struct itimerval itv;
1438 memset(&itv, 0, sizeof(itv));
1439 setitimer(ITIMER_REAL, &itv, NULL);
1442 #endif /* !defined(_WIN32) */
1444 #ifdef _WIN32
1446 static int win32_start_timer(struct qemu_alarm_timer *t)
1448 TIMECAPS tc;
1449 struct qemu_alarm_win32 *data = t->priv;
1450 UINT flags;
1452 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1453 if (!data->host_alarm) {
1454 perror("Failed CreateEvent");
1455 return -1;
1458 memset(&tc, 0, sizeof(tc));
1459 timeGetDevCaps(&tc, sizeof(tc));
1461 if (data->period < tc.wPeriodMin)
1462 data->period = tc.wPeriodMin;
1464 timeBeginPeriod(data->period);
1466 flags = TIME_CALLBACK_FUNCTION;
1467 if (alarm_has_dynticks(t))
1468 flags |= TIME_ONESHOT;
1469 else
1470 flags |= TIME_PERIODIC;
1472 data->timerId = timeSetEvent(1, // interval (ms)
1473 data->period, // resolution
1474 host_alarm_handler, // function
1475 (DWORD)t, // parameter
1476 flags);
1478 if (!data->timerId) {
1479 perror("Failed to initialize win32 alarm timer");
1481 timeEndPeriod(data->period);
1482 CloseHandle(data->host_alarm);
1483 return -1;
1486 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1488 return 0;
1491 static void win32_stop_timer(struct qemu_alarm_timer *t)
1493 struct qemu_alarm_win32 *data = t->priv;
1495 timeKillEvent(data->timerId);
1496 timeEndPeriod(data->period);
1498 CloseHandle(data->host_alarm);
1501 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1503 struct qemu_alarm_win32 *data = t->priv;
1504 uint64_t nearest_delta_us;
1506 if (!active_timers[QEMU_TIMER_REALTIME] &&
1507 !active_timers[QEMU_TIMER_VIRTUAL])
1508 return;
1510 nearest_delta_us = qemu_next_deadline();
1511 nearest_delta_us /= 1000;
1513 timeKillEvent(data->timerId);
1515 data->timerId = timeSetEvent(1,
1516 data->period,
1517 host_alarm_handler,
1518 (DWORD)t,
1519 TIME_ONESHOT | TIME_PERIODIC);
1521 if (!data->timerId) {
1522 perror("Failed to re-arm win32 alarm timer");
1524 timeEndPeriod(data->period);
1525 CloseHandle(data->host_alarm);
1526 exit(1);
1530 #endif /* _WIN32 */
1532 static void init_timer_alarm(void)
1534 struct qemu_alarm_timer *t;
1535 int i, err = -1;
1537 for (i = 0; alarm_timers[i].name; i++) {
1538 t = &alarm_timers[i];
1540 err = t->start(t);
1541 if (!err)
1542 break;
1545 if (err) {
1546 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1547 fprintf(stderr, "Terminating\n");
1548 exit(1);
1551 alarm_timer = t;
1554 static void quit_timers(void)
1556 alarm_timer->stop(alarm_timer);
1557 alarm_timer = NULL;
1560 /***********************************************************/
1561 /* character device */
1563 static void qemu_chr_event(CharDriverState *s, int event)
1565 if (!s->chr_event)
1566 return;
1567 s->chr_event(s->handler_opaque, event);
1570 static void qemu_chr_reset_bh(void *opaque)
1572 CharDriverState *s = opaque;
1573 qemu_chr_event(s, CHR_EVENT_RESET);
1574 qemu_bh_delete(s->bh);
1575 s->bh = NULL;
1578 void qemu_chr_reset(CharDriverState *s)
1580 if (s->bh == NULL) {
1581 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1582 qemu_bh_schedule(s->bh);
1586 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1588 return s->chr_write(s, buf, len);
1591 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1593 if (!s->chr_ioctl)
1594 return -ENOTSUP;
1595 return s->chr_ioctl(s, cmd, arg);
1598 int qemu_chr_can_read(CharDriverState *s)
1600 if (!s->chr_can_read)
1601 return 0;
1602 return s->chr_can_read(s->handler_opaque);
1605 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1607 s->chr_read(s->handler_opaque, buf, len);
1610 void qemu_chr_accept_input(CharDriverState *s)
1612 if (s->chr_accept_input)
1613 s->chr_accept_input(s);
1616 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1618 char buf[4096];
1619 va_list ap;
1620 va_start(ap, fmt);
1621 vsnprintf(buf, sizeof(buf), fmt, ap);
1622 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1623 va_end(ap);
1626 void qemu_chr_send_event(CharDriverState *s, int event)
1628 if (s->chr_send_event)
1629 s->chr_send_event(s, event);
1632 void qemu_chr_add_handlers(CharDriverState *s,
1633 IOCanRWHandler *fd_can_read,
1634 IOReadHandler *fd_read,
1635 IOEventHandler *fd_event,
1636 void *opaque)
1638 s->chr_can_read = fd_can_read;
1639 s->chr_read = fd_read;
1640 s->chr_event = fd_event;
1641 s->handler_opaque = opaque;
1642 if (s->chr_update_read_handler)
1643 s->chr_update_read_handler(s);
1646 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1648 return len;
1651 static CharDriverState *qemu_chr_open_null(void)
1653 CharDriverState *chr;
1655 chr = qemu_mallocz(sizeof(CharDriverState));
1656 if (!chr)
1657 return NULL;
1658 chr->chr_write = null_chr_write;
1659 return chr;
1662 /* MUX driver for serial I/O splitting */
1663 static int term_timestamps;
1664 static int64_t term_timestamps_start;
1665 #define MAX_MUX 4
1666 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1667 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1668 typedef struct {
1669 IOCanRWHandler *chr_can_read[MAX_MUX];
1670 IOReadHandler *chr_read[MAX_MUX];
1671 IOEventHandler *chr_event[MAX_MUX];
1672 void *ext_opaque[MAX_MUX];
1673 CharDriverState *drv;
1674 unsigned char buffer[MUX_BUFFER_SIZE];
1675 int prod;
1676 int cons;
1677 int mux_cnt;
1678 int term_got_escape;
1679 int max_size;
1680 } MuxDriver;
1683 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1685 MuxDriver *d = chr->opaque;
1686 int ret;
1687 if (!term_timestamps) {
1688 ret = d->drv->chr_write(d->drv, buf, len);
1689 } else {
1690 int i;
1692 ret = 0;
1693 for(i = 0; i < len; i++) {
1694 ret += d->drv->chr_write(d->drv, buf+i, 1);
1695 if (buf[i] == '\n') {
1696 char buf1[64];
1697 int64_t ti;
1698 int secs;
1700 ti = get_clock();
1701 if (term_timestamps_start == -1)
1702 term_timestamps_start = ti;
1703 ti -= term_timestamps_start;
1704 secs = ti / 1000000000;
1705 snprintf(buf1, sizeof(buf1),
1706 "[%02d:%02d:%02d.%03d] ",
1707 secs / 3600,
1708 (secs / 60) % 60,
1709 secs % 60,
1710 (int)((ti / 1000000) % 1000));
1711 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1715 return ret;
1718 static char *mux_help[] = {
1719 "% h print this help\n\r",
1720 "% x exit emulator\n\r",
1721 "% s save disk data back to file (if -snapshot)\n\r",
1722 "% t toggle console timestamps\n\r"
1723 "% b send break (magic sysrq)\n\r",
1724 "% c switch between console and monitor\n\r",
1725 "% % sends %\n\r",
1726 NULL
1729 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1730 static void mux_print_help(CharDriverState *chr)
1732 int i, j;
1733 char ebuf[15] = "Escape-Char";
1734 char cbuf[50] = "\n\r";
1736 if (term_escape_char > 0 && term_escape_char < 26) {
1737 sprintf(cbuf,"\n\r");
1738 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1739 } else {
1740 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1741 term_escape_char);
1743 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1744 for (i = 0; mux_help[i] != NULL; i++) {
1745 for (j=0; mux_help[i][j] != '\0'; j++) {
1746 if (mux_help[i][j] == '%')
1747 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1748 else
1749 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1754 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1756 if (d->term_got_escape) {
1757 d->term_got_escape = 0;
1758 if (ch == term_escape_char)
1759 goto send_char;
1760 switch(ch) {
1761 case '?':
1762 case 'h':
1763 mux_print_help(chr);
1764 break;
1765 case 'x':
1767 char *term = "QEMU: Terminated\n\r";
1768 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1769 exit(0);
1770 break;
1772 case 's':
1774 int i;
1775 for (i = 0; i < nb_drives; i++) {
1776 bdrv_commit(drives_table[i].bdrv);
1779 break;
1780 case 'b':
1781 qemu_chr_event(chr, CHR_EVENT_BREAK);
1782 break;
1783 case 'c':
1784 /* Switch to the next registered device */
1785 chr->focus++;
1786 if (chr->focus >= d->mux_cnt)
1787 chr->focus = 0;
1788 break;
1789 case 't':
1790 term_timestamps = !term_timestamps;
1791 term_timestamps_start = -1;
1792 break;
1794 } else if (ch == term_escape_char) {
1795 d->term_got_escape = 1;
1796 } else {
1797 send_char:
1798 return 1;
1800 return 0;
1803 static void mux_chr_accept_input(CharDriverState *chr)
1805 int m = chr->focus;
1806 MuxDriver *d = chr->opaque;
1808 while (d->prod != d->cons &&
1809 d->chr_can_read[m] &&
1810 d->chr_can_read[m](d->ext_opaque[m])) {
1811 d->chr_read[m](d->ext_opaque[m],
1812 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1816 static int mux_chr_can_read(void *opaque)
1818 CharDriverState *chr = opaque;
1819 MuxDriver *d = chr->opaque;
1821 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1822 return 1;
1823 if (d->chr_can_read[chr->focus])
1824 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1825 return 0;
1828 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1830 CharDriverState *chr = opaque;
1831 MuxDriver *d = chr->opaque;
1832 int m = chr->focus;
1833 int i;
1835 mux_chr_accept_input (opaque);
1837 for(i = 0; i < size; i++)
1838 if (mux_proc_byte(chr, d, buf[i])) {
1839 if (d->prod == d->cons &&
1840 d->chr_can_read[m] &&
1841 d->chr_can_read[m](d->ext_opaque[m]))
1842 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1843 else
1844 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1848 static void mux_chr_event(void *opaque, int event)
1850 CharDriverState *chr = opaque;
1851 MuxDriver *d = chr->opaque;
1852 int i;
1854 /* Send the event to all registered listeners */
1855 for (i = 0; i < d->mux_cnt; i++)
1856 if (d->chr_event[i])
1857 d->chr_event[i](d->ext_opaque[i], event);
1860 static void mux_chr_update_read_handler(CharDriverState *chr)
1862 MuxDriver *d = chr->opaque;
1864 if (d->mux_cnt >= MAX_MUX) {
1865 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1866 return;
1868 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1869 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1870 d->chr_read[d->mux_cnt] = chr->chr_read;
1871 d->chr_event[d->mux_cnt] = chr->chr_event;
1872 /* Fix up the real driver with mux routines */
1873 if (d->mux_cnt == 0) {
1874 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1875 mux_chr_event, chr);
1877 chr->focus = d->mux_cnt;
1878 d->mux_cnt++;
1881 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1883 CharDriverState *chr;
1884 MuxDriver *d;
1886 chr = qemu_mallocz(sizeof(CharDriverState));
1887 if (!chr)
1888 return NULL;
1889 d = qemu_mallocz(sizeof(MuxDriver));
1890 if (!d) {
1891 free(chr);
1892 return NULL;
1895 chr->opaque = d;
1896 d->drv = drv;
1897 chr->focus = -1;
1898 chr->chr_write = mux_chr_write;
1899 chr->chr_update_read_handler = mux_chr_update_read_handler;
1900 chr->chr_accept_input = mux_chr_accept_input;
1901 return chr;
1905 #ifdef _WIN32
1907 static void socket_cleanup(void)
1909 WSACleanup();
1912 static int socket_init(void)
1914 WSADATA Data;
1915 int ret, err;
1917 ret = WSAStartup(MAKEWORD(2,2), &Data);
1918 if (ret != 0) {
1919 err = WSAGetLastError();
1920 fprintf(stderr, "WSAStartup: %d\n", err);
1921 return -1;
1923 atexit(socket_cleanup);
1924 return 0;
1927 static int send_all(int fd, const uint8_t *buf, int len1)
1929 int ret, len;
1931 len = len1;
1932 while (len > 0) {
1933 ret = send(fd, buf, len, 0);
1934 if (ret < 0) {
1935 int errno;
1936 errno = WSAGetLastError();
1937 if (errno != WSAEWOULDBLOCK) {
1938 return -1;
1940 } else if (ret == 0) {
1941 break;
1942 } else {
1943 buf += ret;
1944 len -= ret;
1947 return len1 - len;
1950 void socket_set_nonblock(int fd)
1952 unsigned long opt = 1;
1953 ioctlsocket(fd, FIONBIO, &opt);
1956 #else
1958 static int unix_write(int fd, const uint8_t *buf, int len1)
1960 int ret, len;
1962 len = len1;
1963 while (len > 0) {
1964 ret = write(fd, buf, len);
1965 if (ret < 0) {
1966 if (errno != EINTR && errno != EAGAIN)
1967 return -1;
1968 } else if (ret == 0) {
1969 break;
1970 } else {
1971 buf += ret;
1972 len -= ret;
1975 return len1 - len;
1978 static inline int send_all(int fd, const uint8_t *buf, int len1)
1980 return unix_write(fd, buf, len1);
1983 void socket_set_nonblock(int fd)
1985 fcntl(fd, F_SETFL, O_NONBLOCK);
1987 #endif /* !_WIN32 */
1989 #ifndef _WIN32
1991 typedef struct {
1992 int fd_in, fd_out;
1993 int max_size;
1994 } FDCharDriver;
1996 #define STDIO_MAX_CLIENTS 1
1997 static int stdio_nb_clients = 0;
1999 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2001 FDCharDriver *s = chr->opaque;
2002 return unix_write(s->fd_out, buf, len);
2005 static int fd_chr_read_poll(void *opaque)
2007 CharDriverState *chr = opaque;
2008 FDCharDriver *s = chr->opaque;
2010 s->max_size = qemu_chr_can_read(chr);
2011 return s->max_size;
2014 static void fd_chr_read(void *opaque)
2016 CharDriverState *chr = opaque;
2017 FDCharDriver *s = chr->opaque;
2018 int size, len;
2019 uint8_t buf[1024];
2021 len = sizeof(buf);
2022 if (len > s->max_size)
2023 len = s->max_size;
2024 if (len == 0)
2025 return;
2026 size = read(s->fd_in, buf, len);
2027 if (size == 0) {
2028 /* FD has been closed. Remove it from the active list. */
2029 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2030 return;
2032 if (size > 0) {
2033 qemu_chr_read(chr, buf, size);
2037 static void fd_chr_update_read_handler(CharDriverState *chr)
2039 FDCharDriver *s = chr->opaque;
2041 if (s->fd_in >= 0) {
2042 if (nographic && s->fd_in == 0) {
2043 } else {
2044 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2045 fd_chr_read, NULL, chr);
2050 /* open a character device to a unix fd */
2051 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2053 CharDriverState *chr;
2054 FDCharDriver *s;
2056 chr = qemu_mallocz(sizeof(CharDriverState));
2057 if (!chr)
2058 return NULL;
2059 s = qemu_mallocz(sizeof(FDCharDriver));
2060 if (!s) {
2061 free(chr);
2062 return NULL;
2064 s->fd_in = fd_in;
2065 s->fd_out = fd_out;
2066 chr->opaque = s;
2067 chr->chr_write = fd_chr_write;
2068 chr->chr_update_read_handler = fd_chr_update_read_handler;
2070 qemu_chr_reset(chr);
2072 return chr;
2075 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2077 int fd_out;
2079 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2080 if (fd_out < 0)
2081 return NULL;
2082 return qemu_chr_open_fd(-1, fd_out);
2085 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2087 int fd_in, fd_out;
2088 char filename_in[256], filename_out[256];
2090 snprintf(filename_in, 256, "%s.in", filename);
2091 snprintf(filename_out, 256, "%s.out", filename);
2092 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2093 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2094 if (fd_in < 0 || fd_out < 0) {
2095 if (fd_in >= 0)
2096 close(fd_in);
2097 if (fd_out >= 0)
2098 close(fd_out);
2099 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2100 if (fd_in < 0)
2101 return NULL;
2103 return qemu_chr_open_fd(fd_in, fd_out);
2107 /* for STDIO, we handle the case where several clients use it
2108 (nographic mode) */
2110 #define TERM_FIFO_MAX_SIZE 1
2112 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2113 static int term_fifo_size;
2115 static int stdio_read_poll(void *opaque)
2117 CharDriverState *chr = opaque;
2119 /* try to flush the queue if needed */
2120 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2121 qemu_chr_read(chr, term_fifo, 1);
2122 term_fifo_size = 0;
2124 /* see if we can absorb more chars */
2125 if (term_fifo_size == 0)
2126 return 1;
2127 else
2128 return 0;
2131 static void stdio_read(void *opaque)
2133 int size;
2134 uint8_t buf[1];
2135 CharDriverState *chr = opaque;
2137 size = read(0, buf, 1);
2138 if (size == 0) {
2139 /* stdin has been closed. Remove it from the active list. */
2140 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2141 return;
2143 if (size > 0) {
2144 if (qemu_chr_can_read(chr) > 0) {
2145 qemu_chr_read(chr, buf, 1);
2146 } else if (term_fifo_size == 0) {
2147 term_fifo[term_fifo_size++] = buf[0];
2152 /* init terminal so that we can grab keys */
2153 static struct termios oldtty;
2154 static int old_fd0_flags;
2156 static void term_exit(void)
2158 tcsetattr (0, TCSANOW, &oldtty);
2159 fcntl(0, F_SETFL, old_fd0_flags);
2162 static void term_init(void)
2164 struct termios tty;
2166 tcgetattr (0, &tty);
2167 oldtty = tty;
2168 old_fd0_flags = fcntl(0, F_GETFL);
2170 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2171 |INLCR|IGNCR|ICRNL|IXON);
2172 tty.c_oflag |= OPOST;
2173 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2174 /* if graphical mode, we allow Ctrl-C handling */
2175 if (nographic)
2176 tty.c_lflag &= ~ISIG;
2177 tty.c_cflag &= ~(CSIZE|PARENB);
2178 tty.c_cflag |= CS8;
2179 tty.c_cc[VMIN] = 1;
2180 tty.c_cc[VTIME] = 0;
2182 tcsetattr (0, TCSANOW, &tty);
2184 atexit(term_exit);
2186 fcntl(0, F_SETFL, O_NONBLOCK);
2189 static CharDriverState *qemu_chr_open_stdio(void)
2191 CharDriverState *chr;
2193 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2194 return NULL;
2195 chr = qemu_chr_open_fd(0, 1);
2196 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2197 stdio_nb_clients++;
2198 term_init();
2200 return chr;
2203 #if defined(__linux__) || defined(__sun__)
2204 static CharDriverState *qemu_chr_open_pty(void)
2206 struct termios tty;
2207 char slave_name[1024];
2208 int master_fd, slave_fd;
2210 #if defined(__linux__)
2211 /* Not satisfying */
2212 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2213 return NULL;
2215 #endif
2217 /* Disabling local echo and line-buffered output */
2218 tcgetattr (master_fd, &tty);
2219 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2220 tty.c_cc[VMIN] = 1;
2221 tty.c_cc[VTIME] = 0;
2222 tcsetattr (master_fd, TCSAFLUSH, &tty);
2224 fprintf(stderr, "char device redirected to %s\n", slave_name);
2225 return qemu_chr_open_fd(master_fd, master_fd);
2228 static void tty_serial_init(int fd, int speed,
2229 int parity, int data_bits, int stop_bits)
2231 struct termios tty;
2232 speed_t spd;
2234 #if 0
2235 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2236 speed, parity, data_bits, stop_bits);
2237 #endif
2238 tcgetattr (fd, &tty);
2240 switch(speed) {
2241 case 50:
2242 spd = B50;
2243 break;
2244 case 75:
2245 spd = B75;
2246 break;
2247 case 300:
2248 spd = B300;
2249 break;
2250 case 600:
2251 spd = B600;
2252 break;
2253 case 1200:
2254 spd = B1200;
2255 break;
2256 case 2400:
2257 spd = B2400;
2258 break;
2259 case 4800:
2260 spd = B4800;
2261 break;
2262 case 9600:
2263 spd = B9600;
2264 break;
2265 case 19200:
2266 spd = B19200;
2267 break;
2268 case 38400:
2269 spd = B38400;
2270 break;
2271 case 57600:
2272 spd = B57600;
2273 break;
2274 default:
2275 case 115200:
2276 spd = B115200;
2277 break;
2280 cfsetispeed(&tty, spd);
2281 cfsetospeed(&tty, spd);
2283 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2284 |INLCR|IGNCR|ICRNL|IXON);
2285 tty.c_oflag |= OPOST;
2286 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2287 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2288 switch(data_bits) {
2289 default:
2290 case 8:
2291 tty.c_cflag |= CS8;
2292 break;
2293 case 7:
2294 tty.c_cflag |= CS7;
2295 break;
2296 case 6:
2297 tty.c_cflag |= CS6;
2298 break;
2299 case 5:
2300 tty.c_cflag |= CS5;
2301 break;
2303 switch(parity) {
2304 default:
2305 case 'N':
2306 break;
2307 case 'E':
2308 tty.c_cflag |= PARENB;
2309 break;
2310 case 'O':
2311 tty.c_cflag |= PARENB | PARODD;
2312 break;
2314 if (stop_bits == 2)
2315 tty.c_cflag |= CSTOPB;
2317 tcsetattr (fd, TCSANOW, &tty);
2320 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2322 FDCharDriver *s = chr->opaque;
2324 switch(cmd) {
2325 case CHR_IOCTL_SERIAL_SET_PARAMS:
2327 QEMUSerialSetParams *ssp = arg;
2328 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2329 ssp->data_bits, ssp->stop_bits);
2331 break;
2332 case CHR_IOCTL_SERIAL_SET_BREAK:
2334 int enable = *(int *)arg;
2335 if (enable)
2336 tcsendbreak(s->fd_in, 1);
2338 break;
2339 default:
2340 return -ENOTSUP;
2342 return 0;
2345 static CharDriverState *qemu_chr_open_tty(const char *filename)
2347 CharDriverState *chr;
2348 int fd;
2350 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2351 fcntl(fd, F_SETFL, O_NONBLOCK);
2352 tty_serial_init(fd, 115200, 'N', 8, 1);
2353 chr = qemu_chr_open_fd(fd, fd);
2354 if (!chr) {
2355 close(fd);
2356 return NULL;
2358 chr->chr_ioctl = tty_serial_ioctl;
2359 qemu_chr_reset(chr);
2360 return chr;
2362 #else /* ! __linux__ && ! __sun__ */
2363 static CharDriverState *qemu_chr_open_pty(void)
2365 return NULL;
2367 #endif /* __linux__ || __sun__ */
2369 #if defined(__linux__)
2370 typedef struct {
2371 int fd;
2372 int mode;
2373 } ParallelCharDriver;
2375 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2377 if (s->mode != mode) {
2378 int m = mode;
2379 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2380 return 0;
2381 s->mode = mode;
2383 return 1;
2386 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2388 ParallelCharDriver *drv = chr->opaque;
2389 int fd = drv->fd;
2390 uint8_t b;
2392 switch(cmd) {
2393 case CHR_IOCTL_PP_READ_DATA:
2394 if (ioctl(fd, PPRDATA, &b) < 0)
2395 return -ENOTSUP;
2396 *(uint8_t *)arg = b;
2397 break;
2398 case CHR_IOCTL_PP_WRITE_DATA:
2399 b = *(uint8_t *)arg;
2400 if (ioctl(fd, PPWDATA, &b) < 0)
2401 return -ENOTSUP;
2402 break;
2403 case CHR_IOCTL_PP_READ_CONTROL:
2404 if (ioctl(fd, PPRCONTROL, &b) < 0)
2405 return -ENOTSUP;
2406 /* Linux gives only the lowest bits, and no way to know data
2407 direction! For better compatibility set the fixed upper
2408 bits. */
2409 *(uint8_t *)arg = b | 0xc0;
2410 break;
2411 case CHR_IOCTL_PP_WRITE_CONTROL:
2412 b = *(uint8_t *)arg;
2413 if (ioctl(fd, PPWCONTROL, &b) < 0)
2414 return -ENOTSUP;
2415 break;
2416 case CHR_IOCTL_PP_READ_STATUS:
2417 if (ioctl(fd, PPRSTATUS, &b) < 0)
2418 return -ENOTSUP;
2419 *(uint8_t *)arg = b;
2420 break;
2421 case CHR_IOCTL_PP_EPP_READ_ADDR:
2422 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
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_READ:
2431 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2432 struct ParallelIOArg *parg = arg;
2433 int n = read(fd, parg->buffer, parg->count);
2434 if (n != parg->count) {
2435 return -EIO;
2438 break;
2439 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2440 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
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 case CHR_IOCTL_PP_EPP_WRITE:
2449 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2450 struct ParallelIOArg *parg = arg;
2451 int n = write(fd, parg->buffer, parg->count);
2452 if (n != parg->count) {
2453 return -EIO;
2456 break;
2457 default:
2458 return -ENOTSUP;
2460 return 0;
2463 static void pp_close(CharDriverState *chr)
2465 ParallelCharDriver *drv = chr->opaque;
2466 int fd = drv->fd;
2468 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2469 ioctl(fd, PPRELEASE);
2470 close(fd);
2471 qemu_free(drv);
2474 static CharDriverState *qemu_chr_open_pp(const char *filename)
2476 CharDriverState *chr;
2477 ParallelCharDriver *drv;
2478 int fd;
2480 TFR(fd = open(filename, O_RDWR));
2481 if (fd < 0)
2482 return NULL;
2484 if (ioctl(fd, PPCLAIM) < 0) {
2485 close(fd);
2486 return NULL;
2489 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2490 if (!drv) {
2491 close(fd);
2492 return NULL;
2494 drv->fd = fd;
2495 drv->mode = IEEE1284_MODE_COMPAT;
2497 chr = qemu_mallocz(sizeof(CharDriverState));
2498 if (!chr) {
2499 qemu_free(drv);
2500 close(fd);
2501 return NULL;
2503 chr->chr_write = null_chr_write;
2504 chr->chr_ioctl = pp_ioctl;
2505 chr->chr_close = pp_close;
2506 chr->opaque = drv;
2508 qemu_chr_reset(chr);
2510 return chr;
2512 #endif /* __linux__ */
2514 #else /* _WIN32 */
2516 typedef struct {
2517 int max_size;
2518 HANDLE hcom, hrecv, hsend;
2519 OVERLAPPED orecv, osend;
2520 BOOL fpipe;
2521 DWORD len;
2522 } WinCharState;
2524 #define NSENDBUF 2048
2525 #define NRECVBUF 2048
2526 #define MAXCONNECT 1
2527 #define NTIMEOUT 5000
2529 static int win_chr_poll(void *opaque);
2530 static int win_chr_pipe_poll(void *opaque);
2532 static void win_chr_close(CharDriverState *chr)
2534 WinCharState *s = chr->opaque;
2536 if (s->hsend) {
2537 CloseHandle(s->hsend);
2538 s->hsend = NULL;
2540 if (s->hrecv) {
2541 CloseHandle(s->hrecv);
2542 s->hrecv = NULL;
2544 if (s->hcom) {
2545 CloseHandle(s->hcom);
2546 s->hcom = NULL;
2548 if (s->fpipe)
2549 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2550 else
2551 qemu_del_polling_cb(win_chr_poll, chr);
2554 static int win_chr_init(CharDriverState *chr, const char *filename)
2556 WinCharState *s = chr->opaque;
2557 COMMCONFIG comcfg;
2558 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2559 COMSTAT comstat;
2560 DWORD size;
2561 DWORD err;
2563 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2564 if (!s->hsend) {
2565 fprintf(stderr, "Failed CreateEvent\n");
2566 goto fail;
2568 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2569 if (!s->hrecv) {
2570 fprintf(stderr, "Failed CreateEvent\n");
2571 goto fail;
2574 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2575 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2576 if (s->hcom == INVALID_HANDLE_VALUE) {
2577 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2578 s->hcom = NULL;
2579 goto fail;
2582 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2583 fprintf(stderr, "Failed SetupComm\n");
2584 goto fail;
2587 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2588 size = sizeof(COMMCONFIG);
2589 GetDefaultCommConfig(filename, &comcfg, &size);
2590 comcfg.dcb.DCBlength = sizeof(DCB);
2591 CommConfigDialog(filename, NULL, &comcfg);
2593 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2594 fprintf(stderr, "Failed SetCommState\n");
2595 goto fail;
2598 if (!SetCommMask(s->hcom, EV_ERR)) {
2599 fprintf(stderr, "Failed SetCommMask\n");
2600 goto fail;
2603 cto.ReadIntervalTimeout = MAXDWORD;
2604 if (!SetCommTimeouts(s->hcom, &cto)) {
2605 fprintf(stderr, "Failed SetCommTimeouts\n");
2606 goto fail;
2609 if (!ClearCommError(s->hcom, &err, &comstat)) {
2610 fprintf(stderr, "Failed ClearCommError\n");
2611 goto fail;
2613 qemu_add_polling_cb(win_chr_poll, chr);
2614 return 0;
2616 fail:
2617 win_chr_close(chr);
2618 return -1;
2621 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2623 WinCharState *s = chr->opaque;
2624 DWORD len, ret, size, err;
2626 len = len1;
2627 ZeroMemory(&s->osend, sizeof(s->osend));
2628 s->osend.hEvent = s->hsend;
2629 while (len > 0) {
2630 if (s->hsend)
2631 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2632 else
2633 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2634 if (!ret) {
2635 err = GetLastError();
2636 if (err == ERROR_IO_PENDING) {
2637 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2638 if (ret) {
2639 buf += size;
2640 len -= size;
2641 } else {
2642 break;
2644 } else {
2645 break;
2647 } else {
2648 buf += size;
2649 len -= size;
2652 return len1 - len;
2655 static int win_chr_read_poll(CharDriverState *chr)
2657 WinCharState *s = chr->opaque;
2659 s->max_size = qemu_chr_can_read(chr);
2660 return s->max_size;
2663 static void win_chr_readfile(CharDriverState *chr)
2665 WinCharState *s = chr->opaque;
2666 int ret, err;
2667 uint8_t buf[1024];
2668 DWORD size;
2670 ZeroMemory(&s->orecv, sizeof(s->orecv));
2671 s->orecv.hEvent = s->hrecv;
2672 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2673 if (!ret) {
2674 err = GetLastError();
2675 if (err == ERROR_IO_PENDING) {
2676 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2680 if (size > 0) {
2681 qemu_chr_read(chr, buf, size);
2685 static void win_chr_read(CharDriverState *chr)
2687 WinCharState *s = chr->opaque;
2689 if (s->len > s->max_size)
2690 s->len = s->max_size;
2691 if (s->len == 0)
2692 return;
2694 win_chr_readfile(chr);
2697 static int win_chr_poll(void *opaque)
2699 CharDriverState *chr = opaque;
2700 WinCharState *s = chr->opaque;
2701 COMSTAT status;
2702 DWORD comerr;
2704 ClearCommError(s->hcom, &comerr, &status);
2705 if (status.cbInQue > 0) {
2706 s->len = status.cbInQue;
2707 win_chr_read_poll(chr);
2708 win_chr_read(chr);
2709 return 1;
2711 return 0;
2714 static CharDriverState *qemu_chr_open_win(const char *filename)
2716 CharDriverState *chr;
2717 WinCharState *s;
2719 chr = qemu_mallocz(sizeof(CharDriverState));
2720 if (!chr)
2721 return NULL;
2722 s = qemu_mallocz(sizeof(WinCharState));
2723 if (!s) {
2724 free(chr);
2725 return NULL;
2727 chr->opaque = s;
2728 chr->chr_write = win_chr_write;
2729 chr->chr_close = win_chr_close;
2731 if (win_chr_init(chr, filename) < 0) {
2732 free(s);
2733 free(chr);
2734 return NULL;
2736 qemu_chr_reset(chr);
2737 return chr;
2740 static int win_chr_pipe_poll(void *opaque)
2742 CharDriverState *chr = opaque;
2743 WinCharState *s = chr->opaque;
2744 DWORD size;
2746 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2747 if (size > 0) {
2748 s->len = size;
2749 win_chr_read_poll(chr);
2750 win_chr_read(chr);
2751 return 1;
2753 return 0;
2756 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2758 WinCharState *s = chr->opaque;
2759 OVERLAPPED ov;
2760 int ret;
2761 DWORD size;
2762 char openname[256];
2764 s->fpipe = TRUE;
2766 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2767 if (!s->hsend) {
2768 fprintf(stderr, "Failed CreateEvent\n");
2769 goto fail;
2771 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2772 if (!s->hrecv) {
2773 fprintf(stderr, "Failed CreateEvent\n");
2774 goto fail;
2777 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2778 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2779 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2780 PIPE_WAIT,
2781 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2782 if (s->hcom == INVALID_HANDLE_VALUE) {
2783 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2784 s->hcom = NULL;
2785 goto fail;
2788 ZeroMemory(&ov, sizeof(ov));
2789 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2790 ret = ConnectNamedPipe(s->hcom, &ov);
2791 if (ret) {
2792 fprintf(stderr, "Failed ConnectNamedPipe\n");
2793 goto fail;
2796 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2797 if (!ret) {
2798 fprintf(stderr, "Failed GetOverlappedResult\n");
2799 if (ov.hEvent) {
2800 CloseHandle(ov.hEvent);
2801 ov.hEvent = NULL;
2803 goto fail;
2806 if (ov.hEvent) {
2807 CloseHandle(ov.hEvent);
2808 ov.hEvent = NULL;
2810 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2811 return 0;
2813 fail:
2814 win_chr_close(chr);
2815 return -1;
2819 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2821 CharDriverState *chr;
2822 WinCharState *s;
2824 chr = qemu_mallocz(sizeof(CharDriverState));
2825 if (!chr)
2826 return NULL;
2827 s = qemu_mallocz(sizeof(WinCharState));
2828 if (!s) {
2829 free(chr);
2830 return NULL;
2832 chr->opaque = s;
2833 chr->chr_write = win_chr_write;
2834 chr->chr_close = win_chr_close;
2836 if (win_chr_pipe_init(chr, filename) < 0) {
2837 free(s);
2838 free(chr);
2839 return NULL;
2841 qemu_chr_reset(chr);
2842 return chr;
2845 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2847 CharDriverState *chr;
2848 WinCharState *s;
2850 chr = qemu_mallocz(sizeof(CharDriverState));
2851 if (!chr)
2852 return NULL;
2853 s = qemu_mallocz(sizeof(WinCharState));
2854 if (!s) {
2855 free(chr);
2856 return NULL;
2858 s->hcom = fd_out;
2859 chr->opaque = s;
2860 chr->chr_write = win_chr_write;
2861 qemu_chr_reset(chr);
2862 return chr;
2865 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2867 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2870 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2872 HANDLE fd_out;
2874 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2875 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2876 if (fd_out == INVALID_HANDLE_VALUE)
2877 return NULL;
2879 return qemu_chr_open_win_file(fd_out);
2881 #endif /* !_WIN32 */
2883 /***********************************************************/
2884 /* UDP Net console */
2886 typedef struct {
2887 int fd;
2888 struct sockaddr_in daddr;
2889 uint8_t buf[1024];
2890 int bufcnt;
2891 int bufptr;
2892 int max_size;
2893 } NetCharDriver;
2895 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2897 NetCharDriver *s = chr->opaque;
2899 return sendto(s->fd, buf, len, 0,
2900 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2903 static int udp_chr_read_poll(void *opaque)
2905 CharDriverState *chr = opaque;
2906 NetCharDriver *s = chr->opaque;
2908 s->max_size = qemu_chr_can_read(chr);
2910 /* If there were any stray characters in the queue process them
2911 * first
2913 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2914 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2915 s->bufptr++;
2916 s->max_size = qemu_chr_can_read(chr);
2918 return s->max_size;
2921 static void udp_chr_read(void *opaque)
2923 CharDriverState *chr = opaque;
2924 NetCharDriver *s = chr->opaque;
2926 if (s->max_size == 0)
2927 return;
2928 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2929 s->bufptr = s->bufcnt;
2930 if (s->bufcnt <= 0)
2931 return;
2933 s->bufptr = 0;
2934 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2935 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2936 s->bufptr++;
2937 s->max_size = qemu_chr_can_read(chr);
2941 static void udp_chr_update_read_handler(CharDriverState *chr)
2943 NetCharDriver *s = chr->opaque;
2945 if (s->fd >= 0) {
2946 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2947 udp_chr_read, NULL, chr);
2951 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2952 #ifndef _WIN32
2953 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2954 #endif
2955 int parse_host_src_port(struct sockaddr_in *haddr,
2956 struct sockaddr_in *saddr,
2957 const char *str);
2959 static CharDriverState *qemu_chr_open_udp(const char *def)
2961 CharDriverState *chr = NULL;
2962 NetCharDriver *s = NULL;
2963 int fd = -1;
2964 struct sockaddr_in saddr;
2966 chr = qemu_mallocz(sizeof(CharDriverState));
2967 if (!chr)
2968 goto return_err;
2969 s = qemu_mallocz(sizeof(NetCharDriver));
2970 if (!s)
2971 goto return_err;
2973 fd = socket(PF_INET, SOCK_DGRAM, 0);
2974 if (fd < 0) {
2975 perror("socket(PF_INET, SOCK_DGRAM)");
2976 goto return_err;
2979 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2980 printf("Could not parse: %s\n", def);
2981 goto return_err;
2984 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2986 perror("bind");
2987 goto return_err;
2990 s->fd = fd;
2991 s->bufcnt = 0;
2992 s->bufptr = 0;
2993 chr->opaque = s;
2994 chr->chr_write = udp_chr_write;
2995 chr->chr_update_read_handler = udp_chr_update_read_handler;
2996 return chr;
2998 return_err:
2999 if (chr)
3000 free(chr);
3001 if (s)
3002 free(s);
3003 if (fd >= 0)
3004 closesocket(fd);
3005 return NULL;
3008 /***********************************************************/
3009 /* TCP Net console */
3011 typedef struct {
3012 int fd, listen_fd;
3013 int connected;
3014 int max_size;
3015 int do_telnetopt;
3016 int do_nodelay;
3017 int is_unix;
3018 } TCPCharDriver;
3020 static void tcp_chr_accept(void *opaque);
3022 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3024 TCPCharDriver *s = chr->opaque;
3025 if (s->connected) {
3026 return send_all(s->fd, buf, len);
3027 } else {
3028 /* XXX: indicate an error ? */
3029 return len;
3033 static int tcp_chr_read_poll(void *opaque)
3035 CharDriverState *chr = opaque;
3036 TCPCharDriver *s = chr->opaque;
3037 if (!s->connected)
3038 return 0;
3039 s->max_size = qemu_chr_can_read(chr);
3040 return s->max_size;
3043 #define IAC 255
3044 #define IAC_BREAK 243
3045 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3046 TCPCharDriver *s,
3047 uint8_t *buf, int *size)
3049 /* Handle any telnet client's basic IAC options to satisfy char by
3050 * char mode with no echo. All IAC options will be removed from
3051 * the buf and the do_telnetopt variable will be used to track the
3052 * state of the width of the IAC information.
3054 * IAC commands come in sets of 3 bytes with the exception of the
3055 * "IAC BREAK" command and the double IAC.
3058 int i;
3059 int j = 0;
3061 for (i = 0; i < *size; i++) {
3062 if (s->do_telnetopt > 1) {
3063 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3064 /* Double IAC means send an IAC */
3065 if (j != i)
3066 buf[j] = buf[i];
3067 j++;
3068 s->do_telnetopt = 1;
3069 } else {
3070 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3071 /* Handle IAC break commands by sending a serial break */
3072 qemu_chr_event(chr, CHR_EVENT_BREAK);
3073 s->do_telnetopt++;
3075 s->do_telnetopt++;
3077 if (s->do_telnetopt >= 4) {
3078 s->do_telnetopt = 1;
3080 } else {
3081 if ((unsigned char)buf[i] == IAC) {
3082 s->do_telnetopt = 2;
3083 } else {
3084 if (j != i)
3085 buf[j] = buf[i];
3086 j++;
3090 *size = j;
3093 static void tcp_chr_read(void *opaque)
3095 CharDriverState *chr = opaque;
3096 TCPCharDriver *s = chr->opaque;
3097 uint8_t buf[1024];
3098 int len, size;
3100 if (!s->connected || s->max_size <= 0)
3101 return;
3102 len = sizeof(buf);
3103 if (len > s->max_size)
3104 len = s->max_size;
3105 size = recv(s->fd, buf, len, 0);
3106 if (size == 0) {
3107 /* connection closed */
3108 s->connected = 0;
3109 if (s->listen_fd >= 0) {
3110 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3112 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3113 closesocket(s->fd);
3114 s->fd = -1;
3115 } else if (size > 0) {
3116 if (s->do_telnetopt)
3117 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3118 if (size > 0)
3119 qemu_chr_read(chr, buf, size);
3123 static void tcp_chr_connect(void *opaque)
3125 CharDriverState *chr = opaque;
3126 TCPCharDriver *s = chr->opaque;
3128 s->connected = 1;
3129 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3130 tcp_chr_read, NULL, chr);
3131 qemu_chr_reset(chr);
3134 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3135 static void tcp_chr_telnet_init(int fd)
3137 char buf[3];
3138 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3139 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3140 send(fd, (char *)buf, 3, 0);
3141 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3142 send(fd, (char *)buf, 3, 0);
3143 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3144 send(fd, (char *)buf, 3, 0);
3145 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3146 send(fd, (char *)buf, 3, 0);
3149 static void socket_set_nodelay(int fd)
3151 int val = 1;
3152 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3155 static void tcp_chr_accept(void *opaque)
3157 CharDriverState *chr = opaque;
3158 TCPCharDriver *s = chr->opaque;
3159 struct sockaddr_in saddr;
3160 #ifndef _WIN32
3161 struct sockaddr_un uaddr;
3162 #endif
3163 struct sockaddr *addr;
3164 socklen_t len;
3165 int fd;
3167 for(;;) {
3168 #ifndef _WIN32
3169 if (s->is_unix) {
3170 len = sizeof(uaddr);
3171 addr = (struct sockaddr *)&uaddr;
3172 } else
3173 #endif
3175 len = sizeof(saddr);
3176 addr = (struct sockaddr *)&saddr;
3178 fd = accept(s->listen_fd, addr, &len);
3179 if (fd < 0 && errno != EINTR) {
3180 return;
3181 } else if (fd >= 0) {
3182 if (s->do_telnetopt)
3183 tcp_chr_telnet_init(fd);
3184 break;
3187 socket_set_nonblock(fd);
3188 if (s->do_nodelay)
3189 socket_set_nodelay(fd);
3190 s->fd = fd;
3191 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3192 tcp_chr_connect(chr);
3195 static void tcp_chr_close(CharDriverState *chr)
3197 TCPCharDriver *s = chr->opaque;
3198 if (s->fd >= 0)
3199 closesocket(s->fd);
3200 if (s->listen_fd >= 0)
3201 closesocket(s->listen_fd);
3202 qemu_free(s);
3205 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3206 int is_telnet,
3207 int is_unix)
3209 CharDriverState *chr = NULL;
3210 TCPCharDriver *s = NULL;
3211 int fd = -1, ret, err, val;
3212 int is_listen = 0;
3213 int is_waitconnect = 1;
3214 int do_nodelay = 0;
3215 const char *ptr;
3216 struct sockaddr_in saddr;
3217 #ifndef _WIN32
3218 struct sockaddr_un uaddr;
3219 #endif
3220 struct sockaddr *addr;
3221 socklen_t addrlen;
3223 #ifndef _WIN32
3224 if (is_unix) {
3225 addr = (struct sockaddr *)&uaddr;
3226 addrlen = sizeof(uaddr);
3227 if (parse_unix_path(&uaddr, host_str) < 0)
3228 goto fail;
3229 } else
3230 #endif
3232 addr = (struct sockaddr *)&saddr;
3233 addrlen = sizeof(saddr);
3234 if (parse_host_port(&saddr, host_str) < 0)
3235 goto fail;
3238 ptr = host_str;
3239 while((ptr = strchr(ptr,','))) {
3240 ptr++;
3241 if (!strncmp(ptr,"server",6)) {
3242 is_listen = 1;
3243 } else if (!strncmp(ptr,"nowait",6)) {
3244 is_waitconnect = 0;
3245 } else if (!strncmp(ptr,"nodelay",6)) {
3246 do_nodelay = 1;
3247 } else {
3248 printf("Unknown option: %s\n", ptr);
3249 goto fail;
3252 if (!is_listen)
3253 is_waitconnect = 0;
3255 chr = qemu_mallocz(sizeof(CharDriverState));
3256 if (!chr)
3257 goto fail;
3258 s = qemu_mallocz(sizeof(TCPCharDriver));
3259 if (!s)
3260 goto fail;
3262 #ifndef _WIN32
3263 if (is_unix)
3264 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3265 else
3266 #endif
3267 fd = socket(PF_INET, SOCK_STREAM, 0);
3269 if (fd < 0)
3270 goto fail;
3272 if (!is_waitconnect)
3273 socket_set_nonblock(fd);
3275 s->connected = 0;
3276 s->fd = -1;
3277 s->listen_fd = -1;
3278 s->is_unix = is_unix;
3279 s->do_nodelay = do_nodelay && !is_unix;
3281 chr->opaque = s;
3282 chr->chr_write = tcp_chr_write;
3283 chr->chr_close = tcp_chr_close;
3285 if (is_listen) {
3286 /* allow fast reuse */
3287 #ifndef _WIN32
3288 if (is_unix) {
3289 char path[109];
3290 strncpy(path, uaddr.sun_path, 108);
3291 path[108] = 0;
3292 unlink(path);
3293 } else
3294 #endif
3296 val = 1;
3297 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3300 ret = bind(fd, addr, addrlen);
3301 if (ret < 0)
3302 goto fail;
3304 ret = listen(fd, 0);
3305 if (ret < 0)
3306 goto fail;
3308 s->listen_fd = fd;
3309 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3310 if (is_telnet)
3311 s->do_telnetopt = 1;
3312 } else {
3313 for(;;) {
3314 ret = connect(fd, addr, addrlen);
3315 if (ret < 0) {
3316 err = socket_error();
3317 if (err == EINTR || err == EWOULDBLOCK) {
3318 } else if (err == EINPROGRESS) {
3319 break;
3320 #ifdef _WIN32
3321 } else if (err == WSAEALREADY) {
3322 break;
3323 #endif
3324 } else {
3325 goto fail;
3327 } else {
3328 s->connected = 1;
3329 break;
3332 s->fd = fd;
3333 socket_set_nodelay(fd);
3334 if (s->connected)
3335 tcp_chr_connect(chr);
3336 else
3337 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3340 if (is_listen && is_waitconnect) {
3341 printf("QEMU waiting for connection on: %s\n", host_str);
3342 tcp_chr_accept(chr);
3343 socket_set_nonblock(s->listen_fd);
3346 return chr;
3347 fail:
3348 if (fd >= 0)
3349 closesocket(fd);
3350 qemu_free(s);
3351 qemu_free(chr);
3352 return NULL;
3355 CharDriverState *qemu_chr_open(const char *filename)
3357 const char *p;
3359 if (!strcmp(filename, "vc")) {
3360 return text_console_init(&display_state, 0);
3361 } else if (strstart(filename, "vc:", &p)) {
3362 return text_console_init(&display_state, p);
3363 } else if (!strcmp(filename, "null")) {
3364 return qemu_chr_open_null();
3365 } else
3366 if (strstart(filename, "tcp:", &p)) {
3367 return qemu_chr_open_tcp(p, 0, 0);
3368 } else
3369 if (strstart(filename, "telnet:", &p)) {
3370 return qemu_chr_open_tcp(p, 1, 0);
3371 } else
3372 if (strstart(filename, "udp:", &p)) {
3373 return qemu_chr_open_udp(p);
3374 } else
3375 if (strstart(filename, "mon:", &p)) {
3376 CharDriverState *drv = qemu_chr_open(p);
3377 if (drv) {
3378 drv = qemu_chr_open_mux(drv);
3379 monitor_init(drv, !nographic);
3380 return drv;
3382 printf("Unable to open driver: %s\n", p);
3383 return 0;
3384 } else
3385 #ifndef _WIN32
3386 if (strstart(filename, "unix:", &p)) {
3387 return qemu_chr_open_tcp(p, 0, 1);
3388 } else if (strstart(filename, "file:", &p)) {
3389 return qemu_chr_open_file_out(p);
3390 } else if (strstart(filename, "pipe:", &p)) {
3391 return qemu_chr_open_pipe(p);
3392 } else if (!strcmp(filename, "pty")) {
3393 return qemu_chr_open_pty();
3394 } else if (!strcmp(filename, "stdio")) {
3395 return qemu_chr_open_stdio();
3396 } else
3397 #if defined(__linux__)
3398 if (strstart(filename, "/dev/parport", NULL)) {
3399 return qemu_chr_open_pp(filename);
3400 } else
3401 #endif
3402 #if defined(__linux__) || defined(__sun__)
3403 if (strstart(filename, "/dev/", NULL)) {
3404 return qemu_chr_open_tty(filename);
3405 } else
3406 #endif
3407 #else /* !_WIN32 */
3408 if (strstart(filename, "COM", NULL)) {
3409 return qemu_chr_open_win(filename);
3410 } else
3411 if (strstart(filename, "pipe:", &p)) {
3412 return qemu_chr_open_win_pipe(p);
3413 } else
3414 if (strstart(filename, "con:", NULL)) {
3415 return qemu_chr_open_win_con(filename);
3416 } else
3417 if (strstart(filename, "file:", &p)) {
3418 return qemu_chr_open_win_file_out(p);
3420 #endif
3422 return NULL;
3426 void qemu_chr_close(CharDriverState *chr)
3428 if (chr->chr_close)
3429 chr->chr_close(chr);
3432 /***********************************************************/
3433 /* network device redirectors */
3435 __attribute__ (( unused ))
3436 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3438 int len, i, j, c;
3440 for(i=0;i<size;i+=16) {
3441 len = size - i;
3442 if (len > 16)
3443 len = 16;
3444 fprintf(f, "%08x ", i);
3445 for(j=0;j<16;j++) {
3446 if (j < len)
3447 fprintf(f, " %02x", buf[i+j]);
3448 else
3449 fprintf(f, " ");
3451 fprintf(f, " ");
3452 for(j=0;j<len;j++) {
3453 c = buf[i+j];
3454 if (c < ' ' || c > '~')
3455 c = '.';
3456 fprintf(f, "%c", c);
3458 fprintf(f, "\n");
3462 static int parse_macaddr(uint8_t *macaddr, const char *p)
3464 int i;
3465 char *last_char;
3466 long int offset;
3468 errno = 0;
3469 offset = strtol(p, &last_char, 0);
3470 if (0 == errno && '\0' == *last_char &&
3471 offset >= 0 && offset <= 0xFFFFFF) {
3472 macaddr[3] = (offset & 0xFF0000) >> 16;
3473 macaddr[4] = (offset & 0xFF00) >> 8;
3474 macaddr[5] = offset & 0xFF;
3475 return 0;
3476 } else {
3477 for(i = 0; i < 6; i++) {
3478 macaddr[i] = strtol(p, (char **)&p, 16);
3479 if (i == 5) {
3480 if (*p != '\0')
3481 return -1;
3482 } else {
3483 if (*p != ':' && *p != '-')
3484 return -1;
3485 p++;
3488 return 0;
3491 return -1;
3494 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3496 const char *p, *p1;
3497 int len;
3498 p = *pp;
3499 p1 = strchr(p, sep);
3500 if (!p1)
3501 return -1;
3502 len = p1 - p;
3503 p1++;
3504 if (buf_size > 0) {
3505 if (len > buf_size - 1)
3506 len = buf_size - 1;
3507 memcpy(buf, p, len);
3508 buf[len] = '\0';
3510 *pp = p1;
3511 return 0;
3514 int parse_host_src_port(struct sockaddr_in *haddr,
3515 struct sockaddr_in *saddr,
3516 const char *input_str)
3518 char *str = strdup(input_str);
3519 char *host_str = str;
3520 char *src_str;
3521 char *ptr;
3524 * Chop off any extra arguments at the end of the string which
3525 * would start with a comma, then fill in the src port information
3526 * if it was provided else use the "any address" and "any port".
3528 if ((ptr = strchr(str,',')))
3529 *ptr = '\0';
3531 if ((src_str = strchr(input_str,'@'))) {
3532 *src_str = '\0';
3533 src_str++;
3536 if (parse_host_port(haddr, host_str) < 0)
3537 goto fail;
3539 if (!src_str || *src_str == '\0')
3540 src_str = ":0";
3542 if (parse_host_port(saddr, src_str) < 0)
3543 goto fail;
3545 free(str);
3546 return(0);
3548 fail:
3549 free(str);
3550 return -1;
3553 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3555 char buf[512];
3556 struct hostent *he;
3557 const char *p, *r;
3558 int port;
3560 p = str;
3561 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3562 return -1;
3563 saddr->sin_family = AF_INET;
3564 if (buf[0] == '\0') {
3565 saddr->sin_addr.s_addr = 0;
3566 } else {
3567 if (isdigit(buf[0])) {
3568 if (!inet_aton(buf, &saddr->sin_addr))
3569 return -1;
3570 } else {
3571 if ((he = gethostbyname(buf)) == NULL)
3572 return - 1;
3573 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3576 port = strtol(p, (char **)&r, 0);
3577 if (r == p)
3578 return -1;
3579 saddr->sin_port = htons(port);
3580 return 0;
3583 #ifndef _WIN32
3584 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3586 const char *p;
3587 int len;
3589 len = MIN(108, strlen(str));
3590 p = strchr(str, ',');
3591 if (p)
3592 len = MIN(len, p - str);
3594 memset(uaddr, 0, sizeof(*uaddr));
3596 uaddr->sun_family = AF_UNIX;
3597 memcpy(uaddr->sun_path, str, len);
3599 return 0;
3601 #endif
3603 /* find or alloc a new VLAN */
3604 VLANState *qemu_find_vlan(int id)
3606 VLANState **pvlan, *vlan;
3607 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3608 if (vlan->id == id)
3609 return vlan;
3611 vlan = qemu_mallocz(sizeof(VLANState));
3612 if (!vlan)
3613 return NULL;
3614 vlan->id = id;
3615 vlan->next = NULL;
3616 pvlan = &first_vlan;
3617 while (*pvlan != NULL)
3618 pvlan = &(*pvlan)->next;
3619 *pvlan = vlan;
3620 return vlan;
3623 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3624 IOReadHandler *fd_read,
3625 IOCanRWHandler *fd_can_read,
3626 void *opaque)
3628 VLANClientState *vc, **pvc;
3629 vc = qemu_mallocz(sizeof(VLANClientState));
3630 if (!vc)
3631 return NULL;
3632 vc->fd_read = fd_read;
3633 vc->fd_can_read = fd_can_read;
3634 vc->opaque = opaque;
3635 vc->vlan = vlan;
3637 vc->next = NULL;
3638 pvc = &vlan->first_client;
3639 while (*pvc != NULL)
3640 pvc = &(*pvc)->next;
3641 *pvc = vc;
3642 return vc;
3645 int qemu_can_send_packet(VLANClientState *vc1)
3647 VLANState *vlan = vc1->vlan;
3648 VLANClientState *vc;
3650 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3651 if (vc != vc1) {
3652 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3653 return 1;
3656 return 0;
3659 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3661 VLANState *vlan = vc1->vlan;
3662 VLANClientState *vc;
3664 #if 0
3665 printf("vlan %d send:\n", vlan->id);
3666 hex_dump(stdout, buf, size);
3667 #endif
3668 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3669 if (vc != vc1) {
3670 vc->fd_read(vc->opaque, buf, size);
3675 #if defined(CONFIG_SLIRP)
3677 /* slirp network adapter */
3679 static int slirp_inited;
3680 static VLANClientState *slirp_vc;
3682 int slirp_can_output(void)
3684 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3687 void slirp_output(const uint8_t *pkt, int pkt_len)
3689 #if 0
3690 printf("slirp output:\n");
3691 hex_dump(stdout, pkt, pkt_len);
3692 #endif
3693 if (!slirp_vc)
3694 return;
3695 qemu_send_packet(slirp_vc, pkt, pkt_len);
3698 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3700 #if 0
3701 printf("slirp input:\n");
3702 hex_dump(stdout, buf, size);
3703 #endif
3704 slirp_input(buf, size);
3707 static int net_slirp_init(VLANState *vlan)
3709 if (!slirp_inited) {
3710 slirp_inited = 1;
3711 slirp_init();
3713 slirp_vc = qemu_new_vlan_client(vlan,
3714 slirp_receive, NULL, NULL);
3715 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3716 return 0;
3719 static void net_slirp_redir(const char *redir_str)
3721 int is_udp;
3722 char buf[256], *r;
3723 const char *p;
3724 struct in_addr guest_addr;
3725 int host_port, guest_port;
3727 if (!slirp_inited) {
3728 slirp_inited = 1;
3729 slirp_init();
3732 p = redir_str;
3733 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3734 goto fail;
3735 if (!strcmp(buf, "tcp")) {
3736 is_udp = 0;
3737 } else if (!strcmp(buf, "udp")) {
3738 is_udp = 1;
3739 } else {
3740 goto fail;
3743 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3744 goto fail;
3745 host_port = strtol(buf, &r, 0);
3746 if (r == buf)
3747 goto fail;
3749 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3750 goto fail;
3751 if (buf[0] == '\0') {
3752 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3754 if (!inet_aton(buf, &guest_addr))
3755 goto fail;
3757 guest_port = strtol(p, &r, 0);
3758 if (r == p)
3759 goto fail;
3761 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3762 fprintf(stderr, "qemu: could not set up redirection\n");
3763 exit(1);
3765 return;
3766 fail:
3767 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3768 exit(1);
3771 #ifndef _WIN32
3773 char smb_dir[1024];
3775 static void smb_exit(void)
3777 DIR *d;
3778 struct dirent *de;
3779 char filename[1024];
3781 /* erase all the files in the directory */
3782 d = opendir(smb_dir);
3783 for(;;) {
3784 de = readdir(d);
3785 if (!de)
3786 break;
3787 if (strcmp(de->d_name, ".") != 0 &&
3788 strcmp(de->d_name, "..") != 0) {
3789 snprintf(filename, sizeof(filename), "%s/%s",
3790 smb_dir, de->d_name);
3791 unlink(filename);
3794 closedir(d);
3795 rmdir(smb_dir);
3798 /* automatic user mode samba server configuration */
3799 static void net_slirp_smb(const char *exported_dir)
3801 char smb_conf[1024];
3802 char smb_cmdline[1024];
3803 FILE *f;
3805 if (!slirp_inited) {
3806 slirp_inited = 1;
3807 slirp_init();
3810 /* XXX: better tmp dir construction */
3811 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3812 if (mkdir(smb_dir, 0700) < 0) {
3813 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3814 exit(1);
3816 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3818 f = fopen(smb_conf, "w");
3819 if (!f) {
3820 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3821 exit(1);
3823 fprintf(f,
3824 "[global]\n"
3825 "private dir=%s\n"
3826 "smb ports=0\n"
3827 "socket address=127.0.0.1\n"
3828 "pid directory=%s\n"
3829 "lock directory=%s\n"
3830 "log file=%s/log.smbd\n"
3831 "smb passwd file=%s/smbpasswd\n"
3832 "security = share\n"
3833 "[qemu]\n"
3834 "path=%s\n"
3835 "read only=no\n"
3836 "guest ok=yes\n",
3837 smb_dir,
3838 smb_dir,
3839 smb_dir,
3840 smb_dir,
3841 smb_dir,
3842 exported_dir
3844 fclose(f);
3845 atexit(smb_exit);
3847 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3848 SMBD_COMMAND, smb_conf);
3850 slirp_add_exec(0, smb_cmdline, 4, 139);
3853 #endif /* !defined(_WIN32) */
3854 void do_info_slirp(void)
3856 slirp_stats();
3859 #endif /* CONFIG_SLIRP */
3861 #if !defined(_WIN32)
3863 typedef struct TAPState {
3864 VLANClientState *vc;
3865 int fd;
3866 char down_script[1024];
3867 } TAPState;
3869 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3871 TAPState *s = opaque;
3872 int ret;
3873 for(;;) {
3874 ret = write(s->fd, buf, size);
3875 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3876 } else {
3877 break;
3882 static void tap_send(void *opaque)
3884 TAPState *s = opaque;
3885 uint8_t buf[4096];
3886 int size;
3888 #ifdef __sun__
3889 struct strbuf sbuf;
3890 int f = 0;
3891 sbuf.maxlen = sizeof(buf);
3892 sbuf.buf = buf;
3893 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3894 #else
3895 size = read(s->fd, buf, sizeof(buf));
3896 #endif
3897 if (size > 0) {
3898 qemu_send_packet(s->vc, buf, size);
3902 /* fd support */
3904 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3906 TAPState *s;
3908 s = qemu_mallocz(sizeof(TAPState));
3909 if (!s)
3910 return NULL;
3911 s->fd = fd;
3912 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3913 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3914 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3915 return s;
3918 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3919 static int tap_open(char *ifname, int ifname_size)
3921 int fd;
3922 char *dev;
3923 struct stat s;
3925 TFR(fd = open("/dev/tap", O_RDWR));
3926 if (fd < 0) {
3927 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3928 return -1;
3931 fstat(fd, &s);
3932 dev = devname(s.st_rdev, S_IFCHR);
3933 pstrcpy(ifname, ifname_size, dev);
3935 fcntl(fd, F_SETFL, O_NONBLOCK);
3936 return fd;
3938 #elif defined(__sun__)
3939 #define TUNNEWPPA (('T'<<16) | 0x0001)
3941 * Allocate TAP device, returns opened fd.
3942 * Stores dev name in the first arg(must be large enough).
3944 int tap_alloc(char *dev)
3946 int tap_fd, if_fd, ppa = -1;
3947 static int ip_fd = 0;
3948 char *ptr;
3950 static int arp_fd = 0;
3951 int ip_muxid, arp_muxid;
3952 struct strioctl strioc_if, strioc_ppa;
3953 int link_type = I_PLINK;;
3954 struct lifreq ifr;
3955 char actual_name[32] = "";
3957 memset(&ifr, 0x0, sizeof(ifr));
3959 if( *dev ){
3960 ptr = dev;
3961 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3962 ppa = atoi(ptr);
3965 /* Check if IP device was opened */
3966 if( ip_fd )
3967 close(ip_fd);
3969 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3970 if (ip_fd < 0) {
3971 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3972 return -1;
3975 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3976 if (tap_fd < 0) {
3977 syslog(LOG_ERR, "Can't open /dev/tap");
3978 return -1;
3981 /* Assign a new PPA and get its unit number. */
3982 strioc_ppa.ic_cmd = TUNNEWPPA;
3983 strioc_ppa.ic_timout = 0;
3984 strioc_ppa.ic_len = sizeof(ppa);
3985 strioc_ppa.ic_dp = (char *)&ppa;
3986 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3987 syslog (LOG_ERR, "Can't assign new interface");
3989 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3990 if (if_fd < 0) {
3991 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3992 return -1;
3994 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3995 syslog(LOG_ERR, "Can't push IP module");
3996 return -1;
3999 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4000 syslog(LOG_ERR, "Can't get flags\n");
4002 snprintf (actual_name, 32, "tap%d", ppa);
4003 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4005 ifr.lifr_ppa = ppa;
4006 /* Assign ppa according to the unit number returned by tun device */
4008 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4009 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4010 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4011 syslog (LOG_ERR, "Can't get flags\n");
4012 /* Push arp module to if_fd */
4013 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4014 syslog (LOG_ERR, "Can't push ARP module (2)");
4016 /* Push arp module to ip_fd */
4017 if (ioctl (ip_fd, I_POP, NULL) < 0)
4018 syslog (LOG_ERR, "I_POP failed\n");
4019 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4020 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4021 /* Open arp_fd */
4022 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4023 if (arp_fd < 0)
4024 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4026 /* Set ifname to arp */
4027 strioc_if.ic_cmd = SIOCSLIFNAME;
4028 strioc_if.ic_timout = 0;
4029 strioc_if.ic_len = sizeof(ifr);
4030 strioc_if.ic_dp = (char *)&ifr;
4031 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4032 syslog (LOG_ERR, "Can't set ifname to arp\n");
4035 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4036 syslog(LOG_ERR, "Can't link TAP device to IP");
4037 return -1;
4040 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4041 syslog (LOG_ERR, "Can't link TAP device to ARP");
4043 close (if_fd);
4045 memset(&ifr, 0x0, sizeof(ifr));
4046 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4047 ifr.lifr_ip_muxid = ip_muxid;
4048 ifr.lifr_arp_muxid = arp_muxid;
4050 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4052 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4053 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4054 syslog (LOG_ERR, "Can't set multiplexor id");
4057 sprintf(dev, "tap%d", ppa);
4058 return tap_fd;
4061 static int tap_open(char *ifname, int ifname_size)
4063 char dev[10]="";
4064 int fd;
4065 if( (fd = tap_alloc(dev)) < 0 ){
4066 fprintf(stderr, "Cannot allocate TAP device\n");
4067 return -1;
4069 pstrcpy(ifname, ifname_size, dev);
4070 fcntl(fd, F_SETFL, O_NONBLOCK);
4071 return fd;
4073 #else
4074 static int tap_open(char *ifname, int ifname_size)
4076 struct ifreq ifr;
4077 int fd, ret;
4079 TFR(fd = open("/dev/net/tun", O_RDWR));
4080 if (fd < 0) {
4081 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4082 return -1;
4084 memset(&ifr, 0, sizeof(ifr));
4085 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4086 if (ifname[0] != '\0')
4087 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4088 else
4089 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4090 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4091 if (ret != 0) {
4092 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4093 close(fd);
4094 return -1;
4096 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4097 fcntl(fd, F_SETFL, O_NONBLOCK);
4098 return fd;
4100 #endif
4102 static int launch_script(const char *setup_script, const char *ifname, int fd)
4104 int pid, status;
4105 char *args[3];
4106 char **parg;
4108 /* try to launch network script */
4109 pid = fork();
4110 if (pid >= 0) {
4111 if (pid == 0) {
4112 int open_max = sysconf (_SC_OPEN_MAX), i;
4113 for (i = 0; i < open_max; i++)
4114 if (i != STDIN_FILENO &&
4115 i != STDOUT_FILENO &&
4116 i != STDERR_FILENO &&
4117 i != fd)
4118 close(i);
4120 parg = args;
4121 *parg++ = (char *)setup_script;
4122 *parg++ = (char *)ifname;
4123 *parg++ = NULL;
4124 execv(setup_script, args);
4125 _exit(1);
4127 while (waitpid(pid, &status, 0) != pid);
4128 if (!WIFEXITED(status) ||
4129 WEXITSTATUS(status) != 0) {
4130 fprintf(stderr, "%s: could not launch network script\n",
4131 setup_script);
4132 return -1;
4135 return 0;
4138 static int net_tap_init(VLANState *vlan, const char *ifname1,
4139 const char *setup_script, const char *down_script)
4141 TAPState *s;
4142 int fd;
4143 char ifname[128];
4145 if (ifname1 != NULL)
4146 pstrcpy(ifname, sizeof(ifname), ifname1);
4147 else
4148 ifname[0] = '\0';
4149 TFR(fd = tap_open(ifname, sizeof(ifname)));
4150 if (fd < 0)
4151 return -1;
4153 if (!setup_script || !strcmp(setup_script, "no"))
4154 setup_script = "";
4155 if (setup_script[0] != '\0') {
4156 if (launch_script(setup_script, ifname, fd))
4157 return -1;
4159 s = net_tap_fd_init(vlan, fd);
4160 if (!s)
4161 return -1;
4162 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4163 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4164 if (down_script && strcmp(down_script, "no"))
4165 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4166 return 0;
4169 #endif /* !_WIN32 */
4171 /* network connection */
4172 typedef struct NetSocketState {
4173 VLANClientState *vc;
4174 int fd;
4175 int state; /* 0 = getting length, 1 = getting data */
4176 int index;
4177 int packet_len;
4178 uint8_t buf[4096];
4179 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4180 } NetSocketState;
4182 typedef struct NetSocketListenState {
4183 VLANState *vlan;
4184 int fd;
4185 } NetSocketListenState;
4187 /* XXX: we consider we can send the whole packet without blocking */
4188 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4190 NetSocketState *s = opaque;
4191 uint32_t len;
4192 len = htonl(size);
4194 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4195 send_all(s->fd, buf, size);
4198 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4200 NetSocketState *s = opaque;
4201 sendto(s->fd, buf, size, 0,
4202 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4205 static void net_socket_send(void *opaque)
4207 NetSocketState *s = opaque;
4208 int l, size, err;
4209 uint8_t buf1[4096];
4210 const uint8_t *buf;
4212 size = recv(s->fd, buf1, sizeof(buf1), 0);
4213 if (size < 0) {
4214 err = socket_error();
4215 if (err != EWOULDBLOCK)
4216 goto eoc;
4217 } else if (size == 0) {
4218 /* end of connection */
4219 eoc:
4220 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4221 closesocket(s->fd);
4222 return;
4224 buf = buf1;
4225 while (size > 0) {
4226 /* reassemble a packet from the network */
4227 switch(s->state) {
4228 case 0:
4229 l = 4 - s->index;
4230 if (l > size)
4231 l = size;
4232 memcpy(s->buf + s->index, buf, l);
4233 buf += l;
4234 size -= l;
4235 s->index += l;
4236 if (s->index == 4) {
4237 /* got length */
4238 s->packet_len = ntohl(*(uint32_t *)s->buf);
4239 s->index = 0;
4240 s->state = 1;
4242 break;
4243 case 1:
4244 l = s->packet_len - s->index;
4245 if (l > size)
4246 l = size;
4247 memcpy(s->buf + s->index, buf, l);
4248 s->index += l;
4249 buf += l;
4250 size -= l;
4251 if (s->index >= s->packet_len) {
4252 qemu_send_packet(s->vc, s->buf, s->packet_len);
4253 s->index = 0;
4254 s->state = 0;
4256 break;
4261 static void net_socket_send_dgram(void *opaque)
4263 NetSocketState *s = opaque;
4264 int size;
4266 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4267 if (size < 0)
4268 return;
4269 if (size == 0) {
4270 /* end of connection */
4271 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4272 return;
4274 qemu_send_packet(s->vc, s->buf, size);
4277 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4279 struct ip_mreq imr;
4280 int fd;
4281 int val, ret;
4282 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4283 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4284 inet_ntoa(mcastaddr->sin_addr),
4285 (int)ntohl(mcastaddr->sin_addr.s_addr));
4286 return -1;
4289 fd = socket(PF_INET, SOCK_DGRAM, 0);
4290 if (fd < 0) {
4291 perror("socket(PF_INET, SOCK_DGRAM)");
4292 return -1;
4295 val = 1;
4296 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4297 (const char *)&val, sizeof(val));
4298 if (ret < 0) {
4299 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4300 goto fail;
4303 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4304 if (ret < 0) {
4305 perror("bind");
4306 goto fail;
4309 /* Add host to multicast group */
4310 imr.imr_multiaddr = mcastaddr->sin_addr;
4311 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4313 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4314 (const char *)&imr, sizeof(struct ip_mreq));
4315 if (ret < 0) {
4316 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4317 goto fail;
4320 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4321 val = 1;
4322 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4323 (const char *)&val, sizeof(val));
4324 if (ret < 0) {
4325 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4326 goto fail;
4329 socket_set_nonblock(fd);
4330 return fd;
4331 fail:
4332 if (fd >= 0)
4333 closesocket(fd);
4334 return -1;
4337 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4338 int is_connected)
4340 struct sockaddr_in saddr;
4341 int newfd;
4342 socklen_t saddr_len;
4343 NetSocketState *s;
4345 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4346 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4347 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4350 if (is_connected) {
4351 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4352 /* must be bound */
4353 if (saddr.sin_addr.s_addr==0) {
4354 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4355 fd);
4356 return NULL;
4358 /* clone dgram socket */
4359 newfd = net_socket_mcast_create(&saddr);
4360 if (newfd < 0) {
4361 /* error already reported by net_socket_mcast_create() */
4362 close(fd);
4363 return NULL;
4365 /* clone newfd to fd, close newfd */
4366 dup2(newfd, fd);
4367 close(newfd);
4369 } else {
4370 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4371 fd, strerror(errno));
4372 return NULL;
4376 s = qemu_mallocz(sizeof(NetSocketState));
4377 if (!s)
4378 return NULL;
4379 s->fd = fd;
4381 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4382 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4384 /* mcast: save bound address as dst */
4385 if (is_connected) s->dgram_dst=saddr;
4387 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4388 "socket: fd=%d (%s mcast=%s:%d)",
4389 fd, is_connected? "cloned" : "",
4390 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4391 return s;
4394 static void net_socket_connect(void *opaque)
4396 NetSocketState *s = opaque;
4397 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4400 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4401 int is_connected)
4403 NetSocketState *s;
4404 s = qemu_mallocz(sizeof(NetSocketState));
4405 if (!s)
4406 return NULL;
4407 s->fd = fd;
4408 s->vc = qemu_new_vlan_client(vlan,
4409 net_socket_receive, NULL, s);
4410 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4411 "socket: fd=%d", fd);
4412 if (is_connected) {
4413 net_socket_connect(s);
4414 } else {
4415 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4417 return s;
4420 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4421 int is_connected)
4423 int so_type=-1, optlen=sizeof(so_type);
4425 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4426 (socklen_t *)&optlen)< 0) {
4427 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4428 return NULL;
4430 switch(so_type) {
4431 case SOCK_DGRAM:
4432 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4433 case SOCK_STREAM:
4434 return net_socket_fd_init_stream(vlan, fd, is_connected);
4435 default:
4436 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4437 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4438 return net_socket_fd_init_stream(vlan, fd, is_connected);
4440 return NULL;
4443 static void net_socket_accept(void *opaque)
4445 NetSocketListenState *s = opaque;
4446 NetSocketState *s1;
4447 struct sockaddr_in saddr;
4448 socklen_t len;
4449 int fd;
4451 for(;;) {
4452 len = sizeof(saddr);
4453 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4454 if (fd < 0 && errno != EINTR) {
4455 return;
4456 } else if (fd >= 0) {
4457 break;
4460 s1 = net_socket_fd_init(s->vlan, fd, 1);
4461 if (!s1) {
4462 closesocket(fd);
4463 } else {
4464 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4465 "socket: connection from %s:%d",
4466 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4470 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4472 NetSocketListenState *s;
4473 int fd, val, ret;
4474 struct sockaddr_in saddr;
4476 if (parse_host_port(&saddr, host_str) < 0)
4477 return -1;
4479 s = qemu_mallocz(sizeof(NetSocketListenState));
4480 if (!s)
4481 return -1;
4483 fd = socket(PF_INET, SOCK_STREAM, 0);
4484 if (fd < 0) {
4485 perror("socket");
4486 return -1;
4488 socket_set_nonblock(fd);
4490 /* allow fast reuse */
4491 val = 1;
4492 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4494 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4495 if (ret < 0) {
4496 perror("bind");
4497 return -1;
4499 ret = listen(fd, 0);
4500 if (ret < 0) {
4501 perror("listen");
4502 return -1;
4504 s->vlan = vlan;
4505 s->fd = fd;
4506 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4507 return 0;
4510 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4512 NetSocketState *s;
4513 int fd, connected, ret, err;
4514 struct sockaddr_in saddr;
4516 if (parse_host_port(&saddr, host_str) < 0)
4517 return -1;
4519 fd = socket(PF_INET, SOCK_STREAM, 0);
4520 if (fd < 0) {
4521 perror("socket");
4522 return -1;
4524 socket_set_nonblock(fd);
4526 connected = 0;
4527 for(;;) {
4528 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4529 if (ret < 0) {
4530 err = socket_error();
4531 if (err == EINTR || err == EWOULDBLOCK) {
4532 } else if (err == EINPROGRESS) {
4533 break;
4534 #ifdef _WIN32
4535 } else if (err == WSAEALREADY) {
4536 break;
4537 #endif
4538 } else {
4539 perror("connect");
4540 closesocket(fd);
4541 return -1;
4543 } else {
4544 connected = 1;
4545 break;
4548 s = net_socket_fd_init(vlan, fd, connected);
4549 if (!s)
4550 return -1;
4551 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4552 "socket: connect to %s:%d",
4553 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4554 return 0;
4557 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4559 NetSocketState *s;
4560 int fd;
4561 struct sockaddr_in saddr;
4563 if (parse_host_port(&saddr, host_str) < 0)
4564 return -1;
4567 fd = net_socket_mcast_create(&saddr);
4568 if (fd < 0)
4569 return -1;
4571 s = net_socket_fd_init(vlan, fd, 0);
4572 if (!s)
4573 return -1;
4575 s->dgram_dst = saddr;
4577 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4578 "socket: mcast=%s:%d",
4579 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4580 return 0;
4584 static const char *get_word(char *buf, int buf_size, const char *p)
4586 char *q;
4587 int substring;
4589 substring = 0;
4590 q = buf;
4591 while (*p != '\0') {
4592 if (*p == '\\') {
4593 p++;
4594 if (*p == '\0')
4595 break;
4596 } else if (*p == '\"') {
4597 substring = !substring;
4598 p++;
4599 continue;
4600 } else if (!substring && (*p == ',' || *p == '='))
4601 break;
4602 if (q && (q - buf) < buf_size - 1)
4603 *q++ = *p;
4604 p++;
4606 if (q)
4607 *q = '\0';
4609 return p;
4612 static int get_param_value(char *buf, int buf_size,
4613 const char *tag, const char *str)
4615 const char *p;
4616 char option[128];
4618 p = str;
4619 for(;;) {
4620 p = get_word(option, sizeof(option), p);
4621 if (*p != '=')
4622 break;
4623 p++;
4624 if (!strcmp(tag, option)) {
4625 (void)get_word(buf, buf_size, p);
4626 return strlen(buf);
4627 } else {
4628 p = get_word(NULL, 0, p);
4630 if (*p != ',')
4631 break;
4632 p++;
4634 return 0;
4637 static int check_params(char *buf, int buf_size,
4638 char **params, const char *str)
4640 const char *p;
4641 int i;
4643 p = str;
4644 for(;;) {
4645 p = get_word(buf, buf_size, p);
4646 if (*p != '=')
4647 return -1;
4648 p++;
4649 for(i = 0; params[i] != NULL; i++)
4650 if (!strcmp(params[i], buf))
4651 break;
4652 if (params[i] == NULL)
4653 return -1;
4654 p = get_word(NULL, 0, p);
4655 if (*p != ',')
4656 break;
4657 p++;
4659 return 0;
4663 static int net_client_init(const char *str)
4665 const char *p;
4666 char *q;
4667 char device[64];
4668 char buf[1024];
4669 int vlan_id, ret;
4670 VLANState *vlan;
4672 p = str;
4673 q = device;
4674 while (*p != '\0' && *p != ',') {
4675 if ((q - device) < sizeof(device) - 1)
4676 *q++ = *p;
4677 p++;
4679 *q = '\0';
4680 if (*p == ',')
4681 p++;
4682 vlan_id = 0;
4683 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4684 vlan_id = strtol(buf, NULL, 0);
4686 vlan = qemu_find_vlan(vlan_id);
4687 if (!vlan) {
4688 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4689 return -1;
4691 if (!strcmp(device, "nic")) {
4692 NICInfo *nd;
4693 uint8_t *macaddr;
4695 if (nb_nics >= MAX_NICS) {
4696 fprintf(stderr, "Too Many NICs\n");
4697 return -1;
4699 nd = &nd_table[nb_nics];
4700 macaddr = nd->macaddr;
4701 macaddr[0] = 0x52;
4702 macaddr[1] = 0x54;
4703 macaddr[2] = 0x00;
4704 macaddr[3] = 0x12;
4705 macaddr[4] = 0x34;
4706 macaddr[5] = 0x56 + nb_nics;
4708 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4709 if (parse_macaddr(macaddr, buf) < 0) {
4710 fprintf(stderr, "invalid syntax for ethernet address\n");
4711 return -1;
4714 if (get_param_value(buf, sizeof(buf), "model", p)) {
4715 nd->model = strdup(buf);
4717 nd->vlan = vlan;
4718 nb_nics++;
4719 vlan->nb_guest_devs++;
4720 ret = 0;
4721 } else
4722 if (!strcmp(device, "none")) {
4723 /* does nothing. It is needed to signal that no network cards
4724 are wanted */
4725 ret = 0;
4726 } else
4727 #ifdef CONFIG_SLIRP
4728 if (!strcmp(device, "user")) {
4729 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4730 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4732 vlan->nb_host_devs++;
4733 ret = net_slirp_init(vlan);
4734 } else
4735 #endif
4736 #ifdef _WIN32
4737 if (!strcmp(device, "tap")) {
4738 char ifname[64];
4739 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4740 fprintf(stderr, "tap: no interface name\n");
4741 return -1;
4743 vlan->nb_host_devs++;
4744 ret = tap_win32_init(vlan, ifname);
4745 } else
4746 #else
4747 if (!strcmp(device, "tap")) {
4748 char ifname[64];
4749 char setup_script[1024], down_script[1024];
4750 int fd;
4751 vlan->nb_host_devs++;
4752 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4753 fd = strtol(buf, NULL, 0);
4754 ret = -1;
4755 if (net_tap_fd_init(vlan, fd))
4756 ret = 0;
4757 } else {
4758 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4759 ifname[0] = '\0';
4761 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4762 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4764 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4765 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4767 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4769 } else
4770 #endif
4771 if (!strcmp(device, "socket")) {
4772 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4773 int fd;
4774 fd = strtol(buf, NULL, 0);
4775 ret = -1;
4776 if (net_socket_fd_init(vlan, fd, 1))
4777 ret = 0;
4778 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4779 ret = net_socket_listen_init(vlan, buf);
4780 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4781 ret = net_socket_connect_init(vlan, buf);
4782 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4783 ret = net_socket_mcast_init(vlan, buf);
4784 } else {
4785 fprintf(stderr, "Unknown socket options: %s\n", p);
4786 return -1;
4788 vlan->nb_host_devs++;
4789 } else
4791 fprintf(stderr, "Unknown network device: %s\n", device);
4792 return -1;
4794 if (ret < 0) {
4795 fprintf(stderr, "Could not initialize device '%s'\n", device);
4798 return ret;
4801 void do_info_network(void)
4803 VLANState *vlan;
4804 VLANClientState *vc;
4806 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4807 term_printf("VLAN %d devices:\n", vlan->id);
4808 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4809 term_printf(" %s\n", vc->info_str);
4813 #define HD_ALIAS "file=\"%s\",index=%d,media=disk"
4814 #ifdef TARGET_PPC
4815 #define CDROM_ALIAS "index=1,media=cdrom"
4816 #else
4817 #define CDROM_ALIAS "index=2,media=cdrom"
4818 #endif
4819 #define FD_ALIAS "index=%d,if=floppy"
4820 #define PFLASH_ALIAS "file=\"%s\",if=pflash"
4821 #define MTD_ALIAS "file=\"%s\",if=mtd"
4822 #define SD_ALIAS "index=0,if=sd"
4824 static int drive_add(const char *fmt, ...)
4826 va_list ap;
4828 if (nb_drives_opt >= MAX_DRIVES) {
4829 fprintf(stderr, "qemu: too many drives\n");
4830 exit(1);
4833 va_start(ap, fmt);
4834 vsnprintf(drives_opt[nb_drives_opt], sizeof(drives_opt[0]), fmt, ap);
4835 va_end(ap);
4837 return nb_drives_opt++;
4840 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4842 int index;
4844 /* seek interface, bus and unit */
4846 for (index = 0; index < nb_drives; index++)
4847 if (drives_table[index].type == type &&
4848 drives_table[index].bus == bus &&
4849 drives_table[index].unit == unit)
4850 return index;
4852 return -1;
4855 int drive_get_max_bus(BlockInterfaceType type)
4857 int max_bus;
4858 int index;
4860 max_bus = -1;
4861 for (index = 0; index < nb_drives; index++) {
4862 if(drives_table[index].type == type &&
4863 drives_table[index].bus > max_bus)
4864 max_bus = drives_table[index].bus;
4866 return max_bus;
4869 static int drive_init(const char *str, int snapshot, QEMUMachine *machine)
4871 char buf[128];
4872 char file[1024];
4873 char devname[128];
4874 const char *mediastr = "";
4875 BlockInterfaceType type;
4876 enum { MEDIA_DISK, MEDIA_CDROM } media;
4877 int bus_id, unit_id;
4878 int cyls, heads, secs, translation;
4879 BlockDriverState *bdrv;
4880 int max_devs;
4881 int index;
4882 int cache;
4883 int bdrv_flags;
4884 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4885 "secs", "trans", "media", "snapshot", "file",
4886 "cache", NULL };
4888 if (check_params(buf, sizeof(buf), params, str) < 0) {
4889 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4890 buf, str);
4891 return -1;
4894 file[0] = 0;
4895 cyls = heads = secs = 0;
4896 bus_id = 0;
4897 unit_id = -1;
4898 translation = BIOS_ATA_TRANSLATION_AUTO;
4899 index = -1;
4900 cache = 1;
4902 if (!strcmp(machine->name, "realview") ||
4903 !strcmp(machine->name, "SS-5") ||
4904 !strcmp(machine->name, "SS-10") ||
4905 !strcmp(machine->name, "SS-600MP") ||
4906 !strcmp(machine->name, "versatilepb") ||
4907 !strcmp(machine->name, "versatileab")) {
4908 type = IF_SCSI;
4909 max_devs = MAX_SCSI_DEVS;
4910 strcpy(devname, "scsi");
4911 } else {
4912 type = IF_IDE;
4913 max_devs = MAX_IDE_DEVS;
4914 strcpy(devname, "ide");
4916 media = MEDIA_DISK;
4918 /* extract parameters */
4920 if (get_param_value(buf, sizeof(buf), "bus", str)) {
4921 bus_id = strtol(buf, NULL, 0);
4922 if (bus_id < 0) {
4923 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4924 return -1;
4928 if (get_param_value(buf, sizeof(buf), "unit", str)) {
4929 unit_id = strtol(buf, NULL, 0);
4930 if (unit_id < 0) {
4931 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4932 return -1;
4936 if (get_param_value(buf, sizeof(buf), "if", str)) {
4937 strncpy(devname, buf, sizeof(devname));
4938 if (!strcmp(buf, "ide")) {
4939 type = IF_IDE;
4940 max_devs = MAX_IDE_DEVS;
4941 } else if (!strcmp(buf, "scsi")) {
4942 type = IF_SCSI;
4943 max_devs = MAX_SCSI_DEVS;
4944 } else if (!strcmp(buf, "floppy")) {
4945 type = IF_FLOPPY;
4946 max_devs = 0;
4947 } else if (!strcmp(buf, "pflash")) {
4948 type = IF_PFLASH;
4949 max_devs = 0;
4950 } else if (!strcmp(buf, "mtd")) {
4951 type = IF_MTD;
4952 max_devs = 0;
4953 } else if (!strcmp(buf, "sd")) {
4954 type = IF_SD;
4955 max_devs = 0;
4956 } else {
4957 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
4958 return -1;
4962 if (get_param_value(buf, sizeof(buf), "index", str)) {
4963 index = strtol(buf, NULL, 0);
4964 if (index < 0) {
4965 fprintf(stderr, "qemu: '%s' invalid index\n", str);
4966 return -1;
4970 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
4971 cyls = strtol(buf, NULL, 0);
4974 if (get_param_value(buf, sizeof(buf), "heads", str)) {
4975 heads = strtol(buf, NULL, 0);
4978 if (get_param_value(buf, sizeof(buf), "secs", str)) {
4979 secs = strtol(buf, NULL, 0);
4982 if (cyls || heads || secs) {
4983 if (cyls < 1 || cyls > 16383) {
4984 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
4985 return -1;
4987 if (heads < 1 || heads > 16) {
4988 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
4989 return -1;
4991 if (secs < 1 || secs > 63) {
4992 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
4993 return -1;
4997 if (get_param_value(buf, sizeof(buf), "trans", str)) {
4998 if (!cyls) {
4999 fprintf(stderr,
5000 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5001 str);
5002 return -1;
5004 if (!strcmp(buf, "none"))
5005 translation = BIOS_ATA_TRANSLATION_NONE;
5006 else if (!strcmp(buf, "lba"))
5007 translation = BIOS_ATA_TRANSLATION_LBA;
5008 else if (!strcmp(buf, "auto"))
5009 translation = BIOS_ATA_TRANSLATION_AUTO;
5010 else {
5011 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5012 return -1;
5016 if (get_param_value(buf, sizeof(buf), "media", str)) {
5017 if (!strcmp(buf, "disk")) {
5018 media = MEDIA_DISK;
5019 } else if (!strcmp(buf, "cdrom")) {
5020 if (cyls || secs || heads) {
5021 fprintf(stderr,
5022 "qemu: '%s' invalid physical CHS format\n", str);
5023 return -1;
5025 media = MEDIA_CDROM;
5026 } else {
5027 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5028 return -1;
5032 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5033 if (!strcmp(buf, "on"))
5034 snapshot = 1;
5035 else if (!strcmp(buf, "off"))
5036 snapshot = 0;
5037 else {
5038 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5039 return -1;
5043 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5044 if (!strcmp(buf, "off"))
5045 cache = 0;
5046 else if (!strcmp(buf, "on"))
5047 cache = 1;
5048 else {
5049 fprintf(stderr, "qemu: invalid cache option\n");
5050 return -1;
5054 get_param_value(file, sizeof(file), "file", str);
5056 /* compute bus and unit according index */
5058 if (index != -1) {
5059 if (bus_id != 0 || unit_id != -1) {
5060 fprintf(stderr,
5061 "qemu: '%s' index cannot be used with bus and unit\n", str);
5062 return -1;
5064 if (max_devs == 0)
5066 unit_id = index;
5067 bus_id = 0;
5068 } else {
5069 unit_id = index % max_devs;
5070 bus_id = index / max_devs;
5074 /* if user doesn't specify a unit_id,
5075 * try to find the first free
5078 if (unit_id == -1) {
5079 unit_id = 0;
5080 while (drive_get_index(type, bus_id, unit_id) != -1) {
5081 unit_id++;
5082 if (max_devs && unit_id >= max_devs) {
5083 unit_id -= max_devs;
5084 bus_id++;
5089 /* check unit id */
5091 if (max_devs && unit_id >= max_devs) {
5092 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5093 str, unit_id, max_devs - 1);
5094 return -1;
5098 * ignore multiple definitions
5101 if (drive_get_index(type, bus_id, unit_id) != -1)
5102 return 0;
5104 /* init */
5106 if (type == IF_IDE || type == IF_SCSI)
5107 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5108 if (max_devs)
5109 snprintf(buf, sizeof(buf), "%s%i%s%i",
5110 devname, bus_id, mediastr, unit_id);
5111 else
5112 snprintf(buf, sizeof(buf), "%s%s%i",
5113 devname, mediastr, unit_id);
5114 bdrv = bdrv_new(buf);
5115 drives_table[nb_drives].bdrv = bdrv;
5116 drives_table[nb_drives].type = type;
5117 drives_table[nb_drives].bus = bus_id;
5118 drives_table[nb_drives].unit = unit_id;
5119 nb_drives++;
5121 switch(type) {
5122 case IF_IDE:
5123 case IF_SCSI:
5124 switch(media) {
5125 case MEDIA_DISK:
5126 if (cyls != 0) {
5127 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5128 bdrv_set_translation_hint(bdrv, translation);
5130 break;
5131 case MEDIA_CDROM:
5132 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5133 break;
5135 break;
5136 case IF_SD:
5137 /* FIXME: This isn't really a floppy, but it's a reasonable
5138 approximation. */
5139 case IF_FLOPPY:
5140 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5141 break;
5142 case IF_PFLASH:
5143 case IF_MTD:
5144 break;
5146 if (!file[0])
5147 return 0;
5148 bdrv_flags = 0;
5149 if (snapshot)
5150 bdrv_flags |= BDRV_O_SNAPSHOT;
5151 if (!cache)
5152 bdrv_flags |= BDRV_O_DIRECT;
5153 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5154 fprintf(stderr, "qemu: could not open disk image %s\n",
5155 file);
5156 return -1;
5158 return 0;
5161 /***********************************************************/
5162 /* USB devices */
5164 static USBPort *used_usb_ports;
5165 static USBPort *free_usb_ports;
5167 /* ??? Maybe change this to register a hub to keep track of the topology. */
5168 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5169 usb_attachfn attach)
5171 port->opaque = opaque;
5172 port->index = index;
5173 port->attach = attach;
5174 port->next = free_usb_ports;
5175 free_usb_ports = port;
5178 static int usb_device_add(const char *devname)
5180 const char *p;
5181 USBDevice *dev;
5182 USBPort *port;
5184 if (!free_usb_ports)
5185 return -1;
5187 if (strstart(devname, "host:", &p)) {
5188 dev = usb_host_device_open(p);
5189 } else if (!strcmp(devname, "mouse")) {
5190 dev = usb_mouse_init();
5191 } else if (!strcmp(devname, "tablet")) {
5192 dev = usb_tablet_init();
5193 } else if (!strcmp(devname, "keyboard")) {
5194 dev = usb_keyboard_init();
5195 } else if (strstart(devname, "disk:", &p)) {
5196 dev = usb_msd_init(p);
5197 } else if (!strcmp(devname, "wacom-tablet")) {
5198 dev = usb_wacom_init();
5199 } else {
5200 return -1;
5202 if (!dev)
5203 return -1;
5205 /* Find a USB port to add the device to. */
5206 port = free_usb_ports;
5207 if (!port->next) {
5208 USBDevice *hub;
5210 /* Create a new hub and chain it on. */
5211 free_usb_ports = NULL;
5212 port->next = used_usb_ports;
5213 used_usb_ports = port;
5215 hub = usb_hub_init(VM_USB_HUB_SIZE);
5216 usb_attach(port, hub);
5217 port = free_usb_ports;
5220 free_usb_ports = port->next;
5221 port->next = used_usb_ports;
5222 used_usb_ports = port;
5223 usb_attach(port, dev);
5224 return 0;
5227 static int usb_device_del(const char *devname)
5229 USBPort *port;
5230 USBPort **lastp;
5231 USBDevice *dev;
5232 int bus_num, addr;
5233 const char *p;
5235 if (!used_usb_ports)
5236 return -1;
5238 p = strchr(devname, '.');
5239 if (!p)
5240 return -1;
5241 bus_num = strtoul(devname, NULL, 0);
5242 addr = strtoul(p + 1, NULL, 0);
5243 if (bus_num != 0)
5244 return -1;
5246 lastp = &used_usb_ports;
5247 port = used_usb_ports;
5248 while (port && port->dev->addr != addr) {
5249 lastp = &port->next;
5250 port = port->next;
5253 if (!port)
5254 return -1;
5256 dev = port->dev;
5257 *lastp = port->next;
5258 usb_attach(port, NULL);
5259 dev->handle_destroy(dev);
5260 port->next = free_usb_ports;
5261 free_usb_ports = port;
5262 return 0;
5265 void do_usb_add(const char *devname)
5267 int ret;
5268 ret = usb_device_add(devname);
5269 if (ret < 0)
5270 term_printf("Could not add USB device '%s'\n", devname);
5273 void do_usb_del(const char *devname)
5275 int ret;
5276 ret = usb_device_del(devname);
5277 if (ret < 0)
5278 term_printf("Could not remove USB device '%s'\n", devname);
5281 void usb_info(void)
5283 USBDevice *dev;
5284 USBPort *port;
5285 const char *speed_str;
5287 if (!usb_enabled) {
5288 term_printf("USB support not enabled\n");
5289 return;
5292 for (port = used_usb_ports; port; port = port->next) {
5293 dev = port->dev;
5294 if (!dev)
5295 continue;
5296 switch(dev->speed) {
5297 case USB_SPEED_LOW:
5298 speed_str = "1.5";
5299 break;
5300 case USB_SPEED_FULL:
5301 speed_str = "12";
5302 break;
5303 case USB_SPEED_HIGH:
5304 speed_str = "480";
5305 break;
5306 default:
5307 speed_str = "?";
5308 break;
5310 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5311 0, dev->addr, speed_str, dev->devname);
5315 /***********************************************************/
5316 /* PCMCIA/Cardbus */
5318 static struct pcmcia_socket_entry_s {
5319 struct pcmcia_socket_s *socket;
5320 struct pcmcia_socket_entry_s *next;
5321 } *pcmcia_sockets = 0;
5323 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5325 struct pcmcia_socket_entry_s *entry;
5327 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5328 entry->socket = socket;
5329 entry->next = pcmcia_sockets;
5330 pcmcia_sockets = entry;
5333 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5335 struct pcmcia_socket_entry_s *entry, **ptr;
5337 ptr = &pcmcia_sockets;
5338 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5339 if (entry->socket == socket) {
5340 *ptr = entry->next;
5341 qemu_free(entry);
5345 void pcmcia_info(void)
5347 struct pcmcia_socket_entry_s *iter;
5348 if (!pcmcia_sockets)
5349 term_printf("No PCMCIA sockets\n");
5351 for (iter = pcmcia_sockets; iter; iter = iter->next)
5352 term_printf("%s: %s\n", iter->socket->slot_string,
5353 iter->socket->attached ? iter->socket->card_string :
5354 "Empty");
5357 /***********************************************************/
5358 /* dumb display */
5360 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5364 static void dumb_resize(DisplayState *ds, int w, int h)
5368 static void dumb_refresh(DisplayState *ds)
5370 #if defined(CONFIG_SDL)
5371 vga_hw_update();
5372 #endif
5375 static void dumb_display_init(DisplayState *ds)
5377 ds->data = NULL;
5378 ds->linesize = 0;
5379 ds->depth = 0;
5380 ds->dpy_update = dumb_update;
5381 ds->dpy_resize = dumb_resize;
5382 ds->dpy_refresh = dumb_refresh;
5385 /***********************************************************/
5386 /* I/O handling */
5388 #define MAX_IO_HANDLERS 64
5390 typedef struct IOHandlerRecord {
5391 int fd;
5392 IOCanRWHandler *fd_read_poll;
5393 IOHandler *fd_read;
5394 IOHandler *fd_write;
5395 int deleted;
5396 void *opaque;
5397 /* temporary data */
5398 struct pollfd *ufd;
5399 struct IOHandlerRecord *next;
5400 } IOHandlerRecord;
5402 static IOHandlerRecord *first_io_handler;
5404 /* XXX: fd_read_poll should be suppressed, but an API change is
5405 necessary in the character devices to suppress fd_can_read(). */
5406 int qemu_set_fd_handler2(int fd,
5407 IOCanRWHandler *fd_read_poll,
5408 IOHandler *fd_read,
5409 IOHandler *fd_write,
5410 void *opaque)
5412 IOHandlerRecord **pioh, *ioh;
5414 if (!fd_read && !fd_write) {
5415 pioh = &first_io_handler;
5416 for(;;) {
5417 ioh = *pioh;
5418 if (ioh == NULL)
5419 break;
5420 if (ioh->fd == fd) {
5421 ioh->deleted = 1;
5422 break;
5424 pioh = &ioh->next;
5426 } else {
5427 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5428 if (ioh->fd == fd)
5429 goto found;
5431 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5432 if (!ioh)
5433 return -1;
5434 ioh->next = first_io_handler;
5435 first_io_handler = ioh;
5436 found:
5437 ioh->fd = fd;
5438 ioh->fd_read_poll = fd_read_poll;
5439 ioh->fd_read = fd_read;
5440 ioh->fd_write = fd_write;
5441 ioh->opaque = opaque;
5442 ioh->deleted = 0;
5444 return 0;
5447 int qemu_set_fd_handler(int fd,
5448 IOHandler *fd_read,
5449 IOHandler *fd_write,
5450 void *opaque)
5452 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5455 /***********************************************************/
5456 /* Polling handling */
5458 typedef struct PollingEntry {
5459 PollingFunc *func;
5460 void *opaque;
5461 struct PollingEntry *next;
5462 } PollingEntry;
5464 static PollingEntry *first_polling_entry;
5466 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5468 PollingEntry **ppe, *pe;
5469 pe = qemu_mallocz(sizeof(PollingEntry));
5470 if (!pe)
5471 return -1;
5472 pe->func = func;
5473 pe->opaque = opaque;
5474 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5475 *ppe = pe;
5476 return 0;
5479 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5481 PollingEntry **ppe, *pe;
5482 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5483 pe = *ppe;
5484 if (pe->func == func && pe->opaque == opaque) {
5485 *ppe = pe->next;
5486 qemu_free(pe);
5487 break;
5492 #ifdef _WIN32
5493 /***********************************************************/
5494 /* Wait objects support */
5495 typedef struct WaitObjects {
5496 int num;
5497 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5498 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5499 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5500 } WaitObjects;
5502 static WaitObjects wait_objects = {0};
5504 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5506 WaitObjects *w = &wait_objects;
5508 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5509 return -1;
5510 w->events[w->num] = handle;
5511 w->func[w->num] = func;
5512 w->opaque[w->num] = opaque;
5513 w->num++;
5514 return 0;
5517 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5519 int i, found;
5520 WaitObjects *w = &wait_objects;
5522 found = 0;
5523 for (i = 0; i < w->num; i++) {
5524 if (w->events[i] == handle)
5525 found = 1;
5526 if (found) {
5527 w->events[i] = w->events[i + 1];
5528 w->func[i] = w->func[i + 1];
5529 w->opaque[i] = w->opaque[i + 1];
5532 if (found)
5533 w->num--;
5535 #endif
5537 /***********************************************************/
5538 /* savevm/loadvm support */
5540 #define IO_BUF_SIZE 32768
5542 struct QEMUFile {
5543 FILE *outfile;
5544 BlockDriverState *bs;
5545 int is_file;
5546 int is_writable;
5547 int64_t base_offset;
5548 int64_t buf_offset; /* start of buffer when writing, end of buffer
5549 when reading */
5550 int buf_index;
5551 int buf_size; /* 0 when writing */
5552 uint8_t buf[IO_BUF_SIZE];
5555 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5557 QEMUFile *f;
5559 f = qemu_mallocz(sizeof(QEMUFile));
5560 if (!f)
5561 return NULL;
5562 if (!strcmp(mode, "wb")) {
5563 f->is_writable = 1;
5564 } else if (!strcmp(mode, "rb")) {
5565 f->is_writable = 0;
5566 } else {
5567 goto fail;
5569 f->outfile = fopen(filename, mode);
5570 if (!f->outfile)
5571 goto fail;
5572 f->is_file = 1;
5573 return f;
5574 fail:
5575 if (f->outfile)
5576 fclose(f->outfile);
5577 qemu_free(f);
5578 return NULL;
5581 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5583 QEMUFile *f;
5585 f = qemu_mallocz(sizeof(QEMUFile));
5586 if (!f)
5587 return NULL;
5588 f->is_file = 0;
5589 f->bs = bs;
5590 f->is_writable = is_writable;
5591 f->base_offset = offset;
5592 return f;
5595 void qemu_fflush(QEMUFile *f)
5597 if (!f->is_writable)
5598 return;
5599 if (f->buf_index > 0) {
5600 if (f->is_file) {
5601 fseek(f->outfile, f->buf_offset, SEEK_SET);
5602 fwrite(f->buf, 1, f->buf_index, f->outfile);
5603 } else {
5604 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5605 f->buf, f->buf_index);
5607 f->buf_offset += f->buf_index;
5608 f->buf_index = 0;
5612 static void qemu_fill_buffer(QEMUFile *f)
5614 int len;
5616 if (f->is_writable)
5617 return;
5618 if (f->is_file) {
5619 fseek(f->outfile, f->buf_offset, SEEK_SET);
5620 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5621 if (len < 0)
5622 len = 0;
5623 } else {
5624 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5625 f->buf, IO_BUF_SIZE);
5626 if (len < 0)
5627 len = 0;
5629 f->buf_index = 0;
5630 f->buf_size = len;
5631 f->buf_offset += len;
5634 void qemu_fclose(QEMUFile *f)
5636 if (f->is_writable)
5637 qemu_fflush(f);
5638 if (f->is_file) {
5639 fclose(f->outfile);
5641 qemu_free(f);
5644 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5646 int l;
5647 while (size > 0) {
5648 l = IO_BUF_SIZE - f->buf_index;
5649 if (l > size)
5650 l = size;
5651 memcpy(f->buf + f->buf_index, buf, l);
5652 f->buf_index += l;
5653 buf += l;
5654 size -= l;
5655 if (f->buf_index >= IO_BUF_SIZE)
5656 qemu_fflush(f);
5660 void qemu_put_byte(QEMUFile *f, int v)
5662 f->buf[f->buf_index++] = v;
5663 if (f->buf_index >= IO_BUF_SIZE)
5664 qemu_fflush(f);
5667 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5669 int size, l;
5671 size = size1;
5672 while (size > 0) {
5673 l = f->buf_size - f->buf_index;
5674 if (l == 0) {
5675 qemu_fill_buffer(f);
5676 l = f->buf_size - f->buf_index;
5677 if (l == 0)
5678 break;
5680 if (l > size)
5681 l = size;
5682 memcpy(buf, f->buf + f->buf_index, l);
5683 f->buf_index += l;
5684 buf += l;
5685 size -= l;
5687 return size1 - size;
5690 int qemu_get_byte(QEMUFile *f)
5692 if (f->buf_index >= f->buf_size) {
5693 qemu_fill_buffer(f);
5694 if (f->buf_index >= f->buf_size)
5695 return 0;
5697 return f->buf[f->buf_index++];
5700 int64_t qemu_ftell(QEMUFile *f)
5702 return f->buf_offset - f->buf_size + f->buf_index;
5705 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5707 if (whence == SEEK_SET) {
5708 /* nothing to do */
5709 } else if (whence == SEEK_CUR) {
5710 pos += qemu_ftell(f);
5711 } else {
5712 /* SEEK_END not supported */
5713 return -1;
5715 if (f->is_writable) {
5716 qemu_fflush(f);
5717 f->buf_offset = pos;
5718 } else {
5719 f->buf_offset = pos;
5720 f->buf_index = 0;
5721 f->buf_size = 0;
5723 return pos;
5726 void qemu_put_be16(QEMUFile *f, unsigned int v)
5728 qemu_put_byte(f, v >> 8);
5729 qemu_put_byte(f, v);
5732 void qemu_put_be32(QEMUFile *f, unsigned int v)
5734 qemu_put_byte(f, v >> 24);
5735 qemu_put_byte(f, v >> 16);
5736 qemu_put_byte(f, v >> 8);
5737 qemu_put_byte(f, v);
5740 void qemu_put_be64(QEMUFile *f, uint64_t v)
5742 qemu_put_be32(f, v >> 32);
5743 qemu_put_be32(f, v);
5746 unsigned int qemu_get_be16(QEMUFile *f)
5748 unsigned int v;
5749 v = qemu_get_byte(f) << 8;
5750 v |= qemu_get_byte(f);
5751 return v;
5754 unsigned int qemu_get_be32(QEMUFile *f)
5756 unsigned int v;
5757 v = qemu_get_byte(f) << 24;
5758 v |= qemu_get_byte(f) << 16;
5759 v |= qemu_get_byte(f) << 8;
5760 v |= qemu_get_byte(f);
5761 return v;
5764 uint64_t qemu_get_be64(QEMUFile *f)
5766 uint64_t v;
5767 v = (uint64_t)qemu_get_be32(f) << 32;
5768 v |= qemu_get_be32(f);
5769 return v;
5772 typedef struct SaveStateEntry {
5773 char idstr[256];
5774 int instance_id;
5775 int version_id;
5776 SaveStateHandler *save_state;
5777 LoadStateHandler *load_state;
5778 void *opaque;
5779 struct SaveStateEntry *next;
5780 } SaveStateEntry;
5782 static SaveStateEntry *first_se;
5784 int register_savevm(const char *idstr,
5785 int instance_id,
5786 int version_id,
5787 SaveStateHandler *save_state,
5788 LoadStateHandler *load_state,
5789 void *opaque)
5791 SaveStateEntry *se, **pse;
5793 se = qemu_malloc(sizeof(SaveStateEntry));
5794 if (!se)
5795 return -1;
5796 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5797 se->instance_id = instance_id;
5798 se->version_id = version_id;
5799 se->save_state = save_state;
5800 se->load_state = load_state;
5801 se->opaque = opaque;
5802 se->next = NULL;
5804 /* add at the end of list */
5805 pse = &first_se;
5806 while (*pse != NULL)
5807 pse = &(*pse)->next;
5808 *pse = se;
5809 return 0;
5812 #define QEMU_VM_FILE_MAGIC 0x5145564d
5813 #define QEMU_VM_FILE_VERSION 0x00000002
5815 static int qemu_savevm_state(QEMUFile *f)
5817 SaveStateEntry *se;
5818 int len, ret;
5819 int64_t cur_pos, len_pos, total_len_pos;
5821 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5822 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5823 total_len_pos = qemu_ftell(f);
5824 qemu_put_be64(f, 0); /* total size */
5826 for(se = first_se; se != NULL; se = se->next) {
5827 /* ID string */
5828 len = strlen(se->idstr);
5829 qemu_put_byte(f, len);
5830 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5832 qemu_put_be32(f, se->instance_id);
5833 qemu_put_be32(f, se->version_id);
5835 /* record size: filled later */
5836 len_pos = qemu_ftell(f);
5837 qemu_put_be32(f, 0);
5838 se->save_state(f, se->opaque);
5840 /* fill record size */
5841 cur_pos = qemu_ftell(f);
5842 len = cur_pos - len_pos - 4;
5843 qemu_fseek(f, len_pos, SEEK_SET);
5844 qemu_put_be32(f, len);
5845 qemu_fseek(f, cur_pos, SEEK_SET);
5847 cur_pos = qemu_ftell(f);
5848 qemu_fseek(f, total_len_pos, SEEK_SET);
5849 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5850 qemu_fseek(f, cur_pos, SEEK_SET);
5852 ret = 0;
5853 return ret;
5856 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5858 SaveStateEntry *se;
5860 for(se = first_se; se != NULL; se = se->next) {
5861 if (!strcmp(se->idstr, idstr) &&
5862 instance_id == se->instance_id)
5863 return se;
5865 return NULL;
5868 static int qemu_loadvm_state(QEMUFile *f)
5870 SaveStateEntry *se;
5871 int len, ret, instance_id, record_len, version_id;
5872 int64_t total_len, end_pos, cur_pos;
5873 unsigned int v;
5874 char idstr[256];
5876 v = qemu_get_be32(f);
5877 if (v != QEMU_VM_FILE_MAGIC)
5878 goto fail;
5879 v = qemu_get_be32(f);
5880 if (v != QEMU_VM_FILE_VERSION) {
5881 fail:
5882 ret = -1;
5883 goto the_end;
5885 total_len = qemu_get_be64(f);
5886 end_pos = total_len + qemu_ftell(f);
5887 for(;;) {
5888 if (qemu_ftell(f) >= end_pos)
5889 break;
5890 len = qemu_get_byte(f);
5891 qemu_get_buffer(f, (uint8_t *)idstr, len);
5892 idstr[len] = '\0';
5893 instance_id = qemu_get_be32(f);
5894 version_id = qemu_get_be32(f);
5895 record_len = qemu_get_be32(f);
5896 #if 0
5897 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5898 idstr, instance_id, version_id, record_len);
5899 #endif
5900 cur_pos = qemu_ftell(f);
5901 se = find_se(idstr, instance_id);
5902 if (!se) {
5903 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5904 instance_id, idstr);
5905 } else {
5906 ret = se->load_state(f, se->opaque, version_id);
5907 if (ret < 0) {
5908 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5909 instance_id, idstr);
5912 /* always seek to exact end of record */
5913 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5915 ret = 0;
5916 the_end:
5917 return ret;
5920 /* device can contain snapshots */
5921 static int bdrv_can_snapshot(BlockDriverState *bs)
5923 return (bs &&
5924 !bdrv_is_removable(bs) &&
5925 !bdrv_is_read_only(bs));
5928 /* device must be snapshots in order to have a reliable snapshot */
5929 static int bdrv_has_snapshot(BlockDriverState *bs)
5931 return (bs &&
5932 !bdrv_is_removable(bs) &&
5933 !bdrv_is_read_only(bs));
5936 static BlockDriverState *get_bs_snapshots(void)
5938 BlockDriverState *bs;
5939 int i;
5941 if (bs_snapshots)
5942 return bs_snapshots;
5943 for(i = 0; i <= nb_drives; i++) {
5944 bs = drives_table[i].bdrv;
5945 if (bdrv_can_snapshot(bs))
5946 goto ok;
5948 return NULL;
5950 bs_snapshots = bs;
5951 return bs;
5954 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5955 const char *name)
5957 QEMUSnapshotInfo *sn_tab, *sn;
5958 int nb_sns, i, ret;
5960 ret = -ENOENT;
5961 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5962 if (nb_sns < 0)
5963 return ret;
5964 for(i = 0; i < nb_sns; i++) {
5965 sn = &sn_tab[i];
5966 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5967 *sn_info = *sn;
5968 ret = 0;
5969 break;
5972 qemu_free(sn_tab);
5973 return ret;
5976 void do_savevm(const char *name)
5978 BlockDriverState *bs, *bs1;
5979 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5980 int must_delete, ret, i;
5981 BlockDriverInfo bdi1, *bdi = &bdi1;
5982 QEMUFile *f;
5983 int saved_vm_running;
5984 #ifdef _WIN32
5985 struct _timeb tb;
5986 #else
5987 struct timeval tv;
5988 #endif
5990 bs = get_bs_snapshots();
5991 if (!bs) {
5992 term_printf("No block device can accept snapshots\n");
5993 return;
5996 /* ??? Should this occur after vm_stop? */
5997 qemu_aio_flush();
5999 saved_vm_running = vm_running;
6000 vm_stop(0);
6002 must_delete = 0;
6003 if (name) {
6004 ret = bdrv_snapshot_find(bs, old_sn, name);
6005 if (ret >= 0) {
6006 must_delete = 1;
6009 memset(sn, 0, sizeof(*sn));
6010 if (must_delete) {
6011 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6012 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6013 } else {
6014 if (name)
6015 pstrcpy(sn->name, sizeof(sn->name), name);
6018 /* fill auxiliary fields */
6019 #ifdef _WIN32
6020 _ftime(&tb);
6021 sn->date_sec = tb.time;
6022 sn->date_nsec = tb.millitm * 1000000;
6023 #else
6024 gettimeofday(&tv, NULL);
6025 sn->date_sec = tv.tv_sec;
6026 sn->date_nsec = tv.tv_usec * 1000;
6027 #endif
6028 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6030 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6031 term_printf("Device %s does not support VM state snapshots\n",
6032 bdrv_get_device_name(bs));
6033 goto the_end;
6036 /* save the VM state */
6037 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6038 if (!f) {
6039 term_printf("Could not open VM state file\n");
6040 goto the_end;
6042 ret = qemu_savevm_state(f);
6043 sn->vm_state_size = qemu_ftell(f);
6044 qemu_fclose(f);
6045 if (ret < 0) {
6046 term_printf("Error %d while writing VM\n", ret);
6047 goto the_end;
6050 /* create the snapshots */
6052 for(i = 0; i < nb_drives; i++) {
6053 bs1 = drives_table[i].bdrv;
6054 if (bdrv_has_snapshot(bs1)) {
6055 if (must_delete) {
6056 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6057 if (ret < 0) {
6058 term_printf("Error while deleting snapshot on '%s'\n",
6059 bdrv_get_device_name(bs1));
6062 ret = bdrv_snapshot_create(bs1, sn);
6063 if (ret < 0) {
6064 term_printf("Error while creating snapshot on '%s'\n",
6065 bdrv_get_device_name(bs1));
6070 the_end:
6071 if (saved_vm_running)
6072 vm_start();
6075 void do_loadvm(const char *name)
6077 BlockDriverState *bs, *bs1;
6078 BlockDriverInfo bdi1, *bdi = &bdi1;
6079 QEMUFile *f;
6080 int i, ret;
6081 int saved_vm_running;
6083 bs = get_bs_snapshots();
6084 if (!bs) {
6085 term_printf("No block device supports snapshots\n");
6086 return;
6089 /* Flush all IO requests so they don't interfere with the new state. */
6090 qemu_aio_flush();
6092 saved_vm_running = vm_running;
6093 vm_stop(0);
6095 for(i = 0; i <= nb_drives; i++) {
6096 bs1 = drives_table[i].bdrv;
6097 if (bdrv_has_snapshot(bs1)) {
6098 ret = bdrv_snapshot_goto(bs1, name);
6099 if (ret < 0) {
6100 if (bs != bs1)
6101 term_printf("Warning: ");
6102 switch(ret) {
6103 case -ENOTSUP:
6104 term_printf("Snapshots not supported on device '%s'\n",
6105 bdrv_get_device_name(bs1));
6106 break;
6107 case -ENOENT:
6108 term_printf("Could not find snapshot '%s' on device '%s'\n",
6109 name, bdrv_get_device_name(bs1));
6110 break;
6111 default:
6112 term_printf("Error %d while activating snapshot on '%s'\n",
6113 ret, bdrv_get_device_name(bs1));
6114 break;
6116 /* fatal on snapshot block device */
6117 if (bs == bs1)
6118 goto the_end;
6123 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6124 term_printf("Device %s does not support VM state snapshots\n",
6125 bdrv_get_device_name(bs));
6126 return;
6129 /* restore the VM state */
6130 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6131 if (!f) {
6132 term_printf("Could not open VM state file\n");
6133 goto the_end;
6135 ret = qemu_loadvm_state(f);
6136 qemu_fclose(f);
6137 if (ret < 0) {
6138 term_printf("Error %d while loading VM state\n", ret);
6140 the_end:
6141 if (saved_vm_running)
6142 vm_start();
6145 void do_delvm(const char *name)
6147 BlockDriverState *bs, *bs1;
6148 int i, ret;
6150 bs = get_bs_snapshots();
6151 if (!bs) {
6152 term_printf("No block device supports snapshots\n");
6153 return;
6156 for(i = 0; i <= nb_drives; i++) {
6157 bs1 = drives_table[i].bdrv;
6158 if (bdrv_has_snapshot(bs1)) {
6159 ret = bdrv_snapshot_delete(bs1, name);
6160 if (ret < 0) {
6161 if (ret == -ENOTSUP)
6162 term_printf("Snapshots not supported on device '%s'\n",
6163 bdrv_get_device_name(bs1));
6164 else
6165 term_printf("Error %d while deleting snapshot on '%s'\n",
6166 ret, bdrv_get_device_name(bs1));
6172 void do_info_snapshots(void)
6174 BlockDriverState *bs, *bs1;
6175 QEMUSnapshotInfo *sn_tab, *sn;
6176 int nb_sns, i;
6177 char buf[256];
6179 bs = get_bs_snapshots();
6180 if (!bs) {
6181 term_printf("No available block device supports snapshots\n");
6182 return;
6184 term_printf("Snapshot devices:");
6185 for(i = 0; i <= nb_drives; i++) {
6186 bs1 = drives_table[i].bdrv;
6187 if (bdrv_has_snapshot(bs1)) {
6188 if (bs == bs1)
6189 term_printf(" %s", bdrv_get_device_name(bs1));
6192 term_printf("\n");
6194 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6195 if (nb_sns < 0) {
6196 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6197 return;
6199 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6200 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6201 for(i = 0; i < nb_sns; i++) {
6202 sn = &sn_tab[i];
6203 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6205 qemu_free(sn_tab);
6208 /***********************************************************/
6209 /* cpu save/restore */
6211 #if defined(TARGET_I386)
6213 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6215 qemu_put_be32(f, dt->selector);
6216 qemu_put_betl(f, dt->base);
6217 qemu_put_be32(f, dt->limit);
6218 qemu_put_be32(f, dt->flags);
6221 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6223 dt->selector = qemu_get_be32(f);
6224 dt->base = qemu_get_betl(f);
6225 dt->limit = qemu_get_be32(f);
6226 dt->flags = qemu_get_be32(f);
6229 void cpu_save(QEMUFile *f, void *opaque)
6231 CPUState *env = opaque;
6232 uint16_t fptag, fpus, fpuc, fpregs_format;
6233 uint32_t hflags;
6234 int i;
6236 for(i = 0; i < CPU_NB_REGS; i++)
6237 qemu_put_betls(f, &env->regs[i]);
6238 qemu_put_betls(f, &env->eip);
6239 qemu_put_betls(f, &env->eflags);
6240 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6241 qemu_put_be32s(f, &hflags);
6243 /* FPU */
6244 fpuc = env->fpuc;
6245 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6246 fptag = 0;
6247 for(i = 0; i < 8; i++) {
6248 fptag |= ((!env->fptags[i]) << i);
6251 qemu_put_be16s(f, &fpuc);
6252 qemu_put_be16s(f, &fpus);
6253 qemu_put_be16s(f, &fptag);
6255 #ifdef USE_X86LDOUBLE
6256 fpregs_format = 0;
6257 #else
6258 fpregs_format = 1;
6259 #endif
6260 qemu_put_be16s(f, &fpregs_format);
6262 for(i = 0; i < 8; i++) {
6263 #ifdef USE_X86LDOUBLE
6265 uint64_t mant;
6266 uint16_t exp;
6267 /* we save the real CPU data (in case of MMX usage only 'mant'
6268 contains the MMX register */
6269 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6270 qemu_put_be64(f, mant);
6271 qemu_put_be16(f, exp);
6273 #else
6274 /* if we use doubles for float emulation, we save the doubles to
6275 avoid losing information in case of MMX usage. It can give
6276 problems if the image is restored on a CPU where long
6277 doubles are used instead. */
6278 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6279 #endif
6282 for(i = 0; i < 6; i++)
6283 cpu_put_seg(f, &env->segs[i]);
6284 cpu_put_seg(f, &env->ldt);
6285 cpu_put_seg(f, &env->tr);
6286 cpu_put_seg(f, &env->gdt);
6287 cpu_put_seg(f, &env->idt);
6289 qemu_put_be32s(f, &env->sysenter_cs);
6290 qemu_put_be32s(f, &env->sysenter_esp);
6291 qemu_put_be32s(f, &env->sysenter_eip);
6293 qemu_put_betls(f, &env->cr[0]);
6294 qemu_put_betls(f, &env->cr[2]);
6295 qemu_put_betls(f, &env->cr[3]);
6296 qemu_put_betls(f, &env->cr[4]);
6298 for(i = 0; i < 8; i++)
6299 qemu_put_betls(f, &env->dr[i]);
6301 /* MMU */
6302 qemu_put_be32s(f, &env->a20_mask);
6304 /* XMM */
6305 qemu_put_be32s(f, &env->mxcsr);
6306 for(i = 0; i < CPU_NB_REGS; i++) {
6307 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6308 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6311 #ifdef TARGET_X86_64
6312 qemu_put_be64s(f, &env->efer);
6313 qemu_put_be64s(f, &env->star);
6314 qemu_put_be64s(f, &env->lstar);
6315 qemu_put_be64s(f, &env->cstar);
6316 qemu_put_be64s(f, &env->fmask);
6317 qemu_put_be64s(f, &env->kernelgsbase);
6318 #endif
6319 qemu_put_be32s(f, &env->smbase);
6322 #ifdef USE_X86LDOUBLE
6323 /* XXX: add that in a FPU generic layer */
6324 union x86_longdouble {
6325 uint64_t mant;
6326 uint16_t exp;
6329 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6330 #define EXPBIAS1 1023
6331 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6332 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6334 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6336 int e;
6337 /* mantissa */
6338 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6339 /* exponent + sign */
6340 e = EXPD1(temp) - EXPBIAS1 + 16383;
6341 e |= SIGND1(temp) >> 16;
6342 p->exp = e;
6344 #endif
6346 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6348 CPUState *env = opaque;
6349 int i, guess_mmx;
6350 uint32_t hflags;
6351 uint16_t fpus, fpuc, fptag, fpregs_format;
6353 if (version_id != 3 && version_id != 4)
6354 return -EINVAL;
6355 for(i = 0; i < CPU_NB_REGS; i++)
6356 qemu_get_betls(f, &env->regs[i]);
6357 qemu_get_betls(f, &env->eip);
6358 qemu_get_betls(f, &env->eflags);
6359 qemu_get_be32s(f, &hflags);
6361 qemu_get_be16s(f, &fpuc);
6362 qemu_get_be16s(f, &fpus);
6363 qemu_get_be16s(f, &fptag);
6364 qemu_get_be16s(f, &fpregs_format);
6366 /* NOTE: we cannot always restore the FPU state if the image come
6367 from a host with a different 'USE_X86LDOUBLE' define. We guess
6368 if we are in an MMX state to restore correctly in that case. */
6369 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6370 for(i = 0; i < 8; i++) {
6371 uint64_t mant;
6372 uint16_t exp;
6374 switch(fpregs_format) {
6375 case 0:
6376 mant = qemu_get_be64(f);
6377 exp = qemu_get_be16(f);
6378 #ifdef USE_X86LDOUBLE
6379 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6380 #else
6381 /* difficult case */
6382 if (guess_mmx)
6383 env->fpregs[i].mmx.MMX_Q(0) = mant;
6384 else
6385 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6386 #endif
6387 break;
6388 case 1:
6389 mant = qemu_get_be64(f);
6390 #ifdef USE_X86LDOUBLE
6392 union x86_longdouble *p;
6393 /* difficult case */
6394 p = (void *)&env->fpregs[i];
6395 if (guess_mmx) {
6396 p->mant = mant;
6397 p->exp = 0xffff;
6398 } else {
6399 fp64_to_fp80(p, mant);
6402 #else
6403 env->fpregs[i].mmx.MMX_Q(0) = mant;
6404 #endif
6405 break;
6406 default:
6407 return -EINVAL;
6411 env->fpuc = fpuc;
6412 /* XXX: restore FPU round state */
6413 env->fpstt = (fpus >> 11) & 7;
6414 env->fpus = fpus & ~0x3800;
6415 fptag ^= 0xff;
6416 for(i = 0; i < 8; i++) {
6417 env->fptags[i] = (fptag >> i) & 1;
6420 for(i = 0; i < 6; i++)
6421 cpu_get_seg(f, &env->segs[i]);
6422 cpu_get_seg(f, &env->ldt);
6423 cpu_get_seg(f, &env->tr);
6424 cpu_get_seg(f, &env->gdt);
6425 cpu_get_seg(f, &env->idt);
6427 qemu_get_be32s(f, &env->sysenter_cs);
6428 qemu_get_be32s(f, &env->sysenter_esp);
6429 qemu_get_be32s(f, &env->sysenter_eip);
6431 qemu_get_betls(f, &env->cr[0]);
6432 qemu_get_betls(f, &env->cr[2]);
6433 qemu_get_betls(f, &env->cr[3]);
6434 qemu_get_betls(f, &env->cr[4]);
6436 for(i = 0; i < 8; i++)
6437 qemu_get_betls(f, &env->dr[i]);
6439 /* MMU */
6440 qemu_get_be32s(f, &env->a20_mask);
6442 qemu_get_be32s(f, &env->mxcsr);
6443 for(i = 0; i < CPU_NB_REGS; i++) {
6444 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6445 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6448 #ifdef TARGET_X86_64
6449 qemu_get_be64s(f, &env->efer);
6450 qemu_get_be64s(f, &env->star);
6451 qemu_get_be64s(f, &env->lstar);
6452 qemu_get_be64s(f, &env->cstar);
6453 qemu_get_be64s(f, &env->fmask);
6454 qemu_get_be64s(f, &env->kernelgsbase);
6455 #endif
6456 if (version_id >= 4)
6457 qemu_get_be32s(f, &env->smbase);
6459 /* XXX: compute hflags from scratch, except for CPL and IIF */
6460 env->hflags = hflags;
6461 tlb_flush(env, 1);
6462 return 0;
6465 #elif defined(TARGET_PPC)
6466 void cpu_save(QEMUFile *f, void *opaque)
6470 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6472 return 0;
6475 #elif defined(TARGET_MIPS)
6476 void cpu_save(QEMUFile *f, void *opaque)
6480 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6482 return 0;
6485 #elif defined(TARGET_SPARC)
6486 void cpu_save(QEMUFile *f, void *opaque)
6488 CPUState *env = opaque;
6489 int i;
6490 uint32_t tmp;
6492 for(i = 0; i < 8; i++)
6493 qemu_put_betls(f, &env->gregs[i]);
6494 for(i = 0; i < NWINDOWS * 16; i++)
6495 qemu_put_betls(f, &env->regbase[i]);
6497 /* FPU */
6498 for(i = 0; i < TARGET_FPREGS; i++) {
6499 union {
6500 float32 f;
6501 uint32_t i;
6502 } u;
6503 u.f = env->fpr[i];
6504 qemu_put_be32(f, u.i);
6507 qemu_put_betls(f, &env->pc);
6508 qemu_put_betls(f, &env->npc);
6509 qemu_put_betls(f, &env->y);
6510 tmp = GET_PSR(env);
6511 qemu_put_be32(f, tmp);
6512 qemu_put_betls(f, &env->fsr);
6513 qemu_put_betls(f, &env->tbr);
6514 #ifndef TARGET_SPARC64
6515 qemu_put_be32s(f, &env->wim);
6516 /* MMU */
6517 for(i = 0; i < 16; i++)
6518 qemu_put_be32s(f, &env->mmuregs[i]);
6519 #endif
6522 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6524 CPUState *env = opaque;
6525 int i;
6526 uint32_t tmp;
6528 for(i = 0; i < 8; i++)
6529 qemu_get_betls(f, &env->gregs[i]);
6530 for(i = 0; i < NWINDOWS * 16; i++)
6531 qemu_get_betls(f, &env->regbase[i]);
6533 /* FPU */
6534 for(i = 0; i < TARGET_FPREGS; i++) {
6535 union {
6536 float32 f;
6537 uint32_t i;
6538 } u;
6539 u.i = qemu_get_be32(f);
6540 env->fpr[i] = u.f;
6543 qemu_get_betls(f, &env->pc);
6544 qemu_get_betls(f, &env->npc);
6545 qemu_get_betls(f, &env->y);
6546 tmp = qemu_get_be32(f);
6547 env->cwp = 0; /* needed to ensure that the wrapping registers are
6548 correctly updated */
6549 PUT_PSR(env, tmp);
6550 qemu_get_betls(f, &env->fsr);
6551 qemu_get_betls(f, &env->tbr);
6552 #ifndef TARGET_SPARC64
6553 qemu_get_be32s(f, &env->wim);
6554 /* MMU */
6555 for(i = 0; i < 16; i++)
6556 qemu_get_be32s(f, &env->mmuregs[i]);
6557 #endif
6558 tlb_flush(env, 1);
6559 return 0;
6562 #elif defined(TARGET_ARM)
6564 void cpu_save(QEMUFile *f, void *opaque)
6566 int i;
6567 CPUARMState *env = (CPUARMState *)opaque;
6569 for (i = 0; i < 16; i++) {
6570 qemu_put_be32(f, env->regs[i]);
6572 qemu_put_be32(f, cpsr_read(env));
6573 qemu_put_be32(f, env->spsr);
6574 for (i = 0; i < 6; i++) {
6575 qemu_put_be32(f, env->banked_spsr[i]);
6576 qemu_put_be32(f, env->banked_r13[i]);
6577 qemu_put_be32(f, env->banked_r14[i]);
6579 for (i = 0; i < 5; i++) {
6580 qemu_put_be32(f, env->usr_regs[i]);
6581 qemu_put_be32(f, env->fiq_regs[i]);
6583 qemu_put_be32(f, env->cp15.c0_cpuid);
6584 qemu_put_be32(f, env->cp15.c0_cachetype);
6585 qemu_put_be32(f, env->cp15.c1_sys);
6586 qemu_put_be32(f, env->cp15.c1_coproc);
6587 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6588 qemu_put_be32(f, env->cp15.c2_base0);
6589 qemu_put_be32(f, env->cp15.c2_base1);
6590 qemu_put_be32(f, env->cp15.c2_mask);
6591 qemu_put_be32(f, env->cp15.c2_data);
6592 qemu_put_be32(f, env->cp15.c2_insn);
6593 qemu_put_be32(f, env->cp15.c3);
6594 qemu_put_be32(f, env->cp15.c5_insn);
6595 qemu_put_be32(f, env->cp15.c5_data);
6596 for (i = 0; i < 8; i++) {
6597 qemu_put_be32(f, env->cp15.c6_region[i]);
6599 qemu_put_be32(f, env->cp15.c6_insn);
6600 qemu_put_be32(f, env->cp15.c6_data);
6601 qemu_put_be32(f, env->cp15.c9_insn);
6602 qemu_put_be32(f, env->cp15.c9_data);
6603 qemu_put_be32(f, env->cp15.c13_fcse);
6604 qemu_put_be32(f, env->cp15.c13_context);
6605 qemu_put_be32(f, env->cp15.c13_tls1);
6606 qemu_put_be32(f, env->cp15.c13_tls2);
6607 qemu_put_be32(f, env->cp15.c13_tls3);
6608 qemu_put_be32(f, env->cp15.c15_cpar);
6610 qemu_put_be32(f, env->features);
6612 if (arm_feature(env, ARM_FEATURE_VFP)) {
6613 for (i = 0; i < 16; i++) {
6614 CPU_DoubleU u;
6615 u.d = env->vfp.regs[i];
6616 qemu_put_be32(f, u.l.upper);
6617 qemu_put_be32(f, u.l.lower);
6619 for (i = 0; i < 16; i++) {
6620 qemu_put_be32(f, env->vfp.xregs[i]);
6623 /* TODO: Should use proper FPSCR access functions. */
6624 qemu_put_be32(f, env->vfp.vec_len);
6625 qemu_put_be32(f, env->vfp.vec_stride);
6627 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6628 for (i = 16; i < 32; i++) {
6629 CPU_DoubleU u;
6630 u.d = env->vfp.regs[i];
6631 qemu_put_be32(f, u.l.upper);
6632 qemu_put_be32(f, u.l.lower);
6637 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6638 for (i = 0; i < 16; i++) {
6639 qemu_put_be64(f, env->iwmmxt.regs[i]);
6641 for (i = 0; i < 16; i++) {
6642 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6646 if (arm_feature(env, ARM_FEATURE_M)) {
6647 qemu_put_be32(f, env->v7m.other_sp);
6648 qemu_put_be32(f, env->v7m.vecbase);
6649 qemu_put_be32(f, env->v7m.basepri);
6650 qemu_put_be32(f, env->v7m.control);
6651 qemu_put_be32(f, env->v7m.current_sp);
6652 qemu_put_be32(f, env->v7m.exception);
6656 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6658 CPUARMState *env = (CPUARMState *)opaque;
6659 int i;
6661 if (version_id != ARM_CPU_SAVE_VERSION)
6662 return -EINVAL;
6664 for (i = 0; i < 16; i++) {
6665 env->regs[i] = qemu_get_be32(f);
6667 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6668 env->spsr = qemu_get_be32(f);
6669 for (i = 0; i < 6; i++) {
6670 env->banked_spsr[i] = qemu_get_be32(f);
6671 env->banked_r13[i] = qemu_get_be32(f);
6672 env->banked_r14[i] = qemu_get_be32(f);
6674 for (i = 0; i < 5; i++) {
6675 env->usr_regs[i] = qemu_get_be32(f);
6676 env->fiq_regs[i] = qemu_get_be32(f);
6678 env->cp15.c0_cpuid = qemu_get_be32(f);
6679 env->cp15.c0_cachetype = qemu_get_be32(f);
6680 env->cp15.c1_sys = qemu_get_be32(f);
6681 env->cp15.c1_coproc = qemu_get_be32(f);
6682 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6683 env->cp15.c2_base0 = qemu_get_be32(f);
6684 env->cp15.c2_base1 = qemu_get_be32(f);
6685 env->cp15.c2_mask = qemu_get_be32(f);
6686 env->cp15.c2_data = qemu_get_be32(f);
6687 env->cp15.c2_insn = qemu_get_be32(f);
6688 env->cp15.c3 = qemu_get_be32(f);
6689 env->cp15.c5_insn = qemu_get_be32(f);
6690 env->cp15.c5_data = qemu_get_be32(f);
6691 for (i = 0; i < 8; i++) {
6692 env->cp15.c6_region[i] = qemu_get_be32(f);
6694 env->cp15.c6_insn = qemu_get_be32(f);
6695 env->cp15.c6_data = qemu_get_be32(f);
6696 env->cp15.c9_insn = qemu_get_be32(f);
6697 env->cp15.c9_data = qemu_get_be32(f);
6698 env->cp15.c13_fcse = qemu_get_be32(f);
6699 env->cp15.c13_context = qemu_get_be32(f);
6700 env->cp15.c13_tls1 = qemu_get_be32(f);
6701 env->cp15.c13_tls2 = qemu_get_be32(f);
6702 env->cp15.c13_tls3 = qemu_get_be32(f);
6703 env->cp15.c15_cpar = qemu_get_be32(f);
6705 env->features = qemu_get_be32(f);
6707 if (arm_feature(env, ARM_FEATURE_VFP)) {
6708 for (i = 0; i < 16; i++) {
6709 CPU_DoubleU u;
6710 u.l.upper = qemu_get_be32(f);
6711 u.l.lower = qemu_get_be32(f);
6712 env->vfp.regs[i] = u.d;
6714 for (i = 0; i < 16; i++) {
6715 env->vfp.xregs[i] = qemu_get_be32(f);
6718 /* TODO: Should use proper FPSCR access functions. */
6719 env->vfp.vec_len = qemu_get_be32(f);
6720 env->vfp.vec_stride = qemu_get_be32(f);
6722 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6723 for (i = 0; i < 16; i++) {
6724 CPU_DoubleU u;
6725 u.l.upper = qemu_get_be32(f);
6726 u.l.lower = qemu_get_be32(f);
6727 env->vfp.regs[i] = u.d;
6732 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6733 for (i = 0; i < 16; i++) {
6734 env->iwmmxt.regs[i] = qemu_get_be64(f);
6736 for (i = 0; i < 16; i++) {
6737 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6741 if (arm_feature(env, ARM_FEATURE_M)) {
6742 env->v7m.other_sp = qemu_get_be32(f);
6743 env->v7m.vecbase = qemu_get_be32(f);
6744 env->v7m.basepri = qemu_get_be32(f);
6745 env->v7m.control = qemu_get_be32(f);
6746 env->v7m.current_sp = qemu_get_be32(f);
6747 env->v7m.exception = qemu_get_be32(f);
6750 return 0;
6753 #else
6755 //#warning No CPU save/restore functions
6757 #endif
6759 /***********************************************************/
6760 /* ram save/restore */
6762 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6764 int v;
6766 v = qemu_get_byte(f);
6767 switch(v) {
6768 case 0:
6769 if (qemu_get_buffer(f, buf, len) != len)
6770 return -EIO;
6771 break;
6772 case 1:
6773 v = qemu_get_byte(f);
6774 memset(buf, v, len);
6775 break;
6776 default:
6777 return -EINVAL;
6779 return 0;
6782 static int ram_load_v1(QEMUFile *f, void *opaque)
6784 int i, ret;
6786 if (qemu_get_be32(f) != phys_ram_size)
6787 return -EINVAL;
6788 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6789 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6790 if (ret)
6791 return ret;
6793 return 0;
6796 #define BDRV_HASH_BLOCK_SIZE 1024
6797 #define IOBUF_SIZE 4096
6798 #define RAM_CBLOCK_MAGIC 0xfabe
6800 typedef struct RamCompressState {
6801 z_stream zstream;
6802 QEMUFile *f;
6803 uint8_t buf[IOBUF_SIZE];
6804 } RamCompressState;
6806 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6808 int ret;
6809 memset(s, 0, sizeof(*s));
6810 s->f = f;
6811 ret = deflateInit2(&s->zstream, 1,
6812 Z_DEFLATED, 15,
6813 9, Z_DEFAULT_STRATEGY);
6814 if (ret != Z_OK)
6815 return -1;
6816 s->zstream.avail_out = IOBUF_SIZE;
6817 s->zstream.next_out = s->buf;
6818 return 0;
6821 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6823 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6824 qemu_put_be16(s->f, len);
6825 qemu_put_buffer(s->f, buf, len);
6828 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6830 int ret;
6832 s->zstream.avail_in = len;
6833 s->zstream.next_in = (uint8_t *)buf;
6834 while (s->zstream.avail_in > 0) {
6835 ret = deflate(&s->zstream, Z_NO_FLUSH);
6836 if (ret != Z_OK)
6837 return -1;
6838 if (s->zstream.avail_out == 0) {
6839 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6840 s->zstream.avail_out = IOBUF_SIZE;
6841 s->zstream.next_out = s->buf;
6844 return 0;
6847 static void ram_compress_close(RamCompressState *s)
6849 int len, ret;
6851 /* compress last bytes */
6852 for(;;) {
6853 ret = deflate(&s->zstream, Z_FINISH);
6854 if (ret == Z_OK || ret == Z_STREAM_END) {
6855 len = IOBUF_SIZE - s->zstream.avail_out;
6856 if (len > 0) {
6857 ram_put_cblock(s, s->buf, len);
6859 s->zstream.avail_out = IOBUF_SIZE;
6860 s->zstream.next_out = s->buf;
6861 if (ret == Z_STREAM_END)
6862 break;
6863 } else {
6864 goto fail;
6867 fail:
6868 deflateEnd(&s->zstream);
6871 typedef struct RamDecompressState {
6872 z_stream zstream;
6873 QEMUFile *f;
6874 uint8_t buf[IOBUF_SIZE];
6875 } RamDecompressState;
6877 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6879 int ret;
6880 memset(s, 0, sizeof(*s));
6881 s->f = f;
6882 ret = inflateInit(&s->zstream);
6883 if (ret != Z_OK)
6884 return -1;
6885 return 0;
6888 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6890 int ret, clen;
6892 s->zstream.avail_out = len;
6893 s->zstream.next_out = buf;
6894 while (s->zstream.avail_out > 0) {
6895 if (s->zstream.avail_in == 0) {
6896 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6897 return -1;
6898 clen = qemu_get_be16(s->f);
6899 if (clen > IOBUF_SIZE)
6900 return -1;
6901 qemu_get_buffer(s->f, s->buf, clen);
6902 s->zstream.avail_in = clen;
6903 s->zstream.next_in = s->buf;
6905 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6906 if (ret != Z_OK && ret != Z_STREAM_END) {
6907 return -1;
6910 return 0;
6913 static void ram_decompress_close(RamDecompressState *s)
6915 inflateEnd(&s->zstream);
6918 static void ram_save(QEMUFile *f, void *opaque)
6920 int i;
6921 RamCompressState s1, *s = &s1;
6922 uint8_t buf[10];
6924 qemu_put_be32(f, phys_ram_size);
6925 if (ram_compress_open(s, f) < 0)
6926 return;
6927 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6928 #if 0
6929 if (tight_savevm_enabled) {
6930 int64_t sector_num;
6931 int j;
6933 /* find if the memory block is available on a virtual
6934 block device */
6935 sector_num = -1;
6936 for(j = 0; j < nb_drives; j++) {
6937 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6938 phys_ram_base + i,
6939 BDRV_HASH_BLOCK_SIZE);
6940 if (sector_num >= 0)
6941 break;
6943 if (j == nb_drives)
6944 goto normal_compress;
6945 buf[0] = 1;
6946 buf[1] = j;
6947 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6948 ram_compress_buf(s, buf, 10);
6949 } else
6950 #endif
6952 // normal_compress:
6953 buf[0] = 0;
6954 ram_compress_buf(s, buf, 1);
6955 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6958 ram_compress_close(s);
6961 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6963 RamDecompressState s1, *s = &s1;
6964 uint8_t buf[10];
6965 int i;
6967 if (version_id == 1)
6968 return ram_load_v1(f, opaque);
6969 if (version_id != 2)
6970 return -EINVAL;
6971 if (qemu_get_be32(f) != phys_ram_size)
6972 return -EINVAL;
6973 if (ram_decompress_open(s, f) < 0)
6974 return -EINVAL;
6975 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6976 if (ram_decompress_buf(s, buf, 1) < 0) {
6977 fprintf(stderr, "Error while reading ram block header\n");
6978 goto error;
6980 if (buf[0] == 0) {
6981 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6982 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6983 goto error;
6985 } else
6986 #if 0
6987 if (buf[0] == 1) {
6988 int bs_index;
6989 int64_t sector_num;
6991 ram_decompress_buf(s, buf + 1, 9);
6992 bs_index = buf[1];
6993 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6994 if (bs_index >= nb_drives) {
6995 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6996 goto error;
6998 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6999 phys_ram_base + i,
7000 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7001 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7002 bs_index, sector_num);
7003 goto error;
7005 } else
7006 #endif
7008 error:
7009 printf("Error block header\n");
7010 return -EINVAL;
7013 ram_decompress_close(s);
7014 return 0;
7017 /***********************************************************/
7018 /* bottom halves (can be seen as timers which expire ASAP) */
7020 struct QEMUBH {
7021 QEMUBHFunc *cb;
7022 void *opaque;
7023 int scheduled;
7024 QEMUBH *next;
7027 static QEMUBH *first_bh = NULL;
7029 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7031 QEMUBH *bh;
7032 bh = qemu_mallocz(sizeof(QEMUBH));
7033 if (!bh)
7034 return NULL;
7035 bh->cb = cb;
7036 bh->opaque = opaque;
7037 return bh;
7040 int qemu_bh_poll(void)
7042 QEMUBH *bh, **pbh;
7043 int ret;
7045 ret = 0;
7046 for(;;) {
7047 pbh = &first_bh;
7048 bh = *pbh;
7049 if (!bh)
7050 break;
7051 ret = 1;
7052 *pbh = bh->next;
7053 bh->scheduled = 0;
7054 bh->cb(bh->opaque);
7056 return ret;
7059 void qemu_bh_schedule(QEMUBH *bh)
7061 CPUState *env = cpu_single_env;
7062 if (bh->scheduled)
7063 return;
7064 bh->scheduled = 1;
7065 bh->next = first_bh;
7066 first_bh = bh;
7068 /* stop the currently executing CPU to execute the BH ASAP */
7069 if (env) {
7070 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7074 void qemu_bh_cancel(QEMUBH *bh)
7076 QEMUBH **pbh;
7077 if (bh->scheduled) {
7078 pbh = &first_bh;
7079 while (*pbh != bh)
7080 pbh = &(*pbh)->next;
7081 *pbh = bh->next;
7082 bh->scheduled = 0;
7086 void qemu_bh_delete(QEMUBH *bh)
7088 qemu_bh_cancel(bh);
7089 qemu_free(bh);
7092 /***********************************************************/
7093 /* machine registration */
7095 QEMUMachine *first_machine = NULL;
7097 int qemu_register_machine(QEMUMachine *m)
7099 QEMUMachine **pm;
7100 pm = &first_machine;
7101 while (*pm != NULL)
7102 pm = &(*pm)->next;
7103 m->next = NULL;
7104 *pm = m;
7105 return 0;
7108 static QEMUMachine *find_machine(const char *name)
7110 QEMUMachine *m;
7112 for(m = first_machine; m != NULL; m = m->next) {
7113 if (!strcmp(m->name, name))
7114 return m;
7116 return NULL;
7119 /***********************************************************/
7120 /* main execution loop */
7122 static void gui_update(void *opaque)
7124 DisplayState *ds = opaque;
7125 ds->dpy_refresh(ds);
7126 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7129 struct vm_change_state_entry {
7130 VMChangeStateHandler *cb;
7131 void *opaque;
7132 LIST_ENTRY (vm_change_state_entry) entries;
7135 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7137 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7138 void *opaque)
7140 VMChangeStateEntry *e;
7142 e = qemu_mallocz(sizeof (*e));
7143 if (!e)
7144 return NULL;
7146 e->cb = cb;
7147 e->opaque = opaque;
7148 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7149 return e;
7152 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7154 LIST_REMOVE (e, entries);
7155 qemu_free (e);
7158 static void vm_state_notify(int running)
7160 VMChangeStateEntry *e;
7162 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7163 e->cb(e->opaque, running);
7167 /* XXX: support several handlers */
7168 static VMStopHandler *vm_stop_cb;
7169 static void *vm_stop_opaque;
7171 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7173 vm_stop_cb = cb;
7174 vm_stop_opaque = opaque;
7175 return 0;
7178 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7180 vm_stop_cb = NULL;
7183 void vm_start(void)
7185 if (!vm_running) {
7186 cpu_enable_ticks();
7187 vm_running = 1;
7188 vm_state_notify(1);
7189 qemu_rearm_alarm_timer(alarm_timer);
7193 void vm_stop(int reason)
7195 if (vm_running) {
7196 cpu_disable_ticks();
7197 vm_running = 0;
7198 if (reason != 0) {
7199 if (vm_stop_cb) {
7200 vm_stop_cb(vm_stop_opaque, reason);
7203 vm_state_notify(0);
7207 /* reset/shutdown handler */
7209 typedef struct QEMUResetEntry {
7210 QEMUResetHandler *func;
7211 void *opaque;
7212 struct QEMUResetEntry *next;
7213 } QEMUResetEntry;
7215 static QEMUResetEntry *first_reset_entry;
7216 static int reset_requested;
7217 static int shutdown_requested;
7218 static int powerdown_requested;
7220 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7222 QEMUResetEntry **pre, *re;
7224 pre = &first_reset_entry;
7225 while (*pre != NULL)
7226 pre = &(*pre)->next;
7227 re = qemu_mallocz(sizeof(QEMUResetEntry));
7228 re->func = func;
7229 re->opaque = opaque;
7230 re->next = NULL;
7231 *pre = re;
7234 static void qemu_system_reset(void)
7236 QEMUResetEntry *re;
7238 /* reset all devices */
7239 for(re = first_reset_entry; re != NULL; re = re->next) {
7240 re->func(re->opaque);
7244 void qemu_system_reset_request(void)
7246 if (no_reboot) {
7247 shutdown_requested = 1;
7248 } else {
7249 reset_requested = 1;
7251 if (cpu_single_env)
7252 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7255 void qemu_system_shutdown_request(void)
7257 shutdown_requested = 1;
7258 if (cpu_single_env)
7259 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7262 void qemu_system_powerdown_request(void)
7264 powerdown_requested = 1;
7265 if (cpu_single_env)
7266 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7269 void main_loop_wait(int timeout)
7271 IOHandlerRecord *ioh;
7272 fd_set rfds, wfds, xfds;
7273 int ret, nfds;
7274 #ifdef _WIN32
7275 int ret2, i;
7276 #endif
7277 struct timeval tv;
7278 PollingEntry *pe;
7281 /* XXX: need to suppress polling by better using win32 events */
7282 ret = 0;
7283 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7284 ret |= pe->func(pe->opaque);
7286 #ifdef _WIN32
7287 if (ret == 0) {
7288 int err;
7289 WaitObjects *w = &wait_objects;
7291 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7292 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7293 if (w->func[ret - WAIT_OBJECT_0])
7294 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7296 /* Check for additional signaled events */
7297 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7299 /* Check if event is signaled */
7300 ret2 = WaitForSingleObject(w->events[i], 0);
7301 if(ret2 == WAIT_OBJECT_0) {
7302 if (w->func[i])
7303 w->func[i](w->opaque[i]);
7304 } else if (ret2 == WAIT_TIMEOUT) {
7305 } else {
7306 err = GetLastError();
7307 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7310 } else if (ret == WAIT_TIMEOUT) {
7311 } else {
7312 err = GetLastError();
7313 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7316 #endif
7317 /* poll any events */
7318 /* XXX: separate device handlers from system ones */
7319 nfds = -1;
7320 FD_ZERO(&rfds);
7321 FD_ZERO(&wfds);
7322 FD_ZERO(&xfds);
7323 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7324 if (ioh->deleted)
7325 continue;
7326 if (ioh->fd_read &&
7327 (!ioh->fd_read_poll ||
7328 ioh->fd_read_poll(ioh->opaque) != 0)) {
7329 FD_SET(ioh->fd, &rfds);
7330 if (ioh->fd > nfds)
7331 nfds = ioh->fd;
7333 if (ioh->fd_write) {
7334 FD_SET(ioh->fd, &wfds);
7335 if (ioh->fd > nfds)
7336 nfds = ioh->fd;
7340 tv.tv_sec = 0;
7341 #ifdef _WIN32
7342 tv.tv_usec = 0;
7343 #else
7344 tv.tv_usec = timeout * 1000;
7345 #endif
7346 #if defined(CONFIG_SLIRP)
7347 if (slirp_inited) {
7348 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7350 #endif
7351 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7352 if (ret > 0) {
7353 IOHandlerRecord **pioh;
7355 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7356 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7357 ioh->fd_read(ioh->opaque);
7359 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7360 ioh->fd_write(ioh->opaque);
7364 /* remove deleted IO handlers */
7365 pioh = &first_io_handler;
7366 while (*pioh) {
7367 ioh = *pioh;
7368 if (ioh->deleted) {
7369 *pioh = ioh->next;
7370 qemu_free(ioh);
7371 } else
7372 pioh = &ioh->next;
7375 #if defined(CONFIG_SLIRP)
7376 if (slirp_inited) {
7377 if (ret < 0) {
7378 FD_ZERO(&rfds);
7379 FD_ZERO(&wfds);
7380 FD_ZERO(&xfds);
7382 slirp_select_poll(&rfds, &wfds, &xfds);
7384 #endif
7385 qemu_aio_poll();
7387 if (vm_running) {
7388 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7389 qemu_get_clock(vm_clock));
7390 /* run dma transfers, if any */
7391 DMA_run();
7394 /* real time timers */
7395 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7396 qemu_get_clock(rt_clock));
7398 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7399 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7400 qemu_rearm_alarm_timer(alarm_timer);
7403 /* Check bottom-halves last in case any of the earlier events triggered
7404 them. */
7405 qemu_bh_poll();
7409 static int main_loop(void)
7411 int ret, timeout;
7412 #ifdef CONFIG_PROFILER
7413 int64_t ti;
7414 #endif
7415 CPUState *env;
7417 cur_cpu = first_cpu;
7418 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7419 for(;;) {
7420 if (vm_running) {
7422 for(;;) {
7423 /* get next cpu */
7424 env = next_cpu;
7425 #ifdef CONFIG_PROFILER
7426 ti = profile_getclock();
7427 #endif
7428 ret = cpu_exec(env);
7429 #ifdef CONFIG_PROFILER
7430 qemu_time += profile_getclock() - ti;
7431 #endif
7432 next_cpu = env->next_cpu ?: first_cpu;
7433 if (event_pending) {
7434 ret = EXCP_INTERRUPT;
7435 event_pending = 0;
7436 break;
7438 if (ret == EXCP_HLT) {
7439 /* Give the next CPU a chance to run. */
7440 cur_cpu = env;
7441 continue;
7443 if (ret != EXCP_HALTED)
7444 break;
7445 /* all CPUs are halted ? */
7446 if (env == cur_cpu)
7447 break;
7449 cur_cpu = env;
7451 if (shutdown_requested) {
7452 ret = EXCP_INTERRUPT;
7453 break;
7455 if (reset_requested) {
7456 reset_requested = 0;
7457 qemu_system_reset();
7458 ret = EXCP_INTERRUPT;
7460 if (powerdown_requested) {
7461 powerdown_requested = 0;
7462 qemu_system_powerdown();
7463 ret = EXCP_INTERRUPT;
7465 if (ret == EXCP_DEBUG) {
7466 vm_stop(EXCP_DEBUG);
7468 /* If all cpus are halted then wait until the next IRQ */
7469 /* XXX: use timeout computed from timers */
7470 if (ret == EXCP_HALTED)
7471 timeout = 10;
7472 else
7473 timeout = 0;
7474 } else {
7475 timeout = 10;
7477 #ifdef CONFIG_PROFILER
7478 ti = profile_getclock();
7479 #endif
7480 main_loop_wait(timeout);
7481 #ifdef CONFIG_PROFILER
7482 dev_time += profile_getclock() - ti;
7483 #endif
7485 cpu_disable_ticks();
7486 return ret;
7489 static void help(int exitcode)
7491 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7492 "usage: %s [options] [disk_image]\n"
7493 "\n"
7494 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7495 "\n"
7496 "Standard options:\n"
7497 "-M machine select emulated machine (-M ? for list)\n"
7498 "-cpu cpu select CPU (-cpu ? for list)\n"
7499 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7500 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7501 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7502 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7503 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7504 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7505 " [,cache=on|off]\n"
7506 " use 'file' as a drive image\n"
7507 "-mtdblock file use 'file' as on-board Flash memory image\n"
7508 "-sd file use 'file' as SecureDigital card image\n"
7509 "-pflash file use 'file' as a parallel flash image\n"
7510 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7511 "-snapshot write to temporary files instead of disk image files\n"
7512 #ifdef CONFIG_SDL
7513 "-no-frame open SDL window without a frame and window decorations\n"
7514 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7515 "-no-quit disable SDL window close capability\n"
7516 #endif
7517 #ifdef TARGET_I386
7518 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7519 #endif
7520 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7521 "-smp n set the number of CPUs to 'n' [default=1]\n"
7522 "-nographic disable graphical output and redirect serial I/Os to console\n"
7523 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7524 #ifndef _WIN32
7525 "-k language use keyboard layout (for example \"fr\" for French)\n"
7526 #endif
7527 #ifdef HAS_AUDIO
7528 "-audio-help print list of audio drivers and their options\n"
7529 "-soundhw c1,... enable audio support\n"
7530 " and only specified sound cards (comma separated list)\n"
7531 " use -soundhw ? to get the list of supported cards\n"
7532 " use -soundhw all to enable all of them\n"
7533 #endif
7534 "-localtime set the real time clock to local time [default=utc]\n"
7535 "-full-screen start in full screen\n"
7536 #ifdef TARGET_I386
7537 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7538 #endif
7539 "-usb enable the USB driver (will be the default soon)\n"
7540 "-usbdevice name add the host or guest USB device 'name'\n"
7541 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7542 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7543 #endif
7544 "-name string set the name of the guest\n"
7545 "\n"
7546 "Network options:\n"
7547 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7548 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7549 #ifdef CONFIG_SLIRP
7550 "-net user[,vlan=n][,hostname=host]\n"
7551 " connect the user mode network stack to VLAN 'n' and send\n"
7552 " hostname 'host' to DHCP clients\n"
7553 #endif
7554 #ifdef _WIN32
7555 "-net tap[,vlan=n],ifname=name\n"
7556 " connect the host TAP network interface to VLAN 'n'\n"
7557 #else
7558 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7559 " connect the host TAP network interface to VLAN 'n' and use the\n"
7560 " network scripts 'file' (default=%s)\n"
7561 " and 'dfile' (default=%s);\n"
7562 " use '[down]script=no' to disable script execution;\n"
7563 " use 'fd=h' to connect to an already opened TAP interface\n"
7564 #endif
7565 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7566 " connect the vlan 'n' to another VLAN using a socket connection\n"
7567 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7568 " connect the vlan 'n' to multicast maddr and port\n"
7569 "-net none use it alone to have zero network devices; if no -net option\n"
7570 " is provided, the default is '-net nic -net user'\n"
7571 "\n"
7572 #ifdef CONFIG_SLIRP
7573 "-tftp dir allow tftp access to files in dir [-net user]\n"
7574 "-bootp file advertise file in BOOTP replies\n"
7575 #ifndef _WIN32
7576 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7577 #endif
7578 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7579 " redirect TCP or UDP connections from host to guest [-net user]\n"
7580 #endif
7581 "\n"
7582 "Linux boot specific:\n"
7583 "-kernel bzImage use 'bzImage' as kernel image\n"
7584 "-append cmdline use 'cmdline' as kernel command line\n"
7585 "-initrd file use 'file' as initial ram disk\n"
7586 "\n"
7587 "Debug/Expert options:\n"
7588 "-monitor dev redirect the monitor to char device 'dev'\n"
7589 "-serial dev redirect the serial port to char device 'dev'\n"
7590 "-parallel dev redirect the parallel port to char device 'dev'\n"
7591 "-pidfile file Write PID to 'file'\n"
7592 "-S freeze CPU at startup (use 'c' to start execution)\n"
7593 "-s wait gdb connection to port\n"
7594 "-p port set gdb connection port [default=%s]\n"
7595 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7596 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7597 " translation (t=none or lba) (usually qemu can guess them)\n"
7598 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7599 #ifdef USE_KQEMU
7600 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7601 "-no-kqemu disable KQEMU kernel module usage\n"
7602 #endif
7603 #ifdef TARGET_I386
7604 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7605 " (default is CL-GD5446 PCI VGA)\n"
7606 "-no-acpi disable ACPI\n"
7607 #endif
7608 "-no-reboot exit instead of rebooting\n"
7609 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7610 "-vnc display start a VNC server on display\n"
7611 #ifndef _WIN32
7612 "-daemonize daemonize QEMU after initializing\n"
7613 #endif
7614 "-option-rom rom load a file, rom, into the option ROM space\n"
7615 #ifdef TARGET_SPARC
7616 "-prom-env variable=value set OpenBIOS nvram variables\n"
7617 #endif
7618 "-clock force the use of the given methods for timer alarm.\n"
7619 " To see what timers are available use -clock help\n"
7620 "\n"
7621 "During emulation, the following keys are useful:\n"
7622 "ctrl-alt-f toggle full screen\n"
7623 "ctrl-alt-n switch to virtual console 'n'\n"
7624 "ctrl-alt toggle mouse and keyboard grab\n"
7625 "\n"
7626 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7628 "qemu",
7629 DEFAULT_RAM_SIZE,
7630 #ifndef _WIN32
7631 DEFAULT_NETWORK_SCRIPT,
7632 DEFAULT_NETWORK_DOWN_SCRIPT,
7633 #endif
7634 DEFAULT_GDBSTUB_PORT,
7635 "/tmp/qemu.log");
7636 exit(exitcode);
7639 #define HAS_ARG 0x0001
7641 enum {
7642 QEMU_OPTION_h,
7644 QEMU_OPTION_M,
7645 QEMU_OPTION_cpu,
7646 QEMU_OPTION_fda,
7647 QEMU_OPTION_fdb,
7648 QEMU_OPTION_hda,
7649 QEMU_OPTION_hdb,
7650 QEMU_OPTION_hdc,
7651 QEMU_OPTION_hdd,
7652 QEMU_OPTION_drive,
7653 QEMU_OPTION_cdrom,
7654 QEMU_OPTION_mtdblock,
7655 QEMU_OPTION_sd,
7656 QEMU_OPTION_pflash,
7657 QEMU_OPTION_boot,
7658 QEMU_OPTION_snapshot,
7659 #ifdef TARGET_I386
7660 QEMU_OPTION_no_fd_bootchk,
7661 #endif
7662 QEMU_OPTION_m,
7663 QEMU_OPTION_nographic,
7664 QEMU_OPTION_portrait,
7665 #ifdef HAS_AUDIO
7666 QEMU_OPTION_audio_help,
7667 QEMU_OPTION_soundhw,
7668 #endif
7670 QEMU_OPTION_net,
7671 QEMU_OPTION_tftp,
7672 QEMU_OPTION_bootp,
7673 QEMU_OPTION_smb,
7674 QEMU_OPTION_redir,
7676 QEMU_OPTION_kernel,
7677 QEMU_OPTION_append,
7678 QEMU_OPTION_initrd,
7680 QEMU_OPTION_S,
7681 QEMU_OPTION_s,
7682 QEMU_OPTION_p,
7683 QEMU_OPTION_d,
7684 QEMU_OPTION_hdachs,
7685 QEMU_OPTION_L,
7686 QEMU_OPTION_bios,
7687 QEMU_OPTION_no_code_copy,
7688 QEMU_OPTION_k,
7689 QEMU_OPTION_localtime,
7690 QEMU_OPTION_cirrusvga,
7691 QEMU_OPTION_vmsvga,
7692 QEMU_OPTION_g,
7693 QEMU_OPTION_std_vga,
7694 QEMU_OPTION_echr,
7695 QEMU_OPTION_monitor,
7696 QEMU_OPTION_serial,
7697 QEMU_OPTION_parallel,
7698 QEMU_OPTION_loadvm,
7699 QEMU_OPTION_full_screen,
7700 QEMU_OPTION_no_frame,
7701 QEMU_OPTION_alt_grab,
7702 QEMU_OPTION_no_quit,
7703 QEMU_OPTION_pidfile,
7704 QEMU_OPTION_no_kqemu,
7705 QEMU_OPTION_kernel_kqemu,
7706 QEMU_OPTION_win2k_hack,
7707 QEMU_OPTION_usb,
7708 QEMU_OPTION_usbdevice,
7709 QEMU_OPTION_smp,
7710 QEMU_OPTION_vnc,
7711 QEMU_OPTION_no_acpi,
7712 QEMU_OPTION_no_reboot,
7713 QEMU_OPTION_show_cursor,
7714 QEMU_OPTION_daemonize,
7715 QEMU_OPTION_option_rom,
7716 QEMU_OPTION_semihosting,
7717 QEMU_OPTION_name,
7718 QEMU_OPTION_prom_env,
7719 QEMU_OPTION_old_param,
7720 QEMU_OPTION_clock,
7721 QEMU_OPTION_startdate,
7724 typedef struct QEMUOption {
7725 const char *name;
7726 int flags;
7727 int index;
7728 } QEMUOption;
7730 const QEMUOption qemu_options[] = {
7731 { "h", 0, QEMU_OPTION_h },
7732 { "help", 0, QEMU_OPTION_h },
7734 { "M", HAS_ARG, QEMU_OPTION_M },
7735 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7736 { "fda", HAS_ARG, QEMU_OPTION_fda },
7737 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7738 { "hda", HAS_ARG, QEMU_OPTION_hda },
7739 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7740 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7741 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7742 { "drive", HAS_ARG, QEMU_OPTION_drive },
7743 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7744 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7745 { "sd", HAS_ARG, QEMU_OPTION_sd },
7746 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7747 { "boot", HAS_ARG, QEMU_OPTION_boot },
7748 { "snapshot", 0, QEMU_OPTION_snapshot },
7749 #ifdef TARGET_I386
7750 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7751 #endif
7752 { "m", HAS_ARG, QEMU_OPTION_m },
7753 { "nographic", 0, QEMU_OPTION_nographic },
7754 { "portrait", 0, QEMU_OPTION_portrait },
7755 { "k", HAS_ARG, QEMU_OPTION_k },
7756 #ifdef HAS_AUDIO
7757 { "audio-help", 0, QEMU_OPTION_audio_help },
7758 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7759 #endif
7761 { "net", HAS_ARG, QEMU_OPTION_net},
7762 #ifdef CONFIG_SLIRP
7763 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7764 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7765 #ifndef _WIN32
7766 { "smb", HAS_ARG, QEMU_OPTION_smb },
7767 #endif
7768 { "redir", HAS_ARG, QEMU_OPTION_redir },
7769 #endif
7771 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7772 { "append", HAS_ARG, QEMU_OPTION_append },
7773 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7775 { "S", 0, QEMU_OPTION_S },
7776 { "s", 0, QEMU_OPTION_s },
7777 { "p", HAS_ARG, QEMU_OPTION_p },
7778 { "d", HAS_ARG, QEMU_OPTION_d },
7779 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7780 { "L", HAS_ARG, QEMU_OPTION_L },
7781 { "bios", HAS_ARG, QEMU_OPTION_bios },
7782 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7783 #ifdef USE_KQEMU
7784 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7785 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7786 #endif
7787 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7788 { "g", 1, QEMU_OPTION_g },
7789 #endif
7790 { "localtime", 0, QEMU_OPTION_localtime },
7791 { "std-vga", 0, QEMU_OPTION_std_vga },
7792 { "echr", HAS_ARG, QEMU_OPTION_echr },
7793 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7794 { "serial", HAS_ARG, QEMU_OPTION_serial },
7795 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7796 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7797 { "full-screen", 0, QEMU_OPTION_full_screen },
7798 #ifdef CONFIG_SDL
7799 { "no-frame", 0, QEMU_OPTION_no_frame },
7800 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7801 { "no-quit", 0, QEMU_OPTION_no_quit },
7802 #endif
7803 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7804 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7805 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7806 { "smp", HAS_ARG, QEMU_OPTION_smp },
7807 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7809 /* temporary options */
7810 { "usb", 0, QEMU_OPTION_usb },
7811 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7812 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7813 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7814 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7815 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7816 { "daemonize", 0, QEMU_OPTION_daemonize },
7817 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7818 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7819 { "semihosting", 0, QEMU_OPTION_semihosting },
7820 #endif
7821 { "name", HAS_ARG, QEMU_OPTION_name },
7822 #if defined(TARGET_SPARC)
7823 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7824 #endif
7825 #if defined(TARGET_ARM)
7826 { "old-param", 0, QEMU_OPTION_old_param },
7827 #endif
7828 { "clock", HAS_ARG, QEMU_OPTION_clock },
7829 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7830 { NULL },
7833 /* password input */
7835 int qemu_key_check(BlockDriverState *bs, const char *name)
7837 char password[256];
7838 int i;
7840 if (!bdrv_is_encrypted(bs))
7841 return 0;
7843 term_printf("%s is encrypted.\n", name);
7844 for(i = 0; i < 3; i++) {
7845 monitor_readline("Password: ", 1, password, sizeof(password));
7846 if (bdrv_set_key(bs, password) == 0)
7847 return 0;
7848 term_printf("invalid password\n");
7850 return -EPERM;
7853 static BlockDriverState *get_bdrv(int index)
7855 if (index > nb_drives)
7856 return NULL;
7857 return drives_table[index].bdrv;
7860 static void read_passwords(void)
7862 BlockDriverState *bs;
7863 int i;
7865 for(i = 0; i < 6; i++) {
7866 bs = get_bdrv(i);
7867 if (bs)
7868 qemu_key_check(bs, bdrv_get_device_name(bs));
7872 /* XXX: currently we cannot use simultaneously different CPUs */
7873 static void register_machines(void)
7875 #if defined(TARGET_I386)
7876 qemu_register_machine(&pc_machine);
7877 qemu_register_machine(&isapc_machine);
7878 #elif defined(TARGET_PPC)
7879 qemu_register_machine(&heathrow_machine);
7880 qemu_register_machine(&core99_machine);
7881 qemu_register_machine(&prep_machine);
7882 qemu_register_machine(&ref405ep_machine);
7883 qemu_register_machine(&taihu_machine);
7884 #elif defined(TARGET_MIPS)
7885 qemu_register_machine(&mips_machine);
7886 qemu_register_machine(&mips_malta_machine);
7887 qemu_register_machine(&mips_pica61_machine);
7888 qemu_register_machine(&mips_mipssim_machine);
7889 #elif defined(TARGET_SPARC)
7890 #ifdef TARGET_SPARC64
7891 qemu_register_machine(&sun4u_machine);
7892 #else
7893 qemu_register_machine(&ss5_machine);
7894 qemu_register_machine(&ss10_machine);
7895 qemu_register_machine(&ss600mp_machine);
7896 qemu_register_machine(&ss20_machine);
7897 qemu_register_machine(&ss2_machine);
7898 qemu_register_machine(&ss1000_machine);
7899 qemu_register_machine(&ss2000_machine);
7900 #endif
7901 #elif defined(TARGET_ARM)
7902 qemu_register_machine(&integratorcp_machine);
7903 qemu_register_machine(&versatilepb_machine);
7904 qemu_register_machine(&versatileab_machine);
7905 qemu_register_machine(&realview_machine);
7906 qemu_register_machine(&akitapda_machine);
7907 qemu_register_machine(&spitzpda_machine);
7908 qemu_register_machine(&borzoipda_machine);
7909 qemu_register_machine(&terrierpda_machine);
7910 qemu_register_machine(&palmte_machine);
7911 qemu_register_machine(&lm3s811evb_machine);
7912 qemu_register_machine(&lm3s6965evb_machine);
7913 qemu_register_machine(&connex_machine);
7914 qemu_register_machine(&verdex_machine);
7915 qemu_register_machine(&mainstone2_machine);
7916 #elif defined(TARGET_SH4)
7917 qemu_register_machine(&shix_machine);
7918 qemu_register_machine(&r2d_machine);
7919 #elif defined(TARGET_ALPHA)
7920 /* XXX: TODO */
7921 #elif defined(TARGET_M68K)
7922 qemu_register_machine(&mcf5208evb_machine);
7923 qemu_register_machine(&an5206_machine);
7924 qemu_register_machine(&dummy_m68k_machine);
7925 #elif defined(TARGET_CRIS)
7926 qemu_register_machine(&bareetraxfs_machine);
7927 #else
7928 #error unsupported CPU
7929 #endif
7932 #ifdef HAS_AUDIO
7933 struct soundhw soundhw[] = {
7934 #ifdef HAS_AUDIO_CHOICE
7935 #ifdef TARGET_I386
7937 "pcspk",
7938 "PC speaker",
7941 { .init_isa = pcspk_audio_init }
7943 #endif
7945 "sb16",
7946 "Creative Sound Blaster 16",
7949 { .init_isa = SB16_init }
7952 #ifdef CONFIG_ADLIB
7954 "adlib",
7955 #ifdef HAS_YMF262
7956 "Yamaha YMF262 (OPL3)",
7957 #else
7958 "Yamaha YM3812 (OPL2)",
7959 #endif
7962 { .init_isa = Adlib_init }
7964 #endif
7966 #ifdef CONFIG_GUS
7968 "gus",
7969 "Gravis Ultrasound GF1",
7972 { .init_isa = GUS_init }
7974 #endif
7977 "es1370",
7978 "ENSONIQ AudioPCI ES1370",
7981 { .init_pci = es1370_init }
7983 #endif
7985 { NULL, NULL, 0, 0, { NULL } }
7988 static void select_soundhw (const char *optarg)
7990 struct soundhw *c;
7992 if (*optarg == '?') {
7993 show_valid_cards:
7995 printf ("Valid sound card names (comma separated):\n");
7996 for (c = soundhw; c->name; ++c) {
7997 printf ("%-11s %s\n", c->name, c->descr);
7999 printf ("\n-soundhw all will enable all of the above\n");
8000 exit (*optarg != '?');
8002 else {
8003 size_t l;
8004 const char *p;
8005 char *e;
8006 int bad_card = 0;
8008 if (!strcmp (optarg, "all")) {
8009 for (c = soundhw; c->name; ++c) {
8010 c->enabled = 1;
8012 return;
8015 p = optarg;
8016 while (*p) {
8017 e = strchr (p, ',');
8018 l = !e ? strlen (p) : (size_t) (e - p);
8020 for (c = soundhw; c->name; ++c) {
8021 if (!strncmp (c->name, p, l)) {
8022 c->enabled = 1;
8023 break;
8027 if (!c->name) {
8028 if (l > 80) {
8029 fprintf (stderr,
8030 "Unknown sound card name (too big to show)\n");
8032 else {
8033 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8034 (int) l, p);
8036 bad_card = 1;
8038 p += l + (e != NULL);
8041 if (bad_card)
8042 goto show_valid_cards;
8045 #endif
8047 #ifdef _WIN32
8048 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8050 exit(STATUS_CONTROL_C_EXIT);
8051 return TRUE;
8053 #endif
8055 #define MAX_NET_CLIENTS 32
8057 int main(int argc, char **argv)
8059 #ifdef CONFIG_GDBSTUB
8060 int use_gdbstub;
8061 const char *gdbstub_port;
8062 #endif
8063 uint32_t boot_devices_bitmap = 0;
8064 int i;
8065 int snapshot, linux_boot, net_boot;
8066 const char *initrd_filename;
8067 const char *kernel_filename, *kernel_cmdline;
8068 const char *boot_devices = "";
8069 DisplayState *ds = &display_state;
8070 int cyls, heads, secs, translation;
8071 char net_clients[MAX_NET_CLIENTS][256];
8072 int nb_net_clients;
8073 int hda_index;
8074 int optind;
8075 const char *r, *optarg;
8076 CharDriverState *monitor_hd;
8077 char monitor_device[128];
8078 char serial_devices[MAX_SERIAL_PORTS][128];
8079 int serial_device_index;
8080 char parallel_devices[MAX_PARALLEL_PORTS][128];
8081 int parallel_device_index;
8082 const char *loadvm = NULL;
8083 QEMUMachine *machine;
8084 const char *cpu_model;
8085 char usb_devices[MAX_USB_CMDLINE][128];
8086 int usb_devices_index;
8087 int fds[2];
8088 const char *pid_file = NULL;
8089 VLANState *vlan;
8091 LIST_INIT (&vm_change_state_head);
8092 #ifndef _WIN32
8094 struct sigaction act;
8095 sigfillset(&act.sa_mask);
8096 act.sa_flags = 0;
8097 act.sa_handler = SIG_IGN;
8098 sigaction(SIGPIPE, &act, NULL);
8100 #else
8101 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8102 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8103 QEMU to run on a single CPU */
8105 HANDLE h;
8106 DWORD mask, smask;
8107 int i;
8108 h = GetCurrentProcess();
8109 if (GetProcessAffinityMask(h, &mask, &smask)) {
8110 for(i = 0; i < 32; i++) {
8111 if (mask & (1 << i))
8112 break;
8114 if (i != 32) {
8115 mask = 1 << i;
8116 SetProcessAffinityMask(h, mask);
8120 #endif
8122 register_machines();
8123 machine = first_machine;
8124 cpu_model = NULL;
8125 initrd_filename = NULL;
8126 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8127 vga_ram_size = VGA_RAM_SIZE;
8128 #ifdef CONFIG_GDBSTUB
8129 use_gdbstub = 0;
8130 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8131 #endif
8132 snapshot = 0;
8133 nographic = 0;
8134 kernel_filename = NULL;
8135 kernel_cmdline = "";
8136 cyls = heads = secs = 0;
8137 translation = BIOS_ATA_TRANSLATION_AUTO;
8138 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8140 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8141 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8142 serial_devices[i][0] = '\0';
8143 serial_device_index = 0;
8145 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8146 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8147 parallel_devices[i][0] = '\0';
8148 parallel_device_index = 0;
8150 usb_devices_index = 0;
8152 nb_net_clients = 0;
8153 nb_drives = 0;
8154 nb_drives_opt = 0;
8155 hda_index = -1;
8157 nb_nics = 0;
8158 /* default mac address of the first network interface */
8160 optind = 1;
8161 for(;;) {
8162 if (optind >= argc)
8163 break;
8164 r = argv[optind];
8165 if (r[0] != '-') {
8166 hda_index = drive_add(HD_ALIAS, argv[optind++], 0);
8167 } else {
8168 const QEMUOption *popt;
8170 optind++;
8171 /* Treat --foo the same as -foo. */
8172 if (r[1] == '-')
8173 r++;
8174 popt = qemu_options;
8175 for(;;) {
8176 if (!popt->name) {
8177 fprintf(stderr, "%s: invalid option -- '%s'\n",
8178 argv[0], r);
8179 exit(1);
8181 if (!strcmp(popt->name, r + 1))
8182 break;
8183 popt++;
8185 if (popt->flags & HAS_ARG) {
8186 if (optind >= argc) {
8187 fprintf(stderr, "%s: option '%s' requires an argument\n",
8188 argv[0], r);
8189 exit(1);
8191 optarg = argv[optind++];
8192 } else {
8193 optarg = NULL;
8196 switch(popt->index) {
8197 case QEMU_OPTION_M:
8198 machine = find_machine(optarg);
8199 if (!machine) {
8200 QEMUMachine *m;
8201 printf("Supported machines are:\n");
8202 for(m = first_machine; m != NULL; m = m->next) {
8203 printf("%-10s %s%s\n",
8204 m->name, m->desc,
8205 m == first_machine ? " (default)" : "");
8207 exit(*optarg != '?');
8209 break;
8210 case QEMU_OPTION_cpu:
8211 /* hw initialization will check this */
8212 if (*optarg == '?') {
8213 /* XXX: implement xxx_cpu_list for targets that still miss it */
8214 #if defined(cpu_list)
8215 cpu_list(stdout, &fprintf);
8216 #endif
8217 exit(0);
8218 } else {
8219 cpu_model = optarg;
8221 break;
8222 case QEMU_OPTION_initrd:
8223 initrd_filename = optarg;
8224 break;
8225 case QEMU_OPTION_hda:
8226 if (cyls == 0)
8227 hda_index = drive_add(HD_ALIAS, optarg, 0);
8228 else
8229 hda_index = drive_add(HD_ALIAS
8230 ",cyls=%d,heads=%d,secs=%d%s",
8231 optarg, 0, cyls, heads, secs,
8232 translation == BIOS_ATA_TRANSLATION_LBA ?
8233 ",trans=lba" :
8234 translation == BIOS_ATA_TRANSLATION_NONE ?
8235 ",trans=none" : "");
8236 break;
8237 case QEMU_OPTION_hdb:
8238 case QEMU_OPTION_hdc:
8239 case QEMU_OPTION_hdd:
8240 drive_add(HD_ALIAS, optarg, popt->index - QEMU_OPTION_hda);
8241 break;
8242 case QEMU_OPTION_drive:
8243 drive_add("%s", optarg);
8244 break;
8245 case QEMU_OPTION_mtdblock:
8246 drive_add(MTD_ALIAS, optarg);
8247 break;
8248 case QEMU_OPTION_sd:
8249 drive_add("file=\"%s\"," SD_ALIAS, optarg);
8250 break;
8251 case QEMU_OPTION_pflash:
8252 drive_add(PFLASH_ALIAS, optarg);
8253 break;
8254 case QEMU_OPTION_snapshot:
8255 snapshot = 1;
8256 break;
8257 case QEMU_OPTION_hdachs:
8259 const char *p;
8260 p = optarg;
8261 cyls = strtol(p, (char **)&p, 0);
8262 if (cyls < 1 || cyls > 16383)
8263 goto chs_fail;
8264 if (*p != ',')
8265 goto chs_fail;
8266 p++;
8267 heads = strtol(p, (char **)&p, 0);
8268 if (heads < 1 || heads > 16)
8269 goto chs_fail;
8270 if (*p != ',')
8271 goto chs_fail;
8272 p++;
8273 secs = strtol(p, (char **)&p, 0);
8274 if (secs < 1 || secs > 63)
8275 goto chs_fail;
8276 if (*p == ',') {
8277 p++;
8278 if (!strcmp(p, "none"))
8279 translation = BIOS_ATA_TRANSLATION_NONE;
8280 else if (!strcmp(p, "lba"))
8281 translation = BIOS_ATA_TRANSLATION_LBA;
8282 else if (!strcmp(p, "auto"))
8283 translation = BIOS_ATA_TRANSLATION_AUTO;
8284 else
8285 goto chs_fail;
8286 } else if (*p != '\0') {
8287 chs_fail:
8288 fprintf(stderr, "qemu: invalid physical CHS format\n");
8289 exit(1);
8291 if (hda_index != -1)
8292 snprintf(drives_opt[hda_index] +
8293 strlen(drives_opt[hda_index]),
8294 sizeof(drives_opt[0]) -
8295 strlen(drives_opt[hda_index]),
8296 ",cyls=%d,heads=%d,secs=%d%s",
8297 cyls, heads, secs,
8298 translation == BIOS_ATA_TRANSLATION_LBA ?
8299 ",trans=lba" :
8300 translation == BIOS_ATA_TRANSLATION_NONE ?
8301 ",trans=none" : "");
8303 break;
8304 case QEMU_OPTION_nographic:
8305 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8306 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8307 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8308 nographic = 1;
8309 break;
8310 case QEMU_OPTION_portrait:
8311 graphic_rotate = 1;
8312 break;
8313 case QEMU_OPTION_kernel:
8314 kernel_filename = optarg;
8315 break;
8316 case QEMU_OPTION_append:
8317 kernel_cmdline = optarg;
8318 break;
8319 case QEMU_OPTION_cdrom:
8320 drive_add("file=\"%s\"," CDROM_ALIAS, optarg);
8321 break;
8322 case QEMU_OPTION_boot:
8323 boot_devices = optarg;
8324 /* We just do some generic consistency checks */
8326 /* Could easily be extended to 64 devices if needed */
8327 const char *p;
8329 boot_devices_bitmap = 0;
8330 for (p = boot_devices; *p != '\0'; p++) {
8331 /* Allowed boot devices are:
8332 * a b : floppy disk drives
8333 * c ... f : IDE disk drives
8334 * g ... m : machine implementation dependant drives
8335 * n ... p : network devices
8336 * It's up to each machine implementation to check
8337 * if the given boot devices match the actual hardware
8338 * implementation and firmware features.
8340 if (*p < 'a' || *p > 'q') {
8341 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8342 exit(1);
8344 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8345 fprintf(stderr,
8346 "Boot device '%c' was given twice\n",*p);
8347 exit(1);
8349 boot_devices_bitmap |= 1 << (*p - 'a');
8352 break;
8353 case QEMU_OPTION_fda:
8354 case QEMU_OPTION_fdb:
8355 drive_add("file=\"%s\"," FD_ALIAS, optarg,
8356 popt->index - QEMU_OPTION_fda);
8357 break;
8358 #ifdef TARGET_I386
8359 case QEMU_OPTION_no_fd_bootchk:
8360 fd_bootchk = 0;
8361 break;
8362 #endif
8363 case QEMU_OPTION_no_code_copy:
8364 code_copy_enabled = 0;
8365 break;
8366 case QEMU_OPTION_net:
8367 if (nb_net_clients >= MAX_NET_CLIENTS) {
8368 fprintf(stderr, "qemu: too many network clients\n");
8369 exit(1);
8371 pstrcpy(net_clients[nb_net_clients],
8372 sizeof(net_clients[0]),
8373 optarg);
8374 nb_net_clients++;
8375 break;
8376 #ifdef CONFIG_SLIRP
8377 case QEMU_OPTION_tftp:
8378 tftp_prefix = optarg;
8379 break;
8380 case QEMU_OPTION_bootp:
8381 bootp_filename = optarg;
8382 break;
8383 #ifndef _WIN32
8384 case QEMU_OPTION_smb:
8385 net_slirp_smb(optarg);
8386 break;
8387 #endif
8388 case QEMU_OPTION_redir:
8389 net_slirp_redir(optarg);
8390 break;
8391 #endif
8392 #ifdef HAS_AUDIO
8393 case QEMU_OPTION_audio_help:
8394 AUD_help ();
8395 exit (0);
8396 break;
8397 case QEMU_OPTION_soundhw:
8398 select_soundhw (optarg);
8399 break;
8400 #endif
8401 case QEMU_OPTION_h:
8402 help(0);
8403 break;
8404 case QEMU_OPTION_m:
8405 ram_size = atoi(optarg) * 1024 * 1024;
8406 if (ram_size <= 0)
8407 help(1);
8408 if (ram_size > PHYS_RAM_MAX_SIZE) {
8409 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8410 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8411 exit(1);
8413 break;
8414 case QEMU_OPTION_d:
8416 int mask;
8417 CPULogItem *item;
8419 mask = cpu_str_to_log_mask(optarg);
8420 if (!mask) {
8421 printf("Log items (comma separated):\n");
8422 for(item = cpu_log_items; item->mask != 0; item++) {
8423 printf("%-10s %s\n", item->name, item->help);
8425 exit(1);
8427 cpu_set_log(mask);
8429 break;
8430 #ifdef CONFIG_GDBSTUB
8431 case QEMU_OPTION_s:
8432 use_gdbstub = 1;
8433 break;
8434 case QEMU_OPTION_p:
8435 gdbstub_port = optarg;
8436 break;
8437 #endif
8438 case QEMU_OPTION_L:
8439 bios_dir = optarg;
8440 break;
8441 case QEMU_OPTION_bios:
8442 bios_name = optarg;
8443 break;
8444 case QEMU_OPTION_S:
8445 autostart = 0;
8446 break;
8447 case QEMU_OPTION_k:
8448 keyboard_layout = optarg;
8449 break;
8450 case QEMU_OPTION_localtime:
8451 rtc_utc = 0;
8452 break;
8453 case QEMU_OPTION_cirrusvga:
8454 cirrus_vga_enabled = 1;
8455 vmsvga_enabled = 0;
8456 break;
8457 case QEMU_OPTION_vmsvga:
8458 cirrus_vga_enabled = 0;
8459 vmsvga_enabled = 1;
8460 break;
8461 case QEMU_OPTION_std_vga:
8462 cirrus_vga_enabled = 0;
8463 vmsvga_enabled = 0;
8464 break;
8465 case QEMU_OPTION_g:
8467 const char *p;
8468 int w, h, depth;
8469 p = optarg;
8470 w = strtol(p, (char **)&p, 10);
8471 if (w <= 0) {
8472 graphic_error:
8473 fprintf(stderr, "qemu: invalid resolution or depth\n");
8474 exit(1);
8476 if (*p != 'x')
8477 goto graphic_error;
8478 p++;
8479 h = strtol(p, (char **)&p, 10);
8480 if (h <= 0)
8481 goto graphic_error;
8482 if (*p == 'x') {
8483 p++;
8484 depth = strtol(p, (char **)&p, 10);
8485 if (depth != 8 && depth != 15 && depth != 16 &&
8486 depth != 24 && depth != 32)
8487 goto graphic_error;
8488 } else if (*p == '\0') {
8489 depth = graphic_depth;
8490 } else {
8491 goto graphic_error;
8494 graphic_width = w;
8495 graphic_height = h;
8496 graphic_depth = depth;
8498 break;
8499 case QEMU_OPTION_echr:
8501 char *r;
8502 term_escape_char = strtol(optarg, &r, 0);
8503 if (r == optarg)
8504 printf("Bad argument to echr\n");
8505 break;
8507 case QEMU_OPTION_monitor:
8508 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8509 break;
8510 case QEMU_OPTION_serial:
8511 if (serial_device_index >= MAX_SERIAL_PORTS) {
8512 fprintf(stderr, "qemu: too many serial ports\n");
8513 exit(1);
8515 pstrcpy(serial_devices[serial_device_index],
8516 sizeof(serial_devices[0]), optarg);
8517 serial_device_index++;
8518 break;
8519 case QEMU_OPTION_parallel:
8520 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8521 fprintf(stderr, "qemu: too many parallel ports\n");
8522 exit(1);
8524 pstrcpy(parallel_devices[parallel_device_index],
8525 sizeof(parallel_devices[0]), optarg);
8526 parallel_device_index++;
8527 break;
8528 case QEMU_OPTION_loadvm:
8529 loadvm = optarg;
8530 break;
8531 case QEMU_OPTION_full_screen:
8532 full_screen = 1;
8533 break;
8534 #ifdef CONFIG_SDL
8535 case QEMU_OPTION_no_frame:
8536 no_frame = 1;
8537 break;
8538 case QEMU_OPTION_alt_grab:
8539 alt_grab = 1;
8540 break;
8541 case QEMU_OPTION_no_quit:
8542 no_quit = 1;
8543 break;
8544 #endif
8545 case QEMU_OPTION_pidfile:
8546 pid_file = optarg;
8547 break;
8548 #ifdef TARGET_I386
8549 case QEMU_OPTION_win2k_hack:
8550 win2k_install_hack = 1;
8551 break;
8552 #endif
8553 #ifdef USE_KQEMU
8554 case QEMU_OPTION_no_kqemu:
8555 kqemu_allowed = 0;
8556 break;
8557 case QEMU_OPTION_kernel_kqemu:
8558 kqemu_allowed = 2;
8559 break;
8560 #endif
8561 case QEMU_OPTION_usb:
8562 usb_enabled = 1;
8563 break;
8564 case QEMU_OPTION_usbdevice:
8565 usb_enabled = 1;
8566 if (usb_devices_index >= MAX_USB_CMDLINE) {
8567 fprintf(stderr, "Too many USB devices\n");
8568 exit(1);
8570 pstrcpy(usb_devices[usb_devices_index],
8571 sizeof(usb_devices[usb_devices_index]),
8572 optarg);
8573 usb_devices_index++;
8574 break;
8575 case QEMU_OPTION_smp:
8576 smp_cpus = atoi(optarg);
8577 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8578 fprintf(stderr, "Invalid number of CPUs\n");
8579 exit(1);
8581 break;
8582 case QEMU_OPTION_vnc:
8583 vnc_display = optarg;
8584 break;
8585 case QEMU_OPTION_no_acpi:
8586 acpi_enabled = 0;
8587 break;
8588 case QEMU_OPTION_no_reboot:
8589 no_reboot = 1;
8590 break;
8591 case QEMU_OPTION_show_cursor:
8592 cursor_hide = 0;
8593 break;
8594 case QEMU_OPTION_daemonize:
8595 daemonize = 1;
8596 break;
8597 case QEMU_OPTION_option_rom:
8598 if (nb_option_roms >= MAX_OPTION_ROMS) {
8599 fprintf(stderr, "Too many option ROMs\n");
8600 exit(1);
8602 option_rom[nb_option_roms] = optarg;
8603 nb_option_roms++;
8604 break;
8605 case QEMU_OPTION_semihosting:
8606 semihosting_enabled = 1;
8607 break;
8608 case QEMU_OPTION_name:
8609 qemu_name = optarg;
8610 break;
8611 #ifdef TARGET_SPARC
8612 case QEMU_OPTION_prom_env:
8613 if (nb_prom_envs >= MAX_PROM_ENVS) {
8614 fprintf(stderr, "Too many prom variables\n");
8615 exit(1);
8617 prom_envs[nb_prom_envs] = optarg;
8618 nb_prom_envs++;
8619 break;
8620 #endif
8621 #ifdef TARGET_ARM
8622 case QEMU_OPTION_old_param:
8623 old_param = 1;
8624 break;
8625 #endif
8626 case QEMU_OPTION_clock:
8627 configure_alarms(optarg);
8628 break;
8629 case QEMU_OPTION_startdate:
8631 struct tm tm;
8632 if (!strcmp(optarg, "now")) {
8633 rtc_start_date = -1;
8634 } else {
8635 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8636 &tm.tm_year,
8637 &tm.tm_mon,
8638 &tm.tm_mday,
8639 &tm.tm_hour,
8640 &tm.tm_min,
8641 &tm.tm_sec) == 6) {
8642 /* OK */
8643 } else if (sscanf(optarg, "%d-%d-%d",
8644 &tm.tm_year,
8645 &tm.tm_mon,
8646 &tm.tm_mday) == 3) {
8647 tm.tm_hour = 0;
8648 tm.tm_min = 0;
8649 tm.tm_sec = 0;
8650 } else {
8651 goto date_fail;
8653 tm.tm_year -= 1900;
8654 tm.tm_mon--;
8655 rtc_start_date = mktimegm(&tm);
8656 if (rtc_start_date == -1) {
8657 date_fail:
8658 fprintf(stderr, "Invalid date format. Valid format are:\n"
8659 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8660 exit(1);
8664 break;
8669 #ifndef _WIN32
8670 if (daemonize && !nographic && vnc_display == NULL) {
8671 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8672 daemonize = 0;
8675 if (daemonize) {
8676 pid_t pid;
8678 if (pipe(fds) == -1)
8679 exit(1);
8681 pid = fork();
8682 if (pid > 0) {
8683 uint8_t status;
8684 ssize_t len;
8686 close(fds[1]);
8688 again:
8689 len = read(fds[0], &status, 1);
8690 if (len == -1 && (errno == EINTR))
8691 goto again;
8693 if (len != 1)
8694 exit(1);
8695 else if (status == 1) {
8696 fprintf(stderr, "Could not acquire pidfile\n");
8697 exit(1);
8698 } else
8699 exit(0);
8700 } else if (pid < 0)
8701 exit(1);
8703 setsid();
8705 pid = fork();
8706 if (pid > 0)
8707 exit(0);
8708 else if (pid < 0)
8709 exit(1);
8711 umask(027);
8712 chdir("/");
8714 signal(SIGTSTP, SIG_IGN);
8715 signal(SIGTTOU, SIG_IGN);
8716 signal(SIGTTIN, SIG_IGN);
8718 #endif
8720 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8721 if (daemonize) {
8722 uint8_t status = 1;
8723 write(fds[1], &status, 1);
8724 } else
8725 fprintf(stderr, "Could not acquire pid file\n");
8726 exit(1);
8729 #ifdef USE_KQEMU
8730 if (smp_cpus > 1)
8731 kqemu_allowed = 0;
8732 #endif
8733 linux_boot = (kernel_filename != NULL);
8734 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8736 /* XXX: this should not be: some embedded targets just have flash */
8737 if (!linux_boot && net_boot == 0 &&
8738 nb_drives_opt == 0)
8739 help(1);
8741 /* boot to floppy or the default cd if no hard disk defined yet */
8742 if (!boot_devices[0]) {
8743 boot_devices = "cad";
8745 setvbuf(stdout, NULL, _IOLBF, 0);
8747 init_timers();
8748 init_timer_alarm();
8749 qemu_aio_init();
8751 #ifdef _WIN32
8752 socket_init();
8753 #endif
8755 /* init network clients */
8756 if (nb_net_clients == 0) {
8757 /* if no clients, we use a default config */
8758 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8759 "nic");
8760 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8761 "user");
8762 nb_net_clients = 2;
8765 for(i = 0;i < nb_net_clients; i++) {
8766 if (net_client_init(net_clients[i]) < 0)
8767 exit(1);
8769 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8770 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8771 continue;
8772 if (vlan->nb_guest_devs == 0) {
8773 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8774 exit(1);
8776 if (vlan->nb_host_devs == 0)
8777 fprintf(stderr,
8778 "Warning: vlan %d is not connected to host network\n",
8779 vlan->id);
8782 #ifdef TARGET_I386
8783 /* XXX: this should be moved in the PC machine instantiation code */
8784 if (net_boot != 0) {
8785 int netroms = 0;
8786 for (i = 0; i < nb_nics && i < 4; i++) {
8787 const char *model = nd_table[i].model;
8788 char buf[1024];
8789 if (net_boot & (1 << i)) {
8790 if (model == NULL)
8791 model = "ne2k_pci";
8792 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8793 if (get_image_size(buf) > 0) {
8794 if (nb_option_roms >= MAX_OPTION_ROMS) {
8795 fprintf(stderr, "Too many option ROMs\n");
8796 exit(1);
8798 option_rom[nb_option_roms] = strdup(buf);
8799 nb_option_roms++;
8800 netroms++;
8804 if (netroms == 0) {
8805 fprintf(stderr, "No valid PXE rom found for network device\n");
8806 exit(1);
8809 #endif
8811 /* init the memory */
8812 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8814 phys_ram_base = qemu_vmalloc(phys_ram_size);
8815 if (!phys_ram_base) {
8816 fprintf(stderr, "Could not allocate physical memory\n");
8817 exit(1);
8820 bdrv_init();
8822 /* we always create the cdrom drive, even if no disk is there */
8824 if (nb_drives_opt < MAX_DRIVES)
8825 drive_add(CDROM_ALIAS);
8827 /* we always create at least one floppy */
8829 if (nb_drives_opt < MAX_DRIVES)
8830 drive_add(FD_ALIAS, 0);
8832 /* we always create one sd slot, even if no card is in it */
8834 if (nb_drives_opt < MAX_DRIVES)
8835 drive_add(SD_ALIAS);
8837 /* open the virtual block devices */
8839 for(i = 0; i < nb_drives_opt; i++)
8840 if (drive_init(drives_opt[i], snapshot, machine) == -1)
8841 exit(1);
8843 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8844 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8846 init_ioports();
8848 /* terminal init */
8849 memset(&display_state, 0, sizeof(display_state));
8850 if (nographic) {
8851 /* nearly nothing to do */
8852 dumb_display_init(ds);
8853 } else if (vnc_display != NULL) {
8854 vnc_display_init(ds);
8855 if (vnc_display_open(ds, vnc_display) < 0)
8856 exit(1);
8857 } else {
8858 #if defined(CONFIG_SDL)
8859 sdl_display_init(ds, full_screen, no_frame);
8860 #elif defined(CONFIG_COCOA)
8861 cocoa_display_init(ds, full_screen);
8862 #else
8863 dumb_display_init(ds);
8864 #endif
8867 /* Maintain compatibility with multiple stdio monitors */
8868 if (!strcmp(monitor_device,"stdio")) {
8869 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8870 if (!strcmp(serial_devices[i],"mon:stdio")) {
8871 monitor_device[0] = '\0';
8872 break;
8873 } else if (!strcmp(serial_devices[i],"stdio")) {
8874 monitor_device[0] = '\0';
8875 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8876 break;
8880 if (monitor_device[0] != '\0') {
8881 monitor_hd = qemu_chr_open(monitor_device);
8882 if (!monitor_hd) {
8883 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8884 exit(1);
8886 monitor_init(monitor_hd, !nographic);
8889 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8890 const char *devname = serial_devices[i];
8891 if (devname[0] != '\0' && strcmp(devname, "none")) {
8892 serial_hds[i] = qemu_chr_open(devname);
8893 if (!serial_hds[i]) {
8894 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8895 devname);
8896 exit(1);
8898 if (strstart(devname, "vc", 0))
8899 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8903 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8904 const char *devname = parallel_devices[i];
8905 if (devname[0] != '\0' && strcmp(devname, "none")) {
8906 parallel_hds[i] = qemu_chr_open(devname);
8907 if (!parallel_hds[i]) {
8908 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8909 devname);
8910 exit(1);
8912 if (strstart(devname, "vc", 0))
8913 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8917 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8918 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8920 /* init USB devices */
8921 if (usb_enabled) {
8922 for(i = 0; i < usb_devices_index; i++) {
8923 if (usb_device_add(usb_devices[i]) < 0) {
8924 fprintf(stderr, "Warning: could not add USB device %s\n",
8925 usb_devices[i]);
8930 if (display_state.dpy_refresh) {
8931 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8932 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8935 #ifdef CONFIG_GDBSTUB
8936 if (use_gdbstub) {
8937 /* XXX: use standard host:port notation and modify options
8938 accordingly. */
8939 if (gdbserver_start(gdbstub_port) < 0) {
8940 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8941 gdbstub_port);
8942 exit(1);
8945 #endif
8947 if (loadvm)
8948 do_loadvm(loadvm);
8951 /* XXX: simplify init */
8952 read_passwords();
8953 if (autostart) {
8954 vm_start();
8958 if (daemonize) {
8959 uint8_t status = 0;
8960 ssize_t len;
8961 int fd;
8963 again1:
8964 len = write(fds[1], &status, 1);
8965 if (len == -1 && (errno == EINTR))
8966 goto again1;
8968 if (len != 1)
8969 exit(1);
8971 TFR(fd = open("/dev/null", O_RDWR));
8972 if (fd == -1)
8973 exit(1);
8975 dup2(fd, 0);
8976 dup2(fd, 1);
8977 dup2(fd, 2);
8979 close(fd);
8982 main_loop();
8983 quit_timers();
8985 #if !defined(_WIN32)
8986 /* close network clients */
8987 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8988 VLANClientState *vc;
8990 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8991 if (vc->fd_read == tap_receive) {
8992 char ifname[64];
8993 TAPState *s = vc->opaque;
8995 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8996 s->down_script[0])
8997 launch_script(s->down_script, ifname, s->fd);
9001 #endif
9002 return 0;