Fix opparam_buf size estimate.
[qemu/mini2440.git] / vl.c
blobdeff1496ef69e75401b0bf8d2c502ff98249e777
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 struct drive_opt {
235 const char *file;
236 char opt[1024];
237 } drives_opt[MAX_DRIVES];
239 static CPUState *cur_cpu;
240 static CPUState *next_cpu;
241 static int event_pending = 1;
243 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
245 /***********************************************************/
246 /* x86 ISA bus support */
248 target_phys_addr_t isa_mem_base = 0;
249 PicState2 *isa_pic;
251 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
253 #ifdef DEBUG_UNUSED_IOPORT
254 fprintf(stderr, "unused inb: port=0x%04x\n", address);
255 #endif
256 return 0xff;
259 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
261 #ifdef DEBUG_UNUSED_IOPORT
262 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
263 #endif
266 /* default is to make two byte accesses */
267 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
269 uint32_t data;
270 data = ioport_read_table[0][address](ioport_opaque[address], address);
271 address = (address + 1) & (MAX_IOPORTS - 1);
272 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
273 return data;
276 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
278 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
279 address = (address + 1) & (MAX_IOPORTS - 1);
280 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
283 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
285 #ifdef DEBUG_UNUSED_IOPORT
286 fprintf(stderr, "unused inl: port=0x%04x\n", address);
287 #endif
288 return 0xffffffff;
291 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
293 #ifdef DEBUG_UNUSED_IOPORT
294 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
295 #endif
298 static void init_ioports(void)
300 int i;
302 for(i = 0; i < MAX_IOPORTS; i++) {
303 ioport_read_table[0][i] = default_ioport_readb;
304 ioport_write_table[0][i] = default_ioport_writeb;
305 ioport_read_table[1][i] = default_ioport_readw;
306 ioport_write_table[1][i] = default_ioport_writew;
307 ioport_read_table[2][i] = default_ioport_readl;
308 ioport_write_table[2][i] = default_ioport_writel;
312 /* size is the word size in byte */
313 int register_ioport_read(int start, int length, int size,
314 IOPortReadFunc *func, void *opaque)
316 int i, bsize;
318 if (size == 1) {
319 bsize = 0;
320 } else if (size == 2) {
321 bsize = 1;
322 } else if (size == 4) {
323 bsize = 2;
324 } else {
325 hw_error("register_ioport_read: invalid size");
326 return -1;
328 for(i = start; i < start + length; i += size) {
329 ioport_read_table[bsize][i] = func;
330 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
331 hw_error("register_ioport_read: invalid opaque");
332 ioport_opaque[i] = opaque;
334 return 0;
337 /* size is the word size in byte */
338 int register_ioport_write(int start, int length, int size,
339 IOPortWriteFunc *func, void *opaque)
341 int i, bsize;
343 if (size == 1) {
344 bsize = 0;
345 } else if (size == 2) {
346 bsize = 1;
347 } else if (size == 4) {
348 bsize = 2;
349 } else {
350 hw_error("register_ioport_write: invalid size");
351 return -1;
353 for(i = start; i < start + length; i += size) {
354 ioport_write_table[bsize][i] = func;
355 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
356 hw_error("register_ioport_write: invalid opaque");
357 ioport_opaque[i] = opaque;
359 return 0;
362 void isa_unassign_ioport(int start, int length)
364 int i;
366 for(i = start; i < start + length; i++) {
367 ioport_read_table[0][i] = default_ioport_readb;
368 ioport_read_table[1][i] = default_ioport_readw;
369 ioport_read_table[2][i] = default_ioport_readl;
371 ioport_write_table[0][i] = default_ioport_writeb;
372 ioport_write_table[1][i] = default_ioport_writew;
373 ioport_write_table[2][i] = default_ioport_writel;
377 /***********************************************************/
379 void cpu_outb(CPUState *env, int addr, int val)
381 #ifdef DEBUG_IOPORT
382 if (loglevel & CPU_LOG_IOPORT)
383 fprintf(logfile, "outb: %04x %02x\n", addr, val);
384 #endif
385 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
386 #ifdef USE_KQEMU
387 if (env)
388 env->last_io_time = cpu_get_time_fast();
389 #endif
392 void cpu_outw(CPUState *env, int addr, int val)
394 #ifdef DEBUG_IOPORT
395 if (loglevel & CPU_LOG_IOPORT)
396 fprintf(logfile, "outw: %04x %04x\n", addr, val);
397 #endif
398 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
399 #ifdef USE_KQEMU
400 if (env)
401 env->last_io_time = cpu_get_time_fast();
402 #endif
405 void cpu_outl(CPUState *env, int addr, int val)
407 #ifdef DEBUG_IOPORT
408 if (loglevel & CPU_LOG_IOPORT)
409 fprintf(logfile, "outl: %04x %08x\n", addr, val);
410 #endif
411 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
412 #ifdef USE_KQEMU
413 if (env)
414 env->last_io_time = cpu_get_time_fast();
415 #endif
418 int cpu_inb(CPUState *env, int addr)
420 int val;
421 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
422 #ifdef DEBUG_IOPORT
423 if (loglevel & CPU_LOG_IOPORT)
424 fprintf(logfile, "inb : %04x %02x\n", addr, val);
425 #endif
426 #ifdef USE_KQEMU
427 if (env)
428 env->last_io_time = cpu_get_time_fast();
429 #endif
430 return val;
433 int cpu_inw(CPUState *env, int addr)
435 int val;
436 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
437 #ifdef DEBUG_IOPORT
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "inw : %04x %04x\n", addr, val);
440 #endif
441 #ifdef USE_KQEMU
442 if (env)
443 env->last_io_time = cpu_get_time_fast();
444 #endif
445 return val;
448 int cpu_inl(CPUState *env, int addr)
450 int val;
451 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
452 #ifdef DEBUG_IOPORT
453 if (loglevel & CPU_LOG_IOPORT)
454 fprintf(logfile, "inl : %04x %08x\n", addr, val);
455 #endif
456 #ifdef USE_KQEMU
457 if (env)
458 env->last_io_time = cpu_get_time_fast();
459 #endif
460 return val;
463 /***********************************************************/
464 void hw_error(const char *fmt, ...)
466 va_list ap;
467 CPUState *env;
469 va_start(ap, fmt);
470 fprintf(stderr, "qemu: hardware error: ");
471 vfprintf(stderr, fmt, ap);
472 fprintf(stderr, "\n");
473 for(env = first_cpu; env != NULL; env = env->next_cpu) {
474 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
475 #ifdef TARGET_I386
476 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
477 #else
478 cpu_dump_state(env, stderr, fprintf, 0);
479 #endif
481 va_end(ap);
482 abort();
485 /***********************************************************/
486 /* keyboard/mouse */
488 static QEMUPutKBDEvent *qemu_put_kbd_event;
489 static void *qemu_put_kbd_event_opaque;
490 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
491 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
493 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
495 qemu_put_kbd_event_opaque = opaque;
496 qemu_put_kbd_event = func;
499 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
500 void *opaque, int absolute,
501 const char *name)
503 QEMUPutMouseEntry *s, *cursor;
505 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
506 if (!s)
507 return NULL;
509 s->qemu_put_mouse_event = func;
510 s->qemu_put_mouse_event_opaque = opaque;
511 s->qemu_put_mouse_event_absolute = absolute;
512 s->qemu_put_mouse_event_name = qemu_strdup(name);
513 s->next = NULL;
515 if (!qemu_put_mouse_event_head) {
516 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
517 return s;
520 cursor = qemu_put_mouse_event_head;
521 while (cursor->next != NULL)
522 cursor = cursor->next;
524 cursor->next = s;
525 qemu_put_mouse_event_current = s;
527 return s;
530 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
532 QEMUPutMouseEntry *prev = NULL, *cursor;
534 if (!qemu_put_mouse_event_head || entry == NULL)
535 return;
537 cursor = qemu_put_mouse_event_head;
538 while (cursor != NULL && cursor != entry) {
539 prev = cursor;
540 cursor = cursor->next;
543 if (cursor == NULL) // does not exist or list empty
544 return;
545 else if (prev == NULL) { // entry is head
546 qemu_put_mouse_event_head = cursor->next;
547 if (qemu_put_mouse_event_current == entry)
548 qemu_put_mouse_event_current = cursor->next;
549 qemu_free(entry->qemu_put_mouse_event_name);
550 qemu_free(entry);
551 return;
554 prev->next = entry->next;
556 if (qemu_put_mouse_event_current == entry)
557 qemu_put_mouse_event_current = prev;
559 qemu_free(entry->qemu_put_mouse_event_name);
560 qemu_free(entry);
563 void kbd_put_keycode(int keycode)
565 if (qemu_put_kbd_event) {
566 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
570 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
572 QEMUPutMouseEvent *mouse_event;
573 void *mouse_event_opaque;
574 int width;
576 if (!qemu_put_mouse_event_current) {
577 return;
580 mouse_event =
581 qemu_put_mouse_event_current->qemu_put_mouse_event;
582 mouse_event_opaque =
583 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
585 if (mouse_event) {
586 if (graphic_rotate) {
587 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
588 width = 0x7fff;
589 else
590 width = graphic_width;
591 mouse_event(mouse_event_opaque,
592 width - dy, dx, dz, buttons_state);
593 } else
594 mouse_event(mouse_event_opaque,
595 dx, dy, dz, buttons_state);
599 int kbd_mouse_is_absolute(void)
601 if (!qemu_put_mouse_event_current)
602 return 0;
604 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
607 void do_info_mice(void)
609 QEMUPutMouseEntry *cursor;
610 int index = 0;
612 if (!qemu_put_mouse_event_head) {
613 term_printf("No mouse devices connected\n");
614 return;
617 term_printf("Mouse devices available:\n");
618 cursor = qemu_put_mouse_event_head;
619 while (cursor != NULL) {
620 term_printf("%c Mouse #%d: %s\n",
621 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
622 index, cursor->qemu_put_mouse_event_name);
623 index++;
624 cursor = cursor->next;
628 void do_mouse_set(int index)
630 QEMUPutMouseEntry *cursor;
631 int i = 0;
633 if (!qemu_put_mouse_event_head) {
634 term_printf("No mouse devices connected\n");
635 return;
638 cursor = qemu_put_mouse_event_head;
639 while (cursor != NULL && index != i) {
640 i++;
641 cursor = cursor->next;
644 if (cursor != NULL)
645 qemu_put_mouse_event_current = cursor;
646 else
647 term_printf("Mouse at given index not found\n");
650 /* compute with 96 bit intermediate result: (a*b)/c */
651 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
653 union {
654 uint64_t ll;
655 struct {
656 #ifdef WORDS_BIGENDIAN
657 uint32_t high, low;
658 #else
659 uint32_t low, high;
660 #endif
661 } l;
662 } u, res;
663 uint64_t rl, rh;
665 u.ll = a;
666 rl = (uint64_t)u.l.low * (uint64_t)b;
667 rh = (uint64_t)u.l.high * (uint64_t)b;
668 rh += (rl >> 32);
669 res.l.high = rh / c;
670 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
671 return res.ll;
674 /***********************************************************/
675 /* real time host monotonic timer */
677 #define QEMU_TIMER_BASE 1000000000LL
679 #ifdef WIN32
681 static int64_t clock_freq;
683 static void init_get_clock(void)
685 LARGE_INTEGER freq;
686 int ret;
687 ret = QueryPerformanceFrequency(&freq);
688 if (ret == 0) {
689 fprintf(stderr, "Could not calibrate ticks\n");
690 exit(1);
692 clock_freq = freq.QuadPart;
695 static int64_t get_clock(void)
697 LARGE_INTEGER ti;
698 QueryPerformanceCounter(&ti);
699 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
702 #else
704 static int use_rt_clock;
706 static void init_get_clock(void)
708 use_rt_clock = 0;
709 #if defined(__linux__)
711 struct timespec ts;
712 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
713 use_rt_clock = 1;
716 #endif
719 static int64_t get_clock(void)
721 #if defined(__linux__)
722 if (use_rt_clock) {
723 struct timespec ts;
724 clock_gettime(CLOCK_MONOTONIC, &ts);
725 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
726 } else
727 #endif
729 /* XXX: using gettimeofday leads to problems if the date
730 changes, so it should be avoided. */
731 struct timeval tv;
732 gettimeofday(&tv, NULL);
733 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
737 #endif
739 /***********************************************************/
740 /* guest cycle counter */
742 static int64_t cpu_ticks_prev;
743 static int64_t cpu_ticks_offset;
744 static int64_t cpu_clock_offset;
745 static int cpu_ticks_enabled;
747 /* return the host CPU cycle counter and handle stop/restart */
748 int64_t cpu_get_ticks(void)
750 if (!cpu_ticks_enabled) {
751 return cpu_ticks_offset;
752 } else {
753 int64_t ticks;
754 ticks = cpu_get_real_ticks();
755 if (cpu_ticks_prev > ticks) {
756 /* Note: non increasing ticks may happen if the host uses
757 software suspend */
758 cpu_ticks_offset += cpu_ticks_prev - ticks;
760 cpu_ticks_prev = ticks;
761 return ticks + cpu_ticks_offset;
765 /* return the host CPU monotonic timer and handle stop/restart */
766 static int64_t cpu_get_clock(void)
768 int64_t ti;
769 if (!cpu_ticks_enabled) {
770 return cpu_clock_offset;
771 } else {
772 ti = get_clock();
773 return ti + cpu_clock_offset;
777 /* enable cpu_get_ticks() */
778 void cpu_enable_ticks(void)
780 if (!cpu_ticks_enabled) {
781 cpu_ticks_offset -= cpu_get_real_ticks();
782 cpu_clock_offset -= get_clock();
783 cpu_ticks_enabled = 1;
787 /* disable cpu_get_ticks() : the clock is stopped. You must not call
788 cpu_get_ticks() after that. */
789 void cpu_disable_ticks(void)
791 if (cpu_ticks_enabled) {
792 cpu_ticks_offset = cpu_get_ticks();
793 cpu_clock_offset = cpu_get_clock();
794 cpu_ticks_enabled = 0;
798 /***********************************************************/
799 /* timers */
801 #define QEMU_TIMER_REALTIME 0
802 #define QEMU_TIMER_VIRTUAL 1
804 struct QEMUClock {
805 int type;
806 /* XXX: add frequency */
809 struct QEMUTimer {
810 QEMUClock *clock;
811 int64_t expire_time;
812 QEMUTimerCB *cb;
813 void *opaque;
814 struct QEMUTimer *next;
817 struct qemu_alarm_timer {
818 char const *name;
819 unsigned int flags;
821 int (*start)(struct qemu_alarm_timer *t);
822 void (*stop)(struct qemu_alarm_timer *t);
823 void (*rearm)(struct qemu_alarm_timer *t);
824 void *priv;
827 #define ALARM_FLAG_DYNTICKS 0x1
828 #define ALARM_FLAG_EXPIRED 0x2
830 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
832 return t->flags & ALARM_FLAG_DYNTICKS;
835 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
837 if (!alarm_has_dynticks(t))
838 return;
840 t->rearm(t);
843 /* TODO: MIN_TIMER_REARM_US should be optimized */
844 #define MIN_TIMER_REARM_US 250
846 static struct qemu_alarm_timer *alarm_timer;
848 #ifdef _WIN32
850 struct qemu_alarm_win32 {
851 MMRESULT timerId;
852 HANDLE host_alarm;
853 unsigned int period;
854 } alarm_win32_data = {0, NULL, -1};
856 static int win32_start_timer(struct qemu_alarm_timer *t);
857 static void win32_stop_timer(struct qemu_alarm_timer *t);
858 static void win32_rearm_timer(struct qemu_alarm_timer *t);
860 #else
862 static int unix_start_timer(struct qemu_alarm_timer *t);
863 static void unix_stop_timer(struct qemu_alarm_timer *t);
865 #ifdef __linux__
867 static int dynticks_start_timer(struct qemu_alarm_timer *t);
868 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
869 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
871 static int hpet_start_timer(struct qemu_alarm_timer *t);
872 static void hpet_stop_timer(struct qemu_alarm_timer *t);
874 static int rtc_start_timer(struct qemu_alarm_timer *t);
875 static void rtc_stop_timer(struct qemu_alarm_timer *t);
877 #endif /* __linux__ */
879 #endif /* _WIN32 */
881 static struct qemu_alarm_timer alarm_timers[] = {
882 #ifndef _WIN32
883 #ifdef __linux__
884 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
885 dynticks_stop_timer, dynticks_rearm_timer, NULL},
886 /* HPET - if available - is preferred */
887 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
888 /* ...otherwise try RTC */
889 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
890 #endif
891 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
892 #else
893 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
894 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
895 {"win32", 0, win32_start_timer,
896 win32_stop_timer, NULL, &alarm_win32_data},
897 #endif
898 {NULL, }
901 static void show_available_alarms()
903 int i;
905 printf("Available alarm timers, in order of precedence:\n");
906 for (i = 0; alarm_timers[i].name; i++)
907 printf("%s\n", alarm_timers[i].name);
910 static void configure_alarms(char const *opt)
912 int i;
913 int cur = 0;
914 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
915 char *arg;
916 char *name;
918 if (!strcmp(opt, "help")) {
919 show_available_alarms();
920 exit(0);
923 arg = strdup(opt);
925 /* Reorder the array */
926 name = strtok(arg, ",");
927 while (name) {
928 struct qemu_alarm_timer tmp;
930 for (i = 0; i < count && alarm_timers[i].name; i++) {
931 if (!strcmp(alarm_timers[i].name, name))
932 break;
935 if (i == count) {
936 fprintf(stderr, "Unknown clock %s\n", name);
937 goto next;
940 if (i < cur)
941 /* Ignore */
942 goto next;
944 /* Swap */
945 tmp = alarm_timers[i];
946 alarm_timers[i] = alarm_timers[cur];
947 alarm_timers[cur] = tmp;
949 cur++;
950 next:
951 name = strtok(NULL, ",");
954 free(arg);
956 if (cur) {
957 /* Disable remaining timers */
958 for (i = cur; i < count; i++)
959 alarm_timers[i].name = NULL;
962 /* debug */
963 show_available_alarms();
966 QEMUClock *rt_clock;
967 QEMUClock *vm_clock;
969 static QEMUTimer *active_timers[2];
971 static QEMUClock *qemu_new_clock(int type)
973 QEMUClock *clock;
974 clock = qemu_mallocz(sizeof(QEMUClock));
975 if (!clock)
976 return NULL;
977 clock->type = type;
978 return clock;
981 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
983 QEMUTimer *ts;
985 ts = qemu_mallocz(sizeof(QEMUTimer));
986 ts->clock = clock;
987 ts->cb = cb;
988 ts->opaque = opaque;
989 return ts;
992 void qemu_free_timer(QEMUTimer *ts)
994 qemu_free(ts);
997 /* stop a timer, but do not dealloc it */
998 void qemu_del_timer(QEMUTimer *ts)
1000 QEMUTimer **pt, *t;
1002 /* NOTE: this code must be signal safe because
1003 qemu_timer_expired() can be called from a signal. */
1004 pt = &active_timers[ts->clock->type];
1005 for(;;) {
1006 t = *pt;
1007 if (!t)
1008 break;
1009 if (t == ts) {
1010 *pt = t->next;
1011 break;
1013 pt = &t->next;
1017 /* modify the current timer so that it will be fired when current_time
1018 >= expire_time. The corresponding callback will be called. */
1019 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1021 QEMUTimer **pt, *t;
1023 qemu_del_timer(ts);
1025 /* add the timer in the sorted list */
1026 /* NOTE: this code must be signal safe because
1027 qemu_timer_expired() can be called from a signal. */
1028 pt = &active_timers[ts->clock->type];
1029 for(;;) {
1030 t = *pt;
1031 if (!t)
1032 break;
1033 if (t->expire_time > expire_time)
1034 break;
1035 pt = &t->next;
1037 ts->expire_time = expire_time;
1038 ts->next = *pt;
1039 *pt = ts;
1041 /* Rearm if necessary */
1042 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1043 pt == &active_timers[ts->clock->type])
1044 qemu_rearm_alarm_timer(alarm_timer);
1047 int qemu_timer_pending(QEMUTimer *ts)
1049 QEMUTimer *t;
1050 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1051 if (t == ts)
1052 return 1;
1054 return 0;
1057 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1059 if (!timer_head)
1060 return 0;
1061 return (timer_head->expire_time <= current_time);
1064 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1066 QEMUTimer *ts;
1068 for(;;) {
1069 ts = *ptimer_head;
1070 if (!ts || ts->expire_time > current_time)
1071 break;
1072 /* remove timer from the list before calling the callback */
1073 *ptimer_head = ts->next;
1074 ts->next = NULL;
1076 /* run the callback (the timer list can be modified) */
1077 ts->cb(ts->opaque);
1081 int64_t qemu_get_clock(QEMUClock *clock)
1083 switch(clock->type) {
1084 case QEMU_TIMER_REALTIME:
1085 return get_clock() / 1000000;
1086 default:
1087 case QEMU_TIMER_VIRTUAL:
1088 return cpu_get_clock();
1092 static void init_timers(void)
1094 init_get_clock();
1095 ticks_per_sec = QEMU_TIMER_BASE;
1096 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1097 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1100 /* save a timer */
1101 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1103 uint64_t expire_time;
1105 if (qemu_timer_pending(ts)) {
1106 expire_time = ts->expire_time;
1107 } else {
1108 expire_time = -1;
1110 qemu_put_be64(f, expire_time);
1113 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1115 uint64_t expire_time;
1117 expire_time = qemu_get_be64(f);
1118 if (expire_time != -1) {
1119 qemu_mod_timer(ts, expire_time);
1120 } else {
1121 qemu_del_timer(ts);
1125 static void timer_save(QEMUFile *f, void *opaque)
1127 if (cpu_ticks_enabled) {
1128 hw_error("cannot save state if virtual timers are running");
1130 qemu_put_be64(f, cpu_ticks_offset);
1131 qemu_put_be64(f, ticks_per_sec);
1132 qemu_put_be64(f, cpu_clock_offset);
1135 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1137 if (version_id != 1 && version_id != 2)
1138 return -EINVAL;
1139 if (cpu_ticks_enabled) {
1140 return -EINVAL;
1142 cpu_ticks_offset=qemu_get_be64(f);
1143 ticks_per_sec=qemu_get_be64(f);
1144 if (version_id == 2) {
1145 cpu_clock_offset=qemu_get_be64(f);
1147 return 0;
1150 #ifdef _WIN32
1151 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1152 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1153 #else
1154 static void host_alarm_handler(int host_signum)
1155 #endif
1157 #if 0
1158 #define DISP_FREQ 1000
1160 static int64_t delta_min = INT64_MAX;
1161 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1162 static int count;
1163 ti = qemu_get_clock(vm_clock);
1164 if (last_clock != 0) {
1165 delta = ti - last_clock;
1166 if (delta < delta_min)
1167 delta_min = delta;
1168 if (delta > delta_max)
1169 delta_max = delta;
1170 delta_cum += delta;
1171 if (++count == DISP_FREQ) {
1172 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1173 muldiv64(delta_min, 1000000, ticks_per_sec),
1174 muldiv64(delta_max, 1000000, ticks_per_sec),
1175 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1176 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1177 count = 0;
1178 delta_min = INT64_MAX;
1179 delta_max = 0;
1180 delta_cum = 0;
1183 last_clock = ti;
1185 #endif
1186 if (alarm_has_dynticks(alarm_timer) ||
1187 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1188 qemu_get_clock(vm_clock)) ||
1189 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1190 qemu_get_clock(rt_clock))) {
1191 #ifdef _WIN32
1192 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1193 SetEvent(data->host_alarm);
1194 #endif
1195 CPUState *env = next_cpu;
1197 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1199 if (env) {
1200 /* stop the currently executing cpu because a timer occured */
1201 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1202 #ifdef USE_KQEMU
1203 if (env->kqemu_enabled) {
1204 kqemu_cpu_interrupt(env);
1206 #endif
1208 event_pending = 1;
1212 static uint64_t qemu_next_deadline(void)
1214 int64_t nearest_delta_us = INT64_MAX;
1215 int64_t vmdelta_us;
1217 if (active_timers[QEMU_TIMER_REALTIME])
1218 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1219 qemu_get_clock(rt_clock))*1000;
1221 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1222 /* round up */
1223 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1224 qemu_get_clock(vm_clock)+999)/1000;
1225 if (vmdelta_us < nearest_delta_us)
1226 nearest_delta_us = vmdelta_us;
1229 /* Avoid arming the timer to negative, zero, or too low values */
1230 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1231 nearest_delta_us = MIN_TIMER_REARM_US;
1233 return nearest_delta_us;
1236 #ifndef _WIN32
1238 #if defined(__linux__)
1240 #define RTC_FREQ 1024
1242 static void enable_sigio_timer(int fd)
1244 struct sigaction act;
1246 /* timer signal */
1247 sigfillset(&act.sa_mask);
1248 act.sa_flags = 0;
1249 act.sa_handler = host_alarm_handler;
1251 sigaction(SIGIO, &act, NULL);
1252 fcntl(fd, F_SETFL, O_ASYNC);
1253 fcntl(fd, F_SETOWN, getpid());
1256 static int hpet_start_timer(struct qemu_alarm_timer *t)
1258 struct hpet_info info;
1259 int r, fd;
1261 fd = open("/dev/hpet", O_RDONLY);
1262 if (fd < 0)
1263 return -1;
1265 /* Set frequency */
1266 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1267 if (r < 0) {
1268 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1269 "error, but for better emulation accuracy type:\n"
1270 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1271 goto fail;
1274 /* Check capabilities */
1275 r = ioctl(fd, HPET_INFO, &info);
1276 if (r < 0)
1277 goto fail;
1279 /* Enable periodic mode */
1280 r = ioctl(fd, HPET_EPI, 0);
1281 if (info.hi_flags && (r < 0))
1282 goto fail;
1284 /* Enable interrupt */
1285 r = ioctl(fd, HPET_IE_ON, 0);
1286 if (r < 0)
1287 goto fail;
1289 enable_sigio_timer(fd);
1290 t->priv = (void *)(long)fd;
1292 return 0;
1293 fail:
1294 close(fd);
1295 return -1;
1298 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1300 int fd = (long)t->priv;
1302 close(fd);
1305 static int rtc_start_timer(struct qemu_alarm_timer *t)
1307 int rtc_fd;
1308 unsigned long current_rtc_freq = 0;
1310 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1311 if (rtc_fd < 0)
1312 return -1;
1313 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1314 if (current_rtc_freq != RTC_FREQ &&
1315 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1316 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1317 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1318 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1319 goto fail;
1321 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1322 fail:
1323 close(rtc_fd);
1324 return -1;
1327 enable_sigio_timer(rtc_fd);
1329 t->priv = (void *)(long)rtc_fd;
1331 return 0;
1334 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1336 int rtc_fd = (long)t->priv;
1338 close(rtc_fd);
1341 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1343 struct sigevent ev;
1344 timer_t host_timer;
1345 struct sigaction act;
1347 sigfillset(&act.sa_mask);
1348 act.sa_flags = 0;
1349 act.sa_handler = host_alarm_handler;
1351 sigaction(SIGALRM, &act, NULL);
1353 ev.sigev_value.sival_int = 0;
1354 ev.sigev_notify = SIGEV_SIGNAL;
1355 ev.sigev_signo = SIGALRM;
1357 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1358 perror("timer_create");
1360 /* disable dynticks */
1361 fprintf(stderr, "Dynamic Ticks disabled\n");
1363 return -1;
1366 t->priv = (void *)host_timer;
1368 return 0;
1371 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1373 timer_t host_timer = (timer_t)t->priv;
1375 timer_delete(host_timer);
1378 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1380 timer_t host_timer = (timer_t)t->priv;
1381 struct itimerspec timeout;
1382 int64_t nearest_delta_us = INT64_MAX;
1383 int64_t current_us;
1385 if (!active_timers[QEMU_TIMER_REALTIME] &&
1386 !active_timers[QEMU_TIMER_VIRTUAL])
1387 return;
1389 nearest_delta_us = qemu_next_deadline();
1391 /* check whether a timer is already running */
1392 if (timer_gettime(host_timer, &timeout)) {
1393 perror("gettime");
1394 fprintf(stderr, "Internal timer error: aborting\n");
1395 exit(1);
1397 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1398 if (current_us && current_us <= nearest_delta_us)
1399 return;
1401 timeout.it_interval.tv_sec = 0;
1402 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1403 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1404 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1405 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1406 perror("settime");
1407 fprintf(stderr, "Internal timer error: aborting\n");
1408 exit(1);
1412 #endif /* defined(__linux__) */
1414 static int unix_start_timer(struct qemu_alarm_timer *t)
1416 struct sigaction act;
1417 struct itimerval itv;
1418 int err;
1420 /* timer signal */
1421 sigfillset(&act.sa_mask);
1422 act.sa_flags = 0;
1423 act.sa_handler = host_alarm_handler;
1425 sigaction(SIGALRM, &act, NULL);
1427 itv.it_interval.tv_sec = 0;
1428 /* for i386 kernel 2.6 to get 1 ms */
1429 itv.it_interval.tv_usec = 999;
1430 itv.it_value.tv_sec = 0;
1431 itv.it_value.tv_usec = 10 * 1000;
1433 err = setitimer(ITIMER_REAL, &itv, NULL);
1434 if (err)
1435 return -1;
1437 return 0;
1440 static void unix_stop_timer(struct qemu_alarm_timer *t)
1442 struct itimerval itv;
1444 memset(&itv, 0, sizeof(itv));
1445 setitimer(ITIMER_REAL, &itv, NULL);
1448 #endif /* !defined(_WIN32) */
1450 #ifdef _WIN32
1452 static int win32_start_timer(struct qemu_alarm_timer *t)
1454 TIMECAPS tc;
1455 struct qemu_alarm_win32 *data = t->priv;
1456 UINT flags;
1458 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1459 if (!data->host_alarm) {
1460 perror("Failed CreateEvent");
1461 return -1;
1464 memset(&tc, 0, sizeof(tc));
1465 timeGetDevCaps(&tc, sizeof(tc));
1467 if (data->period < tc.wPeriodMin)
1468 data->period = tc.wPeriodMin;
1470 timeBeginPeriod(data->period);
1472 flags = TIME_CALLBACK_FUNCTION;
1473 if (alarm_has_dynticks(t))
1474 flags |= TIME_ONESHOT;
1475 else
1476 flags |= TIME_PERIODIC;
1478 data->timerId = timeSetEvent(1, // interval (ms)
1479 data->period, // resolution
1480 host_alarm_handler, // function
1481 (DWORD)t, // parameter
1482 flags);
1484 if (!data->timerId) {
1485 perror("Failed to initialize win32 alarm timer");
1487 timeEndPeriod(data->period);
1488 CloseHandle(data->host_alarm);
1489 return -1;
1492 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1494 return 0;
1497 static void win32_stop_timer(struct qemu_alarm_timer *t)
1499 struct qemu_alarm_win32 *data = t->priv;
1501 timeKillEvent(data->timerId);
1502 timeEndPeriod(data->period);
1504 CloseHandle(data->host_alarm);
1507 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1509 struct qemu_alarm_win32 *data = t->priv;
1510 uint64_t nearest_delta_us;
1512 if (!active_timers[QEMU_TIMER_REALTIME] &&
1513 !active_timers[QEMU_TIMER_VIRTUAL])
1514 return;
1516 nearest_delta_us = qemu_next_deadline();
1517 nearest_delta_us /= 1000;
1519 timeKillEvent(data->timerId);
1521 data->timerId = timeSetEvent(1,
1522 data->period,
1523 host_alarm_handler,
1524 (DWORD)t,
1525 TIME_ONESHOT | TIME_PERIODIC);
1527 if (!data->timerId) {
1528 perror("Failed to re-arm win32 alarm timer");
1530 timeEndPeriod(data->period);
1531 CloseHandle(data->host_alarm);
1532 exit(1);
1536 #endif /* _WIN32 */
1538 static void init_timer_alarm(void)
1540 struct qemu_alarm_timer *t;
1541 int i, err = -1;
1543 for (i = 0; alarm_timers[i].name; i++) {
1544 t = &alarm_timers[i];
1546 err = t->start(t);
1547 if (!err)
1548 break;
1551 if (err) {
1552 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1553 fprintf(stderr, "Terminating\n");
1554 exit(1);
1557 alarm_timer = t;
1560 static void quit_timers(void)
1562 alarm_timer->stop(alarm_timer);
1563 alarm_timer = NULL;
1566 /***********************************************************/
1567 /* character device */
1569 static void qemu_chr_event(CharDriverState *s, int event)
1571 if (!s->chr_event)
1572 return;
1573 s->chr_event(s->handler_opaque, event);
1576 static void qemu_chr_reset_bh(void *opaque)
1578 CharDriverState *s = opaque;
1579 qemu_chr_event(s, CHR_EVENT_RESET);
1580 qemu_bh_delete(s->bh);
1581 s->bh = NULL;
1584 void qemu_chr_reset(CharDriverState *s)
1586 if (s->bh == NULL) {
1587 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1588 qemu_bh_schedule(s->bh);
1592 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1594 return s->chr_write(s, buf, len);
1597 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1599 if (!s->chr_ioctl)
1600 return -ENOTSUP;
1601 return s->chr_ioctl(s, cmd, arg);
1604 int qemu_chr_can_read(CharDriverState *s)
1606 if (!s->chr_can_read)
1607 return 0;
1608 return s->chr_can_read(s->handler_opaque);
1611 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1613 s->chr_read(s->handler_opaque, buf, len);
1616 void qemu_chr_accept_input(CharDriverState *s)
1618 if (s->chr_accept_input)
1619 s->chr_accept_input(s);
1622 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1624 char buf[4096];
1625 va_list ap;
1626 va_start(ap, fmt);
1627 vsnprintf(buf, sizeof(buf), fmt, ap);
1628 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1629 va_end(ap);
1632 void qemu_chr_send_event(CharDriverState *s, int event)
1634 if (s->chr_send_event)
1635 s->chr_send_event(s, event);
1638 void qemu_chr_add_handlers(CharDriverState *s,
1639 IOCanRWHandler *fd_can_read,
1640 IOReadHandler *fd_read,
1641 IOEventHandler *fd_event,
1642 void *opaque)
1644 s->chr_can_read = fd_can_read;
1645 s->chr_read = fd_read;
1646 s->chr_event = fd_event;
1647 s->handler_opaque = opaque;
1648 if (s->chr_update_read_handler)
1649 s->chr_update_read_handler(s);
1652 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1654 return len;
1657 static CharDriverState *qemu_chr_open_null(void)
1659 CharDriverState *chr;
1661 chr = qemu_mallocz(sizeof(CharDriverState));
1662 if (!chr)
1663 return NULL;
1664 chr->chr_write = null_chr_write;
1665 return chr;
1668 /* MUX driver for serial I/O splitting */
1669 static int term_timestamps;
1670 static int64_t term_timestamps_start;
1671 #define MAX_MUX 4
1672 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1673 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1674 typedef struct {
1675 IOCanRWHandler *chr_can_read[MAX_MUX];
1676 IOReadHandler *chr_read[MAX_MUX];
1677 IOEventHandler *chr_event[MAX_MUX];
1678 void *ext_opaque[MAX_MUX];
1679 CharDriverState *drv;
1680 unsigned char buffer[MUX_BUFFER_SIZE];
1681 int prod;
1682 int cons;
1683 int mux_cnt;
1684 int term_got_escape;
1685 int max_size;
1686 } MuxDriver;
1689 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1691 MuxDriver *d = chr->opaque;
1692 int ret;
1693 if (!term_timestamps) {
1694 ret = d->drv->chr_write(d->drv, buf, len);
1695 } else {
1696 int i;
1698 ret = 0;
1699 for(i = 0; i < len; i++) {
1700 ret += d->drv->chr_write(d->drv, buf+i, 1);
1701 if (buf[i] == '\n') {
1702 char buf1[64];
1703 int64_t ti;
1704 int secs;
1706 ti = get_clock();
1707 if (term_timestamps_start == -1)
1708 term_timestamps_start = ti;
1709 ti -= term_timestamps_start;
1710 secs = ti / 1000000000;
1711 snprintf(buf1, sizeof(buf1),
1712 "[%02d:%02d:%02d.%03d] ",
1713 secs / 3600,
1714 (secs / 60) % 60,
1715 secs % 60,
1716 (int)((ti / 1000000) % 1000));
1717 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1721 return ret;
1724 static char *mux_help[] = {
1725 "% h print this help\n\r",
1726 "% x exit emulator\n\r",
1727 "% s save disk data back to file (if -snapshot)\n\r",
1728 "% t toggle console timestamps\n\r"
1729 "% b send break (magic sysrq)\n\r",
1730 "% c switch between console and monitor\n\r",
1731 "% % sends %\n\r",
1732 NULL
1735 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1736 static void mux_print_help(CharDriverState *chr)
1738 int i, j;
1739 char ebuf[15] = "Escape-Char";
1740 char cbuf[50] = "\n\r";
1742 if (term_escape_char > 0 && term_escape_char < 26) {
1743 sprintf(cbuf,"\n\r");
1744 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1745 } else {
1746 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1747 term_escape_char);
1749 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1750 for (i = 0; mux_help[i] != NULL; i++) {
1751 for (j=0; mux_help[i][j] != '\0'; j++) {
1752 if (mux_help[i][j] == '%')
1753 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1754 else
1755 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1760 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1762 if (d->term_got_escape) {
1763 d->term_got_escape = 0;
1764 if (ch == term_escape_char)
1765 goto send_char;
1766 switch(ch) {
1767 case '?':
1768 case 'h':
1769 mux_print_help(chr);
1770 break;
1771 case 'x':
1773 char *term = "QEMU: Terminated\n\r";
1774 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1775 exit(0);
1776 break;
1778 case 's':
1780 int i;
1781 for (i = 0; i < nb_drives; i++) {
1782 bdrv_commit(drives_table[i].bdrv);
1785 break;
1786 case 'b':
1787 qemu_chr_event(chr, CHR_EVENT_BREAK);
1788 break;
1789 case 'c':
1790 /* Switch to the next registered device */
1791 chr->focus++;
1792 if (chr->focus >= d->mux_cnt)
1793 chr->focus = 0;
1794 break;
1795 case 't':
1796 term_timestamps = !term_timestamps;
1797 term_timestamps_start = -1;
1798 break;
1800 } else if (ch == term_escape_char) {
1801 d->term_got_escape = 1;
1802 } else {
1803 send_char:
1804 return 1;
1806 return 0;
1809 static void mux_chr_accept_input(CharDriverState *chr)
1811 int m = chr->focus;
1812 MuxDriver *d = chr->opaque;
1814 while (d->prod != d->cons &&
1815 d->chr_can_read[m] &&
1816 d->chr_can_read[m](d->ext_opaque[m])) {
1817 d->chr_read[m](d->ext_opaque[m],
1818 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1822 static int mux_chr_can_read(void *opaque)
1824 CharDriverState *chr = opaque;
1825 MuxDriver *d = chr->opaque;
1827 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1828 return 1;
1829 if (d->chr_can_read[chr->focus])
1830 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1831 return 0;
1834 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1836 CharDriverState *chr = opaque;
1837 MuxDriver *d = chr->opaque;
1838 int m = chr->focus;
1839 int i;
1841 mux_chr_accept_input (opaque);
1843 for(i = 0; i < size; i++)
1844 if (mux_proc_byte(chr, d, buf[i])) {
1845 if (d->prod == d->cons &&
1846 d->chr_can_read[m] &&
1847 d->chr_can_read[m](d->ext_opaque[m]))
1848 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1849 else
1850 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1854 static void mux_chr_event(void *opaque, int event)
1856 CharDriverState *chr = opaque;
1857 MuxDriver *d = chr->opaque;
1858 int i;
1860 /* Send the event to all registered listeners */
1861 for (i = 0; i < d->mux_cnt; i++)
1862 if (d->chr_event[i])
1863 d->chr_event[i](d->ext_opaque[i], event);
1866 static void mux_chr_update_read_handler(CharDriverState *chr)
1868 MuxDriver *d = chr->opaque;
1870 if (d->mux_cnt >= MAX_MUX) {
1871 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1872 return;
1874 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1875 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1876 d->chr_read[d->mux_cnt] = chr->chr_read;
1877 d->chr_event[d->mux_cnt] = chr->chr_event;
1878 /* Fix up the real driver with mux routines */
1879 if (d->mux_cnt == 0) {
1880 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1881 mux_chr_event, chr);
1883 chr->focus = d->mux_cnt;
1884 d->mux_cnt++;
1887 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1889 CharDriverState *chr;
1890 MuxDriver *d;
1892 chr = qemu_mallocz(sizeof(CharDriverState));
1893 if (!chr)
1894 return NULL;
1895 d = qemu_mallocz(sizeof(MuxDriver));
1896 if (!d) {
1897 free(chr);
1898 return NULL;
1901 chr->opaque = d;
1902 d->drv = drv;
1903 chr->focus = -1;
1904 chr->chr_write = mux_chr_write;
1905 chr->chr_update_read_handler = mux_chr_update_read_handler;
1906 chr->chr_accept_input = mux_chr_accept_input;
1907 return chr;
1911 #ifdef _WIN32
1913 static void socket_cleanup(void)
1915 WSACleanup();
1918 static int socket_init(void)
1920 WSADATA Data;
1921 int ret, err;
1923 ret = WSAStartup(MAKEWORD(2,2), &Data);
1924 if (ret != 0) {
1925 err = WSAGetLastError();
1926 fprintf(stderr, "WSAStartup: %d\n", err);
1927 return -1;
1929 atexit(socket_cleanup);
1930 return 0;
1933 static int send_all(int fd, const uint8_t *buf, int len1)
1935 int ret, len;
1937 len = len1;
1938 while (len > 0) {
1939 ret = send(fd, buf, len, 0);
1940 if (ret < 0) {
1941 int errno;
1942 errno = WSAGetLastError();
1943 if (errno != WSAEWOULDBLOCK) {
1944 return -1;
1946 } else if (ret == 0) {
1947 break;
1948 } else {
1949 buf += ret;
1950 len -= ret;
1953 return len1 - len;
1956 void socket_set_nonblock(int fd)
1958 unsigned long opt = 1;
1959 ioctlsocket(fd, FIONBIO, &opt);
1962 #else
1964 static int unix_write(int fd, const uint8_t *buf, int len1)
1966 int ret, len;
1968 len = len1;
1969 while (len > 0) {
1970 ret = write(fd, buf, len);
1971 if (ret < 0) {
1972 if (errno != EINTR && errno != EAGAIN)
1973 return -1;
1974 } else if (ret == 0) {
1975 break;
1976 } else {
1977 buf += ret;
1978 len -= ret;
1981 return len1 - len;
1984 static inline int send_all(int fd, const uint8_t *buf, int len1)
1986 return unix_write(fd, buf, len1);
1989 void socket_set_nonblock(int fd)
1991 fcntl(fd, F_SETFL, O_NONBLOCK);
1993 #endif /* !_WIN32 */
1995 #ifndef _WIN32
1997 typedef struct {
1998 int fd_in, fd_out;
1999 int max_size;
2000 } FDCharDriver;
2002 #define STDIO_MAX_CLIENTS 1
2003 static int stdio_nb_clients = 0;
2005 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2007 FDCharDriver *s = chr->opaque;
2008 return unix_write(s->fd_out, buf, len);
2011 static int fd_chr_read_poll(void *opaque)
2013 CharDriverState *chr = opaque;
2014 FDCharDriver *s = chr->opaque;
2016 s->max_size = qemu_chr_can_read(chr);
2017 return s->max_size;
2020 static void fd_chr_read(void *opaque)
2022 CharDriverState *chr = opaque;
2023 FDCharDriver *s = chr->opaque;
2024 int size, len;
2025 uint8_t buf[1024];
2027 len = sizeof(buf);
2028 if (len > s->max_size)
2029 len = s->max_size;
2030 if (len == 0)
2031 return;
2032 size = read(s->fd_in, buf, len);
2033 if (size == 0) {
2034 /* FD has been closed. Remove it from the active list. */
2035 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2036 return;
2038 if (size > 0) {
2039 qemu_chr_read(chr, buf, size);
2043 static void fd_chr_update_read_handler(CharDriverState *chr)
2045 FDCharDriver *s = chr->opaque;
2047 if (s->fd_in >= 0) {
2048 if (nographic && s->fd_in == 0) {
2049 } else {
2050 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2051 fd_chr_read, NULL, chr);
2056 static void fd_chr_close(struct CharDriverState *chr)
2058 FDCharDriver *s = chr->opaque;
2060 if (s->fd_in >= 0) {
2061 if (nographic && s->fd_in == 0) {
2062 } else {
2063 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2067 qemu_free(s);
2070 /* open a character device to a unix fd */
2071 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2073 CharDriverState *chr;
2074 FDCharDriver *s;
2076 chr = qemu_mallocz(sizeof(CharDriverState));
2077 if (!chr)
2078 return NULL;
2079 s = qemu_mallocz(sizeof(FDCharDriver));
2080 if (!s) {
2081 free(chr);
2082 return NULL;
2084 s->fd_in = fd_in;
2085 s->fd_out = fd_out;
2086 chr->opaque = s;
2087 chr->chr_write = fd_chr_write;
2088 chr->chr_update_read_handler = fd_chr_update_read_handler;
2089 chr->chr_close = fd_chr_close;
2091 qemu_chr_reset(chr);
2093 return chr;
2096 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2098 int fd_out;
2100 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2101 if (fd_out < 0)
2102 return NULL;
2103 return qemu_chr_open_fd(-1, fd_out);
2106 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2108 int fd_in, fd_out;
2109 char filename_in[256], filename_out[256];
2111 snprintf(filename_in, 256, "%s.in", filename);
2112 snprintf(filename_out, 256, "%s.out", filename);
2113 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2114 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2115 if (fd_in < 0 || fd_out < 0) {
2116 if (fd_in >= 0)
2117 close(fd_in);
2118 if (fd_out >= 0)
2119 close(fd_out);
2120 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2121 if (fd_in < 0)
2122 return NULL;
2124 return qemu_chr_open_fd(fd_in, fd_out);
2128 /* for STDIO, we handle the case where several clients use it
2129 (nographic mode) */
2131 #define TERM_FIFO_MAX_SIZE 1
2133 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2134 static int term_fifo_size;
2136 static int stdio_read_poll(void *opaque)
2138 CharDriverState *chr = opaque;
2140 /* try to flush the queue if needed */
2141 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2142 qemu_chr_read(chr, term_fifo, 1);
2143 term_fifo_size = 0;
2145 /* see if we can absorb more chars */
2146 if (term_fifo_size == 0)
2147 return 1;
2148 else
2149 return 0;
2152 static void stdio_read(void *opaque)
2154 int size;
2155 uint8_t buf[1];
2156 CharDriverState *chr = opaque;
2158 size = read(0, buf, 1);
2159 if (size == 0) {
2160 /* stdin has been closed. Remove it from the active list. */
2161 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2162 return;
2164 if (size > 0) {
2165 if (qemu_chr_can_read(chr) > 0) {
2166 qemu_chr_read(chr, buf, 1);
2167 } else if (term_fifo_size == 0) {
2168 term_fifo[term_fifo_size++] = buf[0];
2173 /* init terminal so that we can grab keys */
2174 static struct termios oldtty;
2175 static int old_fd0_flags;
2176 static int term_atexit_done;
2178 static void term_exit(void)
2180 tcsetattr (0, TCSANOW, &oldtty);
2181 fcntl(0, F_SETFL, old_fd0_flags);
2184 static void term_init(void)
2186 struct termios tty;
2188 tcgetattr (0, &tty);
2189 oldtty = tty;
2190 old_fd0_flags = fcntl(0, F_GETFL);
2192 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2193 |INLCR|IGNCR|ICRNL|IXON);
2194 tty.c_oflag |= OPOST;
2195 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2196 /* if graphical mode, we allow Ctrl-C handling */
2197 if (nographic)
2198 tty.c_lflag &= ~ISIG;
2199 tty.c_cflag &= ~(CSIZE|PARENB);
2200 tty.c_cflag |= CS8;
2201 tty.c_cc[VMIN] = 1;
2202 tty.c_cc[VTIME] = 0;
2204 tcsetattr (0, TCSANOW, &tty);
2206 if (!term_atexit_done++)
2207 atexit(term_exit);
2209 fcntl(0, F_SETFL, O_NONBLOCK);
2212 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2214 term_exit();
2215 stdio_nb_clients--;
2216 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2217 fd_chr_close(chr);
2220 static CharDriverState *qemu_chr_open_stdio(void)
2222 CharDriverState *chr;
2224 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2225 return NULL;
2226 chr = qemu_chr_open_fd(0, 1);
2227 chr->chr_close = qemu_chr_close_stdio;
2228 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2229 stdio_nb_clients++;
2230 term_init();
2232 return chr;
2235 #if defined(__linux__) || defined(__sun__)
2236 static CharDriverState *qemu_chr_open_pty(void)
2238 struct termios tty;
2239 char slave_name[1024];
2240 int master_fd, slave_fd;
2242 #if defined(__linux__)
2243 /* Not satisfying */
2244 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2245 return NULL;
2247 #endif
2249 /* Disabling local echo and line-buffered output */
2250 tcgetattr (master_fd, &tty);
2251 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2252 tty.c_cc[VMIN] = 1;
2253 tty.c_cc[VTIME] = 0;
2254 tcsetattr (master_fd, TCSAFLUSH, &tty);
2256 fprintf(stderr, "char device redirected to %s\n", slave_name);
2257 return qemu_chr_open_fd(master_fd, master_fd);
2260 static void tty_serial_init(int fd, int speed,
2261 int parity, int data_bits, int stop_bits)
2263 struct termios tty;
2264 speed_t spd;
2266 #if 0
2267 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2268 speed, parity, data_bits, stop_bits);
2269 #endif
2270 tcgetattr (fd, &tty);
2272 #define MARGIN 1.1
2273 if (speed <= 50 * MARGIN)
2274 spd = B50;
2275 else if (speed <= 75 * MARGIN)
2276 spd = B75;
2277 else if (speed <= 300 * MARGIN)
2278 spd = B300;
2279 else if (speed <= 600 * MARGIN)
2280 spd = B600;
2281 else if (speed <= 1200 * MARGIN)
2282 spd = B1200;
2283 else if (speed <= 2400 * MARGIN)
2284 spd = B2400;
2285 else if (speed <= 4800 * MARGIN)
2286 spd = B4800;
2287 else if (speed <= 9600 * MARGIN)
2288 spd = B9600;
2289 else if (speed <= 19200 * MARGIN)
2290 spd = B19200;
2291 else if (speed <= 38400 * MARGIN)
2292 spd = B38400;
2293 else if (speed <= 57600 * MARGIN)
2294 spd = B57600;
2295 else if (speed <= 115200 * MARGIN)
2296 spd = B115200;
2297 else
2298 spd = B115200;
2300 cfsetispeed(&tty, spd);
2301 cfsetospeed(&tty, spd);
2303 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2304 |INLCR|IGNCR|ICRNL|IXON);
2305 tty.c_oflag |= OPOST;
2306 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2307 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2308 switch(data_bits) {
2309 default:
2310 case 8:
2311 tty.c_cflag |= CS8;
2312 break;
2313 case 7:
2314 tty.c_cflag |= CS7;
2315 break;
2316 case 6:
2317 tty.c_cflag |= CS6;
2318 break;
2319 case 5:
2320 tty.c_cflag |= CS5;
2321 break;
2323 switch(parity) {
2324 default:
2325 case 'N':
2326 break;
2327 case 'E':
2328 tty.c_cflag |= PARENB;
2329 break;
2330 case 'O':
2331 tty.c_cflag |= PARENB | PARODD;
2332 break;
2334 if (stop_bits == 2)
2335 tty.c_cflag |= CSTOPB;
2337 tcsetattr (fd, TCSANOW, &tty);
2340 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2342 FDCharDriver *s = chr->opaque;
2344 switch(cmd) {
2345 case CHR_IOCTL_SERIAL_SET_PARAMS:
2347 QEMUSerialSetParams *ssp = arg;
2348 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2349 ssp->data_bits, ssp->stop_bits);
2351 break;
2352 case CHR_IOCTL_SERIAL_SET_BREAK:
2354 int enable = *(int *)arg;
2355 if (enable)
2356 tcsendbreak(s->fd_in, 1);
2358 break;
2359 default:
2360 return -ENOTSUP;
2362 return 0;
2365 static CharDriverState *qemu_chr_open_tty(const char *filename)
2367 CharDriverState *chr;
2368 int fd;
2370 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2371 fcntl(fd, F_SETFL, O_NONBLOCK);
2372 tty_serial_init(fd, 115200, 'N', 8, 1);
2373 chr = qemu_chr_open_fd(fd, fd);
2374 if (!chr) {
2375 close(fd);
2376 return NULL;
2378 chr->chr_ioctl = tty_serial_ioctl;
2379 qemu_chr_reset(chr);
2380 return chr;
2382 #else /* ! __linux__ && ! __sun__ */
2383 static CharDriverState *qemu_chr_open_pty(void)
2385 return NULL;
2387 #endif /* __linux__ || __sun__ */
2389 #if defined(__linux__)
2390 typedef struct {
2391 int fd;
2392 int mode;
2393 } ParallelCharDriver;
2395 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2397 if (s->mode != mode) {
2398 int m = mode;
2399 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2400 return 0;
2401 s->mode = mode;
2403 return 1;
2406 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2408 ParallelCharDriver *drv = chr->opaque;
2409 int fd = drv->fd;
2410 uint8_t b;
2412 switch(cmd) {
2413 case CHR_IOCTL_PP_READ_DATA:
2414 if (ioctl(fd, PPRDATA, &b) < 0)
2415 return -ENOTSUP;
2416 *(uint8_t *)arg = b;
2417 break;
2418 case CHR_IOCTL_PP_WRITE_DATA:
2419 b = *(uint8_t *)arg;
2420 if (ioctl(fd, PPWDATA, &b) < 0)
2421 return -ENOTSUP;
2422 break;
2423 case CHR_IOCTL_PP_READ_CONTROL:
2424 if (ioctl(fd, PPRCONTROL, &b) < 0)
2425 return -ENOTSUP;
2426 /* Linux gives only the lowest bits, and no way to know data
2427 direction! For better compatibility set the fixed upper
2428 bits. */
2429 *(uint8_t *)arg = b | 0xc0;
2430 break;
2431 case CHR_IOCTL_PP_WRITE_CONTROL:
2432 b = *(uint8_t *)arg;
2433 if (ioctl(fd, PPWCONTROL, &b) < 0)
2434 return -ENOTSUP;
2435 break;
2436 case CHR_IOCTL_PP_READ_STATUS:
2437 if (ioctl(fd, PPRSTATUS, &b) < 0)
2438 return -ENOTSUP;
2439 *(uint8_t *)arg = b;
2440 break;
2441 case CHR_IOCTL_PP_EPP_READ_ADDR:
2442 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2443 struct ParallelIOArg *parg = arg;
2444 int n = read(fd, parg->buffer, parg->count);
2445 if (n != parg->count) {
2446 return -EIO;
2449 break;
2450 case CHR_IOCTL_PP_EPP_READ:
2451 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2452 struct ParallelIOArg *parg = arg;
2453 int n = read(fd, parg->buffer, parg->count);
2454 if (n != parg->count) {
2455 return -EIO;
2458 break;
2459 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2460 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2461 struct ParallelIOArg *parg = arg;
2462 int n = write(fd, parg->buffer, parg->count);
2463 if (n != parg->count) {
2464 return -EIO;
2467 break;
2468 case CHR_IOCTL_PP_EPP_WRITE:
2469 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2470 struct ParallelIOArg *parg = arg;
2471 int n = write(fd, parg->buffer, parg->count);
2472 if (n != parg->count) {
2473 return -EIO;
2476 break;
2477 default:
2478 return -ENOTSUP;
2480 return 0;
2483 static void pp_close(CharDriverState *chr)
2485 ParallelCharDriver *drv = chr->opaque;
2486 int fd = drv->fd;
2488 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2489 ioctl(fd, PPRELEASE);
2490 close(fd);
2491 qemu_free(drv);
2494 static CharDriverState *qemu_chr_open_pp(const char *filename)
2496 CharDriverState *chr;
2497 ParallelCharDriver *drv;
2498 int fd;
2500 TFR(fd = open(filename, O_RDWR));
2501 if (fd < 0)
2502 return NULL;
2504 if (ioctl(fd, PPCLAIM) < 0) {
2505 close(fd);
2506 return NULL;
2509 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2510 if (!drv) {
2511 close(fd);
2512 return NULL;
2514 drv->fd = fd;
2515 drv->mode = IEEE1284_MODE_COMPAT;
2517 chr = qemu_mallocz(sizeof(CharDriverState));
2518 if (!chr) {
2519 qemu_free(drv);
2520 close(fd);
2521 return NULL;
2523 chr->chr_write = null_chr_write;
2524 chr->chr_ioctl = pp_ioctl;
2525 chr->chr_close = pp_close;
2526 chr->opaque = drv;
2528 qemu_chr_reset(chr);
2530 return chr;
2532 #endif /* __linux__ */
2534 #else /* _WIN32 */
2536 typedef struct {
2537 int max_size;
2538 HANDLE hcom, hrecv, hsend;
2539 OVERLAPPED orecv, osend;
2540 BOOL fpipe;
2541 DWORD len;
2542 } WinCharState;
2544 #define NSENDBUF 2048
2545 #define NRECVBUF 2048
2546 #define MAXCONNECT 1
2547 #define NTIMEOUT 5000
2549 static int win_chr_poll(void *opaque);
2550 static int win_chr_pipe_poll(void *opaque);
2552 static void win_chr_close(CharDriverState *chr)
2554 WinCharState *s = chr->opaque;
2556 if (s->hsend) {
2557 CloseHandle(s->hsend);
2558 s->hsend = NULL;
2560 if (s->hrecv) {
2561 CloseHandle(s->hrecv);
2562 s->hrecv = NULL;
2564 if (s->hcom) {
2565 CloseHandle(s->hcom);
2566 s->hcom = NULL;
2568 if (s->fpipe)
2569 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2570 else
2571 qemu_del_polling_cb(win_chr_poll, chr);
2574 static int win_chr_init(CharDriverState *chr, const char *filename)
2576 WinCharState *s = chr->opaque;
2577 COMMCONFIG comcfg;
2578 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2579 COMSTAT comstat;
2580 DWORD size;
2581 DWORD err;
2583 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2584 if (!s->hsend) {
2585 fprintf(stderr, "Failed CreateEvent\n");
2586 goto fail;
2588 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2589 if (!s->hrecv) {
2590 fprintf(stderr, "Failed CreateEvent\n");
2591 goto fail;
2594 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2595 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2596 if (s->hcom == INVALID_HANDLE_VALUE) {
2597 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2598 s->hcom = NULL;
2599 goto fail;
2602 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2603 fprintf(stderr, "Failed SetupComm\n");
2604 goto fail;
2607 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2608 size = sizeof(COMMCONFIG);
2609 GetDefaultCommConfig(filename, &comcfg, &size);
2610 comcfg.dcb.DCBlength = sizeof(DCB);
2611 CommConfigDialog(filename, NULL, &comcfg);
2613 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2614 fprintf(stderr, "Failed SetCommState\n");
2615 goto fail;
2618 if (!SetCommMask(s->hcom, EV_ERR)) {
2619 fprintf(stderr, "Failed SetCommMask\n");
2620 goto fail;
2623 cto.ReadIntervalTimeout = MAXDWORD;
2624 if (!SetCommTimeouts(s->hcom, &cto)) {
2625 fprintf(stderr, "Failed SetCommTimeouts\n");
2626 goto fail;
2629 if (!ClearCommError(s->hcom, &err, &comstat)) {
2630 fprintf(stderr, "Failed ClearCommError\n");
2631 goto fail;
2633 qemu_add_polling_cb(win_chr_poll, chr);
2634 return 0;
2636 fail:
2637 win_chr_close(chr);
2638 return -1;
2641 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2643 WinCharState *s = chr->opaque;
2644 DWORD len, ret, size, err;
2646 len = len1;
2647 ZeroMemory(&s->osend, sizeof(s->osend));
2648 s->osend.hEvent = s->hsend;
2649 while (len > 0) {
2650 if (s->hsend)
2651 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2652 else
2653 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2654 if (!ret) {
2655 err = GetLastError();
2656 if (err == ERROR_IO_PENDING) {
2657 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2658 if (ret) {
2659 buf += size;
2660 len -= size;
2661 } else {
2662 break;
2664 } else {
2665 break;
2667 } else {
2668 buf += size;
2669 len -= size;
2672 return len1 - len;
2675 static int win_chr_read_poll(CharDriverState *chr)
2677 WinCharState *s = chr->opaque;
2679 s->max_size = qemu_chr_can_read(chr);
2680 return s->max_size;
2683 static void win_chr_readfile(CharDriverState *chr)
2685 WinCharState *s = chr->opaque;
2686 int ret, err;
2687 uint8_t buf[1024];
2688 DWORD size;
2690 ZeroMemory(&s->orecv, sizeof(s->orecv));
2691 s->orecv.hEvent = s->hrecv;
2692 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2693 if (!ret) {
2694 err = GetLastError();
2695 if (err == ERROR_IO_PENDING) {
2696 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2700 if (size > 0) {
2701 qemu_chr_read(chr, buf, size);
2705 static void win_chr_read(CharDriverState *chr)
2707 WinCharState *s = chr->opaque;
2709 if (s->len > s->max_size)
2710 s->len = s->max_size;
2711 if (s->len == 0)
2712 return;
2714 win_chr_readfile(chr);
2717 static int win_chr_poll(void *opaque)
2719 CharDriverState *chr = opaque;
2720 WinCharState *s = chr->opaque;
2721 COMSTAT status;
2722 DWORD comerr;
2724 ClearCommError(s->hcom, &comerr, &status);
2725 if (status.cbInQue > 0) {
2726 s->len = status.cbInQue;
2727 win_chr_read_poll(chr);
2728 win_chr_read(chr);
2729 return 1;
2731 return 0;
2734 static CharDriverState *qemu_chr_open_win(const char *filename)
2736 CharDriverState *chr;
2737 WinCharState *s;
2739 chr = qemu_mallocz(sizeof(CharDriverState));
2740 if (!chr)
2741 return NULL;
2742 s = qemu_mallocz(sizeof(WinCharState));
2743 if (!s) {
2744 free(chr);
2745 return NULL;
2747 chr->opaque = s;
2748 chr->chr_write = win_chr_write;
2749 chr->chr_close = win_chr_close;
2751 if (win_chr_init(chr, filename) < 0) {
2752 free(s);
2753 free(chr);
2754 return NULL;
2756 qemu_chr_reset(chr);
2757 return chr;
2760 static int win_chr_pipe_poll(void *opaque)
2762 CharDriverState *chr = opaque;
2763 WinCharState *s = chr->opaque;
2764 DWORD size;
2766 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2767 if (size > 0) {
2768 s->len = size;
2769 win_chr_read_poll(chr);
2770 win_chr_read(chr);
2771 return 1;
2773 return 0;
2776 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2778 WinCharState *s = chr->opaque;
2779 OVERLAPPED ov;
2780 int ret;
2781 DWORD size;
2782 char openname[256];
2784 s->fpipe = TRUE;
2786 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2787 if (!s->hsend) {
2788 fprintf(stderr, "Failed CreateEvent\n");
2789 goto fail;
2791 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2792 if (!s->hrecv) {
2793 fprintf(stderr, "Failed CreateEvent\n");
2794 goto fail;
2797 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2798 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2799 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2800 PIPE_WAIT,
2801 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2802 if (s->hcom == INVALID_HANDLE_VALUE) {
2803 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2804 s->hcom = NULL;
2805 goto fail;
2808 ZeroMemory(&ov, sizeof(ov));
2809 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2810 ret = ConnectNamedPipe(s->hcom, &ov);
2811 if (ret) {
2812 fprintf(stderr, "Failed ConnectNamedPipe\n");
2813 goto fail;
2816 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2817 if (!ret) {
2818 fprintf(stderr, "Failed GetOverlappedResult\n");
2819 if (ov.hEvent) {
2820 CloseHandle(ov.hEvent);
2821 ov.hEvent = NULL;
2823 goto fail;
2826 if (ov.hEvent) {
2827 CloseHandle(ov.hEvent);
2828 ov.hEvent = NULL;
2830 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2831 return 0;
2833 fail:
2834 win_chr_close(chr);
2835 return -1;
2839 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2841 CharDriverState *chr;
2842 WinCharState *s;
2844 chr = qemu_mallocz(sizeof(CharDriverState));
2845 if (!chr)
2846 return NULL;
2847 s = qemu_mallocz(sizeof(WinCharState));
2848 if (!s) {
2849 free(chr);
2850 return NULL;
2852 chr->opaque = s;
2853 chr->chr_write = win_chr_write;
2854 chr->chr_close = win_chr_close;
2856 if (win_chr_pipe_init(chr, filename) < 0) {
2857 free(s);
2858 free(chr);
2859 return NULL;
2861 qemu_chr_reset(chr);
2862 return chr;
2865 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2867 CharDriverState *chr;
2868 WinCharState *s;
2870 chr = qemu_mallocz(sizeof(CharDriverState));
2871 if (!chr)
2872 return NULL;
2873 s = qemu_mallocz(sizeof(WinCharState));
2874 if (!s) {
2875 free(chr);
2876 return NULL;
2878 s->hcom = fd_out;
2879 chr->opaque = s;
2880 chr->chr_write = win_chr_write;
2881 qemu_chr_reset(chr);
2882 return chr;
2885 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2887 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2890 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2892 HANDLE fd_out;
2894 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2895 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2896 if (fd_out == INVALID_HANDLE_VALUE)
2897 return NULL;
2899 return qemu_chr_open_win_file(fd_out);
2901 #endif /* !_WIN32 */
2903 /***********************************************************/
2904 /* UDP Net console */
2906 typedef struct {
2907 int fd;
2908 struct sockaddr_in daddr;
2909 uint8_t buf[1024];
2910 int bufcnt;
2911 int bufptr;
2912 int max_size;
2913 } NetCharDriver;
2915 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2917 NetCharDriver *s = chr->opaque;
2919 return sendto(s->fd, buf, len, 0,
2920 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2923 static int udp_chr_read_poll(void *opaque)
2925 CharDriverState *chr = opaque;
2926 NetCharDriver *s = chr->opaque;
2928 s->max_size = qemu_chr_can_read(chr);
2930 /* If there were any stray characters in the queue process them
2931 * first
2933 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2934 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2935 s->bufptr++;
2936 s->max_size = qemu_chr_can_read(chr);
2938 return s->max_size;
2941 static void udp_chr_read(void *opaque)
2943 CharDriverState *chr = opaque;
2944 NetCharDriver *s = chr->opaque;
2946 if (s->max_size == 0)
2947 return;
2948 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2949 s->bufptr = s->bufcnt;
2950 if (s->bufcnt <= 0)
2951 return;
2953 s->bufptr = 0;
2954 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2955 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2956 s->bufptr++;
2957 s->max_size = qemu_chr_can_read(chr);
2961 static void udp_chr_update_read_handler(CharDriverState *chr)
2963 NetCharDriver *s = chr->opaque;
2965 if (s->fd >= 0) {
2966 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2967 udp_chr_read, NULL, chr);
2971 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2972 #ifndef _WIN32
2973 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2974 #endif
2975 int parse_host_src_port(struct sockaddr_in *haddr,
2976 struct sockaddr_in *saddr,
2977 const char *str);
2979 static CharDriverState *qemu_chr_open_udp(const char *def)
2981 CharDriverState *chr = NULL;
2982 NetCharDriver *s = NULL;
2983 int fd = -1;
2984 struct sockaddr_in saddr;
2986 chr = qemu_mallocz(sizeof(CharDriverState));
2987 if (!chr)
2988 goto return_err;
2989 s = qemu_mallocz(sizeof(NetCharDriver));
2990 if (!s)
2991 goto return_err;
2993 fd = socket(PF_INET, SOCK_DGRAM, 0);
2994 if (fd < 0) {
2995 perror("socket(PF_INET, SOCK_DGRAM)");
2996 goto return_err;
2999 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3000 printf("Could not parse: %s\n", def);
3001 goto return_err;
3004 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3006 perror("bind");
3007 goto return_err;
3010 s->fd = fd;
3011 s->bufcnt = 0;
3012 s->bufptr = 0;
3013 chr->opaque = s;
3014 chr->chr_write = udp_chr_write;
3015 chr->chr_update_read_handler = udp_chr_update_read_handler;
3016 return chr;
3018 return_err:
3019 if (chr)
3020 free(chr);
3021 if (s)
3022 free(s);
3023 if (fd >= 0)
3024 closesocket(fd);
3025 return NULL;
3028 /***********************************************************/
3029 /* TCP Net console */
3031 typedef struct {
3032 int fd, listen_fd;
3033 int connected;
3034 int max_size;
3035 int do_telnetopt;
3036 int do_nodelay;
3037 int is_unix;
3038 } TCPCharDriver;
3040 static void tcp_chr_accept(void *opaque);
3042 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3044 TCPCharDriver *s = chr->opaque;
3045 if (s->connected) {
3046 return send_all(s->fd, buf, len);
3047 } else {
3048 /* XXX: indicate an error ? */
3049 return len;
3053 static int tcp_chr_read_poll(void *opaque)
3055 CharDriverState *chr = opaque;
3056 TCPCharDriver *s = chr->opaque;
3057 if (!s->connected)
3058 return 0;
3059 s->max_size = qemu_chr_can_read(chr);
3060 return s->max_size;
3063 #define IAC 255
3064 #define IAC_BREAK 243
3065 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3066 TCPCharDriver *s,
3067 uint8_t *buf, int *size)
3069 /* Handle any telnet client's basic IAC options to satisfy char by
3070 * char mode with no echo. All IAC options will be removed from
3071 * the buf and the do_telnetopt variable will be used to track the
3072 * state of the width of the IAC information.
3074 * IAC commands come in sets of 3 bytes with the exception of the
3075 * "IAC BREAK" command and the double IAC.
3078 int i;
3079 int j = 0;
3081 for (i = 0; i < *size; i++) {
3082 if (s->do_telnetopt > 1) {
3083 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3084 /* Double IAC means send an IAC */
3085 if (j != i)
3086 buf[j] = buf[i];
3087 j++;
3088 s->do_telnetopt = 1;
3089 } else {
3090 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3091 /* Handle IAC break commands by sending a serial break */
3092 qemu_chr_event(chr, CHR_EVENT_BREAK);
3093 s->do_telnetopt++;
3095 s->do_telnetopt++;
3097 if (s->do_telnetopt >= 4) {
3098 s->do_telnetopt = 1;
3100 } else {
3101 if ((unsigned char)buf[i] == IAC) {
3102 s->do_telnetopt = 2;
3103 } else {
3104 if (j != i)
3105 buf[j] = buf[i];
3106 j++;
3110 *size = j;
3113 static void tcp_chr_read(void *opaque)
3115 CharDriverState *chr = opaque;
3116 TCPCharDriver *s = chr->opaque;
3117 uint8_t buf[1024];
3118 int len, size;
3120 if (!s->connected || s->max_size <= 0)
3121 return;
3122 len = sizeof(buf);
3123 if (len > s->max_size)
3124 len = s->max_size;
3125 size = recv(s->fd, buf, len, 0);
3126 if (size == 0) {
3127 /* connection closed */
3128 s->connected = 0;
3129 if (s->listen_fd >= 0) {
3130 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3132 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3133 closesocket(s->fd);
3134 s->fd = -1;
3135 } else if (size > 0) {
3136 if (s->do_telnetopt)
3137 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3138 if (size > 0)
3139 qemu_chr_read(chr, buf, size);
3143 static void tcp_chr_connect(void *opaque)
3145 CharDriverState *chr = opaque;
3146 TCPCharDriver *s = chr->opaque;
3148 s->connected = 1;
3149 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3150 tcp_chr_read, NULL, chr);
3151 qemu_chr_reset(chr);
3154 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3155 static void tcp_chr_telnet_init(int fd)
3157 char buf[3];
3158 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3159 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3160 send(fd, (char *)buf, 3, 0);
3161 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3162 send(fd, (char *)buf, 3, 0);
3163 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3164 send(fd, (char *)buf, 3, 0);
3165 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3166 send(fd, (char *)buf, 3, 0);
3169 static void socket_set_nodelay(int fd)
3171 int val = 1;
3172 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3175 static void tcp_chr_accept(void *opaque)
3177 CharDriverState *chr = opaque;
3178 TCPCharDriver *s = chr->opaque;
3179 struct sockaddr_in saddr;
3180 #ifndef _WIN32
3181 struct sockaddr_un uaddr;
3182 #endif
3183 struct sockaddr *addr;
3184 socklen_t len;
3185 int fd;
3187 for(;;) {
3188 #ifndef _WIN32
3189 if (s->is_unix) {
3190 len = sizeof(uaddr);
3191 addr = (struct sockaddr *)&uaddr;
3192 } else
3193 #endif
3195 len = sizeof(saddr);
3196 addr = (struct sockaddr *)&saddr;
3198 fd = accept(s->listen_fd, addr, &len);
3199 if (fd < 0 && errno != EINTR) {
3200 return;
3201 } else if (fd >= 0) {
3202 if (s->do_telnetopt)
3203 tcp_chr_telnet_init(fd);
3204 break;
3207 socket_set_nonblock(fd);
3208 if (s->do_nodelay)
3209 socket_set_nodelay(fd);
3210 s->fd = fd;
3211 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3212 tcp_chr_connect(chr);
3215 static void tcp_chr_close(CharDriverState *chr)
3217 TCPCharDriver *s = chr->opaque;
3218 if (s->fd >= 0)
3219 closesocket(s->fd);
3220 if (s->listen_fd >= 0)
3221 closesocket(s->listen_fd);
3222 qemu_free(s);
3225 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3226 int is_telnet,
3227 int is_unix)
3229 CharDriverState *chr = NULL;
3230 TCPCharDriver *s = NULL;
3231 int fd = -1, ret, err, val;
3232 int is_listen = 0;
3233 int is_waitconnect = 1;
3234 int do_nodelay = 0;
3235 const char *ptr;
3236 struct sockaddr_in saddr;
3237 #ifndef _WIN32
3238 struct sockaddr_un uaddr;
3239 #endif
3240 struct sockaddr *addr;
3241 socklen_t addrlen;
3243 #ifndef _WIN32
3244 if (is_unix) {
3245 addr = (struct sockaddr *)&uaddr;
3246 addrlen = sizeof(uaddr);
3247 if (parse_unix_path(&uaddr, host_str) < 0)
3248 goto fail;
3249 } else
3250 #endif
3252 addr = (struct sockaddr *)&saddr;
3253 addrlen = sizeof(saddr);
3254 if (parse_host_port(&saddr, host_str) < 0)
3255 goto fail;
3258 ptr = host_str;
3259 while((ptr = strchr(ptr,','))) {
3260 ptr++;
3261 if (!strncmp(ptr,"server",6)) {
3262 is_listen = 1;
3263 } else if (!strncmp(ptr,"nowait",6)) {
3264 is_waitconnect = 0;
3265 } else if (!strncmp(ptr,"nodelay",6)) {
3266 do_nodelay = 1;
3267 } else {
3268 printf("Unknown option: %s\n", ptr);
3269 goto fail;
3272 if (!is_listen)
3273 is_waitconnect = 0;
3275 chr = qemu_mallocz(sizeof(CharDriverState));
3276 if (!chr)
3277 goto fail;
3278 s = qemu_mallocz(sizeof(TCPCharDriver));
3279 if (!s)
3280 goto fail;
3282 #ifndef _WIN32
3283 if (is_unix)
3284 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3285 else
3286 #endif
3287 fd = socket(PF_INET, SOCK_STREAM, 0);
3289 if (fd < 0)
3290 goto fail;
3292 if (!is_waitconnect)
3293 socket_set_nonblock(fd);
3295 s->connected = 0;
3296 s->fd = -1;
3297 s->listen_fd = -1;
3298 s->is_unix = is_unix;
3299 s->do_nodelay = do_nodelay && !is_unix;
3301 chr->opaque = s;
3302 chr->chr_write = tcp_chr_write;
3303 chr->chr_close = tcp_chr_close;
3305 if (is_listen) {
3306 /* allow fast reuse */
3307 #ifndef _WIN32
3308 if (is_unix) {
3309 char path[109];
3310 strncpy(path, uaddr.sun_path, 108);
3311 path[108] = 0;
3312 unlink(path);
3313 } else
3314 #endif
3316 val = 1;
3317 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3320 ret = bind(fd, addr, addrlen);
3321 if (ret < 0)
3322 goto fail;
3324 ret = listen(fd, 0);
3325 if (ret < 0)
3326 goto fail;
3328 s->listen_fd = fd;
3329 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3330 if (is_telnet)
3331 s->do_telnetopt = 1;
3332 } else {
3333 for(;;) {
3334 ret = connect(fd, addr, addrlen);
3335 if (ret < 0) {
3336 err = socket_error();
3337 if (err == EINTR || err == EWOULDBLOCK) {
3338 } else if (err == EINPROGRESS) {
3339 break;
3340 #ifdef _WIN32
3341 } else if (err == WSAEALREADY) {
3342 break;
3343 #endif
3344 } else {
3345 goto fail;
3347 } else {
3348 s->connected = 1;
3349 break;
3352 s->fd = fd;
3353 socket_set_nodelay(fd);
3354 if (s->connected)
3355 tcp_chr_connect(chr);
3356 else
3357 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3360 if (is_listen && is_waitconnect) {
3361 printf("QEMU waiting for connection on: %s\n", host_str);
3362 tcp_chr_accept(chr);
3363 socket_set_nonblock(s->listen_fd);
3366 return chr;
3367 fail:
3368 if (fd >= 0)
3369 closesocket(fd);
3370 qemu_free(s);
3371 qemu_free(chr);
3372 return NULL;
3375 CharDriverState *qemu_chr_open(const char *filename)
3377 const char *p;
3379 if (!strcmp(filename, "vc")) {
3380 return text_console_init(&display_state, 0);
3381 } else if (strstart(filename, "vc:", &p)) {
3382 return text_console_init(&display_state, p);
3383 } else if (!strcmp(filename, "null")) {
3384 return qemu_chr_open_null();
3385 } else
3386 if (strstart(filename, "tcp:", &p)) {
3387 return qemu_chr_open_tcp(p, 0, 0);
3388 } else
3389 if (strstart(filename, "telnet:", &p)) {
3390 return qemu_chr_open_tcp(p, 1, 0);
3391 } else
3392 if (strstart(filename, "udp:", &p)) {
3393 return qemu_chr_open_udp(p);
3394 } else
3395 if (strstart(filename, "mon:", &p)) {
3396 CharDriverState *drv = qemu_chr_open(p);
3397 if (drv) {
3398 drv = qemu_chr_open_mux(drv);
3399 monitor_init(drv, !nographic);
3400 return drv;
3402 printf("Unable to open driver: %s\n", p);
3403 return 0;
3404 } else
3405 #ifndef _WIN32
3406 if (strstart(filename, "unix:", &p)) {
3407 return qemu_chr_open_tcp(p, 0, 1);
3408 } else if (strstart(filename, "file:", &p)) {
3409 return qemu_chr_open_file_out(p);
3410 } else if (strstart(filename, "pipe:", &p)) {
3411 return qemu_chr_open_pipe(p);
3412 } else if (!strcmp(filename, "pty")) {
3413 return qemu_chr_open_pty();
3414 } else if (!strcmp(filename, "stdio")) {
3415 return qemu_chr_open_stdio();
3416 } else
3417 #if defined(__linux__)
3418 if (strstart(filename, "/dev/parport", NULL)) {
3419 return qemu_chr_open_pp(filename);
3420 } else
3421 #endif
3422 #if defined(__linux__) || defined(__sun__)
3423 if (strstart(filename, "/dev/", NULL)) {
3424 return qemu_chr_open_tty(filename);
3425 } else
3426 #endif
3427 #else /* !_WIN32 */
3428 if (strstart(filename, "COM", NULL)) {
3429 return qemu_chr_open_win(filename);
3430 } else
3431 if (strstart(filename, "pipe:", &p)) {
3432 return qemu_chr_open_win_pipe(p);
3433 } else
3434 if (strstart(filename, "con:", NULL)) {
3435 return qemu_chr_open_win_con(filename);
3436 } else
3437 if (strstart(filename, "file:", &p)) {
3438 return qemu_chr_open_win_file_out(p);
3440 #endif
3442 return NULL;
3446 void qemu_chr_close(CharDriverState *chr)
3448 if (chr->chr_close)
3449 chr->chr_close(chr);
3450 qemu_free(chr);
3453 /***********************************************************/
3454 /* network device redirectors */
3456 __attribute__ (( unused ))
3457 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3459 int len, i, j, c;
3461 for(i=0;i<size;i+=16) {
3462 len = size - i;
3463 if (len > 16)
3464 len = 16;
3465 fprintf(f, "%08x ", i);
3466 for(j=0;j<16;j++) {
3467 if (j < len)
3468 fprintf(f, " %02x", buf[i+j]);
3469 else
3470 fprintf(f, " ");
3472 fprintf(f, " ");
3473 for(j=0;j<len;j++) {
3474 c = buf[i+j];
3475 if (c < ' ' || c > '~')
3476 c = '.';
3477 fprintf(f, "%c", c);
3479 fprintf(f, "\n");
3483 static int parse_macaddr(uint8_t *macaddr, const char *p)
3485 int i;
3486 char *last_char;
3487 long int offset;
3489 errno = 0;
3490 offset = strtol(p, &last_char, 0);
3491 if (0 == errno && '\0' == *last_char &&
3492 offset >= 0 && offset <= 0xFFFFFF) {
3493 macaddr[3] = (offset & 0xFF0000) >> 16;
3494 macaddr[4] = (offset & 0xFF00) >> 8;
3495 macaddr[5] = offset & 0xFF;
3496 return 0;
3497 } else {
3498 for(i = 0; i < 6; i++) {
3499 macaddr[i] = strtol(p, (char **)&p, 16);
3500 if (i == 5) {
3501 if (*p != '\0')
3502 return -1;
3503 } else {
3504 if (*p != ':' && *p != '-')
3505 return -1;
3506 p++;
3509 return 0;
3512 return -1;
3515 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3517 const char *p, *p1;
3518 int len;
3519 p = *pp;
3520 p1 = strchr(p, sep);
3521 if (!p1)
3522 return -1;
3523 len = p1 - p;
3524 p1++;
3525 if (buf_size > 0) {
3526 if (len > buf_size - 1)
3527 len = buf_size - 1;
3528 memcpy(buf, p, len);
3529 buf[len] = '\0';
3531 *pp = p1;
3532 return 0;
3535 int parse_host_src_port(struct sockaddr_in *haddr,
3536 struct sockaddr_in *saddr,
3537 const char *input_str)
3539 char *str = strdup(input_str);
3540 char *host_str = str;
3541 char *src_str;
3542 char *ptr;
3545 * Chop off any extra arguments at the end of the string which
3546 * would start with a comma, then fill in the src port information
3547 * if it was provided else use the "any address" and "any port".
3549 if ((ptr = strchr(str,',')))
3550 *ptr = '\0';
3552 if ((src_str = strchr(input_str,'@'))) {
3553 *src_str = '\0';
3554 src_str++;
3557 if (parse_host_port(haddr, host_str) < 0)
3558 goto fail;
3560 if (!src_str || *src_str == '\0')
3561 src_str = ":0";
3563 if (parse_host_port(saddr, src_str) < 0)
3564 goto fail;
3566 free(str);
3567 return(0);
3569 fail:
3570 free(str);
3571 return -1;
3574 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3576 char buf[512];
3577 struct hostent *he;
3578 const char *p, *r;
3579 int port;
3581 p = str;
3582 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3583 return -1;
3584 saddr->sin_family = AF_INET;
3585 if (buf[0] == '\0') {
3586 saddr->sin_addr.s_addr = 0;
3587 } else {
3588 if (isdigit(buf[0])) {
3589 if (!inet_aton(buf, &saddr->sin_addr))
3590 return -1;
3591 } else {
3592 if ((he = gethostbyname(buf)) == NULL)
3593 return - 1;
3594 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3597 port = strtol(p, (char **)&r, 0);
3598 if (r == p)
3599 return -1;
3600 saddr->sin_port = htons(port);
3601 return 0;
3604 #ifndef _WIN32
3605 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3607 const char *p;
3608 int len;
3610 len = MIN(108, strlen(str));
3611 p = strchr(str, ',');
3612 if (p)
3613 len = MIN(len, p - str);
3615 memset(uaddr, 0, sizeof(*uaddr));
3617 uaddr->sun_family = AF_UNIX;
3618 memcpy(uaddr->sun_path, str, len);
3620 return 0;
3622 #endif
3624 /* find or alloc a new VLAN */
3625 VLANState *qemu_find_vlan(int id)
3627 VLANState **pvlan, *vlan;
3628 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3629 if (vlan->id == id)
3630 return vlan;
3632 vlan = qemu_mallocz(sizeof(VLANState));
3633 if (!vlan)
3634 return NULL;
3635 vlan->id = id;
3636 vlan->next = NULL;
3637 pvlan = &first_vlan;
3638 while (*pvlan != NULL)
3639 pvlan = &(*pvlan)->next;
3640 *pvlan = vlan;
3641 return vlan;
3644 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3645 IOReadHandler *fd_read,
3646 IOCanRWHandler *fd_can_read,
3647 void *opaque)
3649 VLANClientState *vc, **pvc;
3650 vc = qemu_mallocz(sizeof(VLANClientState));
3651 if (!vc)
3652 return NULL;
3653 vc->fd_read = fd_read;
3654 vc->fd_can_read = fd_can_read;
3655 vc->opaque = opaque;
3656 vc->vlan = vlan;
3658 vc->next = NULL;
3659 pvc = &vlan->first_client;
3660 while (*pvc != NULL)
3661 pvc = &(*pvc)->next;
3662 *pvc = vc;
3663 return vc;
3666 int qemu_can_send_packet(VLANClientState *vc1)
3668 VLANState *vlan = vc1->vlan;
3669 VLANClientState *vc;
3671 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3672 if (vc != vc1) {
3673 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3674 return 1;
3677 return 0;
3680 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3682 VLANState *vlan = vc1->vlan;
3683 VLANClientState *vc;
3685 #if 0
3686 printf("vlan %d send:\n", vlan->id);
3687 hex_dump(stdout, buf, size);
3688 #endif
3689 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3690 if (vc != vc1) {
3691 vc->fd_read(vc->opaque, buf, size);
3696 #if defined(CONFIG_SLIRP)
3698 /* slirp network adapter */
3700 static int slirp_inited;
3701 static VLANClientState *slirp_vc;
3703 int slirp_can_output(void)
3705 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3708 void slirp_output(const uint8_t *pkt, int pkt_len)
3710 #if 0
3711 printf("slirp output:\n");
3712 hex_dump(stdout, pkt, pkt_len);
3713 #endif
3714 if (!slirp_vc)
3715 return;
3716 qemu_send_packet(slirp_vc, pkt, pkt_len);
3719 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3721 #if 0
3722 printf("slirp input:\n");
3723 hex_dump(stdout, buf, size);
3724 #endif
3725 slirp_input(buf, size);
3728 static int net_slirp_init(VLANState *vlan)
3730 if (!slirp_inited) {
3731 slirp_inited = 1;
3732 slirp_init();
3734 slirp_vc = qemu_new_vlan_client(vlan,
3735 slirp_receive, NULL, NULL);
3736 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3737 return 0;
3740 static void net_slirp_redir(const char *redir_str)
3742 int is_udp;
3743 char buf[256], *r;
3744 const char *p;
3745 struct in_addr guest_addr;
3746 int host_port, guest_port;
3748 if (!slirp_inited) {
3749 slirp_inited = 1;
3750 slirp_init();
3753 p = redir_str;
3754 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3755 goto fail;
3756 if (!strcmp(buf, "tcp")) {
3757 is_udp = 0;
3758 } else if (!strcmp(buf, "udp")) {
3759 is_udp = 1;
3760 } else {
3761 goto fail;
3764 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3765 goto fail;
3766 host_port = strtol(buf, &r, 0);
3767 if (r == buf)
3768 goto fail;
3770 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3771 goto fail;
3772 if (buf[0] == '\0') {
3773 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3775 if (!inet_aton(buf, &guest_addr))
3776 goto fail;
3778 guest_port = strtol(p, &r, 0);
3779 if (r == p)
3780 goto fail;
3782 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3783 fprintf(stderr, "qemu: could not set up redirection\n");
3784 exit(1);
3786 return;
3787 fail:
3788 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3789 exit(1);
3792 #ifndef _WIN32
3794 char smb_dir[1024];
3796 static void erase_dir(char *dir_name)
3798 DIR *d;
3799 struct dirent *de;
3800 char filename[1024];
3802 /* erase all the files in the directory */
3803 if ((d = opendir(dir_name)) != 0) {
3804 for(;;) {
3805 de = readdir(d);
3806 if (!de)
3807 break;
3808 if (strcmp(de->d_name, ".") != 0 &&
3809 strcmp(de->d_name, "..") != 0) {
3810 snprintf(filename, sizeof(filename), "%s/%s",
3811 smb_dir, de->d_name);
3812 if (unlink(filename) != 0) /* is it a directory? */
3813 erase_dir(filename);
3816 closedir(d);
3817 rmdir(dir_name);
3821 /* automatic user mode samba server configuration */
3822 static void smb_exit(void)
3824 erase_dir(smb_dir);
3827 /* automatic user mode samba server configuration */
3828 static void net_slirp_smb(const char *exported_dir)
3830 char smb_conf[1024];
3831 char smb_cmdline[1024];
3832 FILE *f;
3834 if (!slirp_inited) {
3835 slirp_inited = 1;
3836 slirp_init();
3839 /* XXX: better tmp dir construction */
3840 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3841 if (mkdir(smb_dir, 0700) < 0) {
3842 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3843 exit(1);
3845 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3847 f = fopen(smb_conf, "w");
3848 if (!f) {
3849 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3850 exit(1);
3852 fprintf(f,
3853 "[global]\n"
3854 "private dir=%s\n"
3855 "smb ports=0\n"
3856 "socket address=127.0.0.1\n"
3857 "pid directory=%s\n"
3858 "lock directory=%s\n"
3859 "log file=%s/log.smbd\n"
3860 "smb passwd file=%s/smbpasswd\n"
3861 "security = share\n"
3862 "[qemu]\n"
3863 "path=%s\n"
3864 "read only=no\n"
3865 "guest ok=yes\n",
3866 smb_dir,
3867 smb_dir,
3868 smb_dir,
3869 smb_dir,
3870 smb_dir,
3871 exported_dir
3873 fclose(f);
3874 atexit(smb_exit);
3876 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3877 SMBD_COMMAND, smb_conf);
3879 slirp_add_exec(0, smb_cmdline, 4, 139);
3882 #endif /* !defined(_WIN32) */
3883 void do_info_slirp(void)
3885 slirp_stats();
3888 #endif /* CONFIG_SLIRP */
3890 #if !defined(_WIN32)
3892 typedef struct TAPState {
3893 VLANClientState *vc;
3894 int fd;
3895 char down_script[1024];
3896 } TAPState;
3898 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3900 TAPState *s = opaque;
3901 int ret;
3902 for(;;) {
3903 ret = write(s->fd, buf, size);
3904 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3905 } else {
3906 break;
3911 static void tap_send(void *opaque)
3913 TAPState *s = opaque;
3914 uint8_t buf[4096];
3915 int size;
3917 #ifdef __sun__
3918 struct strbuf sbuf;
3919 int f = 0;
3920 sbuf.maxlen = sizeof(buf);
3921 sbuf.buf = buf;
3922 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3923 #else
3924 size = read(s->fd, buf, sizeof(buf));
3925 #endif
3926 if (size > 0) {
3927 qemu_send_packet(s->vc, buf, size);
3931 /* fd support */
3933 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3935 TAPState *s;
3937 s = qemu_mallocz(sizeof(TAPState));
3938 if (!s)
3939 return NULL;
3940 s->fd = fd;
3941 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3942 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3943 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3944 return s;
3947 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3948 static int tap_open(char *ifname, int ifname_size)
3950 int fd;
3951 char *dev;
3952 struct stat s;
3954 TFR(fd = open("/dev/tap", O_RDWR));
3955 if (fd < 0) {
3956 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3957 return -1;
3960 fstat(fd, &s);
3961 dev = devname(s.st_rdev, S_IFCHR);
3962 pstrcpy(ifname, ifname_size, dev);
3964 fcntl(fd, F_SETFL, O_NONBLOCK);
3965 return fd;
3967 #elif defined(__sun__)
3968 #define TUNNEWPPA (('T'<<16) | 0x0001)
3970 * Allocate TAP device, returns opened fd.
3971 * Stores dev name in the first arg(must be large enough).
3973 int tap_alloc(char *dev)
3975 int tap_fd, if_fd, ppa = -1;
3976 static int ip_fd = 0;
3977 char *ptr;
3979 static int arp_fd = 0;
3980 int ip_muxid, arp_muxid;
3981 struct strioctl strioc_if, strioc_ppa;
3982 int link_type = I_PLINK;;
3983 struct lifreq ifr;
3984 char actual_name[32] = "";
3986 memset(&ifr, 0x0, sizeof(ifr));
3988 if( *dev ){
3989 ptr = dev;
3990 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3991 ppa = atoi(ptr);
3994 /* Check if IP device was opened */
3995 if( ip_fd )
3996 close(ip_fd);
3998 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3999 if (ip_fd < 0) {
4000 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4001 return -1;
4004 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4005 if (tap_fd < 0) {
4006 syslog(LOG_ERR, "Can't open /dev/tap");
4007 return -1;
4010 /* Assign a new PPA and get its unit number. */
4011 strioc_ppa.ic_cmd = TUNNEWPPA;
4012 strioc_ppa.ic_timout = 0;
4013 strioc_ppa.ic_len = sizeof(ppa);
4014 strioc_ppa.ic_dp = (char *)&ppa;
4015 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4016 syslog (LOG_ERR, "Can't assign new interface");
4018 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4019 if (if_fd < 0) {
4020 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4021 return -1;
4023 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4024 syslog(LOG_ERR, "Can't push IP module");
4025 return -1;
4028 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4029 syslog(LOG_ERR, "Can't get flags\n");
4031 snprintf (actual_name, 32, "tap%d", ppa);
4032 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4034 ifr.lifr_ppa = ppa;
4035 /* Assign ppa according to the unit number returned by tun device */
4037 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4038 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4039 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4040 syslog (LOG_ERR, "Can't get flags\n");
4041 /* Push arp module to if_fd */
4042 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4043 syslog (LOG_ERR, "Can't push ARP module (2)");
4045 /* Push arp module to ip_fd */
4046 if (ioctl (ip_fd, I_POP, NULL) < 0)
4047 syslog (LOG_ERR, "I_POP failed\n");
4048 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4049 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4050 /* Open arp_fd */
4051 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4052 if (arp_fd < 0)
4053 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4055 /* Set ifname to arp */
4056 strioc_if.ic_cmd = SIOCSLIFNAME;
4057 strioc_if.ic_timout = 0;
4058 strioc_if.ic_len = sizeof(ifr);
4059 strioc_if.ic_dp = (char *)&ifr;
4060 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4061 syslog (LOG_ERR, "Can't set ifname to arp\n");
4064 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4065 syslog(LOG_ERR, "Can't link TAP device to IP");
4066 return -1;
4069 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4070 syslog (LOG_ERR, "Can't link TAP device to ARP");
4072 close (if_fd);
4074 memset(&ifr, 0x0, sizeof(ifr));
4075 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4076 ifr.lifr_ip_muxid = ip_muxid;
4077 ifr.lifr_arp_muxid = arp_muxid;
4079 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4081 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4082 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4083 syslog (LOG_ERR, "Can't set multiplexor id");
4086 sprintf(dev, "tap%d", ppa);
4087 return tap_fd;
4090 static int tap_open(char *ifname, int ifname_size)
4092 char dev[10]="";
4093 int fd;
4094 if( (fd = tap_alloc(dev)) < 0 ){
4095 fprintf(stderr, "Cannot allocate TAP device\n");
4096 return -1;
4098 pstrcpy(ifname, ifname_size, dev);
4099 fcntl(fd, F_SETFL, O_NONBLOCK);
4100 return fd;
4102 #else
4103 static int tap_open(char *ifname, int ifname_size)
4105 struct ifreq ifr;
4106 int fd, ret;
4108 TFR(fd = open("/dev/net/tun", O_RDWR));
4109 if (fd < 0) {
4110 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4111 return -1;
4113 memset(&ifr, 0, sizeof(ifr));
4114 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4115 if (ifname[0] != '\0')
4116 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4117 else
4118 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4119 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4120 if (ret != 0) {
4121 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4122 close(fd);
4123 return -1;
4125 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4126 fcntl(fd, F_SETFL, O_NONBLOCK);
4127 return fd;
4129 #endif
4131 static int launch_script(const char *setup_script, const char *ifname, int fd)
4133 int pid, status;
4134 char *args[3];
4135 char **parg;
4137 /* try to launch network script */
4138 pid = fork();
4139 if (pid >= 0) {
4140 if (pid == 0) {
4141 int open_max = sysconf (_SC_OPEN_MAX), i;
4142 for (i = 0; i < open_max; i++)
4143 if (i != STDIN_FILENO &&
4144 i != STDOUT_FILENO &&
4145 i != STDERR_FILENO &&
4146 i != fd)
4147 close(i);
4149 parg = args;
4150 *parg++ = (char *)setup_script;
4151 *parg++ = (char *)ifname;
4152 *parg++ = NULL;
4153 execv(setup_script, args);
4154 _exit(1);
4156 while (waitpid(pid, &status, 0) != pid);
4157 if (!WIFEXITED(status) ||
4158 WEXITSTATUS(status) != 0) {
4159 fprintf(stderr, "%s: could not launch network script\n",
4160 setup_script);
4161 return -1;
4164 return 0;
4167 static int net_tap_init(VLANState *vlan, const char *ifname1,
4168 const char *setup_script, const char *down_script)
4170 TAPState *s;
4171 int fd;
4172 char ifname[128];
4174 if (ifname1 != NULL)
4175 pstrcpy(ifname, sizeof(ifname), ifname1);
4176 else
4177 ifname[0] = '\0';
4178 TFR(fd = tap_open(ifname, sizeof(ifname)));
4179 if (fd < 0)
4180 return -1;
4182 if (!setup_script || !strcmp(setup_script, "no"))
4183 setup_script = "";
4184 if (setup_script[0] != '\0') {
4185 if (launch_script(setup_script, ifname, fd))
4186 return -1;
4188 s = net_tap_fd_init(vlan, fd);
4189 if (!s)
4190 return -1;
4191 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4192 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4193 if (down_script && strcmp(down_script, "no"))
4194 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4195 return 0;
4198 #endif /* !_WIN32 */
4200 /* network connection */
4201 typedef struct NetSocketState {
4202 VLANClientState *vc;
4203 int fd;
4204 int state; /* 0 = getting length, 1 = getting data */
4205 int index;
4206 int packet_len;
4207 uint8_t buf[4096];
4208 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4209 } NetSocketState;
4211 typedef struct NetSocketListenState {
4212 VLANState *vlan;
4213 int fd;
4214 } NetSocketListenState;
4216 /* XXX: we consider we can send the whole packet without blocking */
4217 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4219 NetSocketState *s = opaque;
4220 uint32_t len;
4221 len = htonl(size);
4223 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4224 send_all(s->fd, buf, size);
4227 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4229 NetSocketState *s = opaque;
4230 sendto(s->fd, buf, size, 0,
4231 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4234 static void net_socket_send(void *opaque)
4236 NetSocketState *s = opaque;
4237 int l, size, err;
4238 uint8_t buf1[4096];
4239 const uint8_t *buf;
4241 size = recv(s->fd, buf1, sizeof(buf1), 0);
4242 if (size < 0) {
4243 err = socket_error();
4244 if (err != EWOULDBLOCK)
4245 goto eoc;
4246 } else if (size == 0) {
4247 /* end of connection */
4248 eoc:
4249 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4250 closesocket(s->fd);
4251 return;
4253 buf = buf1;
4254 while (size > 0) {
4255 /* reassemble a packet from the network */
4256 switch(s->state) {
4257 case 0:
4258 l = 4 - s->index;
4259 if (l > size)
4260 l = size;
4261 memcpy(s->buf + s->index, buf, l);
4262 buf += l;
4263 size -= l;
4264 s->index += l;
4265 if (s->index == 4) {
4266 /* got length */
4267 s->packet_len = ntohl(*(uint32_t *)s->buf);
4268 s->index = 0;
4269 s->state = 1;
4271 break;
4272 case 1:
4273 l = s->packet_len - s->index;
4274 if (l > size)
4275 l = size;
4276 memcpy(s->buf + s->index, buf, l);
4277 s->index += l;
4278 buf += l;
4279 size -= l;
4280 if (s->index >= s->packet_len) {
4281 qemu_send_packet(s->vc, s->buf, s->packet_len);
4282 s->index = 0;
4283 s->state = 0;
4285 break;
4290 static void net_socket_send_dgram(void *opaque)
4292 NetSocketState *s = opaque;
4293 int size;
4295 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4296 if (size < 0)
4297 return;
4298 if (size == 0) {
4299 /* end of connection */
4300 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4301 return;
4303 qemu_send_packet(s->vc, s->buf, size);
4306 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4308 struct ip_mreq imr;
4309 int fd;
4310 int val, ret;
4311 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4312 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4313 inet_ntoa(mcastaddr->sin_addr),
4314 (int)ntohl(mcastaddr->sin_addr.s_addr));
4315 return -1;
4318 fd = socket(PF_INET, SOCK_DGRAM, 0);
4319 if (fd < 0) {
4320 perror("socket(PF_INET, SOCK_DGRAM)");
4321 return -1;
4324 val = 1;
4325 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4326 (const char *)&val, sizeof(val));
4327 if (ret < 0) {
4328 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4329 goto fail;
4332 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4333 if (ret < 0) {
4334 perror("bind");
4335 goto fail;
4338 /* Add host to multicast group */
4339 imr.imr_multiaddr = mcastaddr->sin_addr;
4340 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4342 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4343 (const char *)&imr, sizeof(struct ip_mreq));
4344 if (ret < 0) {
4345 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4346 goto fail;
4349 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4350 val = 1;
4351 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4352 (const char *)&val, sizeof(val));
4353 if (ret < 0) {
4354 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4355 goto fail;
4358 socket_set_nonblock(fd);
4359 return fd;
4360 fail:
4361 if (fd >= 0)
4362 closesocket(fd);
4363 return -1;
4366 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4367 int is_connected)
4369 struct sockaddr_in saddr;
4370 int newfd;
4371 socklen_t saddr_len;
4372 NetSocketState *s;
4374 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4375 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4376 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4379 if (is_connected) {
4380 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4381 /* must be bound */
4382 if (saddr.sin_addr.s_addr==0) {
4383 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4384 fd);
4385 return NULL;
4387 /* clone dgram socket */
4388 newfd = net_socket_mcast_create(&saddr);
4389 if (newfd < 0) {
4390 /* error already reported by net_socket_mcast_create() */
4391 close(fd);
4392 return NULL;
4394 /* clone newfd to fd, close newfd */
4395 dup2(newfd, fd);
4396 close(newfd);
4398 } else {
4399 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4400 fd, strerror(errno));
4401 return NULL;
4405 s = qemu_mallocz(sizeof(NetSocketState));
4406 if (!s)
4407 return NULL;
4408 s->fd = fd;
4410 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4411 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4413 /* mcast: save bound address as dst */
4414 if (is_connected) s->dgram_dst=saddr;
4416 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4417 "socket: fd=%d (%s mcast=%s:%d)",
4418 fd, is_connected? "cloned" : "",
4419 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4420 return s;
4423 static void net_socket_connect(void *opaque)
4425 NetSocketState *s = opaque;
4426 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4429 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4430 int is_connected)
4432 NetSocketState *s;
4433 s = qemu_mallocz(sizeof(NetSocketState));
4434 if (!s)
4435 return NULL;
4436 s->fd = fd;
4437 s->vc = qemu_new_vlan_client(vlan,
4438 net_socket_receive, NULL, s);
4439 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4440 "socket: fd=%d", fd);
4441 if (is_connected) {
4442 net_socket_connect(s);
4443 } else {
4444 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4446 return s;
4449 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4450 int is_connected)
4452 int so_type=-1, optlen=sizeof(so_type);
4454 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4455 (socklen_t *)&optlen)< 0) {
4456 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4457 return NULL;
4459 switch(so_type) {
4460 case SOCK_DGRAM:
4461 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4462 case SOCK_STREAM:
4463 return net_socket_fd_init_stream(vlan, fd, is_connected);
4464 default:
4465 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4466 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4467 return net_socket_fd_init_stream(vlan, fd, is_connected);
4469 return NULL;
4472 static void net_socket_accept(void *opaque)
4474 NetSocketListenState *s = opaque;
4475 NetSocketState *s1;
4476 struct sockaddr_in saddr;
4477 socklen_t len;
4478 int fd;
4480 for(;;) {
4481 len = sizeof(saddr);
4482 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4483 if (fd < 0 && errno != EINTR) {
4484 return;
4485 } else if (fd >= 0) {
4486 break;
4489 s1 = net_socket_fd_init(s->vlan, fd, 1);
4490 if (!s1) {
4491 closesocket(fd);
4492 } else {
4493 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4494 "socket: connection from %s:%d",
4495 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4499 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4501 NetSocketListenState *s;
4502 int fd, val, ret;
4503 struct sockaddr_in saddr;
4505 if (parse_host_port(&saddr, host_str) < 0)
4506 return -1;
4508 s = qemu_mallocz(sizeof(NetSocketListenState));
4509 if (!s)
4510 return -1;
4512 fd = socket(PF_INET, SOCK_STREAM, 0);
4513 if (fd < 0) {
4514 perror("socket");
4515 return -1;
4517 socket_set_nonblock(fd);
4519 /* allow fast reuse */
4520 val = 1;
4521 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4523 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4524 if (ret < 0) {
4525 perror("bind");
4526 return -1;
4528 ret = listen(fd, 0);
4529 if (ret < 0) {
4530 perror("listen");
4531 return -1;
4533 s->vlan = vlan;
4534 s->fd = fd;
4535 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4536 return 0;
4539 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4541 NetSocketState *s;
4542 int fd, connected, ret, err;
4543 struct sockaddr_in saddr;
4545 if (parse_host_port(&saddr, host_str) < 0)
4546 return -1;
4548 fd = socket(PF_INET, SOCK_STREAM, 0);
4549 if (fd < 0) {
4550 perror("socket");
4551 return -1;
4553 socket_set_nonblock(fd);
4555 connected = 0;
4556 for(;;) {
4557 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4558 if (ret < 0) {
4559 err = socket_error();
4560 if (err == EINTR || err == EWOULDBLOCK) {
4561 } else if (err == EINPROGRESS) {
4562 break;
4563 #ifdef _WIN32
4564 } else if (err == WSAEALREADY) {
4565 break;
4566 #endif
4567 } else {
4568 perror("connect");
4569 closesocket(fd);
4570 return -1;
4572 } else {
4573 connected = 1;
4574 break;
4577 s = net_socket_fd_init(vlan, fd, connected);
4578 if (!s)
4579 return -1;
4580 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4581 "socket: connect to %s:%d",
4582 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4583 return 0;
4586 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4588 NetSocketState *s;
4589 int fd;
4590 struct sockaddr_in saddr;
4592 if (parse_host_port(&saddr, host_str) < 0)
4593 return -1;
4596 fd = net_socket_mcast_create(&saddr);
4597 if (fd < 0)
4598 return -1;
4600 s = net_socket_fd_init(vlan, fd, 0);
4601 if (!s)
4602 return -1;
4604 s->dgram_dst = saddr;
4606 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4607 "socket: mcast=%s:%d",
4608 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4609 return 0;
4613 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4615 char *q;
4617 q = buf;
4618 while (*p != '\0' && *p != '=') {
4619 if (q && (q - buf) < buf_size - 1)
4620 *q++ = *p;
4621 p++;
4623 if (q)
4624 *q = '\0';
4626 return p;
4629 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4631 char *q;
4633 q = buf;
4634 while (*p != '\0') {
4635 if (*p == ',') {
4636 if (*(p + 1) != ',')
4637 break;
4638 p++;
4640 if (q && (q - buf) < buf_size - 1)
4641 *q++ = *p;
4642 p++;
4644 if (q)
4645 *q = '\0';
4647 return p;
4650 static int get_param_value(char *buf, int buf_size,
4651 const char *tag, const char *str)
4653 const char *p;
4654 char option[128];
4656 p = str;
4657 for(;;) {
4658 p = get_opt_name(option, sizeof(option), p);
4659 if (*p != '=')
4660 break;
4661 p++;
4662 if (!strcmp(tag, option)) {
4663 (void)get_opt_value(buf, buf_size, p);
4664 return strlen(buf);
4665 } else {
4666 p = get_opt_value(NULL, 0, p);
4668 if (*p != ',')
4669 break;
4670 p++;
4672 return 0;
4675 static int check_params(char *buf, int buf_size,
4676 char **params, const char *str)
4678 const char *p;
4679 int i;
4681 p = str;
4682 for(;;) {
4683 p = get_opt_name(buf, buf_size, p);
4684 if (*p != '=')
4685 return -1;
4686 p++;
4687 for(i = 0; params[i] != NULL; i++)
4688 if (!strcmp(params[i], buf))
4689 break;
4690 if (params[i] == NULL)
4691 return -1;
4692 p = get_opt_value(NULL, 0, p);
4693 if (*p != ',')
4694 break;
4695 p++;
4697 return 0;
4701 static int net_client_init(const char *str)
4703 const char *p;
4704 char *q;
4705 char device[64];
4706 char buf[1024];
4707 int vlan_id, ret;
4708 VLANState *vlan;
4710 p = str;
4711 q = device;
4712 while (*p != '\0' && *p != ',') {
4713 if ((q - device) < sizeof(device) - 1)
4714 *q++ = *p;
4715 p++;
4717 *q = '\0';
4718 if (*p == ',')
4719 p++;
4720 vlan_id = 0;
4721 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4722 vlan_id = strtol(buf, NULL, 0);
4724 vlan = qemu_find_vlan(vlan_id);
4725 if (!vlan) {
4726 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4727 return -1;
4729 if (!strcmp(device, "nic")) {
4730 NICInfo *nd;
4731 uint8_t *macaddr;
4733 if (nb_nics >= MAX_NICS) {
4734 fprintf(stderr, "Too Many NICs\n");
4735 return -1;
4737 nd = &nd_table[nb_nics];
4738 macaddr = nd->macaddr;
4739 macaddr[0] = 0x52;
4740 macaddr[1] = 0x54;
4741 macaddr[2] = 0x00;
4742 macaddr[3] = 0x12;
4743 macaddr[4] = 0x34;
4744 macaddr[5] = 0x56 + nb_nics;
4746 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4747 if (parse_macaddr(macaddr, buf) < 0) {
4748 fprintf(stderr, "invalid syntax for ethernet address\n");
4749 return -1;
4752 if (get_param_value(buf, sizeof(buf), "model", p)) {
4753 nd->model = strdup(buf);
4755 nd->vlan = vlan;
4756 nb_nics++;
4757 vlan->nb_guest_devs++;
4758 ret = 0;
4759 } else
4760 if (!strcmp(device, "none")) {
4761 /* does nothing. It is needed to signal that no network cards
4762 are wanted */
4763 ret = 0;
4764 } else
4765 #ifdef CONFIG_SLIRP
4766 if (!strcmp(device, "user")) {
4767 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4768 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4770 vlan->nb_host_devs++;
4771 ret = net_slirp_init(vlan);
4772 } else
4773 #endif
4774 #ifdef _WIN32
4775 if (!strcmp(device, "tap")) {
4776 char ifname[64];
4777 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4778 fprintf(stderr, "tap: no interface name\n");
4779 return -1;
4781 vlan->nb_host_devs++;
4782 ret = tap_win32_init(vlan, ifname);
4783 } else
4784 #else
4785 if (!strcmp(device, "tap")) {
4786 char ifname[64];
4787 char setup_script[1024], down_script[1024];
4788 int fd;
4789 vlan->nb_host_devs++;
4790 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4791 fd = strtol(buf, NULL, 0);
4792 ret = -1;
4793 if (net_tap_fd_init(vlan, fd))
4794 ret = 0;
4795 } else {
4796 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4797 ifname[0] = '\0';
4799 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4800 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4802 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4803 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4805 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4807 } else
4808 #endif
4809 if (!strcmp(device, "socket")) {
4810 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4811 int fd;
4812 fd = strtol(buf, NULL, 0);
4813 ret = -1;
4814 if (net_socket_fd_init(vlan, fd, 1))
4815 ret = 0;
4816 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4817 ret = net_socket_listen_init(vlan, buf);
4818 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4819 ret = net_socket_connect_init(vlan, buf);
4820 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4821 ret = net_socket_mcast_init(vlan, buf);
4822 } else {
4823 fprintf(stderr, "Unknown socket options: %s\n", p);
4824 return -1;
4826 vlan->nb_host_devs++;
4827 } else
4829 fprintf(stderr, "Unknown network device: %s\n", device);
4830 return -1;
4832 if (ret < 0) {
4833 fprintf(stderr, "Could not initialize device '%s'\n", device);
4836 return ret;
4839 void do_info_network(void)
4841 VLANState *vlan;
4842 VLANClientState *vc;
4844 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4845 term_printf("VLAN %d devices:\n", vlan->id);
4846 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4847 term_printf(" %s\n", vc->info_str);
4851 #define HD_ALIAS "index=%d,media=disk"
4852 #ifdef TARGET_PPC
4853 #define CDROM_ALIAS "index=1,media=cdrom"
4854 #else
4855 #define CDROM_ALIAS "index=2,media=cdrom"
4856 #endif
4857 #define FD_ALIAS "index=%d,if=floppy"
4858 #define PFLASH_ALIAS "if=pflash"
4859 #define MTD_ALIAS "if=mtd"
4860 #define SD_ALIAS "index=0,if=sd"
4862 static int drive_add(const char *file, const char *fmt, ...)
4864 va_list ap;
4866 if (nb_drives_opt >= MAX_DRIVES) {
4867 fprintf(stderr, "qemu: too many drives\n");
4868 exit(1);
4871 drives_opt[nb_drives_opt].file = file;
4872 va_start(ap, fmt);
4873 vsnprintf(drives_opt[nb_drives_opt].opt,
4874 sizeof(drives_opt[0].opt), fmt, ap);
4875 va_end(ap);
4877 return nb_drives_opt++;
4880 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4882 int index;
4884 /* seek interface, bus and unit */
4886 for (index = 0; index < nb_drives; index++)
4887 if (drives_table[index].type == type &&
4888 drives_table[index].bus == bus &&
4889 drives_table[index].unit == unit)
4890 return index;
4892 return -1;
4895 int drive_get_max_bus(BlockInterfaceType type)
4897 int max_bus;
4898 int index;
4900 max_bus = -1;
4901 for (index = 0; index < nb_drives; index++) {
4902 if(drives_table[index].type == type &&
4903 drives_table[index].bus > max_bus)
4904 max_bus = drives_table[index].bus;
4906 return max_bus;
4909 static int drive_init(struct drive_opt *arg, int snapshot,
4910 QEMUMachine *machine)
4912 char buf[128];
4913 char file[1024];
4914 char devname[128];
4915 const char *mediastr = "";
4916 BlockInterfaceType type;
4917 enum { MEDIA_DISK, MEDIA_CDROM } media;
4918 int bus_id, unit_id;
4919 int cyls, heads, secs, translation;
4920 BlockDriverState *bdrv;
4921 int max_devs;
4922 int index;
4923 int cache;
4924 int bdrv_flags;
4925 char *str = arg->opt;
4926 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4927 "secs", "trans", "media", "snapshot", "file",
4928 "cache", NULL };
4930 if (check_params(buf, sizeof(buf), params, str) < 0) {
4931 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4932 buf, str);
4933 return -1;
4936 file[0] = 0;
4937 cyls = heads = secs = 0;
4938 bus_id = 0;
4939 unit_id = -1;
4940 translation = BIOS_ATA_TRANSLATION_AUTO;
4941 index = -1;
4942 cache = 1;
4944 if (!strcmp(machine->name, "realview") ||
4945 !strcmp(machine->name, "SS-5") ||
4946 !strcmp(machine->name, "SS-10") ||
4947 !strcmp(machine->name, "SS-600MP") ||
4948 !strcmp(machine->name, "versatilepb") ||
4949 !strcmp(machine->name, "versatileab")) {
4950 type = IF_SCSI;
4951 max_devs = MAX_SCSI_DEVS;
4952 strcpy(devname, "scsi");
4953 } else {
4954 type = IF_IDE;
4955 max_devs = MAX_IDE_DEVS;
4956 strcpy(devname, "ide");
4958 media = MEDIA_DISK;
4960 /* extract parameters */
4962 if (get_param_value(buf, sizeof(buf), "bus", str)) {
4963 bus_id = strtol(buf, NULL, 0);
4964 if (bus_id < 0) {
4965 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4966 return -1;
4970 if (get_param_value(buf, sizeof(buf), "unit", str)) {
4971 unit_id = strtol(buf, NULL, 0);
4972 if (unit_id < 0) {
4973 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4974 return -1;
4978 if (get_param_value(buf, sizeof(buf), "if", str)) {
4979 strncpy(devname, buf, sizeof(devname));
4980 if (!strcmp(buf, "ide")) {
4981 type = IF_IDE;
4982 max_devs = MAX_IDE_DEVS;
4983 } else if (!strcmp(buf, "scsi")) {
4984 type = IF_SCSI;
4985 max_devs = MAX_SCSI_DEVS;
4986 } else if (!strcmp(buf, "floppy")) {
4987 type = IF_FLOPPY;
4988 max_devs = 0;
4989 } else if (!strcmp(buf, "pflash")) {
4990 type = IF_PFLASH;
4991 max_devs = 0;
4992 } else if (!strcmp(buf, "mtd")) {
4993 type = IF_MTD;
4994 max_devs = 0;
4995 } else if (!strcmp(buf, "sd")) {
4996 type = IF_SD;
4997 max_devs = 0;
4998 } else {
4999 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5000 return -1;
5004 if (get_param_value(buf, sizeof(buf), "index", str)) {
5005 index = strtol(buf, NULL, 0);
5006 if (index < 0) {
5007 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5008 return -1;
5012 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5013 cyls = strtol(buf, NULL, 0);
5016 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5017 heads = strtol(buf, NULL, 0);
5020 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5021 secs = strtol(buf, NULL, 0);
5024 if (cyls || heads || secs) {
5025 if (cyls < 1 || cyls > 16383) {
5026 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5027 return -1;
5029 if (heads < 1 || heads > 16) {
5030 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5031 return -1;
5033 if (secs < 1 || secs > 63) {
5034 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5035 return -1;
5039 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5040 if (!cyls) {
5041 fprintf(stderr,
5042 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5043 str);
5044 return -1;
5046 if (!strcmp(buf, "none"))
5047 translation = BIOS_ATA_TRANSLATION_NONE;
5048 else if (!strcmp(buf, "lba"))
5049 translation = BIOS_ATA_TRANSLATION_LBA;
5050 else if (!strcmp(buf, "auto"))
5051 translation = BIOS_ATA_TRANSLATION_AUTO;
5052 else {
5053 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5054 return -1;
5058 if (get_param_value(buf, sizeof(buf), "media", str)) {
5059 if (!strcmp(buf, "disk")) {
5060 media = MEDIA_DISK;
5061 } else if (!strcmp(buf, "cdrom")) {
5062 if (cyls || secs || heads) {
5063 fprintf(stderr,
5064 "qemu: '%s' invalid physical CHS format\n", str);
5065 return -1;
5067 media = MEDIA_CDROM;
5068 } else {
5069 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5070 return -1;
5074 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5075 if (!strcmp(buf, "on"))
5076 snapshot = 1;
5077 else if (!strcmp(buf, "off"))
5078 snapshot = 0;
5079 else {
5080 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5081 return -1;
5085 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5086 if (!strcmp(buf, "off"))
5087 cache = 0;
5088 else if (!strcmp(buf, "on"))
5089 cache = 1;
5090 else {
5091 fprintf(stderr, "qemu: invalid cache option\n");
5092 return -1;
5096 if (arg->file == NULL)
5097 get_param_value(file, sizeof(file), "file", str);
5098 else
5099 pstrcpy(file, sizeof(file), arg->file);
5101 /* compute bus and unit according index */
5103 if (index != -1) {
5104 if (bus_id != 0 || unit_id != -1) {
5105 fprintf(stderr,
5106 "qemu: '%s' index cannot be used with bus and unit\n", str);
5107 return -1;
5109 if (max_devs == 0)
5111 unit_id = index;
5112 bus_id = 0;
5113 } else {
5114 unit_id = index % max_devs;
5115 bus_id = index / max_devs;
5119 /* if user doesn't specify a unit_id,
5120 * try to find the first free
5123 if (unit_id == -1) {
5124 unit_id = 0;
5125 while (drive_get_index(type, bus_id, unit_id) != -1) {
5126 unit_id++;
5127 if (max_devs && unit_id >= max_devs) {
5128 unit_id -= max_devs;
5129 bus_id++;
5134 /* check unit id */
5136 if (max_devs && unit_id >= max_devs) {
5137 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5138 str, unit_id, max_devs - 1);
5139 return -1;
5143 * ignore multiple definitions
5146 if (drive_get_index(type, bus_id, unit_id) != -1)
5147 return 0;
5149 /* init */
5151 if (type == IF_IDE || type == IF_SCSI)
5152 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5153 if (max_devs)
5154 snprintf(buf, sizeof(buf), "%s%i%s%i",
5155 devname, bus_id, mediastr, unit_id);
5156 else
5157 snprintf(buf, sizeof(buf), "%s%s%i",
5158 devname, mediastr, unit_id);
5159 bdrv = bdrv_new(buf);
5160 drives_table[nb_drives].bdrv = bdrv;
5161 drives_table[nb_drives].type = type;
5162 drives_table[nb_drives].bus = bus_id;
5163 drives_table[nb_drives].unit = unit_id;
5164 nb_drives++;
5166 switch(type) {
5167 case IF_IDE:
5168 case IF_SCSI:
5169 switch(media) {
5170 case MEDIA_DISK:
5171 if (cyls != 0) {
5172 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5173 bdrv_set_translation_hint(bdrv, translation);
5175 break;
5176 case MEDIA_CDROM:
5177 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5178 break;
5180 break;
5181 case IF_SD:
5182 /* FIXME: This isn't really a floppy, but it's a reasonable
5183 approximation. */
5184 case IF_FLOPPY:
5185 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5186 break;
5187 case IF_PFLASH:
5188 case IF_MTD:
5189 break;
5191 if (!file[0])
5192 return 0;
5193 bdrv_flags = 0;
5194 if (snapshot)
5195 bdrv_flags |= BDRV_O_SNAPSHOT;
5196 if (!cache)
5197 bdrv_flags |= BDRV_O_DIRECT;
5198 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5199 fprintf(stderr, "qemu: could not open disk image %s\n",
5200 file);
5201 return -1;
5203 return 0;
5206 /***********************************************************/
5207 /* USB devices */
5209 static USBPort *used_usb_ports;
5210 static USBPort *free_usb_ports;
5212 /* ??? Maybe change this to register a hub to keep track of the topology. */
5213 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5214 usb_attachfn attach)
5216 port->opaque = opaque;
5217 port->index = index;
5218 port->attach = attach;
5219 port->next = free_usb_ports;
5220 free_usb_ports = port;
5223 static int usb_device_add(const char *devname)
5225 const char *p;
5226 USBDevice *dev;
5227 USBPort *port;
5229 if (!free_usb_ports)
5230 return -1;
5232 if (strstart(devname, "host:", &p)) {
5233 dev = usb_host_device_open(p);
5234 } else if (!strcmp(devname, "mouse")) {
5235 dev = usb_mouse_init();
5236 } else if (!strcmp(devname, "tablet")) {
5237 dev = usb_tablet_init();
5238 } else if (!strcmp(devname, "keyboard")) {
5239 dev = usb_keyboard_init();
5240 } else if (strstart(devname, "disk:", &p)) {
5241 dev = usb_msd_init(p);
5242 } else if (!strcmp(devname, "wacom-tablet")) {
5243 dev = usb_wacom_init();
5244 } else if (strstart(devname, "serial:", &p)) {
5245 dev = usb_serial_init(p);
5246 } else {
5247 return -1;
5249 if (!dev)
5250 return -1;
5252 /* Find a USB port to add the device to. */
5253 port = free_usb_ports;
5254 if (!port->next) {
5255 USBDevice *hub;
5257 /* Create a new hub and chain it on. */
5258 free_usb_ports = NULL;
5259 port->next = used_usb_ports;
5260 used_usb_ports = port;
5262 hub = usb_hub_init(VM_USB_HUB_SIZE);
5263 usb_attach(port, hub);
5264 port = free_usb_ports;
5267 free_usb_ports = port->next;
5268 port->next = used_usb_ports;
5269 used_usb_ports = port;
5270 usb_attach(port, dev);
5271 return 0;
5274 static int usb_device_del(const char *devname)
5276 USBPort *port;
5277 USBPort **lastp;
5278 USBDevice *dev;
5279 int bus_num, addr;
5280 const char *p;
5282 if (!used_usb_ports)
5283 return -1;
5285 p = strchr(devname, '.');
5286 if (!p)
5287 return -1;
5288 bus_num = strtoul(devname, NULL, 0);
5289 addr = strtoul(p + 1, NULL, 0);
5290 if (bus_num != 0)
5291 return -1;
5293 lastp = &used_usb_ports;
5294 port = used_usb_ports;
5295 while (port && port->dev->addr != addr) {
5296 lastp = &port->next;
5297 port = port->next;
5300 if (!port)
5301 return -1;
5303 dev = port->dev;
5304 *lastp = port->next;
5305 usb_attach(port, NULL);
5306 dev->handle_destroy(dev);
5307 port->next = free_usb_ports;
5308 free_usb_ports = port;
5309 return 0;
5312 void do_usb_add(const char *devname)
5314 int ret;
5315 ret = usb_device_add(devname);
5316 if (ret < 0)
5317 term_printf("Could not add USB device '%s'\n", devname);
5320 void do_usb_del(const char *devname)
5322 int ret;
5323 ret = usb_device_del(devname);
5324 if (ret < 0)
5325 term_printf("Could not remove USB device '%s'\n", devname);
5328 void usb_info(void)
5330 USBDevice *dev;
5331 USBPort *port;
5332 const char *speed_str;
5334 if (!usb_enabled) {
5335 term_printf("USB support not enabled\n");
5336 return;
5339 for (port = used_usb_ports; port; port = port->next) {
5340 dev = port->dev;
5341 if (!dev)
5342 continue;
5343 switch(dev->speed) {
5344 case USB_SPEED_LOW:
5345 speed_str = "1.5";
5346 break;
5347 case USB_SPEED_FULL:
5348 speed_str = "12";
5349 break;
5350 case USB_SPEED_HIGH:
5351 speed_str = "480";
5352 break;
5353 default:
5354 speed_str = "?";
5355 break;
5357 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5358 0, dev->addr, speed_str, dev->devname);
5362 /***********************************************************/
5363 /* PCMCIA/Cardbus */
5365 static struct pcmcia_socket_entry_s {
5366 struct pcmcia_socket_s *socket;
5367 struct pcmcia_socket_entry_s *next;
5368 } *pcmcia_sockets = 0;
5370 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5372 struct pcmcia_socket_entry_s *entry;
5374 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5375 entry->socket = socket;
5376 entry->next = pcmcia_sockets;
5377 pcmcia_sockets = entry;
5380 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5382 struct pcmcia_socket_entry_s *entry, **ptr;
5384 ptr = &pcmcia_sockets;
5385 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5386 if (entry->socket == socket) {
5387 *ptr = entry->next;
5388 qemu_free(entry);
5392 void pcmcia_info(void)
5394 struct pcmcia_socket_entry_s *iter;
5395 if (!pcmcia_sockets)
5396 term_printf("No PCMCIA sockets\n");
5398 for (iter = pcmcia_sockets; iter; iter = iter->next)
5399 term_printf("%s: %s\n", iter->socket->slot_string,
5400 iter->socket->attached ? iter->socket->card_string :
5401 "Empty");
5404 /***********************************************************/
5405 /* dumb display */
5407 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5411 static void dumb_resize(DisplayState *ds, int w, int h)
5415 static void dumb_refresh(DisplayState *ds)
5417 #if defined(CONFIG_SDL)
5418 vga_hw_update();
5419 #endif
5422 static void dumb_display_init(DisplayState *ds)
5424 ds->data = NULL;
5425 ds->linesize = 0;
5426 ds->depth = 0;
5427 ds->dpy_update = dumb_update;
5428 ds->dpy_resize = dumb_resize;
5429 ds->dpy_refresh = dumb_refresh;
5432 /***********************************************************/
5433 /* I/O handling */
5435 #define MAX_IO_HANDLERS 64
5437 typedef struct IOHandlerRecord {
5438 int fd;
5439 IOCanRWHandler *fd_read_poll;
5440 IOHandler *fd_read;
5441 IOHandler *fd_write;
5442 int deleted;
5443 void *opaque;
5444 /* temporary data */
5445 struct pollfd *ufd;
5446 struct IOHandlerRecord *next;
5447 } IOHandlerRecord;
5449 static IOHandlerRecord *first_io_handler;
5451 /* XXX: fd_read_poll should be suppressed, but an API change is
5452 necessary in the character devices to suppress fd_can_read(). */
5453 int qemu_set_fd_handler2(int fd,
5454 IOCanRWHandler *fd_read_poll,
5455 IOHandler *fd_read,
5456 IOHandler *fd_write,
5457 void *opaque)
5459 IOHandlerRecord **pioh, *ioh;
5461 if (!fd_read && !fd_write) {
5462 pioh = &first_io_handler;
5463 for(;;) {
5464 ioh = *pioh;
5465 if (ioh == NULL)
5466 break;
5467 if (ioh->fd == fd) {
5468 ioh->deleted = 1;
5469 break;
5471 pioh = &ioh->next;
5473 } else {
5474 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5475 if (ioh->fd == fd)
5476 goto found;
5478 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5479 if (!ioh)
5480 return -1;
5481 ioh->next = first_io_handler;
5482 first_io_handler = ioh;
5483 found:
5484 ioh->fd = fd;
5485 ioh->fd_read_poll = fd_read_poll;
5486 ioh->fd_read = fd_read;
5487 ioh->fd_write = fd_write;
5488 ioh->opaque = opaque;
5489 ioh->deleted = 0;
5491 return 0;
5494 int qemu_set_fd_handler(int fd,
5495 IOHandler *fd_read,
5496 IOHandler *fd_write,
5497 void *opaque)
5499 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5502 /***********************************************************/
5503 /* Polling handling */
5505 typedef struct PollingEntry {
5506 PollingFunc *func;
5507 void *opaque;
5508 struct PollingEntry *next;
5509 } PollingEntry;
5511 static PollingEntry *first_polling_entry;
5513 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5515 PollingEntry **ppe, *pe;
5516 pe = qemu_mallocz(sizeof(PollingEntry));
5517 if (!pe)
5518 return -1;
5519 pe->func = func;
5520 pe->opaque = opaque;
5521 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5522 *ppe = pe;
5523 return 0;
5526 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5528 PollingEntry **ppe, *pe;
5529 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5530 pe = *ppe;
5531 if (pe->func == func && pe->opaque == opaque) {
5532 *ppe = pe->next;
5533 qemu_free(pe);
5534 break;
5539 #ifdef _WIN32
5540 /***********************************************************/
5541 /* Wait objects support */
5542 typedef struct WaitObjects {
5543 int num;
5544 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5545 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5546 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5547 } WaitObjects;
5549 static WaitObjects wait_objects = {0};
5551 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5553 WaitObjects *w = &wait_objects;
5555 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5556 return -1;
5557 w->events[w->num] = handle;
5558 w->func[w->num] = func;
5559 w->opaque[w->num] = opaque;
5560 w->num++;
5561 return 0;
5564 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5566 int i, found;
5567 WaitObjects *w = &wait_objects;
5569 found = 0;
5570 for (i = 0; i < w->num; i++) {
5571 if (w->events[i] == handle)
5572 found = 1;
5573 if (found) {
5574 w->events[i] = w->events[i + 1];
5575 w->func[i] = w->func[i + 1];
5576 w->opaque[i] = w->opaque[i + 1];
5579 if (found)
5580 w->num--;
5582 #endif
5584 /***********************************************************/
5585 /* savevm/loadvm support */
5587 #define IO_BUF_SIZE 32768
5589 struct QEMUFile {
5590 FILE *outfile;
5591 BlockDriverState *bs;
5592 int is_file;
5593 int is_writable;
5594 int64_t base_offset;
5595 int64_t buf_offset; /* start of buffer when writing, end of buffer
5596 when reading */
5597 int buf_index;
5598 int buf_size; /* 0 when writing */
5599 uint8_t buf[IO_BUF_SIZE];
5602 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5604 QEMUFile *f;
5606 f = qemu_mallocz(sizeof(QEMUFile));
5607 if (!f)
5608 return NULL;
5609 if (!strcmp(mode, "wb")) {
5610 f->is_writable = 1;
5611 } else if (!strcmp(mode, "rb")) {
5612 f->is_writable = 0;
5613 } else {
5614 goto fail;
5616 f->outfile = fopen(filename, mode);
5617 if (!f->outfile)
5618 goto fail;
5619 f->is_file = 1;
5620 return f;
5621 fail:
5622 if (f->outfile)
5623 fclose(f->outfile);
5624 qemu_free(f);
5625 return NULL;
5628 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5630 QEMUFile *f;
5632 f = qemu_mallocz(sizeof(QEMUFile));
5633 if (!f)
5634 return NULL;
5635 f->is_file = 0;
5636 f->bs = bs;
5637 f->is_writable = is_writable;
5638 f->base_offset = offset;
5639 return f;
5642 void qemu_fflush(QEMUFile *f)
5644 if (!f->is_writable)
5645 return;
5646 if (f->buf_index > 0) {
5647 if (f->is_file) {
5648 fseek(f->outfile, f->buf_offset, SEEK_SET);
5649 fwrite(f->buf, 1, f->buf_index, f->outfile);
5650 } else {
5651 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5652 f->buf, f->buf_index);
5654 f->buf_offset += f->buf_index;
5655 f->buf_index = 0;
5659 static void qemu_fill_buffer(QEMUFile *f)
5661 int len;
5663 if (f->is_writable)
5664 return;
5665 if (f->is_file) {
5666 fseek(f->outfile, f->buf_offset, SEEK_SET);
5667 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5668 if (len < 0)
5669 len = 0;
5670 } else {
5671 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5672 f->buf, IO_BUF_SIZE);
5673 if (len < 0)
5674 len = 0;
5676 f->buf_index = 0;
5677 f->buf_size = len;
5678 f->buf_offset += len;
5681 void qemu_fclose(QEMUFile *f)
5683 if (f->is_writable)
5684 qemu_fflush(f);
5685 if (f->is_file) {
5686 fclose(f->outfile);
5688 qemu_free(f);
5691 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5693 int l;
5694 while (size > 0) {
5695 l = IO_BUF_SIZE - f->buf_index;
5696 if (l > size)
5697 l = size;
5698 memcpy(f->buf + f->buf_index, buf, l);
5699 f->buf_index += l;
5700 buf += l;
5701 size -= l;
5702 if (f->buf_index >= IO_BUF_SIZE)
5703 qemu_fflush(f);
5707 void qemu_put_byte(QEMUFile *f, int v)
5709 f->buf[f->buf_index++] = v;
5710 if (f->buf_index >= IO_BUF_SIZE)
5711 qemu_fflush(f);
5714 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5716 int size, l;
5718 size = size1;
5719 while (size > 0) {
5720 l = f->buf_size - f->buf_index;
5721 if (l == 0) {
5722 qemu_fill_buffer(f);
5723 l = f->buf_size - f->buf_index;
5724 if (l == 0)
5725 break;
5727 if (l > size)
5728 l = size;
5729 memcpy(buf, f->buf + f->buf_index, l);
5730 f->buf_index += l;
5731 buf += l;
5732 size -= l;
5734 return size1 - size;
5737 int qemu_get_byte(QEMUFile *f)
5739 if (f->buf_index >= f->buf_size) {
5740 qemu_fill_buffer(f);
5741 if (f->buf_index >= f->buf_size)
5742 return 0;
5744 return f->buf[f->buf_index++];
5747 int64_t qemu_ftell(QEMUFile *f)
5749 return f->buf_offset - f->buf_size + f->buf_index;
5752 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5754 if (whence == SEEK_SET) {
5755 /* nothing to do */
5756 } else if (whence == SEEK_CUR) {
5757 pos += qemu_ftell(f);
5758 } else {
5759 /* SEEK_END not supported */
5760 return -1;
5762 if (f->is_writable) {
5763 qemu_fflush(f);
5764 f->buf_offset = pos;
5765 } else {
5766 f->buf_offset = pos;
5767 f->buf_index = 0;
5768 f->buf_size = 0;
5770 return pos;
5773 void qemu_put_be16(QEMUFile *f, unsigned int v)
5775 qemu_put_byte(f, v >> 8);
5776 qemu_put_byte(f, v);
5779 void qemu_put_be32(QEMUFile *f, unsigned int v)
5781 qemu_put_byte(f, v >> 24);
5782 qemu_put_byte(f, v >> 16);
5783 qemu_put_byte(f, v >> 8);
5784 qemu_put_byte(f, v);
5787 void qemu_put_be64(QEMUFile *f, uint64_t v)
5789 qemu_put_be32(f, v >> 32);
5790 qemu_put_be32(f, v);
5793 unsigned int qemu_get_be16(QEMUFile *f)
5795 unsigned int v;
5796 v = qemu_get_byte(f) << 8;
5797 v |= qemu_get_byte(f);
5798 return v;
5801 unsigned int qemu_get_be32(QEMUFile *f)
5803 unsigned int v;
5804 v = qemu_get_byte(f) << 24;
5805 v |= qemu_get_byte(f) << 16;
5806 v |= qemu_get_byte(f) << 8;
5807 v |= qemu_get_byte(f);
5808 return v;
5811 uint64_t qemu_get_be64(QEMUFile *f)
5813 uint64_t v;
5814 v = (uint64_t)qemu_get_be32(f) << 32;
5815 v |= qemu_get_be32(f);
5816 return v;
5819 typedef struct SaveStateEntry {
5820 char idstr[256];
5821 int instance_id;
5822 int version_id;
5823 SaveStateHandler *save_state;
5824 LoadStateHandler *load_state;
5825 void *opaque;
5826 struct SaveStateEntry *next;
5827 } SaveStateEntry;
5829 static SaveStateEntry *first_se;
5831 int register_savevm(const char *idstr,
5832 int instance_id,
5833 int version_id,
5834 SaveStateHandler *save_state,
5835 LoadStateHandler *load_state,
5836 void *opaque)
5838 SaveStateEntry *se, **pse;
5840 se = qemu_malloc(sizeof(SaveStateEntry));
5841 if (!se)
5842 return -1;
5843 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5844 se->instance_id = instance_id;
5845 se->version_id = version_id;
5846 se->save_state = save_state;
5847 se->load_state = load_state;
5848 se->opaque = opaque;
5849 se->next = NULL;
5851 /* add at the end of list */
5852 pse = &first_se;
5853 while (*pse != NULL)
5854 pse = &(*pse)->next;
5855 *pse = se;
5856 return 0;
5859 #define QEMU_VM_FILE_MAGIC 0x5145564d
5860 #define QEMU_VM_FILE_VERSION 0x00000002
5862 static int qemu_savevm_state(QEMUFile *f)
5864 SaveStateEntry *se;
5865 int len, ret;
5866 int64_t cur_pos, len_pos, total_len_pos;
5868 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5869 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5870 total_len_pos = qemu_ftell(f);
5871 qemu_put_be64(f, 0); /* total size */
5873 for(se = first_se; se != NULL; se = se->next) {
5874 /* ID string */
5875 len = strlen(se->idstr);
5876 qemu_put_byte(f, len);
5877 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5879 qemu_put_be32(f, se->instance_id);
5880 qemu_put_be32(f, se->version_id);
5882 /* record size: filled later */
5883 len_pos = qemu_ftell(f);
5884 qemu_put_be32(f, 0);
5885 se->save_state(f, se->opaque);
5887 /* fill record size */
5888 cur_pos = qemu_ftell(f);
5889 len = cur_pos - len_pos - 4;
5890 qemu_fseek(f, len_pos, SEEK_SET);
5891 qemu_put_be32(f, len);
5892 qemu_fseek(f, cur_pos, SEEK_SET);
5894 cur_pos = qemu_ftell(f);
5895 qemu_fseek(f, total_len_pos, SEEK_SET);
5896 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5897 qemu_fseek(f, cur_pos, SEEK_SET);
5899 ret = 0;
5900 return ret;
5903 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5905 SaveStateEntry *se;
5907 for(se = first_se; se != NULL; se = se->next) {
5908 if (!strcmp(se->idstr, idstr) &&
5909 instance_id == se->instance_id)
5910 return se;
5912 return NULL;
5915 static int qemu_loadvm_state(QEMUFile *f)
5917 SaveStateEntry *se;
5918 int len, ret, instance_id, record_len, version_id;
5919 int64_t total_len, end_pos, cur_pos;
5920 unsigned int v;
5921 char idstr[256];
5923 v = qemu_get_be32(f);
5924 if (v != QEMU_VM_FILE_MAGIC)
5925 goto fail;
5926 v = qemu_get_be32(f);
5927 if (v != QEMU_VM_FILE_VERSION) {
5928 fail:
5929 ret = -1;
5930 goto the_end;
5932 total_len = qemu_get_be64(f);
5933 end_pos = total_len + qemu_ftell(f);
5934 for(;;) {
5935 if (qemu_ftell(f) >= end_pos)
5936 break;
5937 len = qemu_get_byte(f);
5938 qemu_get_buffer(f, (uint8_t *)idstr, len);
5939 idstr[len] = '\0';
5940 instance_id = qemu_get_be32(f);
5941 version_id = qemu_get_be32(f);
5942 record_len = qemu_get_be32(f);
5943 #if 0
5944 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5945 idstr, instance_id, version_id, record_len);
5946 #endif
5947 cur_pos = qemu_ftell(f);
5948 se = find_se(idstr, instance_id);
5949 if (!se) {
5950 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5951 instance_id, idstr);
5952 } else {
5953 ret = se->load_state(f, se->opaque, version_id);
5954 if (ret < 0) {
5955 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5956 instance_id, idstr);
5959 /* always seek to exact end of record */
5960 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5962 ret = 0;
5963 the_end:
5964 return ret;
5967 /* device can contain snapshots */
5968 static int bdrv_can_snapshot(BlockDriverState *bs)
5970 return (bs &&
5971 !bdrv_is_removable(bs) &&
5972 !bdrv_is_read_only(bs));
5975 /* device must be snapshots in order to have a reliable snapshot */
5976 static int bdrv_has_snapshot(BlockDriverState *bs)
5978 return (bs &&
5979 !bdrv_is_removable(bs) &&
5980 !bdrv_is_read_only(bs));
5983 static BlockDriverState *get_bs_snapshots(void)
5985 BlockDriverState *bs;
5986 int i;
5988 if (bs_snapshots)
5989 return bs_snapshots;
5990 for(i = 0; i <= nb_drives; i++) {
5991 bs = drives_table[i].bdrv;
5992 if (bdrv_can_snapshot(bs))
5993 goto ok;
5995 return NULL;
5997 bs_snapshots = bs;
5998 return bs;
6001 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6002 const char *name)
6004 QEMUSnapshotInfo *sn_tab, *sn;
6005 int nb_sns, i, ret;
6007 ret = -ENOENT;
6008 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6009 if (nb_sns < 0)
6010 return ret;
6011 for(i = 0; i < nb_sns; i++) {
6012 sn = &sn_tab[i];
6013 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6014 *sn_info = *sn;
6015 ret = 0;
6016 break;
6019 qemu_free(sn_tab);
6020 return ret;
6023 void do_savevm(const char *name)
6025 BlockDriverState *bs, *bs1;
6026 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6027 int must_delete, ret, i;
6028 BlockDriverInfo bdi1, *bdi = &bdi1;
6029 QEMUFile *f;
6030 int saved_vm_running;
6031 #ifdef _WIN32
6032 struct _timeb tb;
6033 #else
6034 struct timeval tv;
6035 #endif
6037 bs = get_bs_snapshots();
6038 if (!bs) {
6039 term_printf("No block device can accept snapshots\n");
6040 return;
6043 /* ??? Should this occur after vm_stop? */
6044 qemu_aio_flush();
6046 saved_vm_running = vm_running;
6047 vm_stop(0);
6049 must_delete = 0;
6050 if (name) {
6051 ret = bdrv_snapshot_find(bs, old_sn, name);
6052 if (ret >= 0) {
6053 must_delete = 1;
6056 memset(sn, 0, sizeof(*sn));
6057 if (must_delete) {
6058 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6059 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6060 } else {
6061 if (name)
6062 pstrcpy(sn->name, sizeof(sn->name), name);
6065 /* fill auxiliary fields */
6066 #ifdef _WIN32
6067 _ftime(&tb);
6068 sn->date_sec = tb.time;
6069 sn->date_nsec = tb.millitm * 1000000;
6070 #else
6071 gettimeofday(&tv, NULL);
6072 sn->date_sec = tv.tv_sec;
6073 sn->date_nsec = tv.tv_usec * 1000;
6074 #endif
6075 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6077 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6078 term_printf("Device %s does not support VM state snapshots\n",
6079 bdrv_get_device_name(bs));
6080 goto the_end;
6083 /* save the VM state */
6084 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6085 if (!f) {
6086 term_printf("Could not open VM state file\n");
6087 goto the_end;
6089 ret = qemu_savevm_state(f);
6090 sn->vm_state_size = qemu_ftell(f);
6091 qemu_fclose(f);
6092 if (ret < 0) {
6093 term_printf("Error %d while writing VM\n", ret);
6094 goto the_end;
6097 /* create the snapshots */
6099 for(i = 0; i < nb_drives; i++) {
6100 bs1 = drives_table[i].bdrv;
6101 if (bdrv_has_snapshot(bs1)) {
6102 if (must_delete) {
6103 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6104 if (ret < 0) {
6105 term_printf("Error while deleting snapshot on '%s'\n",
6106 bdrv_get_device_name(bs1));
6109 ret = bdrv_snapshot_create(bs1, sn);
6110 if (ret < 0) {
6111 term_printf("Error while creating snapshot on '%s'\n",
6112 bdrv_get_device_name(bs1));
6117 the_end:
6118 if (saved_vm_running)
6119 vm_start();
6122 void do_loadvm(const char *name)
6124 BlockDriverState *bs, *bs1;
6125 BlockDriverInfo bdi1, *bdi = &bdi1;
6126 QEMUFile *f;
6127 int i, ret;
6128 int saved_vm_running;
6130 bs = get_bs_snapshots();
6131 if (!bs) {
6132 term_printf("No block device supports snapshots\n");
6133 return;
6136 /* Flush all IO requests so they don't interfere with the new state. */
6137 qemu_aio_flush();
6139 saved_vm_running = vm_running;
6140 vm_stop(0);
6142 for(i = 0; i <= nb_drives; i++) {
6143 bs1 = drives_table[i].bdrv;
6144 if (bdrv_has_snapshot(bs1)) {
6145 ret = bdrv_snapshot_goto(bs1, name);
6146 if (ret < 0) {
6147 if (bs != bs1)
6148 term_printf("Warning: ");
6149 switch(ret) {
6150 case -ENOTSUP:
6151 term_printf("Snapshots not supported on device '%s'\n",
6152 bdrv_get_device_name(bs1));
6153 break;
6154 case -ENOENT:
6155 term_printf("Could not find snapshot '%s' on device '%s'\n",
6156 name, bdrv_get_device_name(bs1));
6157 break;
6158 default:
6159 term_printf("Error %d while activating snapshot on '%s'\n",
6160 ret, bdrv_get_device_name(bs1));
6161 break;
6163 /* fatal on snapshot block device */
6164 if (bs == bs1)
6165 goto the_end;
6170 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6171 term_printf("Device %s does not support VM state snapshots\n",
6172 bdrv_get_device_name(bs));
6173 return;
6176 /* restore the VM state */
6177 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6178 if (!f) {
6179 term_printf("Could not open VM state file\n");
6180 goto the_end;
6182 ret = qemu_loadvm_state(f);
6183 qemu_fclose(f);
6184 if (ret < 0) {
6185 term_printf("Error %d while loading VM state\n", ret);
6187 the_end:
6188 if (saved_vm_running)
6189 vm_start();
6192 void do_delvm(const char *name)
6194 BlockDriverState *bs, *bs1;
6195 int i, ret;
6197 bs = get_bs_snapshots();
6198 if (!bs) {
6199 term_printf("No block device supports snapshots\n");
6200 return;
6203 for(i = 0; i <= nb_drives; i++) {
6204 bs1 = drives_table[i].bdrv;
6205 if (bdrv_has_snapshot(bs1)) {
6206 ret = bdrv_snapshot_delete(bs1, name);
6207 if (ret < 0) {
6208 if (ret == -ENOTSUP)
6209 term_printf("Snapshots not supported on device '%s'\n",
6210 bdrv_get_device_name(bs1));
6211 else
6212 term_printf("Error %d while deleting snapshot on '%s'\n",
6213 ret, bdrv_get_device_name(bs1));
6219 void do_info_snapshots(void)
6221 BlockDriverState *bs, *bs1;
6222 QEMUSnapshotInfo *sn_tab, *sn;
6223 int nb_sns, i;
6224 char buf[256];
6226 bs = get_bs_snapshots();
6227 if (!bs) {
6228 term_printf("No available block device supports snapshots\n");
6229 return;
6231 term_printf("Snapshot devices:");
6232 for(i = 0; i <= nb_drives; i++) {
6233 bs1 = drives_table[i].bdrv;
6234 if (bdrv_has_snapshot(bs1)) {
6235 if (bs == bs1)
6236 term_printf(" %s", bdrv_get_device_name(bs1));
6239 term_printf("\n");
6241 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6242 if (nb_sns < 0) {
6243 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6244 return;
6246 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6247 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6248 for(i = 0; i < nb_sns; i++) {
6249 sn = &sn_tab[i];
6250 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6252 qemu_free(sn_tab);
6255 /***********************************************************/
6256 /* cpu save/restore */
6258 #if defined(TARGET_I386)
6260 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6262 qemu_put_be32(f, dt->selector);
6263 qemu_put_betl(f, dt->base);
6264 qemu_put_be32(f, dt->limit);
6265 qemu_put_be32(f, dt->flags);
6268 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6270 dt->selector = qemu_get_be32(f);
6271 dt->base = qemu_get_betl(f);
6272 dt->limit = qemu_get_be32(f);
6273 dt->flags = qemu_get_be32(f);
6276 void cpu_save(QEMUFile *f, void *opaque)
6278 CPUState *env = opaque;
6279 uint16_t fptag, fpus, fpuc, fpregs_format;
6280 uint32_t hflags;
6281 int i;
6283 for(i = 0; i < CPU_NB_REGS; i++)
6284 qemu_put_betls(f, &env->regs[i]);
6285 qemu_put_betls(f, &env->eip);
6286 qemu_put_betls(f, &env->eflags);
6287 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6288 qemu_put_be32s(f, &hflags);
6290 /* FPU */
6291 fpuc = env->fpuc;
6292 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6293 fptag = 0;
6294 for(i = 0; i < 8; i++) {
6295 fptag |= ((!env->fptags[i]) << i);
6298 qemu_put_be16s(f, &fpuc);
6299 qemu_put_be16s(f, &fpus);
6300 qemu_put_be16s(f, &fptag);
6302 #ifdef USE_X86LDOUBLE
6303 fpregs_format = 0;
6304 #else
6305 fpregs_format = 1;
6306 #endif
6307 qemu_put_be16s(f, &fpregs_format);
6309 for(i = 0; i < 8; i++) {
6310 #ifdef USE_X86LDOUBLE
6312 uint64_t mant;
6313 uint16_t exp;
6314 /* we save the real CPU data (in case of MMX usage only 'mant'
6315 contains the MMX register */
6316 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6317 qemu_put_be64(f, mant);
6318 qemu_put_be16(f, exp);
6320 #else
6321 /* if we use doubles for float emulation, we save the doubles to
6322 avoid losing information in case of MMX usage. It can give
6323 problems if the image is restored on a CPU where long
6324 doubles are used instead. */
6325 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6326 #endif
6329 for(i = 0; i < 6; i++)
6330 cpu_put_seg(f, &env->segs[i]);
6331 cpu_put_seg(f, &env->ldt);
6332 cpu_put_seg(f, &env->tr);
6333 cpu_put_seg(f, &env->gdt);
6334 cpu_put_seg(f, &env->idt);
6336 qemu_put_be32s(f, &env->sysenter_cs);
6337 qemu_put_be32s(f, &env->sysenter_esp);
6338 qemu_put_be32s(f, &env->sysenter_eip);
6340 qemu_put_betls(f, &env->cr[0]);
6341 qemu_put_betls(f, &env->cr[2]);
6342 qemu_put_betls(f, &env->cr[3]);
6343 qemu_put_betls(f, &env->cr[4]);
6345 for(i = 0; i < 8; i++)
6346 qemu_put_betls(f, &env->dr[i]);
6348 /* MMU */
6349 qemu_put_be32s(f, &env->a20_mask);
6351 /* XMM */
6352 qemu_put_be32s(f, &env->mxcsr);
6353 for(i = 0; i < CPU_NB_REGS; i++) {
6354 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6355 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6358 #ifdef TARGET_X86_64
6359 qemu_put_be64s(f, &env->efer);
6360 qemu_put_be64s(f, &env->star);
6361 qemu_put_be64s(f, &env->lstar);
6362 qemu_put_be64s(f, &env->cstar);
6363 qemu_put_be64s(f, &env->fmask);
6364 qemu_put_be64s(f, &env->kernelgsbase);
6365 #endif
6366 qemu_put_be32s(f, &env->smbase);
6369 #ifdef USE_X86LDOUBLE
6370 /* XXX: add that in a FPU generic layer */
6371 union x86_longdouble {
6372 uint64_t mant;
6373 uint16_t exp;
6376 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6377 #define EXPBIAS1 1023
6378 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6379 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6381 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6383 int e;
6384 /* mantissa */
6385 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6386 /* exponent + sign */
6387 e = EXPD1(temp) - EXPBIAS1 + 16383;
6388 e |= SIGND1(temp) >> 16;
6389 p->exp = e;
6391 #endif
6393 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6395 CPUState *env = opaque;
6396 int i, guess_mmx;
6397 uint32_t hflags;
6398 uint16_t fpus, fpuc, fptag, fpregs_format;
6400 if (version_id != 3 && version_id != 4)
6401 return -EINVAL;
6402 for(i = 0; i < CPU_NB_REGS; i++)
6403 qemu_get_betls(f, &env->regs[i]);
6404 qemu_get_betls(f, &env->eip);
6405 qemu_get_betls(f, &env->eflags);
6406 qemu_get_be32s(f, &hflags);
6408 qemu_get_be16s(f, &fpuc);
6409 qemu_get_be16s(f, &fpus);
6410 qemu_get_be16s(f, &fptag);
6411 qemu_get_be16s(f, &fpregs_format);
6413 /* NOTE: we cannot always restore the FPU state if the image come
6414 from a host with a different 'USE_X86LDOUBLE' define. We guess
6415 if we are in an MMX state to restore correctly in that case. */
6416 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6417 for(i = 0; i < 8; i++) {
6418 uint64_t mant;
6419 uint16_t exp;
6421 switch(fpregs_format) {
6422 case 0:
6423 mant = qemu_get_be64(f);
6424 exp = qemu_get_be16(f);
6425 #ifdef USE_X86LDOUBLE
6426 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6427 #else
6428 /* difficult case */
6429 if (guess_mmx)
6430 env->fpregs[i].mmx.MMX_Q(0) = mant;
6431 else
6432 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6433 #endif
6434 break;
6435 case 1:
6436 mant = qemu_get_be64(f);
6437 #ifdef USE_X86LDOUBLE
6439 union x86_longdouble *p;
6440 /* difficult case */
6441 p = (void *)&env->fpregs[i];
6442 if (guess_mmx) {
6443 p->mant = mant;
6444 p->exp = 0xffff;
6445 } else {
6446 fp64_to_fp80(p, mant);
6449 #else
6450 env->fpregs[i].mmx.MMX_Q(0) = mant;
6451 #endif
6452 break;
6453 default:
6454 return -EINVAL;
6458 env->fpuc = fpuc;
6459 /* XXX: restore FPU round state */
6460 env->fpstt = (fpus >> 11) & 7;
6461 env->fpus = fpus & ~0x3800;
6462 fptag ^= 0xff;
6463 for(i = 0; i < 8; i++) {
6464 env->fptags[i] = (fptag >> i) & 1;
6467 for(i = 0; i < 6; i++)
6468 cpu_get_seg(f, &env->segs[i]);
6469 cpu_get_seg(f, &env->ldt);
6470 cpu_get_seg(f, &env->tr);
6471 cpu_get_seg(f, &env->gdt);
6472 cpu_get_seg(f, &env->idt);
6474 qemu_get_be32s(f, &env->sysenter_cs);
6475 qemu_get_be32s(f, &env->sysenter_esp);
6476 qemu_get_be32s(f, &env->sysenter_eip);
6478 qemu_get_betls(f, &env->cr[0]);
6479 qemu_get_betls(f, &env->cr[2]);
6480 qemu_get_betls(f, &env->cr[3]);
6481 qemu_get_betls(f, &env->cr[4]);
6483 for(i = 0; i < 8; i++)
6484 qemu_get_betls(f, &env->dr[i]);
6486 /* MMU */
6487 qemu_get_be32s(f, &env->a20_mask);
6489 qemu_get_be32s(f, &env->mxcsr);
6490 for(i = 0; i < CPU_NB_REGS; i++) {
6491 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6492 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6495 #ifdef TARGET_X86_64
6496 qemu_get_be64s(f, &env->efer);
6497 qemu_get_be64s(f, &env->star);
6498 qemu_get_be64s(f, &env->lstar);
6499 qemu_get_be64s(f, &env->cstar);
6500 qemu_get_be64s(f, &env->fmask);
6501 qemu_get_be64s(f, &env->kernelgsbase);
6502 #endif
6503 if (version_id >= 4)
6504 qemu_get_be32s(f, &env->smbase);
6506 /* XXX: compute hflags from scratch, except for CPL and IIF */
6507 env->hflags = hflags;
6508 tlb_flush(env, 1);
6509 return 0;
6512 #elif defined(TARGET_PPC)
6513 void cpu_save(QEMUFile *f, void *opaque)
6517 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6519 return 0;
6522 #elif defined(TARGET_MIPS)
6523 void cpu_save(QEMUFile *f, void *opaque)
6527 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6529 return 0;
6532 #elif defined(TARGET_SPARC)
6533 void cpu_save(QEMUFile *f, void *opaque)
6535 CPUState *env = opaque;
6536 int i;
6537 uint32_t tmp;
6539 for(i = 0; i < 8; i++)
6540 qemu_put_betls(f, &env->gregs[i]);
6541 for(i = 0; i < NWINDOWS * 16; i++)
6542 qemu_put_betls(f, &env->regbase[i]);
6544 /* FPU */
6545 for(i = 0; i < TARGET_FPREGS; i++) {
6546 union {
6547 float32 f;
6548 uint32_t i;
6549 } u;
6550 u.f = env->fpr[i];
6551 qemu_put_be32(f, u.i);
6554 qemu_put_betls(f, &env->pc);
6555 qemu_put_betls(f, &env->npc);
6556 qemu_put_betls(f, &env->y);
6557 tmp = GET_PSR(env);
6558 qemu_put_be32(f, tmp);
6559 qemu_put_betls(f, &env->fsr);
6560 qemu_put_betls(f, &env->tbr);
6561 #ifndef TARGET_SPARC64
6562 qemu_put_be32s(f, &env->wim);
6563 /* MMU */
6564 for(i = 0; i < 16; i++)
6565 qemu_put_be32s(f, &env->mmuregs[i]);
6566 #endif
6569 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6571 CPUState *env = opaque;
6572 int i;
6573 uint32_t tmp;
6575 for(i = 0; i < 8; i++)
6576 qemu_get_betls(f, &env->gregs[i]);
6577 for(i = 0; i < NWINDOWS * 16; i++)
6578 qemu_get_betls(f, &env->regbase[i]);
6580 /* FPU */
6581 for(i = 0; i < TARGET_FPREGS; i++) {
6582 union {
6583 float32 f;
6584 uint32_t i;
6585 } u;
6586 u.i = qemu_get_be32(f);
6587 env->fpr[i] = u.f;
6590 qemu_get_betls(f, &env->pc);
6591 qemu_get_betls(f, &env->npc);
6592 qemu_get_betls(f, &env->y);
6593 tmp = qemu_get_be32(f);
6594 env->cwp = 0; /* needed to ensure that the wrapping registers are
6595 correctly updated */
6596 PUT_PSR(env, tmp);
6597 qemu_get_betls(f, &env->fsr);
6598 qemu_get_betls(f, &env->tbr);
6599 #ifndef TARGET_SPARC64
6600 qemu_get_be32s(f, &env->wim);
6601 /* MMU */
6602 for(i = 0; i < 16; i++)
6603 qemu_get_be32s(f, &env->mmuregs[i]);
6604 #endif
6605 tlb_flush(env, 1);
6606 return 0;
6609 #elif defined(TARGET_ARM)
6611 void cpu_save(QEMUFile *f, void *opaque)
6613 int i;
6614 CPUARMState *env = (CPUARMState *)opaque;
6616 for (i = 0; i < 16; i++) {
6617 qemu_put_be32(f, env->regs[i]);
6619 qemu_put_be32(f, cpsr_read(env));
6620 qemu_put_be32(f, env->spsr);
6621 for (i = 0; i < 6; i++) {
6622 qemu_put_be32(f, env->banked_spsr[i]);
6623 qemu_put_be32(f, env->banked_r13[i]);
6624 qemu_put_be32(f, env->banked_r14[i]);
6626 for (i = 0; i < 5; i++) {
6627 qemu_put_be32(f, env->usr_regs[i]);
6628 qemu_put_be32(f, env->fiq_regs[i]);
6630 qemu_put_be32(f, env->cp15.c0_cpuid);
6631 qemu_put_be32(f, env->cp15.c0_cachetype);
6632 qemu_put_be32(f, env->cp15.c1_sys);
6633 qemu_put_be32(f, env->cp15.c1_coproc);
6634 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6635 qemu_put_be32(f, env->cp15.c2_base0);
6636 qemu_put_be32(f, env->cp15.c2_base1);
6637 qemu_put_be32(f, env->cp15.c2_mask);
6638 qemu_put_be32(f, env->cp15.c2_data);
6639 qemu_put_be32(f, env->cp15.c2_insn);
6640 qemu_put_be32(f, env->cp15.c3);
6641 qemu_put_be32(f, env->cp15.c5_insn);
6642 qemu_put_be32(f, env->cp15.c5_data);
6643 for (i = 0; i < 8; i++) {
6644 qemu_put_be32(f, env->cp15.c6_region[i]);
6646 qemu_put_be32(f, env->cp15.c6_insn);
6647 qemu_put_be32(f, env->cp15.c6_data);
6648 qemu_put_be32(f, env->cp15.c9_insn);
6649 qemu_put_be32(f, env->cp15.c9_data);
6650 qemu_put_be32(f, env->cp15.c13_fcse);
6651 qemu_put_be32(f, env->cp15.c13_context);
6652 qemu_put_be32(f, env->cp15.c13_tls1);
6653 qemu_put_be32(f, env->cp15.c13_tls2);
6654 qemu_put_be32(f, env->cp15.c13_tls3);
6655 qemu_put_be32(f, env->cp15.c15_cpar);
6657 qemu_put_be32(f, env->features);
6659 if (arm_feature(env, ARM_FEATURE_VFP)) {
6660 for (i = 0; i < 16; i++) {
6661 CPU_DoubleU u;
6662 u.d = env->vfp.regs[i];
6663 qemu_put_be32(f, u.l.upper);
6664 qemu_put_be32(f, u.l.lower);
6666 for (i = 0; i < 16; i++) {
6667 qemu_put_be32(f, env->vfp.xregs[i]);
6670 /* TODO: Should use proper FPSCR access functions. */
6671 qemu_put_be32(f, env->vfp.vec_len);
6672 qemu_put_be32(f, env->vfp.vec_stride);
6674 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6675 for (i = 16; i < 32; i++) {
6676 CPU_DoubleU u;
6677 u.d = env->vfp.regs[i];
6678 qemu_put_be32(f, u.l.upper);
6679 qemu_put_be32(f, u.l.lower);
6684 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6685 for (i = 0; i < 16; i++) {
6686 qemu_put_be64(f, env->iwmmxt.regs[i]);
6688 for (i = 0; i < 16; i++) {
6689 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6693 if (arm_feature(env, ARM_FEATURE_M)) {
6694 qemu_put_be32(f, env->v7m.other_sp);
6695 qemu_put_be32(f, env->v7m.vecbase);
6696 qemu_put_be32(f, env->v7m.basepri);
6697 qemu_put_be32(f, env->v7m.control);
6698 qemu_put_be32(f, env->v7m.current_sp);
6699 qemu_put_be32(f, env->v7m.exception);
6703 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6705 CPUARMState *env = (CPUARMState *)opaque;
6706 int i;
6708 if (version_id != ARM_CPU_SAVE_VERSION)
6709 return -EINVAL;
6711 for (i = 0; i < 16; i++) {
6712 env->regs[i] = qemu_get_be32(f);
6714 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6715 env->spsr = qemu_get_be32(f);
6716 for (i = 0; i < 6; i++) {
6717 env->banked_spsr[i] = qemu_get_be32(f);
6718 env->banked_r13[i] = qemu_get_be32(f);
6719 env->banked_r14[i] = qemu_get_be32(f);
6721 for (i = 0; i < 5; i++) {
6722 env->usr_regs[i] = qemu_get_be32(f);
6723 env->fiq_regs[i] = qemu_get_be32(f);
6725 env->cp15.c0_cpuid = qemu_get_be32(f);
6726 env->cp15.c0_cachetype = qemu_get_be32(f);
6727 env->cp15.c1_sys = qemu_get_be32(f);
6728 env->cp15.c1_coproc = qemu_get_be32(f);
6729 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6730 env->cp15.c2_base0 = qemu_get_be32(f);
6731 env->cp15.c2_base1 = qemu_get_be32(f);
6732 env->cp15.c2_mask = qemu_get_be32(f);
6733 env->cp15.c2_data = qemu_get_be32(f);
6734 env->cp15.c2_insn = qemu_get_be32(f);
6735 env->cp15.c3 = qemu_get_be32(f);
6736 env->cp15.c5_insn = qemu_get_be32(f);
6737 env->cp15.c5_data = qemu_get_be32(f);
6738 for (i = 0; i < 8; i++) {
6739 env->cp15.c6_region[i] = qemu_get_be32(f);
6741 env->cp15.c6_insn = qemu_get_be32(f);
6742 env->cp15.c6_data = qemu_get_be32(f);
6743 env->cp15.c9_insn = qemu_get_be32(f);
6744 env->cp15.c9_data = qemu_get_be32(f);
6745 env->cp15.c13_fcse = qemu_get_be32(f);
6746 env->cp15.c13_context = qemu_get_be32(f);
6747 env->cp15.c13_tls1 = qemu_get_be32(f);
6748 env->cp15.c13_tls2 = qemu_get_be32(f);
6749 env->cp15.c13_tls3 = qemu_get_be32(f);
6750 env->cp15.c15_cpar = qemu_get_be32(f);
6752 env->features = qemu_get_be32(f);
6754 if (arm_feature(env, ARM_FEATURE_VFP)) {
6755 for (i = 0; i < 16; i++) {
6756 CPU_DoubleU u;
6757 u.l.upper = qemu_get_be32(f);
6758 u.l.lower = qemu_get_be32(f);
6759 env->vfp.regs[i] = u.d;
6761 for (i = 0; i < 16; i++) {
6762 env->vfp.xregs[i] = qemu_get_be32(f);
6765 /* TODO: Should use proper FPSCR access functions. */
6766 env->vfp.vec_len = qemu_get_be32(f);
6767 env->vfp.vec_stride = qemu_get_be32(f);
6769 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6770 for (i = 0; i < 16; i++) {
6771 CPU_DoubleU u;
6772 u.l.upper = qemu_get_be32(f);
6773 u.l.lower = qemu_get_be32(f);
6774 env->vfp.regs[i] = u.d;
6779 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6780 for (i = 0; i < 16; i++) {
6781 env->iwmmxt.regs[i] = qemu_get_be64(f);
6783 for (i = 0; i < 16; i++) {
6784 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6788 if (arm_feature(env, ARM_FEATURE_M)) {
6789 env->v7m.other_sp = qemu_get_be32(f);
6790 env->v7m.vecbase = qemu_get_be32(f);
6791 env->v7m.basepri = qemu_get_be32(f);
6792 env->v7m.control = qemu_get_be32(f);
6793 env->v7m.current_sp = qemu_get_be32(f);
6794 env->v7m.exception = qemu_get_be32(f);
6797 return 0;
6800 #else
6802 //#warning No CPU save/restore functions
6804 #endif
6806 /***********************************************************/
6807 /* ram save/restore */
6809 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6811 int v;
6813 v = qemu_get_byte(f);
6814 switch(v) {
6815 case 0:
6816 if (qemu_get_buffer(f, buf, len) != len)
6817 return -EIO;
6818 break;
6819 case 1:
6820 v = qemu_get_byte(f);
6821 memset(buf, v, len);
6822 break;
6823 default:
6824 return -EINVAL;
6826 return 0;
6829 static int ram_load_v1(QEMUFile *f, void *opaque)
6831 int i, ret;
6833 if (qemu_get_be32(f) != phys_ram_size)
6834 return -EINVAL;
6835 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6836 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6837 if (ret)
6838 return ret;
6840 return 0;
6843 #define BDRV_HASH_BLOCK_SIZE 1024
6844 #define IOBUF_SIZE 4096
6845 #define RAM_CBLOCK_MAGIC 0xfabe
6847 typedef struct RamCompressState {
6848 z_stream zstream;
6849 QEMUFile *f;
6850 uint8_t buf[IOBUF_SIZE];
6851 } RamCompressState;
6853 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6855 int ret;
6856 memset(s, 0, sizeof(*s));
6857 s->f = f;
6858 ret = deflateInit2(&s->zstream, 1,
6859 Z_DEFLATED, 15,
6860 9, Z_DEFAULT_STRATEGY);
6861 if (ret != Z_OK)
6862 return -1;
6863 s->zstream.avail_out = IOBUF_SIZE;
6864 s->zstream.next_out = s->buf;
6865 return 0;
6868 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6870 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6871 qemu_put_be16(s->f, len);
6872 qemu_put_buffer(s->f, buf, len);
6875 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6877 int ret;
6879 s->zstream.avail_in = len;
6880 s->zstream.next_in = (uint8_t *)buf;
6881 while (s->zstream.avail_in > 0) {
6882 ret = deflate(&s->zstream, Z_NO_FLUSH);
6883 if (ret != Z_OK)
6884 return -1;
6885 if (s->zstream.avail_out == 0) {
6886 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6887 s->zstream.avail_out = IOBUF_SIZE;
6888 s->zstream.next_out = s->buf;
6891 return 0;
6894 static void ram_compress_close(RamCompressState *s)
6896 int len, ret;
6898 /* compress last bytes */
6899 for(;;) {
6900 ret = deflate(&s->zstream, Z_FINISH);
6901 if (ret == Z_OK || ret == Z_STREAM_END) {
6902 len = IOBUF_SIZE - s->zstream.avail_out;
6903 if (len > 0) {
6904 ram_put_cblock(s, s->buf, len);
6906 s->zstream.avail_out = IOBUF_SIZE;
6907 s->zstream.next_out = s->buf;
6908 if (ret == Z_STREAM_END)
6909 break;
6910 } else {
6911 goto fail;
6914 fail:
6915 deflateEnd(&s->zstream);
6918 typedef struct RamDecompressState {
6919 z_stream zstream;
6920 QEMUFile *f;
6921 uint8_t buf[IOBUF_SIZE];
6922 } RamDecompressState;
6924 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6926 int ret;
6927 memset(s, 0, sizeof(*s));
6928 s->f = f;
6929 ret = inflateInit(&s->zstream);
6930 if (ret != Z_OK)
6931 return -1;
6932 return 0;
6935 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6937 int ret, clen;
6939 s->zstream.avail_out = len;
6940 s->zstream.next_out = buf;
6941 while (s->zstream.avail_out > 0) {
6942 if (s->zstream.avail_in == 0) {
6943 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6944 return -1;
6945 clen = qemu_get_be16(s->f);
6946 if (clen > IOBUF_SIZE)
6947 return -1;
6948 qemu_get_buffer(s->f, s->buf, clen);
6949 s->zstream.avail_in = clen;
6950 s->zstream.next_in = s->buf;
6952 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6953 if (ret != Z_OK && ret != Z_STREAM_END) {
6954 return -1;
6957 return 0;
6960 static void ram_decompress_close(RamDecompressState *s)
6962 inflateEnd(&s->zstream);
6965 static void ram_save(QEMUFile *f, void *opaque)
6967 int i;
6968 RamCompressState s1, *s = &s1;
6969 uint8_t buf[10];
6971 qemu_put_be32(f, phys_ram_size);
6972 if (ram_compress_open(s, f) < 0)
6973 return;
6974 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6975 #if 0
6976 if (tight_savevm_enabled) {
6977 int64_t sector_num;
6978 int j;
6980 /* find if the memory block is available on a virtual
6981 block device */
6982 sector_num = -1;
6983 for(j = 0; j < nb_drives; j++) {
6984 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6985 phys_ram_base + i,
6986 BDRV_HASH_BLOCK_SIZE);
6987 if (sector_num >= 0)
6988 break;
6990 if (j == nb_drives)
6991 goto normal_compress;
6992 buf[0] = 1;
6993 buf[1] = j;
6994 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6995 ram_compress_buf(s, buf, 10);
6996 } else
6997 #endif
6999 // normal_compress:
7000 buf[0] = 0;
7001 ram_compress_buf(s, buf, 1);
7002 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7005 ram_compress_close(s);
7008 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7010 RamDecompressState s1, *s = &s1;
7011 uint8_t buf[10];
7012 int i;
7014 if (version_id == 1)
7015 return ram_load_v1(f, opaque);
7016 if (version_id != 2)
7017 return -EINVAL;
7018 if (qemu_get_be32(f) != phys_ram_size)
7019 return -EINVAL;
7020 if (ram_decompress_open(s, f) < 0)
7021 return -EINVAL;
7022 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7023 if (ram_decompress_buf(s, buf, 1) < 0) {
7024 fprintf(stderr, "Error while reading ram block header\n");
7025 goto error;
7027 if (buf[0] == 0) {
7028 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7029 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7030 goto error;
7032 } else
7033 #if 0
7034 if (buf[0] == 1) {
7035 int bs_index;
7036 int64_t sector_num;
7038 ram_decompress_buf(s, buf + 1, 9);
7039 bs_index = buf[1];
7040 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7041 if (bs_index >= nb_drives) {
7042 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7043 goto error;
7045 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7046 phys_ram_base + i,
7047 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7048 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7049 bs_index, sector_num);
7050 goto error;
7052 } else
7053 #endif
7055 error:
7056 printf("Error block header\n");
7057 return -EINVAL;
7060 ram_decompress_close(s);
7061 return 0;
7064 /***********************************************************/
7065 /* bottom halves (can be seen as timers which expire ASAP) */
7067 struct QEMUBH {
7068 QEMUBHFunc *cb;
7069 void *opaque;
7070 int scheduled;
7071 QEMUBH *next;
7074 static QEMUBH *first_bh = NULL;
7076 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7078 QEMUBH *bh;
7079 bh = qemu_mallocz(sizeof(QEMUBH));
7080 if (!bh)
7081 return NULL;
7082 bh->cb = cb;
7083 bh->opaque = opaque;
7084 return bh;
7087 int qemu_bh_poll(void)
7089 QEMUBH *bh, **pbh;
7090 int ret;
7092 ret = 0;
7093 for(;;) {
7094 pbh = &first_bh;
7095 bh = *pbh;
7096 if (!bh)
7097 break;
7098 ret = 1;
7099 *pbh = bh->next;
7100 bh->scheduled = 0;
7101 bh->cb(bh->opaque);
7103 return ret;
7106 void qemu_bh_schedule(QEMUBH *bh)
7108 CPUState *env = cpu_single_env;
7109 if (bh->scheduled)
7110 return;
7111 bh->scheduled = 1;
7112 bh->next = first_bh;
7113 first_bh = bh;
7115 /* stop the currently executing CPU to execute the BH ASAP */
7116 if (env) {
7117 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7121 void qemu_bh_cancel(QEMUBH *bh)
7123 QEMUBH **pbh;
7124 if (bh->scheduled) {
7125 pbh = &first_bh;
7126 while (*pbh != bh)
7127 pbh = &(*pbh)->next;
7128 *pbh = bh->next;
7129 bh->scheduled = 0;
7133 void qemu_bh_delete(QEMUBH *bh)
7135 qemu_bh_cancel(bh);
7136 qemu_free(bh);
7139 /***********************************************************/
7140 /* machine registration */
7142 QEMUMachine *first_machine = NULL;
7144 int qemu_register_machine(QEMUMachine *m)
7146 QEMUMachine **pm;
7147 pm = &first_machine;
7148 while (*pm != NULL)
7149 pm = &(*pm)->next;
7150 m->next = NULL;
7151 *pm = m;
7152 return 0;
7155 static QEMUMachine *find_machine(const char *name)
7157 QEMUMachine *m;
7159 for(m = first_machine; m != NULL; m = m->next) {
7160 if (!strcmp(m->name, name))
7161 return m;
7163 return NULL;
7166 /***********************************************************/
7167 /* main execution loop */
7169 static void gui_update(void *opaque)
7171 DisplayState *ds = opaque;
7172 ds->dpy_refresh(ds);
7173 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7176 struct vm_change_state_entry {
7177 VMChangeStateHandler *cb;
7178 void *opaque;
7179 LIST_ENTRY (vm_change_state_entry) entries;
7182 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7184 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7185 void *opaque)
7187 VMChangeStateEntry *e;
7189 e = qemu_mallocz(sizeof (*e));
7190 if (!e)
7191 return NULL;
7193 e->cb = cb;
7194 e->opaque = opaque;
7195 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7196 return e;
7199 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7201 LIST_REMOVE (e, entries);
7202 qemu_free (e);
7205 static void vm_state_notify(int running)
7207 VMChangeStateEntry *e;
7209 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7210 e->cb(e->opaque, running);
7214 /* XXX: support several handlers */
7215 static VMStopHandler *vm_stop_cb;
7216 static void *vm_stop_opaque;
7218 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7220 vm_stop_cb = cb;
7221 vm_stop_opaque = opaque;
7222 return 0;
7225 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7227 vm_stop_cb = NULL;
7230 void vm_start(void)
7232 if (!vm_running) {
7233 cpu_enable_ticks();
7234 vm_running = 1;
7235 vm_state_notify(1);
7236 qemu_rearm_alarm_timer(alarm_timer);
7240 void vm_stop(int reason)
7242 if (vm_running) {
7243 cpu_disable_ticks();
7244 vm_running = 0;
7245 if (reason != 0) {
7246 if (vm_stop_cb) {
7247 vm_stop_cb(vm_stop_opaque, reason);
7250 vm_state_notify(0);
7254 /* reset/shutdown handler */
7256 typedef struct QEMUResetEntry {
7257 QEMUResetHandler *func;
7258 void *opaque;
7259 struct QEMUResetEntry *next;
7260 } QEMUResetEntry;
7262 static QEMUResetEntry *first_reset_entry;
7263 static int reset_requested;
7264 static int shutdown_requested;
7265 static int powerdown_requested;
7267 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7269 QEMUResetEntry **pre, *re;
7271 pre = &first_reset_entry;
7272 while (*pre != NULL)
7273 pre = &(*pre)->next;
7274 re = qemu_mallocz(sizeof(QEMUResetEntry));
7275 re->func = func;
7276 re->opaque = opaque;
7277 re->next = NULL;
7278 *pre = re;
7281 static void qemu_system_reset(void)
7283 QEMUResetEntry *re;
7285 /* reset all devices */
7286 for(re = first_reset_entry; re != NULL; re = re->next) {
7287 re->func(re->opaque);
7291 void qemu_system_reset_request(void)
7293 if (no_reboot) {
7294 shutdown_requested = 1;
7295 } else {
7296 reset_requested = 1;
7298 if (cpu_single_env)
7299 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7302 void qemu_system_shutdown_request(void)
7304 shutdown_requested = 1;
7305 if (cpu_single_env)
7306 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7309 void qemu_system_powerdown_request(void)
7311 powerdown_requested = 1;
7312 if (cpu_single_env)
7313 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7316 void main_loop_wait(int timeout)
7318 IOHandlerRecord *ioh;
7319 fd_set rfds, wfds, xfds;
7320 int ret, nfds;
7321 #ifdef _WIN32
7322 int ret2, i;
7323 #endif
7324 struct timeval tv;
7325 PollingEntry *pe;
7328 /* XXX: need to suppress polling by better using win32 events */
7329 ret = 0;
7330 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7331 ret |= pe->func(pe->opaque);
7333 #ifdef _WIN32
7334 if (ret == 0) {
7335 int err;
7336 WaitObjects *w = &wait_objects;
7338 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7339 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7340 if (w->func[ret - WAIT_OBJECT_0])
7341 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7343 /* Check for additional signaled events */
7344 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7346 /* Check if event is signaled */
7347 ret2 = WaitForSingleObject(w->events[i], 0);
7348 if(ret2 == WAIT_OBJECT_0) {
7349 if (w->func[i])
7350 w->func[i](w->opaque[i]);
7351 } else if (ret2 == WAIT_TIMEOUT) {
7352 } else {
7353 err = GetLastError();
7354 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7357 } else if (ret == WAIT_TIMEOUT) {
7358 } else {
7359 err = GetLastError();
7360 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7363 #endif
7364 /* poll any events */
7365 /* XXX: separate device handlers from system ones */
7366 nfds = -1;
7367 FD_ZERO(&rfds);
7368 FD_ZERO(&wfds);
7369 FD_ZERO(&xfds);
7370 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7371 if (ioh->deleted)
7372 continue;
7373 if (ioh->fd_read &&
7374 (!ioh->fd_read_poll ||
7375 ioh->fd_read_poll(ioh->opaque) != 0)) {
7376 FD_SET(ioh->fd, &rfds);
7377 if (ioh->fd > nfds)
7378 nfds = ioh->fd;
7380 if (ioh->fd_write) {
7381 FD_SET(ioh->fd, &wfds);
7382 if (ioh->fd > nfds)
7383 nfds = ioh->fd;
7387 tv.tv_sec = 0;
7388 #ifdef _WIN32
7389 tv.tv_usec = 0;
7390 #else
7391 tv.tv_usec = timeout * 1000;
7392 #endif
7393 #if defined(CONFIG_SLIRP)
7394 if (slirp_inited) {
7395 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7397 #endif
7398 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7399 if (ret > 0) {
7400 IOHandlerRecord **pioh;
7402 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7403 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7404 ioh->fd_read(ioh->opaque);
7406 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7407 ioh->fd_write(ioh->opaque);
7411 /* remove deleted IO handlers */
7412 pioh = &first_io_handler;
7413 while (*pioh) {
7414 ioh = *pioh;
7415 if (ioh->deleted) {
7416 *pioh = ioh->next;
7417 qemu_free(ioh);
7418 } else
7419 pioh = &ioh->next;
7422 #if defined(CONFIG_SLIRP)
7423 if (slirp_inited) {
7424 if (ret < 0) {
7425 FD_ZERO(&rfds);
7426 FD_ZERO(&wfds);
7427 FD_ZERO(&xfds);
7429 slirp_select_poll(&rfds, &wfds, &xfds);
7431 #endif
7432 qemu_aio_poll();
7434 if (vm_running) {
7435 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7436 qemu_get_clock(vm_clock));
7437 /* run dma transfers, if any */
7438 DMA_run();
7441 /* real time timers */
7442 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7443 qemu_get_clock(rt_clock));
7445 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7446 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7447 qemu_rearm_alarm_timer(alarm_timer);
7450 /* Check bottom-halves last in case any of the earlier events triggered
7451 them. */
7452 qemu_bh_poll();
7456 static int main_loop(void)
7458 int ret, timeout;
7459 #ifdef CONFIG_PROFILER
7460 int64_t ti;
7461 #endif
7462 CPUState *env;
7464 cur_cpu = first_cpu;
7465 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7466 for(;;) {
7467 if (vm_running) {
7469 for(;;) {
7470 /* get next cpu */
7471 env = next_cpu;
7472 #ifdef CONFIG_PROFILER
7473 ti = profile_getclock();
7474 #endif
7475 ret = cpu_exec(env);
7476 #ifdef CONFIG_PROFILER
7477 qemu_time += profile_getclock() - ti;
7478 #endif
7479 next_cpu = env->next_cpu ?: first_cpu;
7480 if (event_pending) {
7481 ret = EXCP_INTERRUPT;
7482 event_pending = 0;
7483 break;
7485 if (ret == EXCP_HLT) {
7486 /* Give the next CPU a chance to run. */
7487 cur_cpu = env;
7488 continue;
7490 if (ret != EXCP_HALTED)
7491 break;
7492 /* all CPUs are halted ? */
7493 if (env == cur_cpu)
7494 break;
7496 cur_cpu = env;
7498 if (shutdown_requested) {
7499 ret = EXCP_INTERRUPT;
7500 break;
7502 if (reset_requested) {
7503 reset_requested = 0;
7504 qemu_system_reset();
7505 ret = EXCP_INTERRUPT;
7507 if (powerdown_requested) {
7508 powerdown_requested = 0;
7509 qemu_system_powerdown();
7510 ret = EXCP_INTERRUPT;
7512 if (ret == EXCP_DEBUG) {
7513 vm_stop(EXCP_DEBUG);
7515 /* If all cpus are halted then wait until the next IRQ */
7516 /* XXX: use timeout computed from timers */
7517 if (ret == EXCP_HALTED)
7518 timeout = 10;
7519 else
7520 timeout = 0;
7521 } else {
7522 timeout = 10;
7524 #ifdef CONFIG_PROFILER
7525 ti = profile_getclock();
7526 #endif
7527 main_loop_wait(timeout);
7528 #ifdef CONFIG_PROFILER
7529 dev_time += profile_getclock() - ti;
7530 #endif
7532 cpu_disable_ticks();
7533 return ret;
7536 static void help(int exitcode)
7538 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7539 "usage: %s [options] [disk_image]\n"
7540 "\n"
7541 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7542 "\n"
7543 "Standard options:\n"
7544 "-M machine select emulated machine (-M ? for list)\n"
7545 "-cpu cpu select CPU (-cpu ? for list)\n"
7546 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7547 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7548 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7549 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7550 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7551 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7552 " [,cache=on|off]\n"
7553 " use 'file' as a drive image\n"
7554 "-mtdblock file use 'file' as on-board Flash memory image\n"
7555 "-sd file use 'file' as SecureDigital card image\n"
7556 "-pflash file use 'file' as a parallel flash image\n"
7557 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7558 "-snapshot write to temporary files instead of disk image files\n"
7559 #ifdef CONFIG_SDL
7560 "-no-frame open SDL window without a frame and window decorations\n"
7561 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7562 "-no-quit disable SDL window close capability\n"
7563 #endif
7564 #ifdef TARGET_I386
7565 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7566 #endif
7567 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7568 "-smp n set the number of CPUs to 'n' [default=1]\n"
7569 "-nographic disable graphical output and redirect serial I/Os to console\n"
7570 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7571 #ifndef _WIN32
7572 "-k language use keyboard layout (for example \"fr\" for French)\n"
7573 #endif
7574 #ifdef HAS_AUDIO
7575 "-audio-help print list of audio drivers and their options\n"
7576 "-soundhw c1,... enable audio support\n"
7577 " and only specified sound cards (comma separated list)\n"
7578 " use -soundhw ? to get the list of supported cards\n"
7579 " use -soundhw all to enable all of them\n"
7580 #endif
7581 "-localtime set the real time clock to local time [default=utc]\n"
7582 "-full-screen start in full screen\n"
7583 #ifdef TARGET_I386
7584 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7585 #endif
7586 "-usb enable the USB driver (will be the default soon)\n"
7587 "-usbdevice name add the host or guest USB device 'name'\n"
7588 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7589 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7590 #endif
7591 "-name string set the name of the guest\n"
7592 "\n"
7593 "Network options:\n"
7594 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7595 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7596 #ifdef CONFIG_SLIRP
7597 "-net user[,vlan=n][,hostname=host]\n"
7598 " connect the user mode network stack to VLAN 'n' and send\n"
7599 " hostname 'host' to DHCP clients\n"
7600 #endif
7601 #ifdef _WIN32
7602 "-net tap[,vlan=n],ifname=name\n"
7603 " connect the host TAP network interface to VLAN 'n'\n"
7604 #else
7605 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7606 " connect the host TAP network interface to VLAN 'n' and use the\n"
7607 " network scripts 'file' (default=%s)\n"
7608 " and 'dfile' (default=%s);\n"
7609 " use '[down]script=no' to disable script execution;\n"
7610 " use 'fd=h' to connect to an already opened TAP interface\n"
7611 #endif
7612 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7613 " connect the vlan 'n' to another VLAN using a socket connection\n"
7614 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7615 " connect the vlan 'n' to multicast maddr and port\n"
7616 "-net none use it alone to have zero network devices; if no -net option\n"
7617 " is provided, the default is '-net nic -net user'\n"
7618 "\n"
7619 #ifdef CONFIG_SLIRP
7620 "-tftp dir allow tftp access to files in dir [-net user]\n"
7621 "-bootp file advertise file in BOOTP replies\n"
7622 #ifndef _WIN32
7623 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7624 #endif
7625 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7626 " redirect TCP or UDP connections from host to guest [-net user]\n"
7627 #endif
7628 "\n"
7629 "Linux boot specific:\n"
7630 "-kernel bzImage use 'bzImage' as kernel image\n"
7631 "-append cmdline use 'cmdline' as kernel command line\n"
7632 "-initrd file use 'file' as initial ram disk\n"
7633 "\n"
7634 "Debug/Expert options:\n"
7635 "-monitor dev redirect the monitor to char device 'dev'\n"
7636 "-serial dev redirect the serial port to char device 'dev'\n"
7637 "-parallel dev redirect the parallel port to char device 'dev'\n"
7638 "-pidfile file Write PID to 'file'\n"
7639 "-S freeze CPU at startup (use 'c' to start execution)\n"
7640 "-s wait gdb connection to port\n"
7641 "-p port set gdb connection port [default=%s]\n"
7642 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7643 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7644 " translation (t=none or lba) (usually qemu can guess them)\n"
7645 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7646 #ifdef USE_KQEMU
7647 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7648 "-no-kqemu disable KQEMU kernel module usage\n"
7649 #endif
7650 #ifdef TARGET_I386
7651 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7652 " (default is CL-GD5446 PCI VGA)\n"
7653 "-no-acpi disable ACPI\n"
7654 #endif
7655 "-no-reboot exit instead of rebooting\n"
7656 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7657 "-vnc display start a VNC server on display\n"
7658 #ifndef _WIN32
7659 "-daemonize daemonize QEMU after initializing\n"
7660 #endif
7661 "-option-rom rom load a file, rom, into the option ROM space\n"
7662 #ifdef TARGET_SPARC
7663 "-prom-env variable=value set OpenBIOS nvram variables\n"
7664 #endif
7665 "-clock force the use of the given methods for timer alarm.\n"
7666 " To see what timers are available use -clock help\n"
7667 "-startdate select initial date of the clock\n"
7668 "\n"
7669 "During emulation, the following keys are useful:\n"
7670 "ctrl-alt-f toggle full screen\n"
7671 "ctrl-alt-n switch to virtual console 'n'\n"
7672 "ctrl-alt toggle mouse and keyboard grab\n"
7673 "\n"
7674 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7676 "qemu",
7677 DEFAULT_RAM_SIZE,
7678 #ifndef _WIN32
7679 DEFAULT_NETWORK_SCRIPT,
7680 DEFAULT_NETWORK_DOWN_SCRIPT,
7681 #endif
7682 DEFAULT_GDBSTUB_PORT,
7683 "/tmp/qemu.log");
7684 exit(exitcode);
7687 #define HAS_ARG 0x0001
7689 enum {
7690 QEMU_OPTION_h,
7692 QEMU_OPTION_M,
7693 QEMU_OPTION_cpu,
7694 QEMU_OPTION_fda,
7695 QEMU_OPTION_fdb,
7696 QEMU_OPTION_hda,
7697 QEMU_OPTION_hdb,
7698 QEMU_OPTION_hdc,
7699 QEMU_OPTION_hdd,
7700 QEMU_OPTION_drive,
7701 QEMU_OPTION_cdrom,
7702 QEMU_OPTION_mtdblock,
7703 QEMU_OPTION_sd,
7704 QEMU_OPTION_pflash,
7705 QEMU_OPTION_boot,
7706 QEMU_OPTION_snapshot,
7707 #ifdef TARGET_I386
7708 QEMU_OPTION_no_fd_bootchk,
7709 #endif
7710 QEMU_OPTION_m,
7711 QEMU_OPTION_nographic,
7712 QEMU_OPTION_portrait,
7713 #ifdef HAS_AUDIO
7714 QEMU_OPTION_audio_help,
7715 QEMU_OPTION_soundhw,
7716 #endif
7718 QEMU_OPTION_net,
7719 QEMU_OPTION_tftp,
7720 QEMU_OPTION_bootp,
7721 QEMU_OPTION_smb,
7722 QEMU_OPTION_redir,
7724 QEMU_OPTION_kernel,
7725 QEMU_OPTION_append,
7726 QEMU_OPTION_initrd,
7728 QEMU_OPTION_S,
7729 QEMU_OPTION_s,
7730 QEMU_OPTION_p,
7731 QEMU_OPTION_d,
7732 QEMU_OPTION_hdachs,
7733 QEMU_OPTION_L,
7734 QEMU_OPTION_bios,
7735 QEMU_OPTION_no_code_copy,
7736 QEMU_OPTION_k,
7737 QEMU_OPTION_localtime,
7738 QEMU_OPTION_cirrusvga,
7739 QEMU_OPTION_vmsvga,
7740 QEMU_OPTION_g,
7741 QEMU_OPTION_std_vga,
7742 QEMU_OPTION_echr,
7743 QEMU_OPTION_monitor,
7744 QEMU_OPTION_serial,
7745 QEMU_OPTION_parallel,
7746 QEMU_OPTION_loadvm,
7747 QEMU_OPTION_full_screen,
7748 QEMU_OPTION_no_frame,
7749 QEMU_OPTION_alt_grab,
7750 QEMU_OPTION_no_quit,
7751 QEMU_OPTION_pidfile,
7752 QEMU_OPTION_no_kqemu,
7753 QEMU_OPTION_kernel_kqemu,
7754 QEMU_OPTION_win2k_hack,
7755 QEMU_OPTION_usb,
7756 QEMU_OPTION_usbdevice,
7757 QEMU_OPTION_smp,
7758 QEMU_OPTION_vnc,
7759 QEMU_OPTION_no_acpi,
7760 QEMU_OPTION_no_reboot,
7761 QEMU_OPTION_show_cursor,
7762 QEMU_OPTION_daemonize,
7763 QEMU_OPTION_option_rom,
7764 QEMU_OPTION_semihosting,
7765 QEMU_OPTION_name,
7766 QEMU_OPTION_prom_env,
7767 QEMU_OPTION_old_param,
7768 QEMU_OPTION_clock,
7769 QEMU_OPTION_startdate,
7772 typedef struct QEMUOption {
7773 const char *name;
7774 int flags;
7775 int index;
7776 } QEMUOption;
7778 const QEMUOption qemu_options[] = {
7779 { "h", 0, QEMU_OPTION_h },
7780 { "help", 0, QEMU_OPTION_h },
7782 { "M", HAS_ARG, QEMU_OPTION_M },
7783 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7784 { "fda", HAS_ARG, QEMU_OPTION_fda },
7785 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7786 { "hda", HAS_ARG, QEMU_OPTION_hda },
7787 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7788 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7789 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7790 { "drive", HAS_ARG, QEMU_OPTION_drive },
7791 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7792 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7793 { "sd", HAS_ARG, QEMU_OPTION_sd },
7794 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7795 { "boot", HAS_ARG, QEMU_OPTION_boot },
7796 { "snapshot", 0, QEMU_OPTION_snapshot },
7797 #ifdef TARGET_I386
7798 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7799 #endif
7800 { "m", HAS_ARG, QEMU_OPTION_m },
7801 { "nographic", 0, QEMU_OPTION_nographic },
7802 { "portrait", 0, QEMU_OPTION_portrait },
7803 { "k", HAS_ARG, QEMU_OPTION_k },
7804 #ifdef HAS_AUDIO
7805 { "audio-help", 0, QEMU_OPTION_audio_help },
7806 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7807 #endif
7809 { "net", HAS_ARG, QEMU_OPTION_net},
7810 #ifdef CONFIG_SLIRP
7811 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7812 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7813 #ifndef _WIN32
7814 { "smb", HAS_ARG, QEMU_OPTION_smb },
7815 #endif
7816 { "redir", HAS_ARG, QEMU_OPTION_redir },
7817 #endif
7819 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7820 { "append", HAS_ARG, QEMU_OPTION_append },
7821 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7823 { "S", 0, QEMU_OPTION_S },
7824 { "s", 0, QEMU_OPTION_s },
7825 { "p", HAS_ARG, QEMU_OPTION_p },
7826 { "d", HAS_ARG, QEMU_OPTION_d },
7827 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7828 { "L", HAS_ARG, QEMU_OPTION_L },
7829 { "bios", HAS_ARG, QEMU_OPTION_bios },
7830 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7831 #ifdef USE_KQEMU
7832 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7833 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7834 #endif
7835 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7836 { "g", 1, QEMU_OPTION_g },
7837 #endif
7838 { "localtime", 0, QEMU_OPTION_localtime },
7839 { "std-vga", 0, QEMU_OPTION_std_vga },
7840 { "echr", HAS_ARG, QEMU_OPTION_echr },
7841 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7842 { "serial", HAS_ARG, QEMU_OPTION_serial },
7843 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7844 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7845 { "full-screen", 0, QEMU_OPTION_full_screen },
7846 #ifdef CONFIG_SDL
7847 { "no-frame", 0, QEMU_OPTION_no_frame },
7848 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7849 { "no-quit", 0, QEMU_OPTION_no_quit },
7850 #endif
7851 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7852 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7853 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7854 { "smp", HAS_ARG, QEMU_OPTION_smp },
7855 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7857 /* temporary options */
7858 { "usb", 0, QEMU_OPTION_usb },
7859 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7860 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7861 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7862 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7863 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7864 { "daemonize", 0, QEMU_OPTION_daemonize },
7865 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7866 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7867 { "semihosting", 0, QEMU_OPTION_semihosting },
7868 #endif
7869 { "name", HAS_ARG, QEMU_OPTION_name },
7870 #if defined(TARGET_SPARC)
7871 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7872 #endif
7873 #if defined(TARGET_ARM)
7874 { "old-param", 0, QEMU_OPTION_old_param },
7875 #endif
7876 { "clock", HAS_ARG, QEMU_OPTION_clock },
7877 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7878 { NULL },
7881 /* password input */
7883 int qemu_key_check(BlockDriverState *bs, const char *name)
7885 char password[256];
7886 int i;
7888 if (!bdrv_is_encrypted(bs))
7889 return 0;
7891 term_printf("%s is encrypted.\n", name);
7892 for(i = 0; i < 3; i++) {
7893 monitor_readline("Password: ", 1, password, sizeof(password));
7894 if (bdrv_set_key(bs, password) == 0)
7895 return 0;
7896 term_printf("invalid password\n");
7898 return -EPERM;
7901 static BlockDriverState *get_bdrv(int index)
7903 if (index > nb_drives)
7904 return NULL;
7905 return drives_table[index].bdrv;
7908 static void read_passwords(void)
7910 BlockDriverState *bs;
7911 int i;
7913 for(i = 0; i < 6; i++) {
7914 bs = get_bdrv(i);
7915 if (bs)
7916 qemu_key_check(bs, bdrv_get_device_name(bs));
7920 /* XXX: currently we cannot use simultaneously different CPUs */
7921 static void register_machines(void)
7923 #if defined(TARGET_I386)
7924 qemu_register_machine(&pc_machine);
7925 qemu_register_machine(&isapc_machine);
7926 #elif defined(TARGET_PPC)
7927 qemu_register_machine(&heathrow_machine);
7928 qemu_register_machine(&core99_machine);
7929 qemu_register_machine(&prep_machine);
7930 qemu_register_machine(&ref405ep_machine);
7931 qemu_register_machine(&taihu_machine);
7932 #elif defined(TARGET_MIPS)
7933 qemu_register_machine(&mips_machine);
7934 qemu_register_machine(&mips_malta_machine);
7935 qemu_register_machine(&mips_pica61_machine);
7936 qemu_register_machine(&mips_mipssim_machine);
7937 #elif defined(TARGET_SPARC)
7938 #ifdef TARGET_SPARC64
7939 qemu_register_machine(&sun4u_machine);
7940 #else
7941 qemu_register_machine(&ss5_machine);
7942 qemu_register_machine(&ss10_machine);
7943 qemu_register_machine(&ss600mp_machine);
7944 qemu_register_machine(&ss20_machine);
7945 qemu_register_machine(&ss2_machine);
7946 qemu_register_machine(&ss1000_machine);
7947 qemu_register_machine(&ss2000_machine);
7948 #endif
7949 #elif defined(TARGET_ARM)
7950 qemu_register_machine(&integratorcp_machine);
7951 qemu_register_machine(&versatilepb_machine);
7952 qemu_register_machine(&versatileab_machine);
7953 qemu_register_machine(&realview_machine);
7954 qemu_register_machine(&akitapda_machine);
7955 qemu_register_machine(&spitzpda_machine);
7956 qemu_register_machine(&borzoipda_machine);
7957 qemu_register_machine(&terrierpda_machine);
7958 qemu_register_machine(&palmte_machine);
7959 qemu_register_machine(&lm3s811evb_machine);
7960 qemu_register_machine(&lm3s6965evb_machine);
7961 qemu_register_machine(&connex_machine);
7962 qemu_register_machine(&verdex_machine);
7963 qemu_register_machine(&mainstone2_machine);
7964 #elif defined(TARGET_SH4)
7965 qemu_register_machine(&shix_machine);
7966 qemu_register_machine(&r2d_machine);
7967 #elif defined(TARGET_ALPHA)
7968 /* XXX: TODO */
7969 #elif defined(TARGET_M68K)
7970 qemu_register_machine(&mcf5208evb_machine);
7971 qemu_register_machine(&an5206_machine);
7972 qemu_register_machine(&dummy_m68k_machine);
7973 #elif defined(TARGET_CRIS)
7974 qemu_register_machine(&bareetraxfs_machine);
7975 #else
7976 #error unsupported CPU
7977 #endif
7980 #ifdef HAS_AUDIO
7981 struct soundhw soundhw[] = {
7982 #ifdef HAS_AUDIO_CHOICE
7983 #ifdef TARGET_I386
7985 "pcspk",
7986 "PC speaker",
7989 { .init_isa = pcspk_audio_init }
7991 #endif
7993 "sb16",
7994 "Creative Sound Blaster 16",
7997 { .init_isa = SB16_init }
8000 #ifdef CONFIG_ADLIB
8002 "adlib",
8003 #ifdef HAS_YMF262
8004 "Yamaha YMF262 (OPL3)",
8005 #else
8006 "Yamaha YM3812 (OPL2)",
8007 #endif
8010 { .init_isa = Adlib_init }
8012 #endif
8014 #ifdef CONFIG_GUS
8016 "gus",
8017 "Gravis Ultrasound GF1",
8020 { .init_isa = GUS_init }
8022 #endif
8024 #ifdef CONFIG_AC97
8026 "ac97",
8027 "Intel 82801AA AC97 Audio",
8030 { .init_pci = ac97_init }
8032 #endif
8035 "es1370",
8036 "ENSONIQ AudioPCI ES1370",
8039 { .init_pci = es1370_init }
8041 #endif
8043 { NULL, NULL, 0, 0, { NULL } }
8046 static void select_soundhw (const char *optarg)
8048 struct soundhw *c;
8050 if (*optarg == '?') {
8051 show_valid_cards:
8053 printf ("Valid sound card names (comma separated):\n");
8054 for (c = soundhw; c->name; ++c) {
8055 printf ("%-11s %s\n", c->name, c->descr);
8057 printf ("\n-soundhw all will enable all of the above\n");
8058 exit (*optarg != '?');
8060 else {
8061 size_t l;
8062 const char *p;
8063 char *e;
8064 int bad_card = 0;
8066 if (!strcmp (optarg, "all")) {
8067 for (c = soundhw; c->name; ++c) {
8068 c->enabled = 1;
8070 return;
8073 p = optarg;
8074 while (*p) {
8075 e = strchr (p, ',');
8076 l = !e ? strlen (p) : (size_t) (e - p);
8078 for (c = soundhw; c->name; ++c) {
8079 if (!strncmp (c->name, p, l)) {
8080 c->enabled = 1;
8081 break;
8085 if (!c->name) {
8086 if (l > 80) {
8087 fprintf (stderr,
8088 "Unknown sound card name (too big to show)\n");
8090 else {
8091 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8092 (int) l, p);
8094 bad_card = 1;
8096 p += l + (e != NULL);
8099 if (bad_card)
8100 goto show_valid_cards;
8103 #endif
8105 #ifdef _WIN32
8106 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8108 exit(STATUS_CONTROL_C_EXIT);
8109 return TRUE;
8111 #endif
8113 #define MAX_NET_CLIENTS 32
8115 int main(int argc, char **argv)
8117 #ifdef CONFIG_GDBSTUB
8118 int use_gdbstub;
8119 const char *gdbstub_port;
8120 #endif
8121 uint32_t boot_devices_bitmap = 0;
8122 int i;
8123 int snapshot, linux_boot, net_boot;
8124 const char *initrd_filename;
8125 const char *kernel_filename, *kernel_cmdline;
8126 const char *boot_devices = "";
8127 DisplayState *ds = &display_state;
8128 int cyls, heads, secs, translation;
8129 char net_clients[MAX_NET_CLIENTS][256];
8130 int nb_net_clients;
8131 int hda_index;
8132 int optind;
8133 const char *r, *optarg;
8134 CharDriverState *monitor_hd;
8135 char monitor_device[128];
8136 char serial_devices[MAX_SERIAL_PORTS][128];
8137 int serial_device_index;
8138 char parallel_devices[MAX_PARALLEL_PORTS][128];
8139 int parallel_device_index;
8140 const char *loadvm = NULL;
8141 QEMUMachine *machine;
8142 const char *cpu_model;
8143 char usb_devices[MAX_USB_CMDLINE][128];
8144 int usb_devices_index;
8145 int fds[2];
8146 const char *pid_file = NULL;
8147 VLANState *vlan;
8149 LIST_INIT (&vm_change_state_head);
8150 #ifndef _WIN32
8152 struct sigaction act;
8153 sigfillset(&act.sa_mask);
8154 act.sa_flags = 0;
8155 act.sa_handler = SIG_IGN;
8156 sigaction(SIGPIPE, &act, NULL);
8158 #else
8159 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8160 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8161 QEMU to run on a single CPU */
8163 HANDLE h;
8164 DWORD mask, smask;
8165 int i;
8166 h = GetCurrentProcess();
8167 if (GetProcessAffinityMask(h, &mask, &smask)) {
8168 for(i = 0; i < 32; i++) {
8169 if (mask & (1 << i))
8170 break;
8172 if (i != 32) {
8173 mask = 1 << i;
8174 SetProcessAffinityMask(h, mask);
8178 #endif
8180 register_machines();
8181 machine = first_machine;
8182 cpu_model = NULL;
8183 initrd_filename = NULL;
8184 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8185 vga_ram_size = VGA_RAM_SIZE;
8186 #ifdef CONFIG_GDBSTUB
8187 use_gdbstub = 0;
8188 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8189 #endif
8190 snapshot = 0;
8191 nographic = 0;
8192 kernel_filename = NULL;
8193 kernel_cmdline = "";
8194 cyls = heads = secs = 0;
8195 translation = BIOS_ATA_TRANSLATION_AUTO;
8196 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8198 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8199 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8200 serial_devices[i][0] = '\0';
8201 serial_device_index = 0;
8203 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8204 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8205 parallel_devices[i][0] = '\0';
8206 parallel_device_index = 0;
8208 usb_devices_index = 0;
8210 nb_net_clients = 0;
8211 nb_drives = 0;
8212 nb_drives_opt = 0;
8213 hda_index = -1;
8215 nb_nics = 0;
8216 /* default mac address of the first network interface */
8218 optind = 1;
8219 for(;;) {
8220 if (optind >= argc)
8221 break;
8222 r = argv[optind];
8223 if (r[0] != '-') {
8224 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8225 } else {
8226 const QEMUOption *popt;
8228 optind++;
8229 /* Treat --foo the same as -foo. */
8230 if (r[1] == '-')
8231 r++;
8232 popt = qemu_options;
8233 for(;;) {
8234 if (!popt->name) {
8235 fprintf(stderr, "%s: invalid option -- '%s'\n",
8236 argv[0], r);
8237 exit(1);
8239 if (!strcmp(popt->name, r + 1))
8240 break;
8241 popt++;
8243 if (popt->flags & HAS_ARG) {
8244 if (optind >= argc) {
8245 fprintf(stderr, "%s: option '%s' requires an argument\n",
8246 argv[0], r);
8247 exit(1);
8249 optarg = argv[optind++];
8250 } else {
8251 optarg = NULL;
8254 switch(popt->index) {
8255 case QEMU_OPTION_M:
8256 machine = find_machine(optarg);
8257 if (!machine) {
8258 QEMUMachine *m;
8259 printf("Supported machines are:\n");
8260 for(m = first_machine; m != NULL; m = m->next) {
8261 printf("%-10s %s%s\n",
8262 m->name, m->desc,
8263 m == first_machine ? " (default)" : "");
8265 exit(*optarg != '?');
8267 break;
8268 case QEMU_OPTION_cpu:
8269 /* hw initialization will check this */
8270 if (*optarg == '?') {
8271 /* XXX: implement xxx_cpu_list for targets that still miss it */
8272 #if defined(cpu_list)
8273 cpu_list(stdout, &fprintf);
8274 #endif
8275 exit(0);
8276 } else {
8277 cpu_model = optarg;
8279 break;
8280 case QEMU_OPTION_initrd:
8281 initrd_filename = optarg;
8282 break;
8283 case QEMU_OPTION_hda:
8284 if (cyls == 0)
8285 hda_index = drive_add(optarg, HD_ALIAS, 0);
8286 else
8287 hda_index = drive_add(optarg, HD_ALIAS
8288 ",cyls=%d,heads=%d,secs=%d%s",
8289 0, cyls, heads, secs,
8290 translation == BIOS_ATA_TRANSLATION_LBA ?
8291 ",trans=lba" :
8292 translation == BIOS_ATA_TRANSLATION_NONE ?
8293 ",trans=none" : "");
8294 break;
8295 case QEMU_OPTION_hdb:
8296 case QEMU_OPTION_hdc:
8297 case QEMU_OPTION_hdd:
8298 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8299 break;
8300 case QEMU_OPTION_drive:
8301 drive_add(NULL, "%s", optarg);
8302 break;
8303 case QEMU_OPTION_mtdblock:
8304 drive_add(optarg, MTD_ALIAS);
8305 break;
8306 case QEMU_OPTION_sd:
8307 drive_add(optarg, SD_ALIAS);
8308 break;
8309 case QEMU_OPTION_pflash:
8310 drive_add(optarg, PFLASH_ALIAS);
8311 break;
8312 case QEMU_OPTION_snapshot:
8313 snapshot = 1;
8314 break;
8315 case QEMU_OPTION_hdachs:
8317 const char *p;
8318 p = optarg;
8319 cyls = strtol(p, (char **)&p, 0);
8320 if (cyls < 1 || cyls > 16383)
8321 goto chs_fail;
8322 if (*p != ',')
8323 goto chs_fail;
8324 p++;
8325 heads = strtol(p, (char **)&p, 0);
8326 if (heads < 1 || heads > 16)
8327 goto chs_fail;
8328 if (*p != ',')
8329 goto chs_fail;
8330 p++;
8331 secs = strtol(p, (char **)&p, 0);
8332 if (secs < 1 || secs > 63)
8333 goto chs_fail;
8334 if (*p == ',') {
8335 p++;
8336 if (!strcmp(p, "none"))
8337 translation = BIOS_ATA_TRANSLATION_NONE;
8338 else if (!strcmp(p, "lba"))
8339 translation = BIOS_ATA_TRANSLATION_LBA;
8340 else if (!strcmp(p, "auto"))
8341 translation = BIOS_ATA_TRANSLATION_AUTO;
8342 else
8343 goto chs_fail;
8344 } else if (*p != '\0') {
8345 chs_fail:
8346 fprintf(stderr, "qemu: invalid physical CHS format\n");
8347 exit(1);
8349 if (hda_index != -1)
8350 snprintf(drives_opt[hda_index].opt,
8351 sizeof(drives_opt[hda_index].opt),
8352 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8353 0, cyls, heads, secs,
8354 translation == BIOS_ATA_TRANSLATION_LBA ?
8355 ",trans=lba" :
8356 translation == BIOS_ATA_TRANSLATION_NONE ?
8357 ",trans=none" : "");
8359 break;
8360 case QEMU_OPTION_nographic:
8361 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8362 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8363 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8364 nographic = 1;
8365 break;
8366 case QEMU_OPTION_portrait:
8367 graphic_rotate = 1;
8368 break;
8369 case QEMU_OPTION_kernel:
8370 kernel_filename = optarg;
8371 break;
8372 case QEMU_OPTION_append:
8373 kernel_cmdline = optarg;
8374 break;
8375 case QEMU_OPTION_cdrom:
8376 drive_add(optarg, CDROM_ALIAS);
8377 break;
8378 case QEMU_OPTION_boot:
8379 boot_devices = optarg;
8380 /* We just do some generic consistency checks */
8382 /* Could easily be extended to 64 devices if needed */
8383 const char *p;
8385 boot_devices_bitmap = 0;
8386 for (p = boot_devices; *p != '\0'; p++) {
8387 /* Allowed boot devices are:
8388 * a b : floppy disk drives
8389 * c ... f : IDE disk drives
8390 * g ... m : machine implementation dependant drives
8391 * n ... p : network devices
8392 * It's up to each machine implementation to check
8393 * if the given boot devices match the actual hardware
8394 * implementation and firmware features.
8396 if (*p < 'a' || *p > 'q') {
8397 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8398 exit(1);
8400 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8401 fprintf(stderr,
8402 "Boot device '%c' was given twice\n",*p);
8403 exit(1);
8405 boot_devices_bitmap |= 1 << (*p - 'a');
8408 break;
8409 case QEMU_OPTION_fda:
8410 case QEMU_OPTION_fdb:
8411 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8412 break;
8413 #ifdef TARGET_I386
8414 case QEMU_OPTION_no_fd_bootchk:
8415 fd_bootchk = 0;
8416 break;
8417 #endif
8418 case QEMU_OPTION_no_code_copy:
8419 code_copy_enabled = 0;
8420 break;
8421 case QEMU_OPTION_net:
8422 if (nb_net_clients >= MAX_NET_CLIENTS) {
8423 fprintf(stderr, "qemu: too many network clients\n");
8424 exit(1);
8426 pstrcpy(net_clients[nb_net_clients],
8427 sizeof(net_clients[0]),
8428 optarg);
8429 nb_net_clients++;
8430 break;
8431 #ifdef CONFIG_SLIRP
8432 case QEMU_OPTION_tftp:
8433 tftp_prefix = optarg;
8434 break;
8435 case QEMU_OPTION_bootp:
8436 bootp_filename = optarg;
8437 break;
8438 #ifndef _WIN32
8439 case QEMU_OPTION_smb:
8440 net_slirp_smb(optarg);
8441 break;
8442 #endif
8443 case QEMU_OPTION_redir:
8444 net_slirp_redir(optarg);
8445 break;
8446 #endif
8447 #ifdef HAS_AUDIO
8448 case QEMU_OPTION_audio_help:
8449 AUD_help ();
8450 exit (0);
8451 break;
8452 case QEMU_OPTION_soundhw:
8453 select_soundhw (optarg);
8454 break;
8455 #endif
8456 case QEMU_OPTION_h:
8457 help(0);
8458 break;
8459 case QEMU_OPTION_m:
8460 ram_size = atoi(optarg) * 1024 * 1024;
8461 if (ram_size <= 0)
8462 help(1);
8463 if (ram_size > PHYS_RAM_MAX_SIZE) {
8464 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8465 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8466 exit(1);
8468 break;
8469 case QEMU_OPTION_d:
8471 int mask;
8472 CPULogItem *item;
8474 mask = cpu_str_to_log_mask(optarg);
8475 if (!mask) {
8476 printf("Log items (comma separated):\n");
8477 for(item = cpu_log_items; item->mask != 0; item++) {
8478 printf("%-10s %s\n", item->name, item->help);
8480 exit(1);
8482 cpu_set_log(mask);
8484 break;
8485 #ifdef CONFIG_GDBSTUB
8486 case QEMU_OPTION_s:
8487 use_gdbstub = 1;
8488 break;
8489 case QEMU_OPTION_p:
8490 gdbstub_port = optarg;
8491 break;
8492 #endif
8493 case QEMU_OPTION_L:
8494 bios_dir = optarg;
8495 break;
8496 case QEMU_OPTION_bios:
8497 bios_name = optarg;
8498 break;
8499 case QEMU_OPTION_S:
8500 autostart = 0;
8501 break;
8502 case QEMU_OPTION_k:
8503 keyboard_layout = optarg;
8504 break;
8505 case QEMU_OPTION_localtime:
8506 rtc_utc = 0;
8507 break;
8508 case QEMU_OPTION_cirrusvga:
8509 cirrus_vga_enabled = 1;
8510 vmsvga_enabled = 0;
8511 break;
8512 case QEMU_OPTION_vmsvga:
8513 cirrus_vga_enabled = 0;
8514 vmsvga_enabled = 1;
8515 break;
8516 case QEMU_OPTION_std_vga:
8517 cirrus_vga_enabled = 0;
8518 vmsvga_enabled = 0;
8519 break;
8520 case QEMU_OPTION_g:
8522 const char *p;
8523 int w, h, depth;
8524 p = optarg;
8525 w = strtol(p, (char **)&p, 10);
8526 if (w <= 0) {
8527 graphic_error:
8528 fprintf(stderr, "qemu: invalid resolution or depth\n");
8529 exit(1);
8531 if (*p != 'x')
8532 goto graphic_error;
8533 p++;
8534 h = strtol(p, (char **)&p, 10);
8535 if (h <= 0)
8536 goto graphic_error;
8537 if (*p == 'x') {
8538 p++;
8539 depth = strtol(p, (char **)&p, 10);
8540 if (depth != 8 && depth != 15 && depth != 16 &&
8541 depth != 24 && depth != 32)
8542 goto graphic_error;
8543 } else if (*p == '\0') {
8544 depth = graphic_depth;
8545 } else {
8546 goto graphic_error;
8549 graphic_width = w;
8550 graphic_height = h;
8551 graphic_depth = depth;
8553 break;
8554 case QEMU_OPTION_echr:
8556 char *r;
8557 term_escape_char = strtol(optarg, &r, 0);
8558 if (r == optarg)
8559 printf("Bad argument to echr\n");
8560 break;
8562 case QEMU_OPTION_monitor:
8563 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8564 break;
8565 case QEMU_OPTION_serial:
8566 if (serial_device_index >= MAX_SERIAL_PORTS) {
8567 fprintf(stderr, "qemu: too many serial ports\n");
8568 exit(1);
8570 pstrcpy(serial_devices[serial_device_index],
8571 sizeof(serial_devices[0]), optarg);
8572 serial_device_index++;
8573 break;
8574 case QEMU_OPTION_parallel:
8575 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8576 fprintf(stderr, "qemu: too many parallel ports\n");
8577 exit(1);
8579 pstrcpy(parallel_devices[parallel_device_index],
8580 sizeof(parallel_devices[0]), optarg);
8581 parallel_device_index++;
8582 break;
8583 case QEMU_OPTION_loadvm:
8584 loadvm = optarg;
8585 break;
8586 case QEMU_OPTION_full_screen:
8587 full_screen = 1;
8588 break;
8589 #ifdef CONFIG_SDL
8590 case QEMU_OPTION_no_frame:
8591 no_frame = 1;
8592 break;
8593 case QEMU_OPTION_alt_grab:
8594 alt_grab = 1;
8595 break;
8596 case QEMU_OPTION_no_quit:
8597 no_quit = 1;
8598 break;
8599 #endif
8600 case QEMU_OPTION_pidfile:
8601 pid_file = optarg;
8602 break;
8603 #ifdef TARGET_I386
8604 case QEMU_OPTION_win2k_hack:
8605 win2k_install_hack = 1;
8606 break;
8607 #endif
8608 #ifdef USE_KQEMU
8609 case QEMU_OPTION_no_kqemu:
8610 kqemu_allowed = 0;
8611 break;
8612 case QEMU_OPTION_kernel_kqemu:
8613 kqemu_allowed = 2;
8614 break;
8615 #endif
8616 case QEMU_OPTION_usb:
8617 usb_enabled = 1;
8618 break;
8619 case QEMU_OPTION_usbdevice:
8620 usb_enabled = 1;
8621 if (usb_devices_index >= MAX_USB_CMDLINE) {
8622 fprintf(stderr, "Too many USB devices\n");
8623 exit(1);
8625 pstrcpy(usb_devices[usb_devices_index],
8626 sizeof(usb_devices[usb_devices_index]),
8627 optarg);
8628 usb_devices_index++;
8629 break;
8630 case QEMU_OPTION_smp:
8631 smp_cpus = atoi(optarg);
8632 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8633 fprintf(stderr, "Invalid number of CPUs\n");
8634 exit(1);
8636 break;
8637 case QEMU_OPTION_vnc:
8638 vnc_display = optarg;
8639 break;
8640 case QEMU_OPTION_no_acpi:
8641 acpi_enabled = 0;
8642 break;
8643 case QEMU_OPTION_no_reboot:
8644 no_reboot = 1;
8645 break;
8646 case QEMU_OPTION_show_cursor:
8647 cursor_hide = 0;
8648 break;
8649 case QEMU_OPTION_daemonize:
8650 daemonize = 1;
8651 break;
8652 case QEMU_OPTION_option_rom:
8653 if (nb_option_roms >= MAX_OPTION_ROMS) {
8654 fprintf(stderr, "Too many option ROMs\n");
8655 exit(1);
8657 option_rom[nb_option_roms] = optarg;
8658 nb_option_roms++;
8659 break;
8660 case QEMU_OPTION_semihosting:
8661 semihosting_enabled = 1;
8662 break;
8663 case QEMU_OPTION_name:
8664 qemu_name = optarg;
8665 break;
8666 #ifdef TARGET_SPARC
8667 case QEMU_OPTION_prom_env:
8668 if (nb_prom_envs >= MAX_PROM_ENVS) {
8669 fprintf(stderr, "Too many prom variables\n");
8670 exit(1);
8672 prom_envs[nb_prom_envs] = optarg;
8673 nb_prom_envs++;
8674 break;
8675 #endif
8676 #ifdef TARGET_ARM
8677 case QEMU_OPTION_old_param:
8678 old_param = 1;
8679 break;
8680 #endif
8681 case QEMU_OPTION_clock:
8682 configure_alarms(optarg);
8683 break;
8684 case QEMU_OPTION_startdate:
8686 struct tm tm;
8687 if (!strcmp(optarg, "now")) {
8688 rtc_start_date = -1;
8689 } else {
8690 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8691 &tm.tm_year,
8692 &tm.tm_mon,
8693 &tm.tm_mday,
8694 &tm.tm_hour,
8695 &tm.tm_min,
8696 &tm.tm_sec) == 6) {
8697 /* OK */
8698 } else if (sscanf(optarg, "%d-%d-%d",
8699 &tm.tm_year,
8700 &tm.tm_mon,
8701 &tm.tm_mday) == 3) {
8702 tm.tm_hour = 0;
8703 tm.tm_min = 0;
8704 tm.tm_sec = 0;
8705 } else {
8706 goto date_fail;
8708 tm.tm_year -= 1900;
8709 tm.tm_mon--;
8710 rtc_start_date = mktimegm(&tm);
8711 if (rtc_start_date == -1) {
8712 date_fail:
8713 fprintf(stderr, "Invalid date format. Valid format are:\n"
8714 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8715 exit(1);
8719 break;
8724 #ifndef _WIN32
8725 if (daemonize && !nographic && vnc_display == NULL) {
8726 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8727 daemonize = 0;
8730 if (daemonize) {
8731 pid_t pid;
8733 if (pipe(fds) == -1)
8734 exit(1);
8736 pid = fork();
8737 if (pid > 0) {
8738 uint8_t status;
8739 ssize_t len;
8741 close(fds[1]);
8743 again:
8744 len = read(fds[0], &status, 1);
8745 if (len == -1 && (errno == EINTR))
8746 goto again;
8748 if (len != 1)
8749 exit(1);
8750 else if (status == 1) {
8751 fprintf(stderr, "Could not acquire pidfile\n");
8752 exit(1);
8753 } else
8754 exit(0);
8755 } else if (pid < 0)
8756 exit(1);
8758 setsid();
8760 pid = fork();
8761 if (pid > 0)
8762 exit(0);
8763 else if (pid < 0)
8764 exit(1);
8766 umask(027);
8767 chdir("/");
8769 signal(SIGTSTP, SIG_IGN);
8770 signal(SIGTTOU, SIG_IGN);
8771 signal(SIGTTIN, SIG_IGN);
8773 #endif
8775 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8776 if (daemonize) {
8777 uint8_t status = 1;
8778 write(fds[1], &status, 1);
8779 } else
8780 fprintf(stderr, "Could not acquire pid file\n");
8781 exit(1);
8784 #ifdef USE_KQEMU
8785 if (smp_cpus > 1)
8786 kqemu_allowed = 0;
8787 #endif
8788 linux_boot = (kernel_filename != NULL);
8789 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8791 /* XXX: this should not be: some embedded targets just have flash */
8792 if (!linux_boot && net_boot == 0 &&
8793 nb_drives_opt == 0)
8794 help(1);
8796 /* boot to floppy or the default cd if no hard disk defined yet */
8797 if (!boot_devices[0]) {
8798 boot_devices = "cad";
8800 setvbuf(stdout, NULL, _IOLBF, 0);
8802 init_timers();
8803 init_timer_alarm();
8804 qemu_aio_init();
8806 #ifdef _WIN32
8807 socket_init();
8808 #endif
8810 /* init network clients */
8811 if (nb_net_clients == 0) {
8812 /* if no clients, we use a default config */
8813 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8814 "nic");
8815 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8816 "user");
8817 nb_net_clients = 2;
8820 for(i = 0;i < nb_net_clients; i++) {
8821 if (net_client_init(net_clients[i]) < 0)
8822 exit(1);
8824 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8825 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8826 continue;
8827 if (vlan->nb_guest_devs == 0) {
8828 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8829 exit(1);
8831 if (vlan->nb_host_devs == 0)
8832 fprintf(stderr,
8833 "Warning: vlan %d is not connected to host network\n",
8834 vlan->id);
8837 #ifdef TARGET_I386
8838 /* XXX: this should be moved in the PC machine instantiation code */
8839 if (net_boot != 0) {
8840 int netroms = 0;
8841 for (i = 0; i < nb_nics && i < 4; i++) {
8842 const char *model = nd_table[i].model;
8843 char buf[1024];
8844 if (net_boot & (1 << i)) {
8845 if (model == NULL)
8846 model = "ne2k_pci";
8847 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8848 if (get_image_size(buf) > 0) {
8849 if (nb_option_roms >= MAX_OPTION_ROMS) {
8850 fprintf(stderr, "Too many option ROMs\n");
8851 exit(1);
8853 option_rom[nb_option_roms] = strdup(buf);
8854 nb_option_roms++;
8855 netroms++;
8859 if (netroms == 0) {
8860 fprintf(stderr, "No valid PXE rom found for network device\n");
8861 exit(1);
8864 #endif
8866 /* init the memory */
8867 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8869 phys_ram_base = qemu_vmalloc(phys_ram_size);
8870 if (!phys_ram_base) {
8871 fprintf(stderr, "Could not allocate physical memory\n");
8872 exit(1);
8875 bdrv_init();
8877 /* we always create the cdrom drive, even if no disk is there */
8879 if (nb_drives_opt < MAX_DRIVES)
8880 drive_add(NULL, CDROM_ALIAS);
8882 /* we always create at least one floppy */
8884 if (nb_drives_opt < MAX_DRIVES)
8885 drive_add(NULL, FD_ALIAS, 0);
8887 /* we always create one sd slot, even if no card is in it */
8889 if (nb_drives_opt < MAX_DRIVES)
8890 drive_add(NULL, SD_ALIAS);
8892 /* open the virtual block devices */
8894 for(i = 0; i < nb_drives_opt; i++)
8895 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8896 exit(1);
8898 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8899 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8901 init_ioports();
8903 /* terminal init */
8904 memset(&display_state, 0, sizeof(display_state));
8905 if (nographic) {
8906 /* nearly nothing to do */
8907 dumb_display_init(ds);
8908 } else if (vnc_display != NULL) {
8909 vnc_display_init(ds);
8910 if (vnc_display_open(ds, vnc_display) < 0)
8911 exit(1);
8912 } else {
8913 #if defined(CONFIG_SDL)
8914 sdl_display_init(ds, full_screen, no_frame);
8915 #elif defined(CONFIG_COCOA)
8916 cocoa_display_init(ds, full_screen);
8917 #else
8918 dumb_display_init(ds);
8919 #endif
8922 /* Maintain compatibility with multiple stdio monitors */
8923 if (!strcmp(monitor_device,"stdio")) {
8924 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8925 if (!strcmp(serial_devices[i],"mon:stdio")) {
8926 monitor_device[0] = '\0';
8927 break;
8928 } else if (!strcmp(serial_devices[i],"stdio")) {
8929 monitor_device[0] = '\0';
8930 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8931 break;
8935 if (monitor_device[0] != '\0') {
8936 monitor_hd = qemu_chr_open(monitor_device);
8937 if (!monitor_hd) {
8938 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8939 exit(1);
8941 monitor_init(monitor_hd, !nographic);
8944 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8945 const char *devname = serial_devices[i];
8946 if (devname[0] != '\0' && strcmp(devname, "none")) {
8947 serial_hds[i] = qemu_chr_open(devname);
8948 if (!serial_hds[i]) {
8949 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8950 devname);
8951 exit(1);
8953 if (strstart(devname, "vc", 0))
8954 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8958 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8959 const char *devname = parallel_devices[i];
8960 if (devname[0] != '\0' && strcmp(devname, "none")) {
8961 parallel_hds[i] = qemu_chr_open(devname);
8962 if (!parallel_hds[i]) {
8963 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8964 devname);
8965 exit(1);
8967 if (strstart(devname, "vc", 0))
8968 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8972 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8973 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8975 /* init USB devices */
8976 if (usb_enabled) {
8977 for(i = 0; i < usb_devices_index; i++) {
8978 if (usb_device_add(usb_devices[i]) < 0) {
8979 fprintf(stderr, "Warning: could not add USB device %s\n",
8980 usb_devices[i]);
8985 if (display_state.dpy_refresh) {
8986 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8987 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8990 #ifdef CONFIG_GDBSTUB
8991 if (use_gdbstub) {
8992 /* XXX: use standard host:port notation and modify options
8993 accordingly. */
8994 if (gdbserver_start(gdbstub_port) < 0) {
8995 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8996 gdbstub_port);
8997 exit(1);
9000 #endif
9002 if (loadvm)
9003 do_loadvm(loadvm);
9006 /* XXX: simplify init */
9007 read_passwords();
9008 if (autostart) {
9009 vm_start();
9013 if (daemonize) {
9014 uint8_t status = 0;
9015 ssize_t len;
9016 int fd;
9018 again1:
9019 len = write(fds[1], &status, 1);
9020 if (len == -1 && (errno == EINTR))
9021 goto again1;
9023 if (len != 1)
9024 exit(1);
9026 TFR(fd = open("/dev/null", O_RDWR));
9027 if (fd == -1)
9028 exit(1);
9030 dup2(fd, 0);
9031 dup2(fd, 1);
9032 dup2(fd, 2);
9034 close(fd);
9037 main_loop();
9038 quit_timers();
9040 #if !defined(_WIN32)
9041 /* close network clients */
9042 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9043 VLANClientState *vc;
9045 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9046 if (vc->fd_read == tap_receive) {
9047 char ifname[64];
9048 TAPState *s = vc->opaque;
9050 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9051 s->down_script[0])
9052 launch_script(s->down_script, ifname, s->fd);
9056 #endif
9057 return 0;