Change -drive parsing so that paths don't have to be double-escaped (Laurent Vivier...
[qemu/qemu_0_9_1_stable.git] / vl.c
bloba28858bbb23ae767785652db1657e00559ec7d2e
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;
1309 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1310 if (rtc_fd < 0)
1311 return -1;
1312 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1313 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1314 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1315 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1316 goto fail;
1318 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1319 fail:
1320 close(rtc_fd);
1321 return -1;
1324 enable_sigio_timer(rtc_fd);
1326 t->priv = (void *)(long)rtc_fd;
1328 return 0;
1331 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1333 int rtc_fd = (long)t->priv;
1335 close(rtc_fd);
1338 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1340 struct sigevent ev;
1341 timer_t host_timer;
1342 struct sigaction act;
1344 sigfillset(&act.sa_mask);
1345 act.sa_flags = 0;
1346 act.sa_handler = host_alarm_handler;
1348 sigaction(SIGALRM, &act, NULL);
1350 ev.sigev_value.sival_int = 0;
1351 ev.sigev_notify = SIGEV_SIGNAL;
1352 ev.sigev_signo = SIGALRM;
1354 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1355 perror("timer_create");
1357 /* disable dynticks */
1358 fprintf(stderr, "Dynamic Ticks disabled\n");
1360 return -1;
1363 t->priv = (void *)host_timer;
1365 return 0;
1368 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1370 timer_t host_timer = (timer_t)t->priv;
1372 timer_delete(host_timer);
1375 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1377 timer_t host_timer = (timer_t)t->priv;
1378 struct itimerspec timeout;
1379 int64_t nearest_delta_us = INT64_MAX;
1380 int64_t current_us;
1382 if (!active_timers[QEMU_TIMER_REALTIME] &&
1383 !active_timers[QEMU_TIMER_VIRTUAL])
1384 return;
1386 nearest_delta_us = qemu_next_deadline();
1388 /* check whether a timer is already running */
1389 if (timer_gettime(host_timer, &timeout)) {
1390 perror("gettime");
1391 fprintf(stderr, "Internal timer error: aborting\n");
1392 exit(1);
1394 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1395 if (current_us && current_us <= nearest_delta_us)
1396 return;
1398 timeout.it_interval.tv_sec = 0;
1399 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1400 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1401 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1402 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1403 perror("settime");
1404 fprintf(stderr, "Internal timer error: aborting\n");
1405 exit(1);
1409 #endif /* defined(__linux__) */
1411 static int unix_start_timer(struct qemu_alarm_timer *t)
1413 struct sigaction act;
1414 struct itimerval itv;
1415 int err;
1417 /* timer signal */
1418 sigfillset(&act.sa_mask);
1419 act.sa_flags = 0;
1420 act.sa_handler = host_alarm_handler;
1422 sigaction(SIGALRM, &act, NULL);
1424 itv.it_interval.tv_sec = 0;
1425 /* for i386 kernel 2.6 to get 1 ms */
1426 itv.it_interval.tv_usec = 999;
1427 itv.it_value.tv_sec = 0;
1428 itv.it_value.tv_usec = 10 * 1000;
1430 err = setitimer(ITIMER_REAL, &itv, NULL);
1431 if (err)
1432 return -1;
1434 return 0;
1437 static void unix_stop_timer(struct qemu_alarm_timer *t)
1439 struct itimerval itv;
1441 memset(&itv, 0, sizeof(itv));
1442 setitimer(ITIMER_REAL, &itv, NULL);
1445 #endif /* !defined(_WIN32) */
1447 #ifdef _WIN32
1449 static int win32_start_timer(struct qemu_alarm_timer *t)
1451 TIMECAPS tc;
1452 struct qemu_alarm_win32 *data = t->priv;
1453 UINT flags;
1455 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1456 if (!data->host_alarm) {
1457 perror("Failed CreateEvent");
1458 return -1;
1461 memset(&tc, 0, sizeof(tc));
1462 timeGetDevCaps(&tc, sizeof(tc));
1464 if (data->period < tc.wPeriodMin)
1465 data->period = tc.wPeriodMin;
1467 timeBeginPeriod(data->period);
1469 flags = TIME_CALLBACK_FUNCTION;
1470 if (alarm_has_dynticks(t))
1471 flags |= TIME_ONESHOT;
1472 else
1473 flags |= TIME_PERIODIC;
1475 data->timerId = timeSetEvent(1, // interval (ms)
1476 data->period, // resolution
1477 host_alarm_handler, // function
1478 (DWORD)t, // parameter
1479 flags);
1481 if (!data->timerId) {
1482 perror("Failed to initialize win32 alarm timer");
1484 timeEndPeriod(data->period);
1485 CloseHandle(data->host_alarm);
1486 return -1;
1489 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1491 return 0;
1494 static void win32_stop_timer(struct qemu_alarm_timer *t)
1496 struct qemu_alarm_win32 *data = t->priv;
1498 timeKillEvent(data->timerId);
1499 timeEndPeriod(data->period);
1501 CloseHandle(data->host_alarm);
1504 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1506 struct qemu_alarm_win32 *data = t->priv;
1507 uint64_t nearest_delta_us;
1509 if (!active_timers[QEMU_TIMER_REALTIME] &&
1510 !active_timers[QEMU_TIMER_VIRTUAL])
1511 return;
1513 nearest_delta_us = qemu_next_deadline();
1514 nearest_delta_us /= 1000;
1516 timeKillEvent(data->timerId);
1518 data->timerId = timeSetEvent(1,
1519 data->period,
1520 host_alarm_handler,
1521 (DWORD)t,
1522 TIME_ONESHOT | TIME_PERIODIC);
1524 if (!data->timerId) {
1525 perror("Failed to re-arm win32 alarm timer");
1527 timeEndPeriod(data->period);
1528 CloseHandle(data->host_alarm);
1529 exit(1);
1533 #endif /* _WIN32 */
1535 static void init_timer_alarm(void)
1537 struct qemu_alarm_timer *t;
1538 int i, err = -1;
1540 for (i = 0; alarm_timers[i].name; i++) {
1541 t = &alarm_timers[i];
1543 err = t->start(t);
1544 if (!err)
1545 break;
1548 if (err) {
1549 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1550 fprintf(stderr, "Terminating\n");
1551 exit(1);
1554 alarm_timer = t;
1557 static void quit_timers(void)
1559 alarm_timer->stop(alarm_timer);
1560 alarm_timer = NULL;
1563 /***********************************************************/
1564 /* character device */
1566 static void qemu_chr_event(CharDriverState *s, int event)
1568 if (!s->chr_event)
1569 return;
1570 s->chr_event(s->handler_opaque, event);
1573 static void qemu_chr_reset_bh(void *opaque)
1575 CharDriverState *s = opaque;
1576 qemu_chr_event(s, CHR_EVENT_RESET);
1577 qemu_bh_delete(s->bh);
1578 s->bh = NULL;
1581 void qemu_chr_reset(CharDriverState *s)
1583 if (s->bh == NULL) {
1584 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1585 qemu_bh_schedule(s->bh);
1589 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1591 return s->chr_write(s, buf, len);
1594 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1596 if (!s->chr_ioctl)
1597 return -ENOTSUP;
1598 return s->chr_ioctl(s, cmd, arg);
1601 int qemu_chr_can_read(CharDriverState *s)
1603 if (!s->chr_can_read)
1604 return 0;
1605 return s->chr_can_read(s->handler_opaque);
1608 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1610 s->chr_read(s->handler_opaque, buf, len);
1613 void qemu_chr_accept_input(CharDriverState *s)
1615 if (s->chr_accept_input)
1616 s->chr_accept_input(s);
1619 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1621 char buf[4096];
1622 va_list ap;
1623 va_start(ap, fmt);
1624 vsnprintf(buf, sizeof(buf), fmt, ap);
1625 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1626 va_end(ap);
1629 void qemu_chr_send_event(CharDriverState *s, int event)
1631 if (s->chr_send_event)
1632 s->chr_send_event(s, event);
1635 void qemu_chr_add_handlers(CharDriverState *s,
1636 IOCanRWHandler *fd_can_read,
1637 IOReadHandler *fd_read,
1638 IOEventHandler *fd_event,
1639 void *opaque)
1641 s->chr_can_read = fd_can_read;
1642 s->chr_read = fd_read;
1643 s->chr_event = fd_event;
1644 s->handler_opaque = opaque;
1645 if (s->chr_update_read_handler)
1646 s->chr_update_read_handler(s);
1649 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1651 return len;
1654 static CharDriverState *qemu_chr_open_null(void)
1656 CharDriverState *chr;
1658 chr = qemu_mallocz(sizeof(CharDriverState));
1659 if (!chr)
1660 return NULL;
1661 chr->chr_write = null_chr_write;
1662 return chr;
1665 /* MUX driver for serial I/O splitting */
1666 static int term_timestamps;
1667 static int64_t term_timestamps_start;
1668 #define MAX_MUX 4
1669 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1670 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1671 typedef struct {
1672 IOCanRWHandler *chr_can_read[MAX_MUX];
1673 IOReadHandler *chr_read[MAX_MUX];
1674 IOEventHandler *chr_event[MAX_MUX];
1675 void *ext_opaque[MAX_MUX];
1676 CharDriverState *drv;
1677 unsigned char buffer[MUX_BUFFER_SIZE];
1678 int prod;
1679 int cons;
1680 int mux_cnt;
1681 int term_got_escape;
1682 int max_size;
1683 } MuxDriver;
1686 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1688 MuxDriver *d = chr->opaque;
1689 int ret;
1690 if (!term_timestamps) {
1691 ret = d->drv->chr_write(d->drv, buf, len);
1692 } else {
1693 int i;
1695 ret = 0;
1696 for(i = 0; i < len; i++) {
1697 ret += d->drv->chr_write(d->drv, buf+i, 1);
1698 if (buf[i] == '\n') {
1699 char buf1[64];
1700 int64_t ti;
1701 int secs;
1703 ti = get_clock();
1704 if (term_timestamps_start == -1)
1705 term_timestamps_start = ti;
1706 ti -= term_timestamps_start;
1707 secs = ti / 1000000000;
1708 snprintf(buf1, sizeof(buf1),
1709 "[%02d:%02d:%02d.%03d] ",
1710 secs / 3600,
1711 (secs / 60) % 60,
1712 secs % 60,
1713 (int)((ti / 1000000) % 1000));
1714 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1718 return ret;
1721 static char *mux_help[] = {
1722 "% h print this help\n\r",
1723 "% x exit emulator\n\r",
1724 "% s save disk data back to file (if -snapshot)\n\r",
1725 "% t toggle console timestamps\n\r"
1726 "% b send break (magic sysrq)\n\r",
1727 "% c switch between console and monitor\n\r",
1728 "% % sends %\n\r",
1729 NULL
1732 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1733 static void mux_print_help(CharDriverState *chr)
1735 int i, j;
1736 char ebuf[15] = "Escape-Char";
1737 char cbuf[50] = "\n\r";
1739 if (term_escape_char > 0 && term_escape_char < 26) {
1740 sprintf(cbuf,"\n\r");
1741 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1742 } else {
1743 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1744 term_escape_char);
1746 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1747 for (i = 0; mux_help[i] != NULL; i++) {
1748 for (j=0; mux_help[i][j] != '\0'; j++) {
1749 if (mux_help[i][j] == '%')
1750 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1751 else
1752 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1757 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1759 if (d->term_got_escape) {
1760 d->term_got_escape = 0;
1761 if (ch == term_escape_char)
1762 goto send_char;
1763 switch(ch) {
1764 case '?':
1765 case 'h':
1766 mux_print_help(chr);
1767 break;
1768 case 'x':
1770 char *term = "QEMU: Terminated\n\r";
1771 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1772 exit(0);
1773 break;
1775 case 's':
1777 int i;
1778 for (i = 0; i < nb_drives; i++) {
1779 bdrv_commit(drives_table[i].bdrv);
1782 break;
1783 case 'b':
1784 qemu_chr_event(chr, CHR_EVENT_BREAK);
1785 break;
1786 case 'c':
1787 /* Switch to the next registered device */
1788 chr->focus++;
1789 if (chr->focus >= d->mux_cnt)
1790 chr->focus = 0;
1791 break;
1792 case 't':
1793 term_timestamps = !term_timestamps;
1794 term_timestamps_start = -1;
1795 break;
1797 } else if (ch == term_escape_char) {
1798 d->term_got_escape = 1;
1799 } else {
1800 send_char:
1801 return 1;
1803 return 0;
1806 static void mux_chr_accept_input(CharDriverState *chr)
1808 int m = chr->focus;
1809 MuxDriver *d = chr->opaque;
1811 while (d->prod != d->cons &&
1812 d->chr_can_read[m] &&
1813 d->chr_can_read[m](d->ext_opaque[m])) {
1814 d->chr_read[m](d->ext_opaque[m],
1815 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1819 static int mux_chr_can_read(void *opaque)
1821 CharDriverState *chr = opaque;
1822 MuxDriver *d = chr->opaque;
1824 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1825 return 1;
1826 if (d->chr_can_read[chr->focus])
1827 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1828 return 0;
1831 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1833 CharDriverState *chr = opaque;
1834 MuxDriver *d = chr->opaque;
1835 int m = chr->focus;
1836 int i;
1838 mux_chr_accept_input (opaque);
1840 for(i = 0; i < size; i++)
1841 if (mux_proc_byte(chr, d, buf[i])) {
1842 if (d->prod == d->cons &&
1843 d->chr_can_read[m] &&
1844 d->chr_can_read[m](d->ext_opaque[m]))
1845 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1846 else
1847 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1851 static void mux_chr_event(void *opaque, int event)
1853 CharDriverState *chr = opaque;
1854 MuxDriver *d = chr->opaque;
1855 int i;
1857 /* Send the event to all registered listeners */
1858 for (i = 0; i < d->mux_cnt; i++)
1859 if (d->chr_event[i])
1860 d->chr_event[i](d->ext_opaque[i], event);
1863 static void mux_chr_update_read_handler(CharDriverState *chr)
1865 MuxDriver *d = chr->opaque;
1867 if (d->mux_cnt >= MAX_MUX) {
1868 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1869 return;
1871 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1872 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1873 d->chr_read[d->mux_cnt] = chr->chr_read;
1874 d->chr_event[d->mux_cnt] = chr->chr_event;
1875 /* Fix up the real driver with mux routines */
1876 if (d->mux_cnt == 0) {
1877 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1878 mux_chr_event, chr);
1880 chr->focus = d->mux_cnt;
1881 d->mux_cnt++;
1884 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1886 CharDriverState *chr;
1887 MuxDriver *d;
1889 chr = qemu_mallocz(sizeof(CharDriverState));
1890 if (!chr)
1891 return NULL;
1892 d = qemu_mallocz(sizeof(MuxDriver));
1893 if (!d) {
1894 free(chr);
1895 return NULL;
1898 chr->opaque = d;
1899 d->drv = drv;
1900 chr->focus = -1;
1901 chr->chr_write = mux_chr_write;
1902 chr->chr_update_read_handler = mux_chr_update_read_handler;
1903 chr->chr_accept_input = mux_chr_accept_input;
1904 return chr;
1908 #ifdef _WIN32
1910 static void socket_cleanup(void)
1912 WSACleanup();
1915 static int socket_init(void)
1917 WSADATA Data;
1918 int ret, err;
1920 ret = WSAStartup(MAKEWORD(2,2), &Data);
1921 if (ret != 0) {
1922 err = WSAGetLastError();
1923 fprintf(stderr, "WSAStartup: %d\n", err);
1924 return -1;
1926 atexit(socket_cleanup);
1927 return 0;
1930 static int send_all(int fd, const uint8_t *buf, int len1)
1932 int ret, len;
1934 len = len1;
1935 while (len > 0) {
1936 ret = send(fd, buf, len, 0);
1937 if (ret < 0) {
1938 int errno;
1939 errno = WSAGetLastError();
1940 if (errno != WSAEWOULDBLOCK) {
1941 return -1;
1943 } else if (ret == 0) {
1944 break;
1945 } else {
1946 buf += ret;
1947 len -= ret;
1950 return len1 - len;
1953 void socket_set_nonblock(int fd)
1955 unsigned long opt = 1;
1956 ioctlsocket(fd, FIONBIO, &opt);
1959 #else
1961 static int unix_write(int fd, const uint8_t *buf, int len1)
1963 int ret, len;
1965 len = len1;
1966 while (len > 0) {
1967 ret = write(fd, buf, len);
1968 if (ret < 0) {
1969 if (errno != EINTR && errno != EAGAIN)
1970 return -1;
1971 } else if (ret == 0) {
1972 break;
1973 } else {
1974 buf += ret;
1975 len -= ret;
1978 return len1 - len;
1981 static inline int send_all(int fd, const uint8_t *buf, int len1)
1983 return unix_write(fd, buf, len1);
1986 void socket_set_nonblock(int fd)
1988 fcntl(fd, F_SETFL, O_NONBLOCK);
1990 #endif /* !_WIN32 */
1992 #ifndef _WIN32
1994 typedef struct {
1995 int fd_in, fd_out;
1996 int max_size;
1997 } FDCharDriver;
1999 #define STDIO_MAX_CLIENTS 1
2000 static int stdio_nb_clients = 0;
2002 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2004 FDCharDriver *s = chr->opaque;
2005 return unix_write(s->fd_out, buf, len);
2008 static int fd_chr_read_poll(void *opaque)
2010 CharDriverState *chr = opaque;
2011 FDCharDriver *s = chr->opaque;
2013 s->max_size = qemu_chr_can_read(chr);
2014 return s->max_size;
2017 static void fd_chr_read(void *opaque)
2019 CharDriverState *chr = opaque;
2020 FDCharDriver *s = chr->opaque;
2021 int size, len;
2022 uint8_t buf[1024];
2024 len = sizeof(buf);
2025 if (len > s->max_size)
2026 len = s->max_size;
2027 if (len == 0)
2028 return;
2029 size = read(s->fd_in, buf, len);
2030 if (size == 0) {
2031 /* FD has been closed. Remove it from the active list. */
2032 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2033 return;
2035 if (size > 0) {
2036 qemu_chr_read(chr, buf, size);
2040 static void fd_chr_update_read_handler(CharDriverState *chr)
2042 FDCharDriver *s = chr->opaque;
2044 if (s->fd_in >= 0) {
2045 if (nographic && s->fd_in == 0) {
2046 } else {
2047 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2048 fd_chr_read, NULL, chr);
2053 /* open a character device to a unix fd */
2054 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2056 CharDriverState *chr;
2057 FDCharDriver *s;
2059 chr = qemu_mallocz(sizeof(CharDriverState));
2060 if (!chr)
2061 return NULL;
2062 s = qemu_mallocz(sizeof(FDCharDriver));
2063 if (!s) {
2064 free(chr);
2065 return NULL;
2067 s->fd_in = fd_in;
2068 s->fd_out = fd_out;
2069 chr->opaque = s;
2070 chr->chr_write = fd_chr_write;
2071 chr->chr_update_read_handler = fd_chr_update_read_handler;
2073 qemu_chr_reset(chr);
2075 return chr;
2078 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2080 int fd_out;
2082 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2083 if (fd_out < 0)
2084 return NULL;
2085 return qemu_chr_open_fd(-1, fd_out);
2088 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2090 int fd_in, fd_out;
2091 char filename_in[256], filename_out[256];
2093 snprintf(filename_in, 256, "%s.in", filename);
2094 snprintf(filename_out, 256, "%s.out", filename);
2095 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2096 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2097 if (fd_in < 0 || fd_out < 0) {
2098 if (fd_in >= 0)
2099 close(fd_in);
2100 if (fd_out >= 0)
2101 close(fd_out);
2102 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2103 if (fd_in < 0)
2104 return NULL;
2106 return qemu_chr_open_fd(fd_in, fd_out);
2110 /* for STDIO, we handle the case where several clients use it
2111 (nographic mode) */
2113 #define TERM_FIFO_MAX_SIZE 1
2115 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2116 static int term_fifo_size;
2118 static int stdio_read_poll(void *opaque)
2120 CharDriverState *chr = opaque;
2122 /* try to flush the queue if needed */
2123 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2124 qemu_chr_read(chr, term_fifo, 1);
2125 term_fifo_size = 0;
2127 /* see if we can absorb more chars */
2128 if (term_fifo_size == 0)
2129 return 1;
2130 else
2131 return 0;
2134 static void stdio_read(void *opaque)
2136 int size;
2137 uint8_t buf[1];
2138 CharDriverState *chr = opaque;
2140 size = read(0, buf, 1);
2141 if (size == 0) {
2142 /* stdin has been closed. Remove it from the active list. */
2143 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2144 return;
2146 if (size > 0) {
2147 if (qemu_chr_can_read(chr) > 0) {
2148 qemu_chr_read(chr, buf, 1);
2149 } else if (term_fifo_size == 0) {
2150 term_fifo[term_fifo_size++] = buf[0];
2155 /* init terminal so that we can grab keys */
2156 static struct termios oldtty;
2157 static int old_fd0_flags;
2159 static void term_exit(void)
2161 tcsetattr (0, TCSANOW, &oldtty);
2162 fcntl(0, F_SETFL, old_fd0_flags);
2165 static void term_init(void)
2167 struct termios tty;
2169 tcgetattr (0, &tty);
2170 oldtty = tty;
2171 old_fd0_flags = fcntl(0, F_GETFL);
2173 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2174 |INLCR|IGNCR|ICRNL|IXON);
2175 tty.c_oflag |= OPOST;
2176 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2177 /* if graphical mode, we allow Ctrl-C handling */
2178 if (nographic)
2179 tty.c_lflag &= ~ISIG;
2180 tty.c_cflag &= ~(CSIZE|PARENB);
2181 tty.c_cflag |= CS8;
2182 tty.c_cc[VMIN] = 1;
2183 tty.c_cc[VTIME] = 0;
2185 tcsetattr (0, TCSANOW, &tty);
2187 atexit(term_exit);
2189 fcntl(0, F_SETFL, O_NONBLOCK);
2192 static CharDriverState *qemu_chr_open_stdio(void)
2194 CharDriverState *chr;
2196 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2197 return NULL;
2198 chr = qemu_chr_open_fd(0, 1);
2199 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2200 stdio_nb_clients++;
2201 term_init();
2203 return chr;
2206 #if defined(__linux__) || defined(__sun__)
2207 static CharDriverState *qemu_chr_open_pty(void)
2209 struct termios tty;
2210 char slave_name[1024];
2211 int master_fd, slave_fd;
2213 #if defined(__linux__)
2214 /* Not satisfying */
2215 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2216 return NULL;
2218 #endif
2220 /* Disabling local echo and line-buffered output */
2221 tcgetattr (master_fd, &tty);
2222 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2223 tty.c_cc[VMIN] = 1;
2224 tty.c_cc[VTIME] = 0;
2225 tcsetattr (master_fd, TCSAFLUSH, &tty);
2227 fprintf(stderr, "char device redirected to %s\n", slave_name);
2228 return qemu_chr_open_fd(master_fd, master_fd);
2231 static void tty_serial_init(int fd, int speed,
2232 int parity, int data_bits, int stop_bits)
2234 struct termios tty;
2235 speed_t spd;
2237 #if 0
2238 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2239 speed, parity, data_bits, stop_bits);
2240 #endif
2241 tcgetattr (fd, &tty);
2243 switch(speed) {
2244 case 50:
2245 spd = B50;
2246 break;
2247 case 75:
2248 spd = B75;
2249 break;
2250 case 300:
2251 spd = B300;
2252 break;
2253 case 600:
2254 spd = B600;
2255 break;
2256 case 1200:
2257 spd = B1200;
2258 break;
2259 case 2400:
2260 spd = B2400;
2261 break;
2262 case 4800:
2263 spd = B4800;
2264 break;
2265 case 9600:
2266 spd = B9600;
2267 break;
2268 case 19200:
2269 spd = B19200;
2270 break;
2271 case 38400:
2272 spd = B38400;
2273 break;
2274 case 57600:
2275 spd = B57600;
2276 break;
2277 default:
2278 case 115200:
2279 spd = B115200;
2280 break;
2283 cfsetispeed(&tty, spd);
2284 cfsetospeed(&tty, spd);
2286 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2287 |INLCR|IGNCR|ICRNL|IXON);
2288 tty.c_oflag |= OPOST;
2289 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2290 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2291 switch(data_bits) {
2292 default:
2293 case 8:
2294 tty.c_cflag |= CS8;
2295 break;
2296 case 7:
2297 tty.c_cflag |= CS7;
2298 break;
2299 case 6:
2300 tty.c_cflag |= CS6;
2301 break;
2302 case 5:
2303 tty.c_cflag |= CS5;
2304 break;
2306 switch(parity) {
2307 default:
2308 case 'N':
2309 break;
2310 case 'E':
2311 tty.c_cflag |= PARENB;
2312 break;
2313 case 'O':
2314 tty.c_cflag |= PARENB | PARODD;
2315 break;
2317 if (stop_bits == 2)
2318 tty.c_cflag |= CSTOPB;
2320 tcsetattr (fd, TCSANOW, &tty);
2323 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2325 FDCharDriver *s = chr->opaque;
2327 switch(cmd) {
2328 case CHR_IOCTL_SERIAL_SET_PARAMS:
2330 QEMUSerialSetParams *ssp = arg;
2331 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2332 ssp->data_bits, ssp->stop_bits);
2334 break;
2335 case CHR_IOCTL_SERIAL_SET_BREAK:
2337 int enable = *(int *)arg;
2338 if (enable)
2339 tcsendbreak(s->fd_in, 1);
2341 break;
2342 default:
2343 return -ENOTSUP;
2345 return 0;
2348 static CharDriverState *qemu_chr_open_tty(const char *filename)
2350 CharDriverState *chr;
2351 int fd;
2353 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2354 fcntl(fd, F_SETFL, O_NONBLOCK);
2355 tty_serial_init(fd, 115200, 'N', 8, 1);
2356 chr = qemu_chr_open_fd(fd, fd);
2357 if (!chr) {
2358 close(fd);
2359 return NULL;
2361 chr->chr_ioctl = tty_serial_ioctl;
2362 qemu_chr_reset(chr);
2363 return chr;
2365 #else /* ! __linux__ && ! __sun__ */
2366 static CharDriverState *qemu_chr_open_pty(void)
2368 return NULL;
2370 #endif /* __linux__ || __sun__ */
2372 #if defined(__linux__)
2373 typedef struct {
2374 int fd;
2375 int mode;
2376 } ParallelCharDriver;
2378 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2380 if (s->mode != mode) {
2381 int m = mode;
2382 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2383 return 0;
2384 s->mode = mode;
2386 return 1;
2389 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2391 ParallelCharDriver *drv = chr->opaque;
2392 int fd = drv->fd;
2393 uint8_t b;
2395 switch(cmd) {
2396 case CHR_IOCTL_PP_READ_DATA:
2397 if (ioctl(fd, PPRDATA, &b) < 0)
2398 return -ENOTSUP;
2399 *(uint8_t *)arg = b;
2400 break;
2401 case CHR_IOCTL_PP_WRITE_DATA:
2402 b = *(uint8_t *)arg;
2403 if (ioctl(fd, PPWDATA, &b) < 0)
2404 return -ENOTSUP;
2405 break;
2406 case CHR_IOCTL_PP_READ_CONTROL:
2407 if (ioctl(fd, PPRCONTROL, &b) < 0)
2408 return -ENOTSUP;
2409 /* Linux gives only the lowest bits, and no way to know data
2410 direction! For better compatibility set the fixed upper
2411 bits. */
2412 *(uint8_t *)arg = b | 0xc0;
2413 break;
2414 case CHR_IOCTL_PP_WRITE_CONTROL:
2415 b = *(uint8_t *)arg;
2416 if (ioctl(fd, PPWCONTROL, &b) < 0)
2417 return -ENOTSUP;
2418 break;
2419 case CHR_IOCTL_PP_READ_STATUS:
2420 if (ioctl(fd, PPRSTATUS, &b) < 0)
2421 return -ENOTSUP;
2422 *(uint8_t *)arg = b;
2423 break;
2424 case CHR_IOCTL_PP_EPP_READ_ADDR:
2425 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2426 struct ParallelIOArg *parg = arg;
2427 int n = read(fd, parg->buffer, parg->count);
2428 if (n != parg->count) {
2429 return -EIO;
2432 break;
2433 case CHR_IOCTL_PP_EPP_READ:
2434 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2435 struct ParallelIOArg *parg = arg;
2436 int n = read(fd, parg->buffer, parg->count);
2437 if (n != parg->count) {
2438 return -EIO;
2441 break;
2442 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2443 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2444 struct ParallelIOArg *parg = arg;
2445 int n = write(fd, parg->buffer, parg->count);
2446 if (n != parg->count) {
2447 return -EIO;
2450 break;
2451 case CHR_IOCTL_PP_EPP_WRITE:
2452 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2453 struct ParallelIOArg *parg = arg;
2454 int n = write(fd, parg->buffer, parg->count);
2455 if (n != parg->count) {
2456 return -EIO;
2459 break;
2460 default:
2461 return -ENOTSUP;
2463 return 0;
2466 static void pp_close(CharDriverState *chr)
2468 ParallelCharDriver *drv = chr->opaque;
2469 int fd = drv->fd;
2471 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2472 ioctl(fd, PPRELEASE);
2473 close(fd);
2474 qemu_free(drv);
2477 static CharDriverState *qemu_chr_open_pp(const char *filename)
2479 CharDriverState *chr;
2480 ParallelCharDriver *drv;
2481 int fd;
2483 TFR(fd = open(filename, O_RDWR));
2484 if (fd < 0)
2485 return NULL;
2487 if (ioctl(fd, PPCLAIM) < 0) {
2488 close(fd);
2489 return NULL;
2492 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2493 if (!drv) {
2494 close(fd);
2495 return NULL;
2497 drv->fd = fd;
2498 drv->mode = IEEE1284_MODE_COMPAT;
2500 chr = qemu_mallocz(sizeof(CharDriverState));
2501 if (!chr) {
2502 qemu_free(drv);
2503 close(fd);
2504 return NULL;
2506 chr->chr_write = null_chr_write;
2507 chr->chr_ioctl = pp_ioctl;
2508 chr->chr_close = pp_close;
2509 chr->opaque = drv;
2511 qemu_chr_reset(chr);
2513 return chr;
2515 #endif /* __linux__ */
2517 #else /* _WIN32 */
2519 typedef struct {
2520 int max_size;
2521 HANDLE hcom, hrecv, hsend;
2522 OVERLAPPED orecv, osend;
2523 BOOL fpipe;
2524 DWORD len;
2525 } WinCharState;
2527 #define NSENDBUF 2048
2528 #define NRECVBUF 2048
2529 #define MAXCONNECT 1
2530 #define NTIMEOUT 5000
2532 static int win_chr_poll(void *opaque);
2533 static int win_chr_pipe_poll(void *opaque);
2535 static void win_chr_close(CharDriverState *chr)
2537 WinCharState *s = chr->opaque;
2539 if (s->hsend) {
2540 CloseHandle(s->hsend);
2541 s->hsend = NULL;
2543 if (s->hrecv) {
2544 CloseHandle(s->hrecv);
2545 s->hrecv = NULL;
2547 if (s->hcom) {
2548 CloseHandle(s->hcom);
2549 s->hcom = NULL;
2551 if (s->fpipe)
2552 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2553 else
2554 qemu_del_polling_cb(win_chr_poll, chr);
2557 static int win_chr_init(CharDriverState *chr, const char *filename)
2559 WinCharState *s = chr->opaque;
2560 COMMCONFIG comcfg;
2561 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2562 COMSTAT comstat;
2563 DWORD size;
2564 DWORD err;
2566 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2567 if (!s->hsend) {
2568 fprintf(stderr, "Failed CreateEvent\n");
2569 goto fail;
2571 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2572 if (!s->hrecv) {
2573 fprintf(stderr, "Failed CreateEvent\n");
2574 goto fail;
2577 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2578 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2579 if (s->hcom == INVALID_HANDLE_VALUE) {
2580 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2581 s->hcom = NULL;
2582 goto fail;
2585 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2586 fprintf(stderr, "Failed SetupComm\n");
2587 goto fail;
2590 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2591 size = sizeof(COMMCONFIG);
2592 GetDefaultCommConfig(filename, &comcfg, &size);
2593 comcfg.dcb.DCBlength = sizeof(DCB);
2594 CommConfigDialog(filename, NULL, &comcfg);
2596 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2597 fprintf(stderr, "Failed SetCommState\n");
2598 goto fail;
2601 if (!SetCommMask(s->hcom, EV_ERR)) {
2602 fprintf(stderr, "Failed SetCommMask\n");
2603 goto fail;
2606 cto.ReadIntervalTimeout = MAXDWORD;
2607 if (!SetCommTimeouts(s->hcom, &cto)) {
2608 fprintf(stderr, "Failed SetCommTimeouts\n");
2609 goto fail;
2612 if (!ClearCommError(s->hcom, &err, &comstat)) {
2613 fprintf(stderr, "Failed ClearCommError\n");
2614 goto fail;
2616 qemu_add_polling_cb(win_chr_poll, chr);
2617 return 0;
2619 fail:
2620 win_chr_close(chr);
2621 return -1;
2624 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2626 WinCharState *s = chr->opaque;
2627 DWORD len, ret, size, err;
2629 len = len1;
2630 ZeroMemory(&s->osend, sizeof(s->osend));
2631 s->osend.hEvent = s->hsend;
2632 while (len > 0) {
2633 if (s->hsend)
2634 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2635 else
2636 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2637 if (!ret) {
2638 err = GetLastError();
2639 if (err == ERROR_IO_PENDING) {
2640 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2641 if (ret) {
2642 buf += size;
2643 len -= size;
2644 } else {
2645 break;
2647 } else {
2648 break;
2650 } else {
2651 buf += size;
2652 len -= size;
2655 return len1 - len;
2658 static int win_chr_read_poll(CharDriverState *chr)
2660 WinCharState *s = chr->opaque;
2662 s->max_size = qemu_chr_can_read(chr);
2663 return s->max_size;
2666 static void win_chr_readfile(CharDriverState *chr)
2668 WinCharState *s = chr->opaque;
2669 int ret, err;
2670 uint8_t buf[1024];
2671 DWORD size;
2673 ZeroMemory(&s->orecv, sizeof(s->orecv));
2674 s->orecv.hEvent = s->hrecv;
2675 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2676 if (!ret) {
2677 err = GetLastError();
2678 if (err == ERROR_IO_PENDING) {
2679 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2683 if (size > 0) {
2684 qemu_chr_read(chr, buf, size);
2688 static void win_chr_read(CharDriverState *chr)
2690 WinCharState *s = chr->opaque;
2692 if (s->len > s->max_size)
2693 s->len = s->max_size;
2694 if (s->len == 0)
2695 return;
2697 win_chr_readfile(chr);
2700 static int win_chr_poll(void *opaque)
2702 CharDriverState *chr = opaque;
2703 WinCharState *s = chr->opaque;
2704 COMSTAT status;
2705 DWORD comerr;
2707 ClearCommError(s->hcom, &comerr, &status);
2708 if (status.cbInQue > 0) {
2709 s->len = status.cbInQue;
2710 win_chr_read_poll(chr);
2711 win_chr_read(chr);
2712 return 1;
2714 return 0;
2717 static CharDriverState *qemu_chr_open_win(const char *filename)
2719 CharDriverState *chr;
2720 WinCharState *s;
2722 chr = qemu_mallocz(sizeof(CharDriverState));
2723 if (!chr)
2724 return NULL;
2725 s = qemu_mallocz(sizeof(WinCharState));
2726 if (!s) {
2727 free(chr);
2728 return NULL;
2730 chr->opaque = s;
2731 chr->chr_write = win_chr_write;
2732 chr->chr_close = win_chr_close;
2734 if (win_chr_init(chr, filename) < 0) {
2735 free(s);
2736 free(chr);
2737 return NULL;
2739 qemu_chr_reset(chr);
2740 return chr;
2743 static int win_chr_pipe_poll(void *opaque)
2745 CharDriverState *chr = opaque;
2746 WinCharState *s = chr->opaque;
2747 DWORD size;
2749 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2750 if (size > 0) {
2751 s->len = size;
2752 win_chr_read_poll(chr);
2753 win_chr_read(chr);
2754 return 1;
2756 return 0;
2759 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2761 WinCharState *s = chr->opaque;
2762 OVERLAPPED ov;
2763 int ret;
2764 DWORD size;
2765 char openname[256];
2767 s->fpipe = TRUE;
2769 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2770 if (!s->hsend) {
2771 fprintf(stderr, "Failed CreateEvent\n");
2772 goto fail;
2774 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2775 if (!s->hrecv) {
2776 fprintf(stderr, "Failed CreateEvent\n");
2777 goto fail;
2780 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2781 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2782 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2783 PIPE_WAIT,
2784 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2785 if (s->hcom == INVALID_HANDLE_VALUE) {
2786 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2787 s->hcom = NULL;
2788 goto fail;
2791 ZeroMemory(&ov, sizeof(ov));
2792 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2793 ret = ConnectNamedPipe(s->hcom, &ov);
2794 if (ret) {
2795 fprintf(stderr, "Failed ConnectNamedPipe\n");
2796 goto fail;
2799 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2800 if (!ret) {
2801 fprintf(stderr, "Failed GetOverlappedResult\n");
2802 if (ov.hEvent) {
2803 CloseHandle(ov.hEvent);
2804 ov.hEvent = NULL;
2806 goto fail;
2809 if (ov.hEvent) {
2810 CloseHandle(ov.hEvent);
2811 ov.hEvent = NULL;
2813 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2814 return 0;
2816 fail:
2817 win_chr_close(chr);
2818 return -1;
2822 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2824 CharDriverState *chr;
2825 WinCharState *s;
2827 chr = qemu_mallocz(sizeof(CharDriverState));
2828 if (!chr)
2829 return NULL;
2830 s = qemu_mallocz(sizeof(WinCharState));
2831 if (!s) {
2832 free(chr);
2833 return NULL;
2835 chr->opaque = s;
2836 chr->chr_write = win_chr_write;
2837 chr->chr_close = win_chr_close;
2839 if (win_chr_pipe_init(chr, filename) < 0) {
2840 free(s);
2841 free(chr);
2842 return NULL;
2844 qemu_chr_reset(chr);
2845 return chr;
2848 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2850 CharDriverState *chr;
2851 WinCharState *s;
2853 chr = qemu_mallocz(sizeof(CharDriverState));
2854 if (!chr)
2855 return NULL;
2856 s = qemu_mallocz(sizeof(WinCharState));
2857 if (!s) {
2858 free(chr);
2859 return NULL;
2861 s->hcom = fd_out;
2862 chr->opaque = s;
2863 chr->chr_write = win_chr_write;
2864 qemu_chr_reset(chr);
2865 return chr;
2868 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2870 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2873 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2875 HANDLE fd_out;
2877 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2878 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2879 if (fd_out == INVALID_HANDLE_VALUE)
2880 return NULL;
2882 return qemu_chr_open_win_file(fd_out);
2884 #endif /* !_WIN32 */
2886 /***********************************************************/
2887 /* UDP Net console */
2889 typedef struct {
2890 int fd;
2891 struct sockaddr_in daddr;
2892 uint8_t buf[1024];
2893 int bufcnt;
2894 int bufptr;
2895 int max_size;
2896 } NetCharDriver;
2898 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2900 NetCharDriver *s = chr->opaque;
2902 return sendto(s->fd, buf, len, 0,
2903 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2906 static int udp_chr_read_poll(void *opaque)
2908 CharDriverState *chr = opaque;
2909 NetCharDriver *s = chr->opaque;
2911 s->max_size = qemu_chr_can_read(chr);
2913 /* If there were any stray characters in the queue process them
2914 * first
2916 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2917 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2918 s->bufptr++;
2919 s->max_size = qemu_chr_can_read(chr);
2921 return s->max_size;
2924 static void udp_chr_read(void *opaque)
2926 CharDriverState *chr = opaque;
2927 NetCharDriver *s = chr->opaque;
2929 if (s->max_size == 0)
2930 return;
2931 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2932 s->bufptr = s->bufcnt;
2933 if (s->bufcnt <= 0)
2934 return;
2936 s->bufptr = 0;
2937 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2938 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2939 s->bufptr++;
2940 s->max_size = qemu_chr_can_read(chr);
2944 static void udp_chr_update_read_handler(CharDriverState *chr)
2946 NetCharDriver *s = chr->opaque;
2948 if (s->fd >= 0) {
2949 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2950 udp_chr_read, NULL, chr);
2954 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2955 #ifndef _WIN32
2956 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2957 #endif
2958 int parse_host_src_port(struct sockaddr_in *haddr,
2959 struct sockaddr_in *saddr,
2960 const char *str);
2962 static CharDriverState *qemu_chr_open_udp(const char *def)
2964 CharDriverState *chr = NULL;
2965 NetCharDriver *s = NULL;
2966 int fd = -1;
2967 struct sockaddr_in saddr;
2969 chr = qemu_mallocz(sizeof(CharDriverState));
2970 if (!chr)
2971 goto return_err;
2972 s = qemu_mallocz(sizeof(NetCharDriver));
2973 if (!s)
2974 goto return_err;
2976 fd = socket(PF_INET, SOCK_DGRAM, 0);
2977 if (fd < 0) {
2978 perror("socket(PF_INET, SOCK_DGRAM)");
2979 goto return_err;
2982 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2983 printf("Could not parse: %s\n", def);
2984 goto return_err;
2987 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2989 perror("bind");
2990 goto return_err;
2993 s->fd = fd;
2994 s->bufcnt = 0;
2995 s->bufptr = 0;
2996 chr->opaque = s;
2997 chr->chr_write = udp_chr_write;
2998 chr->chr_update_read_handler = udp_chr_update_read_handler;
2999 return chr;
3001 return_err:
3002 if (chr)
3003 free(chr);
3004 if (s)
3005 free(s);
3006 if (fd >= 0)
3007 closesocket(fd);
3008 return NULL;
3011 /***********************************************************/
3012 /* TCP Net console */
3014 typedef struct {
3015 int fd, listen_fd;
3016 int connected;
3017 int max_size;
3018 int do_telnetopt;
3019 int do_nodelay;
3020 int is_unix;
3021 } TCPCharDriver;
3023 static void tcp_chr_accept(void *opaque);
3025 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3027 TCPCharDriver *s = chr->opaque;
3028 if (s->connected) {
3029 return send_all(s->fd, buf, len);
3030 } else {
3031 /* XXX: indicate an error ? */
3032 return len;
3036 static int tcp_chr_read_poll(void *opaque)
3038 CharDriverState *chr = opaque;
3039 TCPCharDriver *s = chr->opaque;
3040 if (!s->connected)
3041 return 0;
3042 s->max_size = qemu_chr_can_read(chr);
3043 return s->max_size;
3046 #define IAC 255
3047 #define IAC_BREAK 243
3048 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3049 TCPCharDriver *s,
3050 uint8_t *buf, int *size)
3052 /* Handle any telnet client's basic IAC options to satisfy char by
3053 * char mode with no echo. All IAC options will be removed from
3054 * the buf and the do_telnetopt variable will be used to track the
3055 * state of the width of the IAC information.
3057 * IAC commands come in sets of 3 bytes with the exception of the
3058 * "IAC BREAK" command and the double IAC.
3061 int i;
3062 int j = 0;
3064 for (i = 0; i < *size; i++) {
3065 if (s->do_telnetopt > 1) {
3066 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3067 /* Double IAC means send an IAC */
3068 if (j != i)
3069 buf[j] = buf[i];
3070 j++;
3071 s->do_telnetopt = 1;
3072 } else {
3073 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3074 /* Handle IAC break commands by sending a serial break */
3075 qemu_chr_event(chr, CHR_EVENT_BREAK);
3076 s->do_telnetopt++;
3078 s->do_telnetopt++;
3080 if (s->do_telnetopt >= 4) {
3081 s->do_telnetopt = 1;
3083 } else {
3084 if ((unsigned char)buf[i] == IAC) {
3085 s->do_telnetopt = 2;
3086 } else {
3087 if (j != i)
3088 buf[j] = buf[i];
3089 j++;
3093 *size = j;
3096 static void tcp_chr_read(void *opaque)
3098 CharDriverState *chr = opaque;
3099 TCPCharDriver *s = chr->opaque;
3100 uint8_t buf[1024];
3101 int len, size;
3103 if (!s->connected || s->max_size <= 0)
3104 return;
3105 len = sizeof(buf);
3106 if (len > s->max_size)
3107 len = s->max_size;
3108 size = recv(s->fd, buf, len, 0);
3109 if (size == 0) {
3110 /* connection closed */
3111 s->connected = 0;
3112 if (s->listen_fd >= 0) {
3113 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3115 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3116 closesocket(s->fd);
3117 s->fd = -1;
3118 } else if (size > 0) {
3119 if (s->do_telnetopt)
3120 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3121 if (size > 0)
3122 qemu_chr_read(chr, buf, size);
3126 static void tcp_chr_connect(void *opaque)
3128 CharDriverState *chr = opaque;
3129 TCPCharDriver *s = chr->opaque;
3131 s->connected = 1;
3132 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3133 tcp_chr_read, NULL, chr);
3134 qemu_chr_reset(chr);
3137 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3138 static void tcp_chr_telnet_init(int fd)
3140 char buf[3];
3141 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3142 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3143 send(fd, (char *)buf, 3, 0);
3144 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3145 send(fd, (char *)buf, 3, 0);
3146 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3147 send(fd, (char *)buf, 3, 0);
3148 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3149 send(fd, (char *)buf, 3, 0);
3152 static void socket_set_nodelay(int fd)
3154 int val = 1;
3155 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3158 static void tcp_chr_accept(void *opaque)
3160 CharDriverState *chr = opaque;
3161 TCPCharDriver *s = chr->opaque;
3162 struct sockaddr_in saddr;
3163 #ifndef _WIN32
3164 struct sockaddr_un uaddr;
3165 #endif
3166 struct sockaddr *addr;
3167 socklen_t len;
3168 int fd;
3170 for(;;) {
3171 #ifndef _WIN32
3172 if (s->is_unix) {
3173 len = sizeof(uaddr);
3174 addr = (struct sockaddr *)&uaddr;
3175 } else
3176 #endif
3178 len = sizeof(saddr);
3179 addr = (struct sockaddr *)&saddr;
3181 fd = accept(s->listen_fd, addr, &len);
3182 if (fd < 0 && errno != EINTR) {
3183 return;
3184 } else if (fd >= 0) {
3185 if (s->do_telnetopt)
3186 tcp_chr_telnet_init(fd);
3187 break;
3190 socket_set_nonblock(fd);
3191 if (s->do_nodelay)
3192 socket_set_nodelay(fd);
3193 s->fd = fd;
3194 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3195 tcp_chr_connect(chr);
3198 static void tcp_chr_close(CharDriverState *chr)
3200 TCPCharDriver *s = chr->opaque;
3201 if (s->fd >= 0)
3202 closesocket(s->fd);
3203 if (s->listen_fd >= 0)
3204 closesocket(s->listen_fd);
3205 qemu_free(s);
3208 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3209 int is_telnet,
3210 int is_unix)
3212 CharDriverState *chr = NULL;
3213 TCPCharDriver *s = NULL;
3214 int fd = -1, ret, err, val;
3215 int is_listen = 0;
3216 int is_waitconnect = 1;
3217 int do_nodelay = 0;
3218 const char *ptr;
3219 struct sockaddr_in saddr;
3220 #ifndef _WIN32
3221 struct sockaddr_un uaddr;
3222 #endif
3223 struct sockaddr *addr;
3224 socklen_t addrlen;
3226 #ifndef _WIN32
3227 if (is_unix) {
3228 addr = (struct sockaddr *)&uaddr;
3229 addrlen = sizeof(uaddr);
3230 if (parse_unix_path(&uaddr, host_str) < 0)
3231 goto fail;
3232 } else
3233 #endif
3235 addr = (struct sockaddr *)&saddr;
3236 addrlen = sizeof(saddr);
3237 if (parse_host_port(&saddr, host_str) < 0)
3238 goto fail;
3241 ptr = host_str;
3242 while((ptr = strchr(ptr,','))) {
3243 ptr++;
3244 if (!strncmp(ptr,"server",6)) {
3245 is_listen = 1;
3246 } else if (!strncmp(ptr,"nowait",6)) {
3247 is_waitconnect = 0;
3248 } else if (!strncmp(ptr,"nodelay",6)) {
3249 do_nodelay = 1;
3250 } else {
3251 printf("Unknown option: %s\n", ptr);
3252 goto fail;
3255 if (!is_listen)
3256 is_waitconnect = 0;
3258 chr = qemu_mallocz(sizeof(CharDriverState));
3259 if (!chr)
3260 goto fail;
3261 s = qemu_mallocz(sizeof(TCPCharDriver));
3262 if (!s)
3263 goto fail;
3265 #ifndef _WIN32
3266 if (is_unix)
3267 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3268 else
3269 #endif
3270 fd = socket(PF_INET, SOCK_STREAM, 0);
3272 if (fd < 0)
3273 goto fail;
3275 if (!is_waitconnect)
3276 socket_set_nonblock(fd);
3278 s->connected = 0;
3279 s->fd = -1;
3280 s->listen_fd = -1;
3281 s->is_unix = is_unix;
3282 s->do_nodelay = do_nodelay && !is_unix;
3284 chr->opaque = s;
3285 chr->chr_write = tcp_chr_write;
3286 chr->chr_close = tcp_chr_close;
3288 if (is_listen) {
3289 /* allow fast reuse */
3290 #ifndef _WIN32
3291 if (is_unix) {
3292 char path[109];
3293 strncpy(path, uaddr.sun_path, 108);
3294 path[108] = 0;
3295 unlink(path);
3296 } else
3297 #endif
3299 val = 1;
3300 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3303 ret = bind(fd, addr, addrlen);
3304 if (ret < 0)
3305 goto fail;
3307 ret = listen(fd, 0);
3308 if (ret < 0)
3309 goto fail;
3311 s->listen_fd = fd;
3312 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3313 if (is_telnet)
3314 s->do_telnetopt = 1;
3315 } else {
3316 for(;;) {
3317 ret = connect(fd, addr, addrlen);
3318 if (ret < 0) {
3319 err = socket_error();
3320 if (err == EINTR || err == EWOULDBLOCK) {
3321 } else if (err == EINPROGRESS) {
3322 break;
3323 #ifdef _WIN32
3324 } else if (err == WSAEALREADY) {
3325 break;
3326 #endif
3327 } else {
3328 goto fail;
3330 } else {
3331 s->connected = 1;
3332 break;
3335 s->fd = fd;
3336 socket_set_nodelay(fd);
3337 if (s->connected)
3338 tcp_chr_connect(chr);
3339 else
3340 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3343 if (is_listen && is_waitconnect) {
3344 printf("QEMU waiting for connection on: %s\n", host_str);
3345 tcp_chr_accept(chr);
3346 socket_set_nonblock(s->listen_fd);
3349 return chr;
3350 fail:
3351 if (fd >= 0)
3352 closesocket(fd);
3353 qemu_free(s);
3354 qemu_free(chr);
3355 return NULL;
3358 CharDriverState *qemu_chr_open(const char *filename)
3360 const char *p;
3362 if (!strcmp(filename, "vc")) {
3363 return text_console_init(&display_state, 0);
3364 } else if (strstart(filename, "vc:", &p)) {
3365 return text_console_init(&display_state, p);
3366 } else if (!strcmp(filename, "null")) {
3367 return qemu_chr_open_null();
3368 } else
3369 if (strstart(filename, "tcp:", &p)) {
3370 return qemu_chr_open_tcp(p, 0, 0);
3371 } else
3372 if (strstart(filename, "telnet:", &p)) {
3373 return qemu_chr_open_tcp(p, 1, 0);
3374 } else
3375 if (strstart(filename, "udp:", &p)) {
3376 return qemu_chr_open_udp(p);
3377 } else
3378 if (strstart(filename, "mon:", &p)) {
3379 CharDriverState *drv = qemu_chr_open(p);
3380 if (drv) {
3381 drv = qemu_chr_open_mux(drv);
3382 monitor_init(drv, !nographic);
3383 return drv;
3385 printf("Unable to open driver: %s\n", p);
3386 return 0;
3387 } else
3388 #ifndef _WIN32
3389 if (strstart(filename, "unix:", &p)) {
3390 return qemu_chr_open_tcp(p, 0, 1);
3391 } else if (strstart(filename, "file:", &p)) {
3392 return qemu_chr_open_file_out(p);
3393 } else if (strstart(filename, "pipe:", &p)) {
3394 return qemu_chr_open_pipe(p);
3395 } else if (!strcmp(filename, "pty")) {
3396 return qemu_chr_open_pty();
3397 } else if (!strcmp(filename, "stdio")) {
3398 return qemu_chr_open_stdio();
3399 } else
3400 #if defined(__linux__)
3401 if (strstart(filename, "/dev/parport", NULL)) {
3402 return qemu_chr_open_pp(filename);
3403 } else
3404 #endif
3405 #if defined(__linux__) || defined(__sun__)
3406 if (strstart(filename, "/dev/", NULL)) {
3407 return qemu_chr_open_tty(filename);
3408 } else
3409 #endif
3410 #else /* !_WIN32 */
3411 if (strstart(filename, "COM", NULL)) {
3412 return qemu_chr_open_win(filename);
3413 } else
3414 if (strstart(filename, "pipe:", &p)) {
3415 return qemu_chr_open_win_pipe(p);
3416 } else
3417 if (strstart(filename, "con:", NULL)) {
3418 return qemu_chr_open_win_con(filename);
3419 } else
3420 if (strstart(filename, "file:", &p)) {
3421 return qemu_chr_open_win_file_out(p);
3423 #endif
3425 return NULL;
3429 void qemu_chr_close(CharDriverState *chr)
3431 if (chr->chr_close)
3432 chr->chr_close(chr);
3435 /***********************************************************/
3436 /* network device redirectors */
3438 __attribute__ (( unused ))
3439 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3441 int len, i, j, c;
3443 for(i=0;i<size;i+=16) {
3444 len = size - i;
3445 if (len > 16)
3446 len = 16;
3447 fprintf(f, "%08x ", i);
3448 for(j=0;j<16;j++) {
3449 if (j < len)
3450 fprintf(f, " %02x", buf[i+j]);
3451 else
3452 fprintf(f, " ");
3454 fprintf(f, " ");
3455 for(j=0;j<len;j++) {
3456 c = buf[i+j];
3457 if (c < ' ' || c > '~')
3458 c = '.';
3459 fprintf(f, "%c", c);
3461 fprintf(f, "\n");
3465 static int parse_macaddr(uint8_t *macaddr, const char *p)
3467 int i;
3468 char *last_char;
3469 long int offset;
3471 errno = 0;
3472 offset = strtol(p, &last_char, 0);
3473 if (0 == errno && '\0' == *last_char &&
3474 offset >= 0 && offset <= 0xFFFFFF) {
3475 macaddr[3] = (offset & 0xFF0000) >> 16;
3476 macaddr[4] = (offset & 0xFF00) >> 8;
3477 macaddr[5] = offset & 0xFF;
3478 return 0;
3479 } else {
3480 for(i = 0; i < 6; i++) {
3481 macaddr[i] = strtol(p, (char **)&p, 16);
3482 if (i == 5) {
3483 if (*p != '\0')
3484 return -1;
3485 } else {
3486 if (*p != ':' && *p != '-')
3487 return -1;
3488 p++;
3491 return 0;
3494 return -1;
3497 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3499 const char *p, *p1;
3500 int len;
3501 p = *pp;
3502 p1 = strchr(p, sep);
3503 if (!p1)
3504 return -1;
3505 len = p1 - p;
3506 p1++;
3507 if (buf_size > 0) {
3508 if (len > buf_size - 1)
3509 len = buf_size - 1;
3510 memcpy(buf, p, len);
3511 buf[len] = '\0';
3513 *pp = p1;
3514 return 0;
3517 int parse_host_src_port(struct sockaddr_in *haddr,
3518 struct sockaddr_in *saddr,
3519 const char *input_str)
3521 char *str = strdup(input_str);
3522 char *host_str = str;
3523 char *src_str;
3524 char *ptr;
3527 * Chop off any extra arguments at the end of the string which
3528 * would start with a comma, then fill in the src port information
3529 * if it was provided else use the "any address" and "any port".
3531 if ((ptr = strchr(str,',')))
3532 *ptr = '\0';
3534 if ((src_str = strchr(input_str,'@'))) {
3535 *src_str = '\0';
3536 src_str++;
3539 if (parse_host_port(haddr, host_str) < 0)
3540 goto fail;
3542 if (!src_str || *src_str == '\0')
3543 src_str = ":0";
3545 if (parse_host_port(saddr, src_str) < 0)
3546 goto fail;
3548 free(str);
3549 return(0);
3551 fail:
3552 free(str);
3553 return -1;
3556 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3558 char buf[512];
3559 struct hostent *he;
3560 const char *p, *r;
3561 int port;
3563 p = str;
3564 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3565 return -1;
3566 saddr->sin_family = AF_INET;
3567 if (buf[0] == '\0') {
3568 saddr->sin_addr.s_addr = 0;
3569 } else {
3570 if (isdigit(buf[0])) {
3571 if (!inet_aton(buf, &saddr->sin_addr))
3572 return -1;
3573 } else {
3574 if ((he = gethostbyname(buf)) == NULL)
3575 return - 1;
3576 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3579 port = strtol(p, (char **)&r, 0);
3580 if (r == p)
3581 return -1;
3582 saddr->sin_port = htons(port);
3583 return 0;
3586 #ifndef _WIN32
3587 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3589 const char *p;
3590 int len;
3592 len = MIN(108, strlen(str));
3593 p = strchr(str, ',');
3594 if (p)
3595 len = MIN(len, p - str);
3597 memset(uaddr, 0, sizeof(*uaddr));
3599 uaddr->sun_family = AF_UNIX;
3600 memcpy(uaddr->sun_path, str, len);
3602 return 0;
3604 #endif
3606 /* find or alloc a new VLAN */
3607 VLANState *qemu_find_vlan(int id)
3609 VLANState **pvlan, *vlan;
3610 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3611 if (vlan->id == id)
3612 return vlan;
3614 vlan = qemu_mallocz(sizeof(VLANState));
3615 if (!vlan)
3616 return NULL;
3617 vlan->id = id;
3618 vlan->next = NULL;
3619 pvlan = &first_vlan;
3620 while (*pvlan != NULL)
3621 pvlan = &(*pvlan)->next;
3622 *pvlan = vlan;
3623 return vlan;
3626 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3627 IOReadHandler *fd_read,
3628 IOCanRWHandler *fd_can_read,
3629 void *opaque)
3631 VLANClientState *vc, **pvc;
3632 vc = qemu_mallocz(sizeof(VLANClientState));
3633 if (!vc)
3634 return NULL;
3635 vc->fd_read = fd_read;
3636 vc->fd_can_read = fd_can_read;
3637 vc->opaque = opaque;
3638 vc->vlan = vlan;
3640 vc->next = NULL;
3641 pvc = &vlan->first_client;
3642 while (*pvc != NULL)
3643 pvc = &(*pvc)->next;
3644 *pvc = vc;
3645 return vc;
3648 int qemu_can_send_packet(VLANClientState *vc1)
3650 VLANState *vlan = vc1->vlan;
3651 VLANClientState *vc;
3653 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3654 if (vc != vc1) {
3655 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3656 return 1;
3659 return 0;
3662 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3664 VLANState *vlan = vc1->vlan;
3665 VLANClientState *vc;
3667 #if 0
3668 printf("vlan %d send:\n", vlan->id);
3669 hex_dump(stdout, buf, size);
3670 #endif
3671 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3672 if (vc != vc1) {
3673 vc->fd_read(vc->opaque, buf, size);
3678 #if defined(CONFIG_SLIRP)
3680 /* slirp network adapter */
3682 static int slirp_inited;
3683 static VLANClientState *slirp_vc;
3685 int slirp_can_output(void)
3687 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3690 void slirp_output(const uint8_t *pkt, int pkt_len)
3692 #if 0
3693 printf("slirp output:\n");
3694 hex_dump(stdout, pkt, pkt_len);
3695 #endif
3696 if (!slirp_vc)
3697 return;
3698 qemu_send_packet(slirp_vc, pkt, pkt_len);
3701 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3703 #if 0
3704 printf("slirp input:\n");
3705 hex_dump(stdout, buf, size);
3706 #endif
3707 slirp_input(buf, size);
3710 static int net_slirp_init(VLANState *vlan)
3712 if (!slirp_inited) {
3713 slirp_inited = 1;
3714 slirp_init();
3716 slirp_vc = qemu_new_vlan_client(vlan,
3717 slirp_receive, NULL, NULL);
3718 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3719 return 0;
3722 static void net_slirp_redir(const char *redir_str)
3724 int is_udp;
3725 char buf[256], *r;
3726 const char *p;
3727 struct in_addr guest_addr;
3728 int host_port, guest_port;
3730 if (!slirp_inited) {
3731 slirp_inited = 1;
3732 slirp_init();
3735 p = redir_str;
3736 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3737 goto fail;
3738 if (!strcmp(buf, "tcp")) {
3739 is_udp = 0;
3740 } else if (!strcmp(buf, "udp")) {
3741 is_udp = 1;
3742 } else {
3743 goto fail;
3746 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3747 goto fail;
3748 host_port = strtol(buf, &r, 0);
3749 if (r == buf)
3750 goto fail;
3752 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3753 goto fail;
3754 if (buf[0] == '\0') {
3755 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3757 if (!inet_aton(buf, &guest_addr))
3758 goto fail;
3760 guest_port = strtol(p, &r, 0);
3761 if (r == p)
3762 goto fail;
3764 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3765 fprintf(stderr, "qemu: could not set up redirection\n");
3766 exit(1);
3768 return;
3769 fail:
3770 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3771 exit(1);
3774 #ifndef _WIN32
3776 char smb_dir[1024];
3778 static void smb_exit(void)
3780 DIR *d;
3781 struct dirent *de;
3782 char filename[1024];
3784 /* erase all the files in the directory */
3785 d = opendir(smb_dir);
3786 for(;;) {
3787 de = readdir(d);
3788 if (!de)
3789 break;
3790 if (strcmp(de->d_name, ".") != 0 &&
3791 strcmp(de->d_name, "..") != 0) {
3792 snprintf(filename, sizeof(filename), "%s/%s",
3793 smb_dir, de->d_name);
3794 unlink(filename);
3797 closedir(d);
3798 rmdir(smb_dir);
3801 /* automatic user mode samba server configuration */
3802 static void net_slirp_smb(const char *exported_dir)
3804 char smb_conf[1024];
3805 char smb_cmdline[1024];
3806 FILE *f;
3808 if (!slirp_inited) {
3809 slirp_inited = 1;
3810 slirp_init();
3813 /* XXX: better tmp dir construction */
3814 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3815 if (mkdir(smb_dir, 0700) < 0) {
3816 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3817 exit(1);
3819 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3821 f = fopen(smb_conf, "w");
3822 if (!f) {
3823 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3824 exit(1);
3826 fprintf(f,
3827 "[global]\n"
3828 "private dir=%s\n"
3829 "smb ports=0\n"
3830 "socket address=127.0.0.1\n"
3831 "pid directory=%s\n"
3832 "lock directory=%s\n"
3833 "log file=%s/log.smbd\n"
3834 "smb passwd file=%s/smbpasswd\n"
3835 "security = share\n"
3836 "[qemu]\n"
3837 "path=%s\n"
3838 "read only=no\n"
3839 "guest ok=yes\n",
3840 smb_dir,
3841 smb_dir,
3842 smb_dir,
3843 smb_dir,
3844 smb_dir,
3845 exported_dir
3847 fclose(f);
3848 atexit(smb_exit);
3850 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3851 SMBD_COMMAND, smb_conf);
3853 slirp_add_exec(0, smb_cmdline, 4, 139);
3856 #endif /* !defined(_WIN32) */
3857 void do_info_slirp(void)
3859 slirp_stats();
3862 #endif /* CONFIG_SLIRP */
3864 #if !defined(_WIN32)
3866 typedef struct TAPState {
3867 VLANClientState *vc;
3868 int fd;
3869 char down_script[1024];
3870 } TAPState;
3872 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3874 TAPState *s = opaque;
3875 int ret;
3876 for(;;) {
3877 ret = write(s->fd, buf, size);
3878 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3879 } else {
3880 break;
3885 static void tap_send(void *opaque)
3887 TAPState *s = opaque;
3888 uint8_t buf[4096];
3889 int size;
3891 #ifdef __sun__
3892 struct strbuf sbuf;
3893 int f = 0;
3894 sbuf.maxlen = sizeof(buf);
3895 sbuf.buf = buf;
3896 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3897 #else
3898 size = read(s->fd, buf, sizeof(buf));
3899 #endif
3900 if (size > 0) {
3901 qemu_send_packet(s->vc, buf, size);
3905 /* fd support */
3907 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3909 TAPState *s;
3911 s = qemu_mallocz(sizeof(TAPState));
3912 if (!s)
3913 return NULL;
3914 s->fd = fd;
3915 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3916 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3917 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3918 return s;
3921 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3922 static int tap_open(char *ifname, int ifname_size)
3924 int fd;
3925 char *dev;
3926 struct stat s;
3928 TFR(fd = open("/dev/tap", O_RDWR));
3929 if (fd < 0) {
3930 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3931 return -1;
3934 fstat(fd, &s);
3935 dev = devname(s.st_rdev, S_IFCHR);
3936 pstrcpy(ifname, ifname_size, dev);
3938 fcntl(fd, F_SETFL, O_NONBLOCK);
3939 return fd;
3941 #elif defined(__sun__)
3942 #define TUNNEWPPA (('T'<<16) | 0x0001)
3944 * Allocate TAP device, returns opened fd.
3945 * Stores dev name in the first arg(must be large enough).
3947 int tap_alloc(char *dev)
3949 int tap_fd, if_fd, ppa = -1;
3950 static int ip_fd = 0;
3951 char *ptr;
3953 static int arp_fd = 0;
3954 int ip_muxid, arp_muxid;
3955 struct strioctl strioc_if, strioc_ppa;
3956 int link_type = I_PLINK;;
3957 struct lifreq ifr;
3958 char actual_name[32] = "";
3960 memset(&ifr, 0x0, sizeof(ifr));
3962 if( *dev ){
3963 ptr = dev;
3964 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3965 ppa = atoi(ptr);
3968 /* Check if IP device was opened */
3969 if( ip_fd )
3970 close(ip_fd);
3972 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3973 if (ip_fd < 0) {
3974 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3975 return -1;
3978 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3979 if (tap_fd < 0) {
3980 syslog(LOG_ERR, "Can't open /dev/tap");
3981 return -1;
3984 /* Assign a new PPA and get its unit number. */
3985 strioc_ppa.ic_cmd = TUNNEWPPA;
3986 strioc_ppa.ic_timout = 0;
3987 strioc_ppa.ic_len = sizeof(ppa);
3988 strioc_ppa.ic_dp = (char *)&ppa;
3989 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3990 syslog (LOG_ERR, "Can't assign new interface");
3992 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3993 if (if_fd < 0) {
3994 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3995 return -1;
3997 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3998 syslog(LOG_ERR, "Can't push IP module");
3999 return -1;
4002 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4003 syslog(LOG_ERR, "Can't get flags\n");
4005 snprintf (actual_name, 32, "tap%d", ppa);
4006 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4008 ifr.lifr_ppa = ppa;
4009 /* Assign ppa according to the unit number returned by tun device */
4011 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4012 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4013 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4014 syslog (LOG_ERR, "Can't get flags\n");
4015 /* Push arp module to if_fd */
4016 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4017 syslog (LOG_ERR, "Can't push ARP module (2)");
4019 /* Push arp module to ip_fd */
4020 if (ioctl (ip_fd, I_POP, NULL) < 0)
4021 syslog (LOG_ERR, "I_POP failed\n");
4022 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4023 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4024 /* Open arp_fd */
4025 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4026 if (arp_fd < 0)
4027 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4029 /* Set ifname to arp */
4030 strioc_if.ic_cmd = SIOCSLIFNAME;
4031 strioc_if.ic_timout = 0;
4032 strioc_if.ic_len = sizeof(ifr);
4033 strioc_if.ic_dp = (char *)&ifr;
4034 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4035 syslog (LOG_ERR, "Can't set ifname to arp\n");
4038 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4039 syslog(LOG_ERR, "Can't link TAP device to IP");
4040 return -1;
4043 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4044 syslog (LOG_ERR, "Can't link TAP device to ARP");
4046 close (if_fd);
4048 memset(&ifr, 0x0, sizeof(ifr));
4049 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4050 ifr.lifr_ip_muxid = ip_muxid;
4051 ifr.lifr_arp_muxid = arp_muxid;
4053 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4055 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4056 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4057 syslog (LOG_ERR, "Can't set multiplexor id");
4060 sprintf(dev, "tap%d", ppa);
4061 return tap_fd;
4064 static int tap_open(char *ifname, int ifname_size)
4066 char dev[10]="";
4067 int fd;
4068 if( (fd = tap_alloc(dev)) < 0 ){
4069 fprintf(stderr, "Cannot allocate TAP device\n");
4070 return -1;
4072 pstrcpy(ifname, ifname_size, dev);
4073 fcntl(fd, F_SETFL, O_NONBLOCK);
4074 return fd;
4076 #else
4077 static int tap_open(char *ifname, int ifname_size)
4079 struct ifreq ifr;
4080 int fd, ret;
4082 TFR(fd = open("/dev/net/tun", O_RDWR));
4083 if (fd < 0) {
4084 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4085 return -1;
4087 memset(&ifr, 0, sizeof(ifr));
4088 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4089 if (ifname[0] != '\0')
4090 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4091 else
4092 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4093 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4094 if (ret != 0) {
4095 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4096 close(fd);
4097 return -1;
4099 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4100 fcntl(fd, F_SETFL, O_NONBLOCK);
4101 return fd;
4103 #endif
4105 static int launch_script(const char *setup_script, const char *ifname, int fd)
4107 int pid, status;
4108 char *args[3];
4109 char **parg;
4111 /* try to launch network script */
4112 pid = fork();
4113 if (pid >= 0) {
4114 if (pid == 0) {
4115 int open_max = sysconf (_SC_OPEN_MAX), i;
4116 for (i = 0; i < open_max; i++)
4117 if (i != STDIN_FILENO &&
4118 i != STDOUT_FILENO &&
4119 i != STDERR_FILENO &&
4120 i != fd)
4121 close(i);
4123 parg = args;
4124 *parg++ = (char *)setup_script;
4125 *parg++ = (char *)ifname;
4126 *parg++ = NULL;
4127 execv(setup_script, args);
4128 _exit(1);
4130 while (waitpid(pid, &status, 0) != pid);
4131 if (!WIFEXITED(status) ||
4132 WEXITSTATUS(status) != 0) {
4133 fprintf(stderr, "%s: could not launch network script\n",
4134 setup_script);
4135 return -1;
4138 return 0;
4141 static int net_tap_init(VLANState *vlan, const char *ifname1,
4142 const char *setup_script, const char *down_script)
4144 TAPState *s;
4145 int fd;
4146 char ifname[128];
4148 if (ifname1 != NULL)
4149 pstrcpy(ifname, sizeof(ifname), ifname1);
4150 else
4151 ifname[0] = '\0';
4152 TFR(fd = tap_open(ifname, sizeof(ifname)));
4153 if (fd < 0)
4154 return -1;
4156 if (!setup_script || !strcmp(setup_script, "no"))
4157 setup_script = "";
4158 if (setup_script[0] != '\0') {
4159 if (launch_script(setup_script, ifname, fd))
4160 return -1;
4162 s = net_tap_fd_init(vlan, fd);
4163 if (!s)
4164 return -1;
4165 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4166 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4167 if (down_script && strcmp(down_script, "no"))
4168 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4169 return 0;
4172 #endif /* !_WIN32 */
4174 /* network connection */
4175 typedef struct NetSocketState {
4176 VLANClientState *vc;
4177 int fd;
4178 int state; /* 0 = getting length, 1 = getting data */
4179 int index;
4180 int packet_len;
4181 uint8_t buf[4096];
4182 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4183 } NetSocketState;
4185 typedef struct NetSocketListenState {
4186 VLANState *vlan;
4187 int fd;
4188 } NetSocketListenState;
4190 /* XXX: we consider we can send the whole packet without blocking */
4191 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4193 NetSocketState *s = opaque;
4194 uint32_t len;
4195 len = htonl(size);
4197 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4198 send_all(s->fd, buf, size);
4201 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4203 NetSocketState *s = opaque;
4204 sendto(s->fd, buf, size, 0,
4205 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4208 static void net_socket_send(void *opaque)
4210 NetSocketState *s = opaque;
4211 int l, size, err;
4212 uint8_t buf1[4096];
4213 const uint8_t *buf;
4215 size = recv(s->fd, buf1, sizeof(buf1), 0);
4216 if (size < 0) {
4217 err = socket_error();
4218 if (err != EWOULDBLOCK)
4219 goto eoc;
4220 } else if (size == 0) {
4221 /* end of connection */
4222 eoc:
4223 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4224 closesocket(s->fd);
4225 return;
4227 buf = buf1;
4228 while (size > 0) {
4229 /* reassemble a packet from the network */
4230 switch(s->state) {
4231 case 0:
4232 l = 4 - s->index;
4233 if (l > size)
4234 l = size;
4235 memcpy(s->buf + s->index, buf, l);
4236 buf += l;
4237 size -= l;
4238 s->index += l;
4239 if (s->index == 4) {
4240 /* got length */
4241 s->packet_len = ntohl(*(uint32_t *)s->buf);
4242 s->index = 0;
4243 s->state = 1;
4245 break;
4246 case 1:
4247 l = s->packet_len - s->index;
4248 if (l > size)
4249 l = size;
4250 memcpy(s->buf + s->index, buf, l);
4251 s->index += l;
4252 buf += l;
4253 size -= l;
4254 if (s->index >= s->packet_len) {
4255 qemu_send_packet(s->vc, s->buf, s->packet_len);
4256 s->index = 0;
4257 s->state = 0;
4259 break;
4264 static void net_socket_send_dgram(void *opaque)
4266 NetSocketState *s = opaque;
4267 int size;
4269 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4270 if (size < 0)
4271 return;
4272 if (size == 0) {
4273 /* end of connection */
4274 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4275 return;
4277 qemu_send_packet(s->vc, s->buf, size);
4280 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4282 struct ip_mreq imr;
4283 int fd;
4284 int val, ret;
4285 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4286 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4287 inet_ntoa(mcastaddr->sin_addr),
4288 (int)ntohl(mcastaddr->sin_addr.s_addr));
4289 return -1;
4292 fd = socket(PF_INET, SOCK_DGRAM, 0);
4293 if (fd < 0) {
4294 perror("socket(PF_INET, SOCK_DGRAM)");
4295 return -1;
4298 val = 1;
4299 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4300 (const char *)&val, sizeof(val));
4301 if (ret < 0) {
4302 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4303 goto fail;
4306 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4307 if (ret < 0) {
4308 perror("bind");
4309 goto fail;
4312 /* Add host to multicast group */
4313 imr.imr_multiaddr = mcastaddr->sin_addr;
4314 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4316 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4317 (const char *)&imr, sizeof(struct ip_mreq));
4318 if (ret < 0) {
4319 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4320 goto fail;
4323 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4324 val = 1;
4325 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4326 (const char *)&val, sizeof(val));
4327 if (ret < 0) {
4328 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4329 goto fail;
4332 socket_set_nonblock(fd);
4333 return fd;
4334 fail:
4335 if (fd >= 0)
4336 closesocket(fd);
4337 return -1;
4340 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4341 int is_connected)
4343 struct sockaddr_in saddr;
4344 int newfd;
4345 socklen_t saddr_len;
4346 NetSocketState *s;
4348 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4349 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4350 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4353 if (is_connected) {
4354 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4355 /* must be bound */
4356 if (saddr.sin_addr.s_addr==0) {
4357 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4358 fd);
4359 return NULL;
4361 /* clone dgram socket */
4362 newfd = net_socket_mcast_create(&saddr);
4363 if (newfd < 0) {
4364 /* error already reported by net_socket_mcast_create() */
4365 close(fd);
4366 return NULL;
4368 /* clone newfd to fd, close newfd */
4369 dup2(newfd, fd);
4370 close(newfd);
4372 } else {
4373 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4374 fd, strerror(errno));
4375 return NULL;
4379 s = qemu_mallocz(sizeof(NetSocketState));
4380 if (!s)
4381 return NULL;
4382 s->fd = fd;
4384 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4385 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4387 /* mcast: save bound address as dst */
4388 if (is_connected) s->dgram_dst=saddr;
4390 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4391 "socket: fd=%d (%s mcast=%s:%d)",
4392 fd, is_connected? "cloned" : "",
4393 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4394 return s;
4397 static void net_socket_connect(void *opaque)
4399 NetSocketState *s = opaque;
4400 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4403 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4404 int is_connected)
4406 NetSocketState *s;
4407 s = qemu_mallocz(sizeof(NetSocketState));
4408 if (!s)
4409 return NULL;
4410 s->fd = fd;
4411 s->vc = qemu_new_vlan_client(vlan,
4412 net_socket_receive, NULL, s);
4413 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4414 "socket: fd=%d", fd);
4415 if (is_connected) {
4416 net_socket_connect(s);
4417 } else {
4418 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4420 return s;
4423 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4424 int is_connected)
4426 int so_type=-1, optlen=sizeof(so_type);
4428 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4429 (socklen_t *)&optlen)< 0) {
4430 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4431 return NULL;
4433 switch(so_type) {
4434 case SOCK_DGRAM:
4435 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4436 case SOCK_STREAM:
4437 return net_socket_fd_init_stream(vlan, fd, is_connected);
4438 default:
4439 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4440 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4441 return net_socket_fd_init_stream(vlan, fd, is_connected);
4443 return NULL;
4446 static void net_socket_accept(void *opaque)
4448 NetSocketListenState *s = opaque;
4449 NetSocketState *s1;
4450 struct sockaddr_in saddr;
4451 socklen_t len;
4452 int fd;
4454 for(;;) {
4455 len = sizeof(saddr);
4456 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4457 if (fd < 0 && errno != EINTR) {
4458 return;
4459 } else if (fd >= 0) {
4460 break;
4463 s1 = net_socket_fd_init(s->vlan, fd, 1);
4464 if (!s1) {
4465 closesocket(fd);
4466 } else {
4467 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4468 "socket: connection from %s:%d",
4469 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4473 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4475 NetSocketListenState *s;
4476 int fd, val, ret;
4477 struct sockaddr_in saddr;
4479 if (parse_host_port(&saddr, host_str) < 0)
4480 return -1;
4482 s = qemu_mallocz(sizeof(NetSocketListenState));
4483 if (!s)
4484 return -1;
4486 fd = socket(PF_INET, SOCK_STREAM, 0);
4487 if (fd < 0) {
4488 perror("socket");
4489 return -1;
4491 socket_set_nonblock(fd);
4493 /* allow fast reuse */
4494 val = 1;
4495 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4497 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4498 if (ret < 0) {
4499 perror("bind");
4500 return -1;
4502 ret = listen(fd, 0);
4503 if (ret < 0) {
4504 perror("listen");
4505 return -1;
4507 s->vlan = vlan;
4508 s->fd = fd;
4509 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4510 return 0;
4513 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4515 NetSocketState *s;
4516 int fd, connected, ret, err;
4517 struct sockaddr_in saddr;
4519 if (parse_host_port(&saddr, host_str) < 0)
4520 return -1;
4522 fd = socket(PF_INET, SOCK_STREAM, 0);
4523 if (fd < 0) {
4524 perror("socket");
4525 return -1;
4527 socket_set_nonblock(fd);
4529 connected = 0;
4530 for(;;) {
4531 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4532 if (ret < 0) {
4533 err = socket_error();
4534 if (err == EINTR || err == EWOULDBLOCK) {
4535 } else if (err == EINPROGRESS) {
4536 break;
4537 #ifdef _WIN32
4538 } else if (err == WSAEALREADY) {
4539 break;
4540 #endif
4541 } else {
4542 perror("connect");
4543 closesocket(fd);
4544 return -1;
4546 } else {
4547 connected = 1;
4548 break;
4551 s = net_socket_fd_init(vlan, fd, connected);
4552 if (!s)
4553 return -1;
4554 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4555 "socket: connect to %s:%d",
4556 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4557 return 0;
4560 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4562 NetSocketState *s;
4563 int fd;
4564 struct sockaddr_in saddr;
4566 if (parse_host_port(&saddr, host_str) < 0)
4567 return -1;
4570 fd = net_socket_mcast_create(&saddr);
4571 if (fd < 0)
4572 return -1;
4574 s = net_socket_fd_init(vlan, fd, 0);
4575 if (!s)
4576 return -1;
4578 s->dgram_dst = saddr;
4580 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4581 "socket: mcast=%s:%d",
4582 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4583 return 0;
4587 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4589 char *q;
4591 q = buf;
4592 while (*p != '\0' && *p != '=') {
4593 if (q && (q - buf) < buf_size - 1)
4594 *q++ = *p;
4595 p++;
4597 if (q)
4598 *q = '\0';
4600 return p;
4603 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4605 char *q;
4607 q = buf;
4608 while (*p != '\0') {
4609 if (*p == ',') {
4610 if (*(p + 1) != ',')
4611 break;
4612 p++;
4614 if (q && (q - buf) < buf_size - 1)
4615 *q++ = *p;
4616 p++;
4618 if (q)
4619 *q = '\0';
4621 return p;
4624 static int get_param_value(char *buf, int buf_size,
4625 const char *tag, const char *str)
4627 const char *p;
4628 char option[128];
4630 p = str;
4631 for(;;) {
4632 p = get_opt_name(option, sizeof(option), p);
4633 if (*p != '=')
4634 break;
4635 p++;
4636 if (!strcmp(tag, option)) {
4637 (void)get_opt_value(buf, buf_size, p);
4638 return strlen(buf);
4639 } else {
4640 p = get_opt_value(NULL, 0, p);
4642 if (*p != ',')
4643 break;
4644 p++;
4646 return 0;
4649 static int check_params(char *buf, int buf_size,
4650 char **params, const char *str)
4652 const char *p;
4653 int i;
4655 p = str;
4656 for(;;) {
4657 p = get_opt_name(buf, buf_size, p);
4658 if (*p != '=')
4659 return -1;
4660 p++;
4661 for(i = 0; params[i] != NULL; i++)
4662 if (!strcmp(params[i], buf))
4663 break;
4664 if (params[i] == NULL)
4665 return -1;
4666 p = get_opt_value(NULL, 0, p);
4667 if (*p != ',')
4668 break;
4669 p++;
4671 return 0;
4675 static int net_client_init(const char *str)
4677 const char *p;
4678 char *q;
4679 char device[64];
4680 char buf[1024];
4681 int vlan_id, ret;
4682 VLANState *vlan;
4684 p = str;
4685 q = device;
4686 while (*p != '\0' && *p != ',') {
4687 if ((q - device) < sizeof(device) - 1)
4688 *q++ = *p;
4689 p++;
4691 *q = '\0';
4692 if (*p == ',')
4693 p++;
4694 vlan_id = 0;
4695 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4696 vlan_id = strtol(buf, NULL, 0);
4698 vlan = qemu_find_vlan(vlan_id);
4699 if (!vlan) {
4700 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4701 return -1;
4703 if (!strcmp(device, "nic")) {
4704 NICInfo *nd;
4705 uint8_t *macaddr;
4707 if (nb_nics >= MAX_NICS) {
4708 fprintf(stderr, "Too Many NICs\n");
4709 return -1;
4711 nd = &nd_table[nb_nics];
4712 macaddr = nd->macaddr;
4713 macaddr[0] = 0x52;
4714 macaddr[1] = 0x54;
4715 macaddr[2] = 0x00;
4716 macaddr[3] = 0x12;
4717 macaddr[4] = 0x34;
4718 macaddr[5] = 0x56 + nb_nics;
4720 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4721 if (parse_macaddr(macaddr, buf) < 0) {
4722 fprintf(stderr, "invalid syntax for ethernet address\n");
4723 return -1;
4726 if (get_param_value(buf, sizeof(buf), "model", p)) {
4727 nd->model = strdup(buf);
4729 nd->vlan = vlan;
4730 nb_nics++;
4731 vlan->nb_guest_devs++;
4732 ret = 0;
4733 } else
4734 if (!strcmp(device, "none")) {
4735 /* does nothing. It is needed to signal that no network cards
4736 are wanted */
4737 ret = 0;
4738 } else
4739 #ifdef CONFIG_SLIRP
4740 if (!strcmp(device, "user")) {
4741 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4742 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4744 vlan->nb_host_devs++;
4745 ret = net_slirp_init(vlan);
4746 } else
4747 #endif
4748 #ifdef _WIN32
4749 if (!strcmp(device, "tap")) {
4750 char ifname[64];
4751 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4752 fprintf(stderr, "tap: no interface name\n");
4753 return -1;
4755 vlan->nb_host_devs++;
4756 ret = tap_win32_init(vlan, ifname);
4757 } else
4758 #else
4759 if (!strcmp(device, "tap")) {
4760 char ifname[64];
4761 char setup_script[1024], down_script[1024];
4762 int fd;
4763 vlan->nb_host_devs++;
4764 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4765 fd = strtol(buf, NULL, 0);
4766 ret = -1;
4767 if (net_tap_fd_init(vlan, fd))
4768 ret = 0;
4769 } else {
4770 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4771 ifname[0] = '\0';
4773 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4774 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4776 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4777 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4779 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4781 } else
4782 #endif
4783 if (!strcmp(device, "socket")) {
4784 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4785 int fd;
4786 fd = strtol(buf, NULL, 0);
4787 ret = -1;
4788 if (net_socket_fd_init(vlan, fd, 1))
4789 ret = 0;
4790 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4791 ret = net_socket_listen_init(vlan, buf);
4792 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4793 ret = net_socket_connect_init(vlan, buf);
4794 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4795 ret = net_socket_mcast_init(vlan, buf);
4796 } else {
4797 fprintf(stderr, "Unknown socket options: %s\n", p);
4798 return -1;
4800 vlan->nb_host_devs++;
4801 } else
4803 fprintf(stderr, "Unknown network device: %s\n", device);
4804 return -1;
4806 if (ret < 0) {
4807 fprintf(stderr, "Could not initialize device '%s'\n", device);
4810 return ret;
4813 void do_info_network(void)
4815 VLANState *vlan;
4816 VLANClientState *vc;
4818 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4819 term_printf("VLAN %d devices:\n", vlan->id);
4820 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4821 term_printf(" %s\n", vc->info_str);
4825 #define HD_ALIAS "index=%d,media=disk"
4826 #ifdef TARGET_PPC
4827 #define CDROM_ALIAS "index=1,media=cdrom"
4828 #else
4829 #define CDROM_ALIAS "index=2,media=cdrom"
4830 #endif
4831 #define FD_ALIAS "index=%d,if=floppy"
4832 #define PFLASH_ALIAS "if=pflash"
4833 #define MTD_ALIAS "if=mtd"
4834 #define SD_ALIAS "index=0,if=sd"
4836 static int drive_add(const char *file, const char *fmt, ...)
4838 va_list ap;
4840 if (nb_drives_opt >= MAX_DRIVES) {
4841 fprintf(stderr, "qemu: too many drives\n");
4842 exit(1);
4845 drives_opt[nb_drives_opt].file = file;
4846 va_start(ap, fmt);
4847 vsnprintf(drives_opt[nb_drives_opt].opt,
4848 sizeof(drives_opt[0].opt), fmt, ap);
4849 va_end(ap);
4851 return nb_drives_opt++;
4854 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4856 int index;
4858 /* seek interface, bus and unit */
4860 for (index = 0; index < nb_drives; index++)
4861 if (drives_table[index].type == type &&
4862 drives_table[index].bus == bus &&
4863 drives_table[index].unit == unit)
4864 return index;
4866 return -1;
4869 int drive_get_max_bus(BlockInterfaceType type)
4871 int max_bus;
4872 int index;
4874 max_bus = -1;
4875 for (index = 0; index < nb_drives; index++) {
4876 if(drives_table[index].type == type &&
4877 drives_table[index].bus > max_bus)
4878 max_bus = drives_table[index].bus;
4880 return max_bus;
4883 static int drive_init(struct drive_opt *arg, int snapshot,
4884 QEMUMachine *machine)
4886 char buf[128];
4887 char file[1024];
4888 char devname[128];
4889 const char *mediastr = "";
4890 BlockInterfaceType type;
4891 enum { MEDIA_DISK, MEDIA_CDROM } media;
4892 int bus_id, unit_id;
4893 int cyls, heads, secs, translation;
4894 BlockDriverState *bdrv;
4895 int max_devs;
4896 int index;
4897 int cache;
4898 int bdrv_flags;
4899 char *str = arg->opt;
4900 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4901 "secs", "trans", "media", "snapshot", "file",
4902 "cache", NULL };
4904 if (check_params(buf, sizeof(buf), params, str) < 0) {
4905 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4906 buf, str);
4907 return -1;
4910 file[0] = 0;
4911 cyls = heads = secs = 0;
4912 bus_id = 0;
4913 unit_id = -1;
4914 translation = BIOS_ATA_TRANSLATION_AUTO;
4915 index = -1;
4916 cache = 1;
4918 if (!strcmp(machine->name, "realview") ||
4919 !strcmp(machine->name, "SS-5") ||
4920 !strcmp(machine->name, "SS-10") ||
4921 !strcmp(machine->name, "SS-600MP") ||
4922 !strcmp(machine->name, "versatilepb") ||
4923 !strcmp(machine->name, "versatileab")) {
4924 type = IF_SCSI;
4925 max_devs = MAX_SCSI_DEVS;
4926 strcpy(devname, "scsi");
4927 } else {
4928 type = IF_IDE;
4929 max_devs = MAX_IDE_DEVS;
4930 strcpy(devname, "ide");
4932 media = MEDIA_DISK;
4934 /* extract parameters */
4936 if (get_param_value(buf, sizeof(buf), "bus", str)) {
4937 bus_id = strtol(buf, NULL, 0);
4938 if (bus_id < 0) {
4939 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4940 return -1;
4944 if (get_param_value(buf, sizeof(buf), "unit", str)) {
4945 unit_id = strtol(buf, NULL, 0);
4946 if (unit_id < 0) {
4947 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4948 return -1;
4952 if (get_param_value(buf, sizeof(buf), "if", str)) {
4953 strncpy(devname, buf, sizeof(devname));
4954 if (!strcmp(buf, "ide")) {
4955 type = IF_IDE;
4956 max_devs = MAX_IDE_DEVS;
4957 } else if (!strcmp(buf, "scsi")) {
4958 type = IF_SCSI;
4959 max_devs = MAX_SCSI_DEVS;
4960 } else if (!strcmp(buf, "floppy")) {
4961 type = IF_FLOPPY;
4962 max_devs = 0;
4963 } else if (!strcmp(buf, "pflash")) {
4964 type = IF_PFLASH;
4965 max_devs = 0;
4966 } else if (!strcmp(buf, "mtd")) {
4967 type = IF_MTD;
4968 max_devs = 0;
4969 } else if (!strcmp(buf, "sd")) {
4970 type = IF_SD;
4971 max_devs = 0;
4972 } else {
4973 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
4974 return -1;
4978 if (get_param_value(buf, sizeof(buf), "index", str)) {
4979 index = strtol(buf, NULL, 0);
4980 if (index < 0) {
4981 fprintf(stderr, "qemu: '%s' invalid index\n", str);
4982 return -1;
4986 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
4987 cyls = strtol(buf, NULL, 0);
4990 if (get_param_value(buf, sizeof(buf), "heads", str)) {
4991 heads = strtol(buf, NULL, 0);
4994 if (get_param_value(buf, sizeof(buf), "secs", str)) {
4995 secs = strtol(buf, NULL, 0);
4998 if (cyls || heads || secs) {
4999 if (cyls < 1 || cyls > 16383) {
5000 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5001 return -1;
5003 if (heads < 1 || heads > 16) {
5004 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5005 return -1;
5007 if (secs < 1 || secs > 63) {
5008 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5009 return -1;
5013 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5014 if (!cyls) {
5015 fprintf(stderr,
5016 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5017 str);
5018 return -1;
5020 if (!strcmp(buf, "none"))
5021 translation = BIOS_ATA_TRANSLATION_NONE;
5022 else if (!strcmp(buf, "lba"))
5023 translation = BIOS_ATA_TRANSLATION_LBA;
5024 else if (!strcmp(buf, "auto"))
5025 translation = BIOS_ATA_TRANSLATION_AUTO;
5026 else {
5027 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5028 return -1;
5032 if (get_param_value(buf, sizeof(buf), "media", str)) {
5033 if (!strcmp(buf, "disk")) {
5034 media = MEDIA_DISK;
5035 } else if (!strcmp(buf, "cdrom")) {
5036 if (cyls || secs || heads) {
5037 fprintf(stderr,
5038 "qemu: '%s' invalid physical CHS format\n", str);
5039 return -1;
5041 media = MEDIA_CDROM;
5042 } else {
5043 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5044 return -1;
5048 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5049 if (!strcmp(buf, "on"))
5050 snapshot = 1;
5051 else if (!strcmp(buf, "off"))
5052 snapshot = 0;
5053 else {
5054 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5055 return -1;
5059 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5060 if (!strcmp(buf, "off"))
5061 cache = 0;
5062 else if (!strcmp(buf, "on"))
5063 cache = 1;
5064 else {
5065 fprintf(stderr, "qemu: invalid cache option\n");
5066 return -1;
5070 if (arg->file == NULL)
5071 get_param_value(file, sizeof(file), "file", str);
5072 else
5073 pstrcpy(file, sizeof(file), arg->file);
5075 /* compute bus and unit according index */
5077 if (index != -1) {
5078 if (bus_id != 0 || unit_id != -1) {
5079 fprintf(stderr,
5080 "qemu: '%s' index cannot be used with bus and unit\n", str);
5081 return -1;
5083 if (max_devs == 0)
5085 unit_id = index;
5086 bus_id = 0;
5087 } else {
5088 unit_id = index % max_devs;
5089 bus_id = index / max_devs;
5093 /* if user doesn't specify a unit_id,
5094 * try to find the first free
5097 if (unit_id == -1) {
5098 unit_id = 0;
5099 while (drive_get_index(type, bus_id, unit_id) != -1) {
5100 unit_id++;
5101 if (max_devs && unit_id >= max_devs) {
5102 unit_id -= max_devs;
5103 bus_id++;
5108 /* check unit id */
5110 if (max_devs && unit_id >= max_devs) {
5111 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5112 str, unit_id, max_devs - 1);
5113 return -1;
5117 * ignore multiple definitions
5120 if (drive_get_index(type, bus_id, unit_id) != -1)
5121 return 0;
5123 /* init */
5125 if (type == IF_IDE || type == IF_SCSI)
5126 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5127 if (max_devs)
5128 snprintf(buf, sizeof(buf), "%s%i%s%i",
5129 devname, bus_id, mediastr, unit_id);
5130 else
5131 snprintf(buf, sizeof(buf), "%s%s%i",
5132 devname, mediastr, unit_id);
5133 bdrv = bdrv_new(buf);
5134 drives_table[nb_drives].bdrv = bdrv;
5135 drives_table[nb_drives].type = type;
5136 drives_table[nb_drives].bus = bus_id;
5137 drives_table[nb_drives].unit = unit_id;
5138 nb_drives++;
5140 switch(type) {
5141 case IF_IDE:
5142 case IF_SCSI:
5143 switch(media) {
5144 case MEDIA_DISK:
5145 if (cyls != 0) {
5146 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5147 bdrv_set_translation_hint(bdrv, translation);
5149 break;
5150 case MEDIA_CDROM:
5151 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5152 break;
5154 break;
5155 case IF_SD:
5156 /* FIXME: This isn't really a floppy, but it's a reasonable
5157 approximation. */
5158 case IF_FLOPPY:
5159 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5160 break;
5161 case IF_PFLASH:
5162 case IF_MTD:
5163 break;
5165 if (!file[0])
5166 return 0;
5167 bdrv_flags = 0;
5168 if (snapshot)
5169 bdrv_flags |= BDRV_O_SNAPSHOT;
5170 if (!cache)
5171 bdrv_flags |= BDRV_O_DIRECT;
5172 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5173 fprintf(stderr, "qemu: could not open disk image %s\n",
5174 file);
5175 return -1;
5177 return 0;
5180 /***********************************************************/
5181 /* USB devices */
5183 static USBPort *used_usb_ports;
5184 static USBPort *free_usb_ports;
5186 /* ??? Maybe change this to register a hub to keep track of the topology. */
5187 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5188 usb_attachfn attach)
5190 port->opaque = opaque;
5191 port->index = index;
5192 port->attach = attach;
5193 port->next = free_usb_ports;
5194 free_usb_ports = port;
5197 static int usb_device_add(const char *devname)
5199 const char *p;
5200 USBDevice *dev;
5201 USBPort *port;
5203 if (!free_usb_ports)
5204 return -1;
5206 if (strstart(devname, "host:", &p)) {
5207 dev = usb_host_device_open(p);
5208 } else if (!strcmp(devname, "mouse")) {
5209 dev = usb_mouse_init();
5210 } else if (!strcmp(devname, "tablet")) {
5211 dev = usb_tablet_init();
5212 } else if (!strcmp(devname, "keyboard")) {
5213 dev = usb_keyboard_init();
5214 } else if (strstart(devname, "disk:", &p)) {
5215 dev = usb_msd_init(p);
5216 } else if (!strcmp(devname, "wacom-tablet")) {
5217 dev = usb_wacom_init();
5218 } else {
5219 return -1;
5221 if (!dev)
5222 return -1;
5224 /* Find a USB port to add the device to. */
5225 port = free_usb_ports;
5226 if (!port->next) {
5227 USBDevice *hub;
5229 /* Create a new hub and chain it on. */
5230 free_usb_ports = NULL;
5231 port->next = used_usb_ports;
5232 used_usb_ports = port;
5234 hub = usb_hub_init(VM_USB_HUB_SIZE);
5235 usb_attach(port, hub);
5236 port = free_usb_ports;
5239 free_usb_ports = port->next;
5240 port->next = used_usb_ports;
5241 used_usb_ports = port;
5242 usb_attach(port, dev);
5243 return 0;
5246 static int usb_device_del(const char *devname)
5248 USBPort *port;
5249 USBPort **lastp;
5250 USBDevice *dev;
5251 int bus_num, addr;
5252 const char *p;
5254 if (!used_usb_ports)
5255 return -1;
5257 p = strchr(devname, '.');
5258 if (!p)
5259 return -1;
5260 bus_num = strtoul(devname, NULL, 0);
5261 addr = strtoul(p + 1, NULL, 0);
5262 if (bus_num != 0)
5263 return -1;
5265 lastp = &used_usb_ports;
5266 port = used_usb_ports;
5267 while (port && port->dev->addr != addr) {
5268 lastp = &port->next;
5269 port = port->next;
5272 if (!port)
5273 return -1;
5275 dev = port->dev;
5276 *lastp = port->next;
5277 usb_attach(port, NULL);
5278 dev->handle_destroy(dev);
5279 port->next = free_usb_ports;
5280 free_usb_ports = port;
5281 return 0;
5284 void do_usb_add(const char *devname)
5286 int ret;
5287 ret = usb_device_add(devname);
5288 if (ret < 0)
5289 term_printf("Could not add USB device '%s'\n", devname);
5292 void do_usb_del(const char *devname)
5294 int ret;
5295 ret = usb_device_del(devname);
5296 if (ret < 0)
5297 term_printf("Could not remove USB device '%s'\n", devname);
5300 void usb_info(void)
5302 USBDevice *dev;
5303 USBPort *port;
5304 const char *speed_str;
5306 if (!usb_enabled) {
5307 term_printf("USB support not enabled\n");
5308 return;
5311 for (port = used_usb_ports; port; port = port->next) {
5312 dev = port->dev;
5313 if (!dev)
5314 continue;
5315 switch(dev->speed) {
5316 case USB_SPEED_LOW:
5317 speed_str = "1.5";
5318 break;
5319 case USB_SPEED_FULL:
5320 speed_str = "12";
5321 break;
5322 case USB_SPEED_HIGH:
5323 speed_str = "480";
5324 break;
5325 default:
5326 speed_str = "?";
5327 break;
5329 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5330 0, dev->addr, speed_str, dev->devname);
5334 /***********************************************************/
5335 /* PCMCIA/Cardbus */
5337 static struct pcmcia_socket_entry_s {
5338 struct pcmcia_socket_s *socket;
5339 struct pcmcia_socket_entry_s *next;
5340 } *pcmcia_sockets = 0;
5342 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5344 struct pcmcia_socket_entry_s *entry;
5346 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5347 entry->socket = socket;
5348 entry->next = pcmcia_sockets;
5349 pcmcia_sockets = entry;
5352 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5354 struct pcmcia_socket_entry_s *entry, **ptr;
5356 ptr = &pcmcia_sockets;
5357 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5358 if (entry->socket == socket) {
5359 *ptr = entry->next;
5360 qemu_free(entry);
5364 void pcmcia_info(void)
5366 struct pcmcia_socket_entry_s *iter;
5367 if (!pcmcia_sockets)
5368 term_printf("No PCMCIA sockets\n");
5370 for (iter = pcmcia_sockets; iter; iter = iter->next)
5371 term_printf("%s: %s\n", iter->socket->slot_string,
5372 iter->socket->attached ? iter->socket->card_string :
5373 "Empty");
5376 /***********************************************************/
5377 /* dumb display */
5379 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5383 static void dumb_resize(DisplayState *ds, int w, int h)
5387 static void dumb_refresh(DisplayState *ds)
5389 #if defined(CONFIG_SDL)
5390 vga_hw_update();
5391 #endif
5394 static void dumb_display_init(DisplayState *ds)
5396 ds->data = NULL;
5397 ds->linesize = 0;
5398 ds->depth = 0;
5399 ds->dpy_update = dumb_update;
5400 ds->dpy_resize = dumb_resize;
5401 ds->dpy_refresh = dumb_refresh;
5404 /***********************************************************/
5405 /* I/O handling */
5407 #define MAX_IO_HANDLERS 64
5409 typedef struct IOHandlerRecord {
5410 int fd;
5411 IOCanRWHandler *fd_read_poll;
5412 IOHandler *fd_read;
5413 IOHandler *fd_write;
5414 int deleted;
5415 void *opaque;
5416 /* temporary data */
5417 struct pollfd *ufd;
5418 struct IOHandlerRecord *next;
5419 } IOHandlerRecord;
5421 static IOHandlerRecord *first_io_handler;
5423 /* XXX: fd_read_poll should be suppressed, but an API change is
5424 necessary in the character devices to suppress fd_can_read(). */
5425 int qemu_set_fd_handler2(int fd,
5426 IOCanRWHandler *fd_read_poll,
5427 IOHandler *fd_read,
5428 IOHandler *fd_write,
5429 void *opaque)
5431 IOHandlerRecord **pioh, *ioh;
5433 if (!fd_read && !fd_write) {
5434 pioh = &first_io_handler;
5435 for(;;) {
5436 ioh = *pioh;
5437 if (ioh == NULL)
5438 break;
5439 if (ioh->fd == fd) {
5440 ioh->deleted = 1;
5441 break;
5443 pioh = &ioh->next;
5445 } else {
5446 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5447 if (ioh->fd == fd)
5448 goto found;
5450 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5451 if (!ioh)
5452 return -1;
5453 ioh->next = first_io_handler;
5454 first_io_handler = ioh;
5455 found:
5456 ioh->fd = fd;
5457 ioh->fd_read_poll = fd_read_poll;
5458 ioh->fd_read = fd_read;
5459 ioh->fd_write = fd_write;
5460 ioh->opaque = opaque;
5461 ioh->deleted = 0;
5463 return 0;
5466 int qemu_set_fd_handler(int fd,
5467 IOHandler *fd_read,
5468 IOHandler *fd_write,
5469 void *opaque)
5471 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5474 /***********************************************************/
5475 /* Polling handling */
5477 typedef struct PollingEntry {
5478 PollingFunc *func;
5479 void *opaque;
5480 struct PollingEntry *next;
5481 } PollingEntry;
5483 static PollingEntry *first_polling_entry;
5485 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5487 PollingEntry **ppe, *pe;
5488 pe = qemu_mallocz(sizeof(PollingEntry));
5489 if (!pe)
5490 return -1;
5491 pe->func = func;
5492 pe->opaque = opaque;
5493 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5494 *ppe = pe;
5495 return 0;
5498 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5500 PollingEntry **ppe, *pe;
5501 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5502 pe = *ppe;
5503 if (pe->func == func && pe->opaque == opaque) {
5504 *ppe = pe->next;
5505 qemu_free(pe);
5506 break;
5511 #ifdef _WIN32
5512 /***********************************************************/
5513 /* Wait objects support */
5514 typedef struct WaitObjects {
5515 int num;
5516 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5517 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5518 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5519 } WaitObjects;
5521 static WaitObjects wait_objects = {0};
5523 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5525 WaitObjects *w = &wait_objects;
5527 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5528 return -1;
5529 w->events[w->num] = handle;
5530 w->func[w->num] = func;
5531 w->opaque[w->num] = opaque;
5532 w->num++;
5533 return 0;
5536 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5538 int i, found;
5539 WaitObjects *w = &wait_objects;
5541 found = 0;
5542 for (i = 0; i < w->num; i++) {
5543 if (w->events[i] == handle)
5544 found = 1;
5545 if (found) {
5546 w->events[i] = w->events[i + 1];
5547 w->func[i] = w->func[i + 1];
5548 w->opaque[i] = w->opaque[i + 1];
5551 if (found)
5552 w->num--;
5554 #endif
5556 /***********************************************************/
5557 /* savevm/loadvm support */
5559 #define IO_BUF_SIZE 32768
5561 struct QEMUFile {
5562 FILE *outfile;
5563 BlockDriverState *bs;
5564 int is_file;
5565 int is_writable;
5566 int64_t base_offset;
5567 int64_t buf_offset; /* start of buffer when writing, end of buffer
5568 when reading */
5569 int buf_index;
5570 int buf_size; /* 0 when writing */
5571 uint8_t buf[IO_BUF_SIZE];
5574 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5576 QEMUFile *f;
5578 f = qemu_mallocz(sizeof(QEMUFile));
5579 if (!f)
5580 return NULL;
5581 if (!strcmp(mode, "wb")) {
5582 f->is_writable = 1;
5583 } else if (!strcmp(mode, "rb")) {
5584 f->is_writable = 0;
5585 } else {
5586 goto fail;
5588 f->outfile = fopen(filename, mode);
5589 if (!f->outfile)
5590 goto fail;
5591 f->is_file = 1;
5592 return f;
5593 fail:
5594 if (f->outfile)
5595 fclose(f->outfile);
5596 qemu_free(f);
5597 return NULL;
5600 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5602 QEMUFile *f;
5604 f = qemu_mallocz(sizeof(QEMUFile));
5605 if (!f)
5606 return NULL;
5607 f->is_file = 0;
5608 f->bs = bs;
5609 f->is_writable = is_writable;
5610 f->base_offset = offset;
5611 return f;
5614 void qemu_fflush(QEMUFile *f)
5616 if (!f->is_writable)
5617 return;
5618 if (f->buf_index > 0) {
5619 if (f->is_file) {
5620 fseek(f->outfile, f->buf_offset, SEEK_SET);
5621 fwrite(f->buf, 1, f->buf_index, f->outfile);
5622 } else {
5623 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5624 f->buf, f->buf_index);
5626 f->buf_offset += f->buf_index;
5627 f->buf_index = 0;
5631 static void qemu_fill_buffer(QEMUFile *f)
5633 int len;
5635 if (f->is_writable)
5636 return;
5637 if (f->is_file) {
5638 fseek(f->outfile, f->buf_offset, SEEK_SET);
5639 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5640 if (len < 0)
5641 len = 0;
5642 } else {
5643 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5644 f->buf, IO_BUF_SIZE);
5645 if (len < 0)
5646 len = 0;
5648 f->buf_index = 0;
5649 f->buf_size = len;
5650 f->buf_offset += len;
5653 void qemu_fclose(QEMUFile *f)
5655 if (f->is_writable)
5656 qemu_fflush(f);
5657 if (f->is_file) {
5658 fclose(f->outfile);
5660 qemu_free(f);
5663 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5665 int l;
5666 while (size > 0) {
5667 l = IO_BUF_SIZE - f->buf_index;
5668 if (l > size)
5669 l = size;
5670 memcpy(f->buf + f->buf_index, buf, l);
5671 f->buf_index += l;
5672 buf += l;
5673 size -= l;
5674 if (f->buf_index >= IO_BUF_SIZE)
5675 qemu_fflush(f);
5679 void qemu_put_byte(QEMUFile *f, int v)
5681 f->buf[f->buf_index++] = v;
5682 if (f->buf_index >= IO_BUF_SIZE)
5683 qemu_fflush(f);
5686 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5688 int size, l;
5690 size = size1;
5691 while (size > 0) {
5692 l = f->buf_size - f->buf_index;
5693 if (l == 0) {
5694 qemu_fill_buffer(f);
5695 l = f->buf_size - f->buf_index;
5696 if (l == 0)
5697 break;
5699 if (l > size)
5700 l = size;
5701 memcpy(buf, f->buf + f->buf_index, l);
5702 f->buf_index += l;
5703 buf += l;
5704 size -= l;
5706 return size1 - size;
5709 int qemu_get_byte(QEMUFile *f)
5711 if (f->buf_index >= f->buf_size) {
5712 qemu_fill_buffer(f);
5713 if (f->buf_index >= f->buf_size)
5714 return 0;
5716 return f->buf[f->buf_index++];
5719 int64_t qemu_ftell(QEMUFile *f)
5721 return f->buf_offset - f->buf_size + f->buf_index;
5724 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5726 if (whence == SEEK_SET) {
5727 /* nothing to do */
5728 } else if (whence == SEEK_CUR) {
5729 pos += qemu_ftell(f);
5730 } else {
5731 /* SEEK_END not supported */
5732 return -1;
5734 if (f->is_writable) {
5735 qemu_fflush(f);
5736 f->buf_offset = pos;
5737 } else {
5738 f->buf_offset = pos;
5739 f->buf_index = 0;
5740 f->buf_size = 0;
5742 return pos;
5745 void qemu_put_be16(QEMUFile *f, unsigned int v)
5747 qemu_put_byte(f, v >> 8);
5748 qemu_put_byte(f, v);
5751 void qemu_put_be32(QEMUFile *f, unsigned int v)
5753 qemu_put_byte(f, v >> 24);
5754 qemu_put_byte(f, v >> 16);
5755 qemu_put_byte(f, v >> 8);
5756 qemu_put_byte(f, v);
5759 void qemu_put_be64(QEMUFile *f, uint64_t v)
5761 qemu_put_be32(f, v >> 32);
5762 qemu_put_be32(f, v);
5765 unsigned int qemu_get_be16(QEMUFile *f)
5767 unsigned int v;
5768 v = qemu_get_byte(f) << 8;
5769 v |= qemu_get_byte(f);
5770 return v;
5773 unsigned int qemu_get_be32(QEMUFile *f)
5775 unsigned int v;
5776 v = qemu_get_byte(f) << 24;
5777 v |= qemu_get_byte(f) << 16;
5778 v |= qemu_get_byte(f) << 8;
5779 v |= qemu_get_byte(f);
5780 return v;
5783 uint64_t qemu_get_be64(QEMUFile *f)
5785 uint64_t v;
5786 v = (uint64_t)qemu_get_be32(f) << 32;
5787 v |= qemu_get_be32(f);
5788 return v;
5791 typedef struct SaveStateEntry {
5792 char idstr[256];
5793 int instance_id;
5794 int version_id;
5795 SaveStateHandler *save_state;
5796 LoadStateHandler *load_state;
5797 void *opaque;
5798 struct SaveStateEntry *next;
5799 } SaveStateEntry;
5801 static SaveStateEntry *first_se;
5803 int register_savevm(const char *idstr,
5804 int instance_id,
5805 int version_id,
5806 SaveStateHandler *save_state,
5807 LoadStateHandler *load_state,
5808 void *opaque)
5810 SaveStateEntry *se, **pse;
5812 se = qemu_malloc(sizeof(SaveStateEntry));
5813 if (!se)
5814 return -1;
5815 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5816 se->instance_id = instance_id;
5817 se->version_id = version_id;
5818 se->save_state = save_state;
5819 se->load_state = load_state;
5820 se->opaque = opaque;
5821 se->next = NULL;
5823 /* add at the end of list */
5824 pse = &first_se;
5825 while (*pse != NULL)
5826 pse = &(*pse)->next;
5827 *pse = se;
5828 return 0;
5831 #define QEMU_VM_FILE_MAGIC 0x5145564d
5832 #define QEMU_VM_FILE_VERSION 0x00000002
5834 static int qemu_savevm_state(QEMUFile *f)
5836 SaveStateEntry *se;
5837 int len, ret;
5838 int64_t cur_pos, len_pos, total_len_pos;
5840 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5841 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5842 total_len_pos = qemu_ftell(f);
5843 qemu_put_be64(f, 0); /* total size */
5845 for(se = first_se; se != NULL; se = se->next) {
5846 /* ID string */
5847 len = strlen(se->idstr);
5848 qemu_put_byte(f, len);
5849 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5851 qemu_put_be32(f, se->instance_id);
5852 qemu_put_be32(f, se->version_id);
5854 /* record size: filled later */
5855 len_pos = qemu_ftell(f);
5856 qemu_put_be32(f, 0);
5857 se->save_state(f, se->opaque);
5859 /* fill record size */
5860 cur_pos = qemu_ftell(f);
5861 len = cur_pos - len_pos - 4;
5862 qemu_fseek(f, len_pos, SEEK_SET);
5863 qemu_put_be32(f, len);
5864 qemu_fseek(f, cur_pos, SEEK_SET);
5866 cur_pos = qemu_ftell(f);
5867 qemu_fseek(f, total_len_pos, SEEK_SET);
5868 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5869 qemu_fseek(f, cur_pos, SEEK_SET);
5871 ret = 0;
5872 return ret;
5875 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5877 SaveStateEntry *se;
5879 for(se = first_se; se != NULL; se = se->next) {
5880 if (!strcmp(se->idstr, idstr) &&
5881 instance_id == se->instance_id)
5882 return se;
5884 return NULL;
5887 static int qemu_loadvm_state(QEMUFile *f)
5889 SaveStateEntry *se;
5890 int len, ret, instance_id, record_len, version_id;
5891 int64_t total_len, end_pos, cur_pos;
5892 unsigned int v;
5893 char idstr[256];
5895 v = qemu_get_be32(f);
5896 if (v != QEMU_VM_FILE_MAGIC)
5897 goto fail;
5898 v = qemu_get_be32(f);
5899 if (v != QEMU_VM_FILE_VERSION) {
5900 fail:
5901 ret = -1;
5902 goto the_end;
5904 total_len = qemu_get_be64(f);
5905 end_pos = total_len + qemu_ftell(f);
5906 for(;;) {
5907 if (qemu_ftell(f) >= end_pos)
5908 break;
5909 len = qemu_get_byte(f);
5910 qemu_get_buffer(f, (uint8_t *)idstr, len);
5911 idstr[len] = '\0';
5912 instance_id = qemu_get_be32(f);
5913 version_id = qemu_get_be32(f);
5914 record_len = qemu_get_be32(f);
5915 #if 0
5916 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5917 idstr, instance_id, version_id, record_len);
5918 #endif
5919 cur_pos = qemu_ftell(f);
5920 se = find_se(idstr, instance_id);
5921 if (!se) {
5922 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5923 instance_id, idstr);
5924 } else {
5925 ret = se->load_state(f, se->opaque, version_id);
5926 if (ret < 0) {
5927 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5928 instance_id, idstr);
5931 /* always seek to exact end of record */
5932 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5934 ret = 0;
5935 the_end:
5936 return ret;
5939 /* device can contain snapshots */
5940 static int bdrv_can_snapshot(BlockDriverState *bs)
5942 return (bs &&
5943 !bdrv_is_removable(bs) &&
5944 !bdrv_is_read_only(bs));
5947 /* device must be snapshots in order to have a reliable snapshot */
5948 static int bdrv_has_snapshot(BlockDriverState *bs)
5950 return (bs &&
5951 !bdrv_is_removable(bs) &&
5952 !bdrv_is_read_only(bs));
5955 static BlockDriverState *get_bs_snapshots(void)
5957 BlockDriverState *bs;
5958 int i;
5960 if (bs_snapshots)
5961 return bs_snapshots;
5962 for(i = 0; i <= nb_drives; i++) {
5963 bs = drives_table[i].bdrv;
5964 if (bdrv_can_snapshot(bs))
5965 goto ok;
5967 return NULL;
5969 bs_snapshots = bs;
5970 return bs;
5973 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5974 const char *name)
5976 QEMUSnapshotInfo *sn_tab, *sn;
5977 int nb_sns, i, ret;
5979 ret = -ENOENT;
5980 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5981 if (nb_sns < 0)
5982 return ret;
5983 for(i = 0; i < nb_sns; i++) {
5984 sn = &sn_tab[i];
5985 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5986 *sn_info = *sn;
5987 ret = 0;
5988 break;
5991 qemu_free(sn_tab);
5992 return ret;
5995 void do_savevm(const char *name)
5997 BlockDriverState *bs, *bs1;
5998 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5999 int must_delete, ret, i;
6000 BlockDriverInfo bdi1, *bdi = &bdi1;
6001 QEMUFile *f;
6002 int saved_vm_running;
6003 #ifdef _WIN32
6004 struct _timeb tb;
6005 #else
6006 struct timeval tv;
6007 #endif
6009 bs = get_bs_snapshots();
6010 if (!bs) {
6011 term_printf("No block device can accept snapshots\n");
6012 return;
6015 /* ??? Should this occur after vm_stop? */
6016 qemu_aio_flush();
6018 saved_vm_running = vm_running;
6019 vm_stop(0);
6021 must_delete = 0;
6022 if (name) {
6023 ret = bdrv_snapshot_find(bs, old_sn, name);
6024 if (ret >= 0) {
6025 must_delete = 1;
6028 memset(sn, 0, sizeof(*sn));
6029 if (must_delete) {
6030 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6031 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6032 } else {
6033 if (name)
6034 pstrcpy(sn->name, sizeof(sn->name), name);
6037 /* fill auxiliary fields */
6038 #ifdef _WIN32
6039 _ftime(&tb);
6040 sn->date_sec = tb.time;
6041 sn->date_nsec = tb.millitm * 1000000;
6042 #else
6043 gettimeofday(&tv, NULL);
6044 sn->date_sec = tv.tv_sec;
6045 sn->date_nsec = tv.tv_usec * 1000;
6046 #endif
6047 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6049 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6050 term_printf("Device %s does not support VM state snapshots\n",
6051 bdrv_get_device_name(bs));
6052 goto the_end;
6055 /* save the VM state */
6056 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6057 if (!f) {
6058 term_printf("Could not open VM state file\n");
6059 goto the_end;
6061 ret = qemu_savevm_state(f);
6062 sn->vm_state_size = qemu_ftell(f);
6063 qemu_fclose(f);
6064 if (ret < 0) {
6065 term_printf("Error %d while writing VM\n", ret);
6066 goto the_end;
6069 /* create the snapshots */
6071 for(i = 0; i < nb_drives; i++) {
6072 bs1 = drives_table[i].bdrv;
6073 if (bdrv_has_snapshot(bs1)) {
6074 if (must_delete) {
6075 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6076 if (ret < 0) {
6077 term_printf("Error while deleting snapshot on '%s'\n",
6078 bdrv_get_device_name(bs1));
6081 ret = bdrv_snapshot_create(bs1, sn);
6082 if (ret < 0) {
6083 term_printf("Error while creating snapshot on '%s'\n",
6084 bdrv_get_device_name(bs1));
6089 the_end:
6090 if (saved_vm_running)
6091 vm_start();
6094 void do_loadvm(const char *name)
6096 BlockDriverState *bs, *bs1;
6097 BlockDriverInfo bdi1, *bdi = &bdi1;
6098 QEMUFile *f;
6099 int i, ret;
6100 int saved_vm_running;
6102 bs = get_bs_snapshots();
6103 if (!bs) {
6104 term_printf("No block device supports snapshots\n");
6105 return;
6108 /* Flush all IO requests so they don't interfere with the new state. */
6109 qemu_aio_flush();
6111 saved_vm_running = vm_running;
6112 vm_stop(0);
6114 for(i = 0; i <= nb_drives; i++) {
6115 bs1 = drives_table[i].bdrv;
6116 if (bdrv_has_snapshot(bs1)) {
6117 ret = bdrv_snapshot_goto(bs1, name);
6118 if (ret < 0) {
6119 if (bs != bs1)
6120 term_printf("Warning: ");
6121 switch(ret) {
6122 case -ENOTSUP:
6123 term_printf("Snapshots not supported on device '%s'\n",
6124 bdrv_get_device_name(bs1));
6125 break;
6126 case -ENOENT:
6127 term_printf("Could not find snapshot '%s' on device '%s'\n",
6128 name, bdrv_get_device_name(bs1));
6129 break;
6130 default:
6131 term_printf("Error %d while activating snapshot on '%s'\n",
6132 ret, bdrv_get_device_name(bs1));
6133 break;
6135 /* fatal on snapshot block device */
6136 if (bs == bs1)
6137 goto the_end;
6142 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6143 term_printf("Device %s does not support VM state snapshots\n",
6144 bdrv_get_device_name(bs));
6145 return;
6148 /* restore the VM state */
6149 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6150 if (!f) {
6151 term_printf("Could not open VM state file\n");
6152 goto the_end;
6154 ret = qemu_loadvm_state(f);
6155 qemu_fclose(f);
6156 if (ret < 0) {
6157 term_printf("Error %d while loading VM state\n", ret);
6159 the_end:
6160 if (saved_vm_running)
6161 vm_start();
6164 void do_delvm(const char *name)
6166 BlockDriverState *bs, *bs1;
6167 int i, ret;
6169 bs = get_bs_snapshots();
6170 if (!bs) {
6171 term_printf("No block device supports snapshots\n");
6172 return;
6175 for(i = 0; i <= nb_drives; i++) {
6176 bs1 = drives_table[i].bdrv;
6177 if (bdrv_has_snapshot(bs1)) {
6178 ret = bdrv_snapshot_delete(bs1, name);
6179 if (ret < 0) {
6180 if (ret == -ENOTSUP)
6181 term_printf("Snapshots not supported on device '%s'\n",
6182 bdrv_get_device_name(bs1));
6183 else
6184 term_printf("Error %d while deleting snapshot on '%s'\n",
6185 ret, bdrv_get_device_name(bs1));
6191 void do_info_snapshots(void)
6193 BlockDriverState *bs, *bs1;
6194 QEMUSnapshotInfo *sn_tab, *sn;
6195 int nb_sns, i;
6196 char buf[256];
6198 bs = get_bs_snapshots();
6199 if (!bs) {
6200 term_printf("No available block device supports snapshots\n");
6201 return;
6203 term_printf("Snapshot devices:");
6204 for(i = 0; i <= nb_drives; i++) {
6205 bs1 = drives_table[i].bdrv;
6206 if (bdrv_has_snapshot(bs1)) {
6207 if (bs == bs1)
6208 term_printf(" %s", bdrv_get_device_name(bs1));
6211 term_printf("\n");
6213 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6214 if (nb_sns < 0) {
6215 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6216 return;
6218 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6219 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6220 for(i = 0; i < nb_sns; i++) {
6221 sn = &sn_tab[i];
6222 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6224 qemu_free(sn_tab);
6227 /***********************************************************/
6228 /* cpu save/restore */
6230 #if defined(TARGET_I386)
6232 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6234 qemu_put_be32(f, dt->selector);
6235 qemu_put_betl(f, dt->base);
6236 qemu_put_be32(f, dt->limit);
6237 qemu_put_be32(f, dt->flags);
6240 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6242 dt->selector = qemu_get_be32(f);
6243 dt->base = qemu_get_betl(f);
6244 dt->limit = qemu_get_be32(f);
6245 dt->flags = qemu_get_be32(f);
6248 void cpu_save(QEMUFile *f, void *opaque)
6250 CPUState *env = opaque;
6251 uint16_t fptag, fpus, fpuc, fpregs_format;
6252 uint32_t hflags;
6253 int i;
6255 for(i = 0; i < CPU_NB_REGS; i++)
6256 qemu_put_betls(f, &env->regs[i]);
6257 qemu_put_betls(f, &env->eip);
6258 qemu_put_betls(f, &env->eflags);
6259 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6260 qemu_put_be32s(f, &hflags);
6262 /* FPU */
6263 fpuc = env->fpuc;
6264 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6265 fptag = 0;
6266 for(i = 0; i < 8; i++) {
6267 fptag |= ((!env->fptags[i]) << i);
6270 qemu_put_be16s(f, &fpuc);
6271 qemu_put_be16s(f, &fpus);
6272 qemu_put_be16s(f, &fptag);
6274 #ifdef USE_X86LDOUBLE
6275 fpregs_format = 0;
6276 #else
6277 fpregs_format = 1;
6278 #endif
6279 qemu_put_be16s(f, &fpregs_format);
6281 for(i = 0; i < 8; i++) {
6282 #ifdef USE_X86LDOUBLE
6284 uint64_t mant;
6285 uint16_t exp;
6286 /* we save the real CPU data (in case of MMX usage only 'mant'
6287 contains the MMX register */
6288 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6289 qemu_put_be64(f, mant);
6290 qemu_put_be16(f, exp);
6292 #else
6293 /* if we use doubles for float emulation, we save the doubles to
6294 avoid losing information in case of MMX usage. It can give
6295 problems if the image is restored on a CPU where long
6296 doubles are used instead. */
6297 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6298 #endif
6301 for(i = 0; i < 6; i++)
6302 cpu_put_seg(f, &env->segs[i]);
6303 cpu_put_seg(f, &env->ldt);
6304 cpu_put_seg(f, &env->tr);
6305 cpu_put_seg(f, &env->gdt);
6306 cpu_put_seg(f, &env->idt);
6308 qemu_put_be32s(f, &env->sysenter_cs);
6309 qemu_put_be32s(f, &env->sysenter_esp);
6310 qemu_put_be32s(f, &env->sysenter_eip);
6312 qemu_put_betls(f, &env->cr[0]);
6313 qemu_put_betls(f, &env->cr[2]);
6314 qemu_put_betls(f, &env->cr[3]);
6315 qemu_put_betls(f, &env->cr[4]);
6317 for(i = 0; i < 8; i++)
6318 qemu_put_betls(f, &env->dr[i]);
6320 /* MMU */
6321 qemu_put_be32s(f, &env->a20_mask);
6323 /* XMM */
6324 qemu_put_be32s(f, &env->mxcsr);
6325 for(i = 0; i < CPU_NB_REGS; i++) {
6326 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6327 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6330 #ifdef TARGET_X86_64
6331 qemu_put_be64s(f, &env->efer);
6332 qemu_put_be64s(f, &env->star);
6333 qemu_put_be64s(f, &env->lstar);
6334 qemu_put_be64s(f, &env->cstar);
6335 qemu_put_be64s(f, &env->fmask);
6336 qemu_put_be64s(f, &env->kernelgsbase);
6337 #endif
6338 qemu_put_be32s(f, &env->smbase);
6341 #ifdef USE_X86LDOUBLE
6342 /* XXX: add that in a FPU generic layer */
6343 union x86_longdouble {
6344 uint64_t mant;
6345 uint16_t exp;
6348 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6349 #define EXPBIAS1 1023
6350 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6351 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6353 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6355 int e;
6356 /* mantissa */
6357 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6358 /* exponent + sign */
6359 e = EXPD1(temp) - EXPBIAS1 + 16383;
6360 e |= SIGND1(temp) >> 16;
6361 p->exp = e;
6363 #endif
6365 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6367 CPUState *env = opaque;
6368 int i, guess_mmx;
6369 uint32_t hflags;
6370 uint16_t fpus, fpuc, fptag, fpregs_format;
6372 if (version_id != 3 && version_id != 4)
6373 return -EINVAL;
6374 for(i = 0; i < CPU_NB_REGS; i++)
6375 qemu_get_betls(f, &env->regs[i]);
6376 qemu_get_betls(f, &env->eip);
6377 qemu_get_betls(f, &env->eflags);
6378 qemu_get_be32s(f, &hflags);
6380 qemu_get_be16s(f, &fpuc);
6381 qemu_get_be16s(f, &fpus);
6382 qemu_get_be16s(f, &fptag);
6383 qemu_get_be16s(f, &fpregs_format);
6385 /* NOTE: we cannot always restore the FPU state if the image come
6386 from a host with a different 'USE_X86LDOUBLE' define. We guess
6387 if we are in an MMX state to restore correctly in that case. */
6388 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6389 for(i = 0; i < 8; i++) {
6390 uint64_t mant;
6391 uint16_t exp;
6393 switch(fpregs_format) {
6394 case 0:
6395 mant = qemu_get_be64(f);
6396 exp = qemu_get_be16(f);
6397 #ifdef USE_X86LDOUBLE
6398 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6399 #else
6400 /* difficult case */
6401 if (guess_mmx)
6402 env->fpregs[i].mmx.MMX_Q(0) = mant;
6403 else
6404 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6405 #endif
6406 break;
6407 case 1:
6408 mant = qemu_get_be64(f);
6409 #ifdef USE_X86LDOUBLE
6411 union x86_longdouble *p;
6412 /* difficult case */
6413 p = (void *)&env->fpregs[i];
6414 if (guess_mmx) {
6415 p->mant = mant;
6416 p->exp = 0xffff;
6417 } else {
6418 fp64_to_fp80(p, mant);
6421 #else
6422 env->fpregs[i].mmx.MMX_Q(0) = mant;
6423 #endif
6424 break;
6425 default:
6426 return -EINVAL;
6430 env->fpuc = fpuc;
6431 /* XXX: restore FPU round state */
6432 env->fpstt = (fpus >> 11) & 7;
6433 env->fpus = fpus & ~0x3800;
6434 fptag ^= 0xff;
6435 for(i = 0; i < 8; i++) {
6436 env->fptags[i] = (fptag >> i) & 1;
6439 for(i = 0; i < 6; i++)
6440 cpu_get_seg(f, &env->segs[i]);
6441 cpu_get_seg(f, &env->ldt);
6442 cpu_get_seg(f, &env->tr);
6443 cpu_get_seg(f, &env->gdt);
6444 cpu_get_seg(f, &env->idt);
6446 qemu_get_be32s(f, &env->sysenter_cs);
6447 qemu_get_be32s(f, &env->sysenter_esp);
6448 qemu_get_be32s(f, &env->sysenter_eip);
6450 qemu_get_betls(f, &env->cr[0]);
6451 qemu_get_betls(f, &env->cr[2]);
6452 qemu_get_betls(f, &env->cr[3]);
6453 qemu_get_betls(f, &env->cr[4]);
6455 for(i = 0; i < 8; i++)
6456 qemu_get_betls(f, &env->dr[i]);
6458 /* MMU */
6459 qemu_get_be32s(f, &env->a20_mask);
6461 qemu_get_be32s(f, &env->mxcsr);
6462 for(i = 0; i < CPU_NB_REGS; i++) {
6463 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6464 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6467 #ifdef TARGET_X86_64
6468 qemu_get_be64s(f, &env->efer);
6469 qemu_get_be64s(f, &env->star);
6470 qemu_get_be64s(f, &env->lstar);
6471 qemu_get_be64s(f, &env->cstar);
6472 qemu_get_be64s(f, &env->fmask);
6473 qemu_get_be64s(f, &env->kernelgsbase);
6474 #endif
6475 if (version_id >= 4)
6476 qemu_get_be32s(f, &env->smbase);
6478 /* XXX: compute hflags from scratch, except for CPL and IIF */
6479 env->hflags = hflags;
6480 tlb_flush(env, 1);
6481 return 0;
6484 #elif defined(TARGET_PPC)
6485 void cpu_save(QEMUFile *f, void *opaque)
6489 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6491 return 0;
6494 #elif defined(TARGET_MIPS)
6495 void cpu_save(QEMUFile *f, void *opaque)
6499 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6501 return 0;
6504 #elif defined(TARGET_SPARC)
6505 void cpu_save(QEMUFile *f, void *opaque)
6507 CPUState *env = opaque;
6508 int i;
6509 uint32_t tmp;
6511 for(i = 0; i < 8; i++)
6512 qemu_put_betls(f, &env->gregs[i]);
6513 for(i = 0; i < NWINDOWS * 16; i++)
6514 qemu_put_betls(f, &env->regbase[i]);
6516 /* FPU */
6517 for(i = 0; i < TARGET_FPREGS; i++) {
6518 union {
6519 float32 f;
6520 uint32_t i;
6521 } u;
6522 u.f = env->fpr[i];
6523 qemu_put_be32(f, u.i);
6526 qemu_put_betls(f, &env->pc);
6527 qemu_put_betls(f, &env->npc);
6528 qemu_put_betls(f, &env->y);
6529 tmp = GET_PSR(env);
6530 qemu_put_be32(f, tmp);
6531 qemu_put_betls(f, &env->fsr);
6532 qemu_put_betls(f, &env->tbr);
6533 #ifndef TARGET_SPARC64
6534 qemu_put_be32s(f, &env->wim);
6535 /* MMU */
6536 for(i = 0; i < 16; i++)
6537 qemu_put_be32s(f, &env->mmuregs[i]);
6538 #endif
6541 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6543 CPUState *env = opaque;
6544 int i;
6545 uint32_t tmp;
6547 for(i = 0; i < 8; i++)
6548 qemu_get_betls(f, &env->gregs[i]);
6549 for(i = 0; i < NWINDOWS * 16; i++)
6550 qemu_get_betls(f, &env->regbase[i]);
6552 /* FPU */
6553 for(i = 0; i < TARGET_FPREGS; i++) {
6554 union {
6555 float32 f;
6556 uint32_t i;
6557 } u;
6558 u.i = qemu_get_be32(f);
6559 env->fpr[i] = u.f;
6562 qemu_get_betls(f, &env->pc);
6563 qemu_get_betls(f, &env->npc);
6564 qemu_get_betls(f, &env->y);
6565 tmp = qemu_get_be32(f);
6566 env->cwp = 0; /* needed to ensure that the wrapping registers are
6567 correctly updated */
6568 PUT_PSR(env, tmp);
6569 qemu_get_betls(f, &env->fsr);
6570 qemu_get_betls(f, &env->tbr);
6571 #ifndef TARGET_SPARC64
6572 qemu_get_be32s(f, &env->wim);
6573 /* MMU */
6574 for(i = 0; i < 16; i++)
6575 qemu_get_be32s(f, &env->mmuregs[i]);
6576 #endif
6577 tlb_flush(env, 1);
6578 return 0;
6581 #elif defined(TARGET_ARM)
6583 void cpu_save(QEMUFile *f, void *opaque)
6585 int i;
6586 CPUARMState *env = (CPUARMState *)opaque;
6588 for (i = 0; i < 16; i++) {
6589 qemu_put_be32(f, env->regs[i]);
6591 qemu_put_be32(f, cpsr_read(env));
6592 qemu_put_be32(f, env->spsr);
6593 for (i = 0; i < 6; i++) {
6594 qemu_put_be32(f, env->banked_spsr[i]);
6595 qemu_put_be32(f, env->banked_r13[i]);
6596 qemu_put_be32(f, env->banked_r14[i]);
6598 for (i = 0; i < 5; i++) {
6599 qemu_put_be32(f, env->usr_regs[i]);
6600 qemu_put_be32(f, env->fiq_regs[i]);
6602 qemu_put_be32(f, env->cp15.c0_cpuid);
6603 qemu_put_be32(f, env->cp15.c0_cachetype);
6604 qemu_put_be32(f, env->cp15.c1_sys);
6605 qemu_put_be32(f, env->cp15.c1_coproc);
6606 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6607 qemu_put_be32(f, env->cp15.c2_base0);
6608 qemu_put_be32(f, env->cp15.c2_base1);
6609 qemu_put_be32(f, env->cp15.c2_mask);
6610 qemu_put_be32(f, env->cp15.c2_data);
6611 qemu_put_be32(f, env->cp15.c2_insn);
6612 qemu_put_be32(f, env->cp15.c3);
6613 qemu_put_be32(f, env->cp15.c5_insn);
6614 qemu_put_be32(f, env->cp15.c5_data);
6615 for (i = 0; i < 8; i++) {
6616 qemu_put_be32(f, env->cp15.c6_region[i]);
6618 qemu_put_be32(f, env->cp15.c6_insn);
6619 qemu_put_be32(f, env->cp15.c6_data);
6620 qemu_put_be32(f, env->cp15.c9_insn);
6621 qemu_put_be32(f, env->cp15.c9_data);
6622 qemu_put_be32(f, env->cp15.c13_fcse);
6623 qemu_put_be32(f, env->cp15.c13_context);
6624 qemu_put_be32(f, env->cp15.c13_tls1);
6625 qemu_put_be32(f, env->cp15.c13_tls2);
6626 qemu_put_be32(f, env->cp15.c13_tls3);
6627 qemu_put_be32(f, env->cp15.c15_cpar);
6629 qemu_put_be32(f, env->features);
6631 if (arm_feature(env, ARM_FEATURE_VFP)) {
6632 for (i = 0; i < 16; i++) {
6633 CPU_DoubleU u;
6634 u.d = env->vfp.regs[i];
6635 qemu_put_be32(f, u.l.upper);
6636 qemu_put_be32(f, u.l.lower);
6638 for (i = 0; i < 16; i++) {
6639 qemu_put_be32(f, env->vfp.xregs[i]);
6642 /* TODO: Should use proper FPSCR access functions. */
6643 qemu_put_be32(f, env->vfp.vec_len);
6644 qemu_put_be32(f, env->vfp.vec_stride);
6646 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6647 for (i = 16; i < 32; i++) {
6648 CPU_DoubleU u;
6649 u.d = env->vfp.regs[i];
6650 qemu_put_be32(f, u.l.upper);
6651 qemu_put_be32(f, u.l.lower);
6656 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6657 for (i = 0; i < 16; i++) {
6658 qemu_put_be64(f, env->iwmmxt.regs[i]);
6660 for (i = 0; i < 16; i++) {
6661 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6665 if (arm_feature(env, ARM_FEATURE_M)) {
6666 qemu_put_be32(f, env->v7m.other_sp);
6667 qemu_put_be32(f, env->v7m.vecbase);
6668 qemu_put_be32(f, env->v7m.basepri);
6669 qemu_put_be32(f, env->v7m.control);
6670 qemu_put_be32(f, env->v7m.current_sp);
6671 qemu_put_be32(f, env->v7m.exception);
6675 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6677 CPUARMState *env = (CPUARMState *)opaque;
6678 int i;
6680 if (version_id != ARM_CPU_SAVE_VERSION)
6681 return -EINVAL;
6683 for (i = 0; i < 16; i++) {
6684 env->regs[i] = qemu_get_be32(f);
6686 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6687 env->spsr = qemu_get_be32(f);
6688 for (i = 0; i < 6; i++) {
6689 env->banked_spsr[i] = qemu_get_be32(f);
6690 env->banked_r13[i] = qemu_get_be32(f);
6691 env->banked_r14[i] = qemu_get_be32(f);
6693 for (i = 0; i < 5; i++) {
6694 env->usr_regs[i] = qemu_get_be32(f);
6695 env->fiq_regs[i] = qemu_get_be32(f);
6697 env->cp15.c0_cpuid = qemu_get_be32(f);
6698 env->cp15.c0_cachetype = qemu_get_be32(f);
6699 env->cp15.c1_sys = qemu_get_be32(f);
6700 env->cp15.c1_coproc = qemu_get_be32(f);
6701 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6702 env->cp15.c2_base0 = qemu_get_be32(f);
6703 env->cp15.c2_base1 = qemu_get_be32(f);
6704 env->cp15.c2_mask = qemu_get_be32(f);
6705 env->cp15.c2_data = qemu_get_be32(f);
6706 env->cp15.c2_insn = qemu_get_be32(f);
6707 env->cp15.c3 = qemu_get_be32(f);
6708 env->cp15.c5_insn = qemu_get_be32(f);
6709 env->cp15.c5_data = qemu_get_be32(f);
6710 for (i = 0; i < 8; i++) {
6711 env->cp15.c6_region[i] = qemu_get_be32(f);
6713 env->cp15.c6_insn = qemu_get_be32(f);
6714 env->cp15.c6_data = qemu_get_be32(f);
6715 env->cp15.c9_insn = qemu_get_be32(f);
6716 env->cp15.c9_data = qemu_get_be32(f);
6717 env->cp15.c13_fcse = qemu_get_be32(f);
6718 env->cp15.c13_context = qemu_get_be32(f);
6719 env->cp15.c13_tls1 = qemu_get_be32(f);
6720 env->cp15.c13_tls2 = qemu_get_be32(f);
6721 env->cp15.c13_tls3 = qemu_get_be32(f);
6722 env->cp15.c15_cpar = qemu_get_be32(f);
6724 env->features = qemu_get_be32(f);
6726 if (arm_feature(env, ARM_FEATURE_VFP)) {
6727 for (i = 0; i < 16; i++) {
6728 CPU_DoubleU u;
6729 u.l.upper = qemu_get_be32(f);
6730 u.l.lower = qemu_get_be32(f);
6731 env->vfp.regs[i] = u.d;
6733 for (i = 0; i < 16; i++) {
6734 env->vfp.xregs[i] = qemu_get_be32(f);
6737 /* TODO: Should use proper FPSCR access functions. */
6738 env->vfp.vec_len = qemu_get_be32(f);
6739 env->vfp.vec_stride = qemu_get_be32(f);
6741 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6742 for (i = 0; i < 16; i++) {
6743 CPU_DoubleU u;
6744 u.l.upper = qemu_get_be32(f);
6745 u.l.lower = qemu_get_be32(f);
6746 env->vfp.regs[i] = u.d;
6751 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6752 for (i = 0; i < 16; i++) {
6753 env->iwmmxt.regs[i] = qemu_get_be64(f);
6755 for (i = 0; i < 16; i++) {
6756 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6760 if (arm_feature(env, ARM_FEATURE_M)) {
6761 env->v7m.other_sp = qemu_get_be32(f);
6762 env->v7m.vecbase = qemu_get_be32(f);
6763 env->v7m.basepri = qemu_get_be32(f);
6764 env->v7m.control = qemu_get_be32(f);
6765 env->v7m.current_sp = qemu_get_be32(f);
6766 env->v7m.exception = qemu_get_be32(f);
6769 return 0;
6772 #else
6774 //#warning No CPU save/restore functions
6776 #endif
6778 /***********************************************************/
6779 /* ram save/restore */
6781 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6783 int v;
6785 v = qemu_get_byte(f);
6786 switch(v) {
6787 case 0:
6788 if (qemu_get_buffer(f, buf, len) != len)
6789 return -EIO;
6790 break;
6791 case 1:
6792 v = qemu_get_byte(f);
6793 memset(buf, v, len);
6794 break;
6795 default:
6796 return -EINVAL;
6798 return 0;
6801 static int ram_load_v1(QEMUFile *f, void *opaque)
6803 int i, ret;
6805 if (qemu_get_be32(f) != phys_ram_size)
6806 return -EINVAL;
6807 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6808 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6809 if (ret)
6810 return ret;
6812 return 0;
6815 #define BDRV_HASH_BLOCK_SIZE 1024
6816 #define IOBUF_SIZE 4096
6817 #define RAM_CBLOCK_MAGIC 0xfabe
6819 typedef struct RamCompressState {
6820 z_stream zstream;
6821 QEMUFile *f;
6822 uint8_t buf[IOBUF_SIZE];
6823 } RamCompressState;
6825 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6827 int ret;
6828 memset(s, 0, sizeof(*s));
6829 s->f = f;
6830 ret = deflateInit2(&s->zstream, 1,
6831 Z_DEFLATED, 15,
6832 9, Z_DEFAULT_STRATEGY);
6833 if (ret != Z_OK)
6834 return -1;
6835 s->zstream.avail_out = IOBUF_SIZE;
6836 s->zstream.next_out = s->buf;
6837 return 0;
6840 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6842 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6843 qemu_put_be16(s->f, len);
6844 qemu_put_buffer(s->f, buf, len);
6847 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6849 int ret;
6851 s->zstream.avail_in = len;
6852 s->zstream.next_in = (uint8_t *)buf;
6853 while (s->zstream.avail_in > 0) {
6854 ret = deflate(&s->zstream, Z_NO_FLUSH);
6855 if (ret != Z_OK)
6856 return -1;
6857 if (s->zstream.avail_out == 0) {
6858 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6859 s->zstream.avail_out = IOBUF_SIZE;
6860 s->zstream.next_out = s->buf;
6863 return 0;
6866 static void ram_compress_close(RamCompressState *s)
6868 int len, ret;
6870 /* compress last bytes */
6871 for(;;) {
6872 ret = deflate(&s->zstream, Z_FINISH);
6873 if (ret == Z_OK || ret == Z_STREAM_END) {
6874 len = IOBUF_SIZE - s->zstream.avail_out;
6875 if (len > 0) {
6876 ram_put_cblock(s, s->buf, len);
6878 s->zstream.avail_out = IOBUF_SIZE;
6879 s->zstream.next_out = s->buf;
6880 if (ret == Z_STREAM_END)
6881 break;
6882 } else {
6883 goto fail;
6886 fail:
6887 deflateEnd(&s->zstream);
6890 typedef struct RamDecompressState {
6891 z_stream zstream;
6892 QEMUFile *f;
6893 uint8_t buf[IOBUF_SIZE];
6894 } RamDecompressState;
6896 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6898 int ret;
6899 memset(s, 0, sizeof(*s));
6900 s->f = f;
6901 ret = inflateInit(&s->zstream);
6902 if (ret != Z_OK)
6903 return -1;
6904 return 0;
6907 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6909 int ret, clen;
6911 s->zstream.avail_out = len;
6912 s->zstream.next_out = buf;
6913 while (s->zstream.avail_out > 0) {
6914 if (s->zstream.avail_in == 0) {
6915 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6916 return -1;
6917 clen = qemu_get_be16(s->f);
6918 if (clen > IOBUF_SIZE)
6919 return -1;
6920 qemu_get_buffer(s->f, s->buf, clen);
6921 s->zstream.avail_in = clen;
6922 s->zstream.next_in = s->buf;
6924 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6925 if (ret != Z_OK && ret != Z_STREAM_END) {
6926 return -1;
6929 return 0;
6932 static void ram_decompress_close(RamDecompressState *s)
6934 inflateEnd(&s->zstream);
6937 static void ram_save(QEMUFile *f, void *opaque)
6939 int i;
6940 RamCompressState s1, *s = &s1;
6941 uint8_t buf[10];
6943 qemu_put_be32(f, phys_ram_size);
6944 if (ram_compress_open(s, f) < 0)
6945 return;
6946 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6947 #if 0
6948 if (tight_savevm_enabled) {
6949 int64_t sector_num;
6950 int j;
6952 /* find if the memory block is available on a virtual
6953 block device */
6954 sector_num = -1;
6955 for(j = 0; j < nb_drives; j++) {
6956 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6957 phys_ram_base + i,
6958 BDRV_HASH_BLOCK_SIZE);
6959 if (sector_num >= 0)
6960 break;
6962 if (j == nb_drives)
6963 goto normal_compress;
6964 buf[0] = 1;
6965 buf[1] = j;
6966 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6967 ram_compress_buf(s, buf, 10);
6968 } else
6969 #endif
6971 // normal_compress:
6972 buf[0] = 0;
6973 ram_compress_buf(s, buf, 1);
6974 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6977 ram_compress_close(s);
6980 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6982 RamDecompressState s1, *s = &s1;
6983 uint8_t buf[10];
6984 int i;
6986 if (version_id == 1)
6987 return ram_load_v1(f, opaque);
6988 if (version_id != 2)
6989 return -EINVAL;
6990 if (qemu_get_be32(f) != phys_ram_size)
6991 return -EINVAL;
6992 if (ram_decompress_open(s, f) < 0)
6993 return -EINVAL;
6994 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6995 if (ram_decompress_buf(s, buf, 1) < 0) {
6996 fprintf(stderr, "Error while reading ram block header\n");
6997 goto error;
6999 if (buf[0] == 0) {
7000 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7001 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7002 goto error;
7004 } else
7005 #if 0
7006 if (buf[0] == 1) {
7007 int bs_index;
7008 int64_t sector_num;
7010 ram_decompress_buf(s, buf + 1, 9);
7011 bs_index = buf[1];
7012 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7013 if (bs_index >= nb_drives) {
7014 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7015 goto error;
7017 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7018 phys_ram_base + i,
7019 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7020 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7021 bs_index, sector_num);
7022 goto error;
7024 } else
7025 #endif
7027 error:
7028 printf("Error block header\n");
7029 return -EINVAL;
7032 ram_decompress_close(s);
7033 return 0;
7036 /***********************************************************/
7037 /* bottom halves (can be seen as timers which expire ASAP) */
7039 struct QEMUBH {
7040 QEMUBHFunc *cb;
7041 void *opaque;
7042 int scheduled;
7043 QEMUBH *next;
7046 static QEMUBH *first_bh = NULL;
7048 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7050 QEMUBH *bh;
7051 bh = qemu_mallocz(sizeof(QEMUBH));
7052 if (!bh)
7053 return NULL;
7054 bh->cb = cb;
7055 bh->opaque = opaque;
7056 return bh;
7059 int qemu_bh_poll(void)
7061 QEMUBH *bh, **pbh;
7062 int ret;
7064 ret = 0;
7065 for(;;) {
7066 pbh = &first_bh;
7067 bh = *pbh;
7068 if (!bh)
7069 break;
7070 ret = 1;
7071 *pbh = bh->next;
7072 bh->scheduled = 0;
7073 bh->cb(bh->opaque);
7075 return ret;
7078 void qemu_bh_schedule(QEMUBH *bh)
7080 CPUState *env = cpu_single_env;
7081 if (bh->scheduled)
7082 return;
7083 bh->scheduled = 1;
7084 bh->next = first_bh;
7085 first_bh = bh;
7087 /* stop the currently executing CPU to execute the BH ASAP */
7088 if (env) {
7089 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7093 void qemu_bh_cancel(QEMUBH *bh)
7095 QEMUBH **pbh;
7096 if (bh->scheduled) {
7097 pbh = &first_bh;
7098 while (*pbh != bh)
7099 pbh = &(*pbh)->next;
7100 *pbh = bh->next;
7101 bh->scheduled = 0;
7105 void qemu_bh_delete(QEMUBH *bh)
7107 qemu_bh_cancel(bh);
7108 qemu_free(bh);
7111 /***********************************************************/
7112 /* machine registration */
7114 QEMUMachine *first_machine = NULL;
7116 int qemu_register_machine(QEMUMachine *m)
7118 QEMUMachine **pm;
7119 pm = &first_machine;
7120 while (*pm != NULL)
7121 pm = &(*pm)->next;
7122 m->next = NULL;
7123 *pm = m;
7124 return 0;
7127 static QEMUMachine *find_machine(const char *name)
7129 QEMUMachine *m;
7131 for(m = first_machine; m != NULL; m = m->next) {
7132 if (!strcmp(m->name, name))
7133 return m;
7135 return NULL;
7138 /***********************************************************/
7139 /* main execution loop */
7141 static void gui_update(void *opaque)
7143 DisplayState *ds = opaque;
7144 ds->dpy_refresh(ds);
7145 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7148 struct vm_change_state_entry {
7149 VMChangeStateHandler *cb;
7150 void *opaque;
7151 LIST_ENTRY (vm_change_state_entry) entries;
7154 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7156 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7157 void *opaque)
7159 VMChangeStateEntry *e;
7161 e = qemu_mallocz(sizeof (*e));
7162 if (!e)
7163 return NULL;
7165 e->cb = cb;
7166 e->opaque = opaque;
7167 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7168 return e;
7171 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7173 LIST_REMOVE (e, entries);
7174 qemu_free (e);
7177 static void vm_state_notify(int running)
7179 VMChangeStateEntry *e;
7181 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7182 e->cb(e->opaque, running);
7186 /* XXX: support several handlers */
7187 static VMStopHandler *vm_stop_cb;
7188 static void *vm_stop_opaque;
7190 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7192 vm_stop_cb = cb;
7193 vm_stop_opaque = opaque;
7194 return 0;
7197 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7199 vm_stop_cb = NULL;
7202 void vm_start(void)
7204 if (!vm_running) {
7205 cpu_enable_ticks();
7206 vm_running = 1;
7207 vm_state_notify(1);
7208 qemu_rearm_alarm_timer(alarm_timer);
7212 void vm_stop(int reason)
7214 if (vm_running) {
7215 cpu_disable_ticks();
7216 vm_running = 0;
7217 if (reason != 0) {
7218 if (vm_stop_cb) {
7219 vm_stop_cb(vm_stop_opaque, reason);
7222 vm_state_notify(0);
7226 /* reset/shutdown handler */
7228 typedef struct QEMUResetEntry {
7229 QEMUResetHandler *func;
7230 void *opaque;
7231 struct QEMUResetEntry *next;
7232 } QEMUResetEntry;
7234 static QEMUResetEntry *first_reset_entry;
7235 static int reset_requested;
7236 static int shutdown_requested;
7237 static int powerdown_requested;
7239 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7241 QEMUResetEntry **pre, *re;
7243 pre = &first_reset_entry;
7244 while (*pre != NULL)
7245 pre = &(*pre)->next;
7246 re = qemu_mallocz(sizeof(QEMUResetEntry));
7247 re->func = func;
7248 re->opaque = opaque;
7249 re->next = NULL;
7250 *pre = re;
7253 static void qemu_system_reset(void)
7255 QEMUResetEntry *re;
7257 /* reset all devices */
7258 for(re = first_reset_entry; re != NULL; re = re->next) {
7259 re->func(re->opaque);
7263 void qemu_system_reset_request(void)
7265 if (no_reboot) {
7266 shutdown_requested = 1;
7267 } else {
7268 reset_requested = 1;
7270 if (cpu_single_env)
7271 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7274 void qemu_system_shutdown_request(void)
7276 shutdown_requested = 1;
7277 if (cpu_single_env)
7278 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7281 void qemu_system_powerdown_request(void)
7283 powerdown_requested = 1;
7284 if (cpu_single_env)
7285 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7288 void main_loop_wait(int timeout)
7290 IOHandlerRecord *ioh;
7291 fd_set rfds, wfds, xfds;
7292 int ret, nfds;
7293 #ifdef _WIN32
7294 int ret2, i;
7295 #endif
7296 struct timeval tv;
7297 PollingEntry *pe;
7300 /* XXX: need to suppress polling by better using win32 events */
7301 ret = 0;
7302 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7303 ret |= pe->func(pe->opaque);
7305 #ifdef _WIN32
7306 if (ret == 0) {
7307 int err;
7308 WaitObjects *w = &wait_objects;
7310 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7311 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7312 if (w->func[ret - WAIT_OBJECT_0])
7313 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7315 /* Check for additional signaled events */
7316 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7318 /* Check if event is signaled */
7319 ret2 = WaitForSingleObject(w->events[i], 0);
7320 if(ret2 == WAIT_OBJECT_0) {
7321 if (w->func[i])
7322 w->func[i](w->opaque[i]);
7323 } else if (ret2 == WAIT_TIMEOUT) {
7324 } else {
7325 err = GetLastError();
7326 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7329 } else if (ret == WAIT_TIMEOUT) {
7330 } else {
7331 err = GetLastError();
7332 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7335 #endif
7336 /* poll any events */
7337 /* XXX: separate device handlers from system ones */
7338 nfds = -1;
7339 FD_ZERO(&rfds);
7340 FD_ZERO(&wfds);
7341 FD_ZERO(&xfds);
7342 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7343 if (ioh->deleted)
7344 continue;
7345 if (ioh->fd_read &&
7346 (!ioh->fd_read_poll ||
7347 ioh->fd_read_poll(ioh->opaque) != 0)) {
7348 FD_SET(ioh->fd, &rfds);
7349 if (ioh->fd > nfds)
7350 nfds = ioh->fd;
7352 if (ioh->fd_write) {
7353 FD_SET(ioh->fd, &wfds);
7354 if (ioh->fd > nfds)
7355 nfds = ioh->fd;
7359 tv.tv_sec = 0;
7360 #ifdef _WIN32
7361 tv.tv_usec = 0;
7362 #else
7363 tv.tv_usec = timeout * 1000;
7364 #endif
7365 #if defined(CONFIG_SLIRP)
7366 if (slirp_inited) {
7367 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7369 #endif
7370 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7371 if (ret > 0) {
7372 IOHandlerRecord **pioh;
7374 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7375 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7376 ioh->fd_read(ioh->opaque);
7378 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7379 ioh->fd_write(ioh->opaque);
7383 /* remove deleted IO handlers */
7384 pioh = &first_io_handler;
7385 while (*pioh) {
7386 ioh = *pioh;
7387 if (ioh->deleted) {
7388 *pioh = ioh->next;
7389 qemu_free(ioh);
7390 } else
7391 pioh = &ioh->next;
7394 #if defined(CONFIG_SLIRP)
7395 if (slirp_inited) {
7396 if (ret < 0) {
7397 FD_ZERO(&rfds);
7398 FD_ZERO(&wfds);
7399 FD_ZERO(&xfds);
7401 slirp_select_poll(&rfds, &wfds, &xfds);
7403 #endif
7404 qemu_aio_poll();
7406 if (vm_running) {
7407 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7408 qemu_get_clock(vm_clock));
7409 /* run dma transfers, if any */
7410 DMA_run();
7413 /* real time timers */
7414 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7415 qemu_get_clock(rt_clock));
7417 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7418 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7419 qemu_rearm_alarm_timer(alarm_timer);
7422 /* Check bottom-halves last in case any of the earlier events triggered
7423 them. */
7424 qemu_bh_poll();
7428 static int main_loop(void)
7430 int ret, timeout;
7431 #ifdef CONFIG_PROFILER
7432 int64_t ti;
7433 #endif
7434 CPUState *env;
7436 cur_cpu = first_cpu;
7437 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7438 for(;;) {
7439 if (vm_running) {
7441 for(;;) {
7442 /* get next cpu */
7443 env = next_cpu;
7444 #ifdef CONFIG_PROFILER
7445 ti = profile_getclock();
7446 #endif
7447 ret = cpu_exec(env);
7448 #ifdef CONFIG_PROFILER
7449 qemu_time += profile_getclock() - ti;
7450 #endif
7451 next_cpu = env->next_cpu ?: first_cpu;
7452 if (event_pending) {
7453 ret = EXCP_INTERRUPT;
7454 event_pending = 0;
7455 break;
7457 if (ret == EXCP_HLT) {
7458 /* Give the next CPU a chance to run. */
7459 cur_cpu = env;
7460 continue;
7462 if (ret != EXCP_HALTED)
7463 break;
7464 /* all CPUs are halted ? */
7465 if (env == cur_cpu)
7466 break;
7468 cur_cpu = env;
7470 if (shutdown_requested) {
7471 ret = EXCP_INTERRUPT;
7472 break;
7474 if (reset_requested) {
7475 reset_requested = 0;
7476 qemu_system_reset();
7477 ret = EXCP_INTERRUPT;
7479 if (powerdown_requested) {
7480 powerdown_requested = 0;
7481 qemu_system_powerdown();
7482 ret = EXCP_INTERRUPT;
7484 if (ret == EXCP_DEBUG) {
7485 vm_stop(EXCP_DEBUG);
7487 /* If all cpus are halted then wait until the next IRQ */
7488 /* XXX: use timeout computed from timers */
7489 if (ret == EXCP_HALTED)
7490 timeout = 10;
7491 else
7492 timeout = 0;
7493 } else {
7494 timeout = 10;
7496 #ifdef CONFIG_PROFILER
7497 ti = profile_getclock();
7498 #endif
7499 main_loop_wait(timeout);
7500 #ifdef CONFIG_PROFILER
7501 dev_time += profile_getclock() - ti;
7502 #endif
7504 cpu_disable_ticks();
7505 return ret;
7508 static void help(int exitcode)
7510 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7511 "usage: %s [options] [disk_image]\n"
7512 "\n"
7513 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7514 "\n"
7515 "Standard options:\n"
7516 "-M machine select emulated machine (-M ? for list)\n"
7517 "-cpu cpu select CPU (-cpu ? for list)\n"
7518 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7519 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7520 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7521 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7522 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7523 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7524 " [,cache=on|off]\n"
7525 " use 'file' as a drive image\n"
7526 "-mtdblock file use 'file' as on-board Flash memory image\n"
7527 "-sd file use 'file' as SecureDigital card image\n"
7528 "-pflash file use 'file' as a parallel flash image\n"
7529 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7530 "-snapshot write to temporary files instead of disk image files\n"
7531 #ifdef CONFIG_SDL
7532 "-no-frame open SDL window without a frame and window decorations\n"
7533 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7534 "-no-quit disable SDL window close capability\n"
7535 #endif
7536 #ifdef TARGET_I386
7537 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7538 #endif
7539 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7540 "-smp n set the number of CPUs to 'n' [default=1]\n"
7541 "-nographic disable graphical output and redirect serial I/Os to console\n"
7542 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7543 #ifndef _WIN32
7544 "-k language use keyboard layout (for example \"fr\" for French)\n"
7545 #endif
7546 #ifdef HAS_AUDIO
7547 "-audio-help print list of audio drivers and their options\n"
7548 "-soundhw c1,... enable audio support\n"
7549 " and only specified sound cards (comma separated list)\n"
7550 " use -soundhw ? to get the list of supported cards\n"
7551 " use -soundhw all to enable all of them\n"
7552 #endif
7553 "-localtime set the real time clock to local time [default=utc]\n"
7554 "-full-screen start in full screen\n"
7555 #ifdef TARGET_I386
7556 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7557 #endif
7558 "-usb enable the USB driver (will be the default soon)\n"
7559 "-usbdevice name add the host or guest USB device 'name'\n"
7560 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7561 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7562 #endif
7563 "-name string set the name of the guest\n"
7564 "\n"
7565 "Network options:\n"
7566 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7567 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7568 #ifdef CONFIG_SLIRP
7569 "-net user[,vlan=n][,hostname=host]\n"
7570 " connect the user mode network stack to VLAN 'n' and send\n"
7571 " hostname 'host' to DHCP clients\n"
7572 #endif
7573 #ifdef _WIN32
7574 "-net tap[,vlan=n],ifname=name\n"
7575 " connect the host TAP network interface to VLAN 'n'\n"
7576 #else
7577 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7578 " connect the host TAP network interface to VLAN 'n' and use the\n"
7579 " network scripts 'file' (default=%s)\n"
7580 " and 'dfile' (default=%s);\n"
7581 " use '[down]script=no' to disable script execution;\n"
7582 " use 'fd=h' to connect to an already opened TAP interface\n"
7583 #endif
7584 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7585 " connect the vlan 'n' to another VLAN using a socket connection\n"
7586 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7587 " connect the vlan 'n' to multicast maddr and port\n"
7588 "-net none use it alone to have zero network devices; if no -net option\n"
7589 " is provided, the default is '-net nic -net user'\n"
7590 "\n"
7591 #ifdef CONFIG_SLIRP
7592 "-tftp dir allow tftp access to files in dir [-net user]\n"
7593 "-bootp file advertise file in BOOTP replies\n"
7594 #ifndef _WIN32
7595 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7596 #endif
7597 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7598 " redirect TCP or UDP connections from host to guest [-net user]\n"
7599 #endif
7600 "\n"
7601 "Linux boot specific:\n"
7602 "-kernel bzImage use 'bzImage' as kernel image\n"
7603 "-append cmdline use 'cmdline' as kernel command line\n"
7604 "-initrd file use 'file' as initial ram disk\n"
7605 "\n"
7606 "Debug/Expert options:\n"
7607 "-monitor dev redirect the monitor to char device 'dev'\n"
7608 "-serial dev redirect the serial port to char device 'dev'\n"
7609 "-parallel dev redirect the parallel port to char device 'dev'\n"
7610 "-pidfile file Write PID to 'file'\n"
7611 "-S freeze CPU at startup (use 'c' to start execution)\n"
7612 "-s wait gdb connection to port\n"
7613 "-p port set gdb connection port [default=%s]\n"
7614 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7615 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7616 " translation (t=none or lba) (usually qemu can guess them)\n"
7617 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7618 #ifdef USE_KQEMU
7619 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7620 "-no-kqemu disable KQEMU kernel module usage\n"
7621 #endif
7622 #ifdef TARGET_I386
7623 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7624 " (default is CL-GD5446 PCI VGA)\n"
7625 "-no-acpi disable ACPI\n"
7626 #endif
7627 "-no-reboot exit instead of rebooting\n"
7628 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7629 "-vnc display start a VNC server on display\n"
7630 #ifndef _WIN32
7631 "-daemonize daemonize QEMU after initializing\n"
7632 #endif
7633 "-option-rom rom load a file, rom, into the option ROM space\n"
7634 #ifdef TARGET_SPARC
7635 "-prom-env variable=value set OpenBIOS nvram variables\n"
7636 #endif
7637 "-clock force the use of the given methods for timer alarm.\n"
7638 " To see what timers are available use -clock help\n"
7639 "\n"
7640 "During emulation, the following keys are useful:\n"
7641 "ctrl-alt-f toggle full screen\n"
7642 "ctrl-alt-n switch to virtual console 'n'\n"
7643 "ctrl-alt toggle mouse and keyboard grab\n"
7644 "\n"
7645 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7647 "qemu",
7648 DEFAULT_RAM_SIZE,
7649 #ifndef _WIN32
7650 DEFAULT_NETWORK_SCRIPT,
7651 DEFAULT_NETWORK_DOWN_SCRIPT,
7652 #endif
7653 DEFAULT_GDBSTUB_PORT,
7654 "/tmp/qemu.log");
7655 exit(exitcode);
7658 #define HAS_ARG 0x0001
7660 enum {
7661 QEMU_OPTION_h,
7663 QEMU_OPTION_M,
7664 QEMU_OPTION_cpu,
7665 QEMU_OPTION_fda,
7666 QEMU_OPTION_fdb,
7667 QEMU_OPTION_hda,
7668 QEMU_OPTION_hdb,
7669 QEMU_OPTION_hdc,
7670 QEMU_OPTION_hdd,
7671 QEMU_OPTION_drive,
7672 QEMU_OPTION_cdrom,
7673 QEMU_OPTION_mtdblock,
7674 QEMU_OPTION_sd,
7675 QEMU_OPTION_pflash,
7676 QEMU_OPTION_boot,
7677 QEMU_OPTION_snapshot,
7678 #ifdef TARGET_I386
7679 QEMU_OPTION_no_fd_bootchk,
7680 #endif
7681 QEMU_OPTION_m,
7682 QEMU_OPTION_nographic,
7683 QEMU_OPTION_portrait,
7684 #ifdef HAS_AUDIO
7685 QEMU_OPTION_audio_help,
7686 QEMU_OPTION_soundhw,
7687 #endif
7689 QEMU_OPTION_net,
7690 QEMU_OPTION_tftp,
7691 QEMU_OPTION_bootp,
7692 QEMU_OPTION_smb,
7693 QEMU_OPTION_redir,
7695 QEMU_OPTION_kernel,
7696 QEMU_OPTION_append,
7697 QEMU_OPTION_initrd,
7699 QEMU_OPTION_S,
7700 QEMU_OPTION_s,
7701 QEMU_OPTION_p,
7702 QEMU_OPTION_d,
7703 QEMU_OPTION_hdachs,
7704 QEMU_OPTION_L,
7705 QEMU_OPTION_bios,
7706 QEMU_OPTION_no_code_copy,
7707 QEMU_OPTION_k,
7708 QEMU_OPTION_localtime,
7709 QEMU_OPTION_cirrusvga,
7710 QEMU_OPTION_vmsvga,
7711 QEMU_OPTION_g,
7712 QEMU_OPTION_std_vga,
7713 QEMU_OPTION_echr,
7714 QEMU_OPTION_monitor,
7715 QEMU_OPTION_serial,
7716 QEMU_OPTION_parallel,
7717 QEMU_OPTION_loadvm,
7718 QEMU_OPTION_full_screen,
7719 QEMU_OPTION_no_frame,
7720 QEMU_OPTION_alt_grab,
7721 QEMU_OPTION_no_quit,
7722 QEMU_OPTION_pidfile,
7723 QEMU_OPTION_no_kqemu,
7724 QEMU_OPTION_kernel_kqemu,
7725 QEMU_OPTION_win2k_hack,
7726 QEMU_OPTION_usb,
7727 QEMU_OPTION_usbdevice,
7728 QEMU_OPTION_smp,
7729 QEMU_OPTION_vnc,
7730 QEMU_OPTION_no_acpi,
7731 QEMU_OPTION_no_reboot,
7732 QEMU_OPTION_show_cursor,
7733 QEMU_OPTION_daemonize,
7734 QEMU_OPTION_option_rom,
7735 QEMU_OPTION_semihosting,
7736 QEMU_OPTION_name,
7737 QEMU_OPTION_prom_env,
7738 QEMU_OPTION_old_param,
7739 QEMU_OPTION_clock,
7740 QEMU_OPTION_startdate,
7743 typedef struct QEMUOption {
7744 const char *name;
7745 int flags;
7746 int index;
7747 } QEMUOption;
7749 const QEMUOption qemu_options[] = {
7750 { "h", 0, QEMU_OPTION_h },
7751 { "help", 0, QEMU_OPTION_h },
7753 { "M", HAS_ARG, QEMU_OPTION_M },
7754 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7755 { "fda", HAS_ARG, QEMU_OPTION_fda },
7756 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7757 { "hda", HAS_ARG, QEMU_OPTION_hda },
7758 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7759 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7760 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7761 { "drive", HAS_ARG, QEMU_OPTION_drive },
7762 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7763 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7764 { "sd", HAS_ARG, QEMU_OPTION_sd },
7765 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7766 { "boot", HAS_ARG, QEMU_OPTION_boot },
7767 { "snapshot", 0, QEMU_OPTION_snapshot },
7768 #ifdef TARGET_I386
7769 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7770 #endif
7771 { "m", HAS_ARG, QEMU_OPTION_m },
7772 { "nographic", 0, QEMU_OPTION_nographic },
7773 { "portrait", 0, QEMU_OPTION_portrait },
7774 { "k", HAS_ARG, QEMU_OPTION_k },
7775 #ifdef HAS_AUDIO
7776 { "audio-help", 0, QEMU_OPTION_audio_help },
7777 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7778 #endif
7780 { "net", HAS_ARG, QEMU_OPTION_net},
7781 #ifdef CONFIG_SLIRP
7782 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7783 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7784 #ifndef _WIN32
7785 { "smb", HAS_ARG, QEMU_OPTION_smb },
7786 #endif
7787 { "redir", HAS_ARG, QEMU_OPTION_redir },
7788 #endif
7790 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7791 { "append", HAS_ARG, QEMU_OPTION_append },
7792 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7794 { "S", 0, QEMU_OPTION_S },
7795 { "s", 0, QEMU_OPTION_s },
7796 { "p", HAS_ARG, QEMU_OPTION_p },
7797 { "d", HAS_ARG, QEMU_OPTION_d },
7798 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7799 { "L", HAS_ARG, QEMU_OPTION_L },
7800 { "bios", HAS_ARG, QEMU_OPTION_bios },
7801 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7802 #ifdef USE_KQEMU
7803 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7804 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7805 #endif
7806 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7807 { "g", 1, QEMU_OPTION_g },
7808 #endif
7809 { "localtime", 0, QEMU_OPTION_localtime },
7810 { "std-vga", 0, QEMU_OPTION_std_vga },
7811 { "echr", HAS_ARG, QEMU_OPTION_echr },
7812 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7813 { "serial", HAS_ARG, QEMU_OPTION_serial },
7814 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7815 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7816 { "full-screen", 0, QEMU_OPTION_full_screen },
7817 #ifdef CONFIG_SDL
7818 { "no-frame", 0, QEMU_OPTION_no_frame },
7819 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7820 { "no-quit", 0, QEMU_OPTION_no_quit },
7821 #endif
7822 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7823 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7824 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7825 { "smp", HAS_ARG, QEMU_OPTION_smp },
7826 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7828 /* temporary options */
7829 { "usb", 0, QEMU_OPTION_usb },
7830 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7831 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7832 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7833 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7834 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7835 { "daemonize", 0, QEMU_OPTION_daemonize },
7836 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7837 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7838 { "semihosting", 0, QEMU_OPTION_semihosting },
7839 #endif
7840 { "name", HAS_ARG, QEMU_OPTION_name },
7841 #if defined(TARGET_SPARC)
7842 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7843 #endif
7844 #if defined(TARGET_ARM)
7845 { "old-param", 0, QEMU_OPTION_old_param },
7846 #endif
7847 { "clock", HAS_ARG, QEMU_OPTION_clock },
7848 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7849 { NULL },
7852 /* password input */
7854 int qemu_key_check(BlockDriverState *bs, const char *name)
7856 char password[256];
7857 int i;
7859 if (!bdrv_is_encrypted(bs))
7860 return 0;
7862 term_printf("%s is encrypted.\n", name);
7863 for(i = 0; i < 3; i++) {
7864 monitor_readline("Password: ", 1, password, sizeof(password));
7865 if (bdrv_set_key(bs, password) == 0)
7866 return 0;
7867 term_printf("invalid password\n");
7869 return -EPERM;
7872 static BlockDriverState *get_bdrv(int index)
7874 if (index > nb_drives)
7875 return NULL;
7876 return drives_table[index].bdrv;
7879 static void read_passwords(void)
7881 BlockDriverState *bs;
7882 int i;
7884 for(i = 0; i < 6; i++) {
7885 bs = get_bdrv(i);
7886 if (bs)
7887 qemu_key_check(bs, bdrv_get_device_name(bs));
7891 /* XXX: currently we cannot use simultaneously different CPUs */
7892 static void register_machines(void)
7894 #if defined(TARGET_I386)
7895 qemu_register_machine(&pc_machine);
7896 qemu_register_machine(&isapc_machine);
7897 #elif defined(TARGET_PPC)
7898 qemu_register_machine(&heathrow_machine);
7899 qemu_register_machine(&core99_machine);
7900 qemu_register_machine(&prep_machine);
7901 qemu_register_machine(&ref405ep_machine);
7902 qemu_register_machine(&taihu_machine);
7903 #elif defined(TARGET_MIPS)
7904 qemu_register_machine(&mips_machine);
7905 qemu_register_machine(&mips_malta_machine);
7906 qemu_register_machine(&mips_pica61_machine);
7907 qemu_register_machine(&mips_mipssim_machine);
7908 #elif defined(TARGET_SPARC)
7909 #ifdef TARGET_SPARC64
7910 qemu_register_machine(&sun4u_machine);
7911 #else
7912 qemu_register_machine(&ss5_machine);
7913 qemu_register_machine(&ss10_machine);
7914 qemu_register_machine(&ss600mp_machine);
7915 qemu_register_machine(&ss20_machine);
7916 qemu_register_machine(&ss2_machine);
7917 qemu_register_machine(&ss1000_machine);
7918 qemu_register_machine(&ss2000_machine);
7919 #endif
7920 #elif defined(TARGET_ARM)
7921 qemu_register_machine(&integratorcp_machine);
7922 qemu_register_machine(&versatilepb_machine);
7923 qemu_register_machine(&versatileab_machine);
7924 qemu_register_machine(&realview_machine);
7925 qemu_register_machine(&akitapda_machine);
7926 qemu_register_machine(&spitzpda_machine);
7927 qemu_register_machine(&borzoipda_machine);
7928 qemu_register_machine(&terrierpda_machine);
7929 qemu_register_machine(&palmte_machine);
7930 qemu_register_machine(&lm3s811evb_machine);
7931 qemu_register_machine(&lm3s6965evb_machine);
7932 qemu_register_machine(&connex_machine);
7933 qemu_register_machine(&verdex_machine);
7934 qemu_register_machine(&mainstone2_machine);
7935 #elif defined(TARGET_SH4)
7936 qemu_register_machine(&shix_machine);
7937 qemu_register_machine(&r2d_machine);
7938 #elif defined(TARGET_ALPHA)
7939 /* XXX: TODO */
7940 #elif defined(TARGET_M68K)
7941 qemu_register_machine(&mcf5208evb_machine);
7942 qemu_register_machine(&an5206_machine);
7943 qemu_register_machine(&dummy_m68k_machine);
7944 #elif defined(TARGET_CRIS)
7945 qemu_register_machine(&bareetraxfs_machine);
7946 #else
7947 #error unsupported CPU
7948 #endif
7951 #ifdef HAS_AUDIO
7952 struct soundhw soundhw[] = {
7953 #ifdef HAS_AUDIO_CHOICE
7954 #ifdef TARGET_I386
7956 "pcspk",
7957 "PC speaker",
7960 { .init_isa = pcspk_audio_init }
7962 #endif
7964 "sb16",
7965 "Creative Sound Blaster 16",
7968 { .init_isa = SB16_init }
7971 #ifdef CONFIG_ADLIB
7973 "adlib",
7974 #ifdef HAS_YMF262
7975 "Yamaha YMF262 (OPL3)",
7976 #else
7977 "Yamaha YM3812 (OPL2)",
7978 #endif
7981 { .init_isa = Adlib_init }
7983 #endif
7985 #ifdef CONFIG_GUS
7987 "gus",
7988 "Gravis Ultrasound GF1",
7991 { .init_isa = GUS_init }
7993 #endif
7996 "es1370",
7997 "ENSONIQ AudioPCI ES1370",
8000 { .init_pci = es1370_init }
8002 #endif
8004 { NULL, NULL, 0, 0, { NULL } }
8007 static void select_soundhw (const char *optarg)
8009 struct soundhw *c;
8011 if (*optarg == '?') {
8012 show_valid_cards:
8014 printf ("Valid sound card names (comma separated):\n");
8015 for (c = soundhw; c->name; ++c) {
8016 printf ("%-11s %s\n", c->name, c->descr);
8018 printf ("\n-soundhw all will enable all of the above\n");
8019 exit (*optarg != '?');
8021 else {
8022 size_t l;
8023 const char *p;
8024 char *e;
8025 int bad_card = 0;
8027 if (!strcmp (optarg, "all")) {
8028 for (c = soundhw; c->name; ++c) {
8029 c->enabled = 1;
8031 return;
8034 p = optarg;
8035 while (*p) {
8036 e = strchr (p, ',');
8037 l = !e ? strlen (p) : (size_t) (e - p);
8039 for (c = soundhw; c->name; ++c) {
8040 if (!strncmp (c->name, p, l)) {
8041 c->enabled = 1;
8042 break;
8046 if (!c->name) {
8047 if (l > 80) {
8048 fprintf (stderr,
8049 "Unknown sound card name (too big to show)\n");
8051 else {
8052 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8053 (int) l, p);
8055 bad_card = 1;
8057 p += l + (e != NULL);
8060 if (bad_card)
8061 goto show_valid_cards;
8064 #endif
8066 #ifdef _WIN32
8067 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8069 exit(STATUS_CONTROL_C_EXIT);
8070 return TRUE;
8072 #endif
8074 #define MAX_NET_CLIENTS 32
8076 int main(int argc, char **argv)
8078 #ifdef CONFIG_GDBSTUB
8079 int use_gdbstub;
8080 const char *gdbstub_port;
8081 #endif
8082 uint32_t boot_devices_bitmap = 0;
8083 int i;
8084 int snapshot, linux_boot, net_boot;
8085 const char *initrd_filename;
8086 const char *kernel_filename, *kernel_cmdline;
8087 const char *boot_devices = "";
8088 DisplayState *ds = &display_state;
8089 int cyls, heads, secs, translation;
8090 char net_clients[MAX_NET_CLIENTS][256];
8091 int nb_net_clients;
8092 int hda_index;
8093 int optind;
8094 const char *r, *optarg;
8095 CharDriverState *monitor_hd;
8096 char monitor_device[128];
8097 char serial_devices[MAX_SERIAL_PORTS][128];
8098 int serial_device_index;
8099 char parallel_devices[MAX_PARALLEL_PORTS][128];
8100 int parallel_device_index;
8101 const char *loadvm = NULL;
8102 QEMUMachine *machine;
8103 const char *cpu_model;
8104 char usb_devices[MAX_USB_CMDLINE][128];
8105 int usb_devices_index;
8106 int fds[2];
8107 const char *pid_file = NULL;
8108 VLANState *vlan;
8110 LIST_INIT (&vm_change_state_head);
8111 #ifndef _WIN32
8113 struct sigaction act;
8114 sigfillset(&act.sa_mask);
8115 act.sa_flags = 0;
8116 act.sa_handler = SIG_IGN;
8117 sigaction(SIGPIPE, &act, NULL);
8119 #else
8120 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8121 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8122 QEMU to run on a single CPU */
8124 HANDLE h;
8125 DWORD mask, smask;
8126 int i;
8127 h = GetCurrentProcess();
8128 if (GetProcessAffinityMask(h, &mask, &smask)) {
8129 for(i = 0; i < 32; i++) {
8130 if (mask & (1 << i))
8131 break;
8133 if (i != 32) {
8134 mask = 1 << i;
8135 SetProcessAffinityMask(h, mask);
8139 #endif
8141 register_machines();
8142 machine = first_machine;
8143 cpu_model = NULL;
8144 initrd_filename = NULL;
8145 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8146 vga_ram_size = VGA_RAM_SIZE;
8147 #ifdef CONFIG_GDBSTUB
8148 use_gdbstub = 0;
8149 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8150 #endif
8151 snapshot = 0;
8152 nographic = 0;
8153 kernel_filename = NULL;
8154 kernel_cmdline = "";
8155 cyls = heads = secs = 0;
8156 translation = BIOS_ATA_TRANSLATION_AUTO;
8157 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8159 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8160 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8161 serial_devices[i][0] = '\0';
8162 serial_device_index = 0;
8164 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8165 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8166 parallel_devices[i][0] = '\0';
8167 parallel_device_index = 0;
8169 usb_devices_index = 0;
8171 nb_net_clients = 0;
8172 nb_drives = 0;
8173 nb_drives_opt = 0;
8174 hda_index = -1;
8176 nb_nics = 0;
8177 /* default mac address of the first network interface */
8179 optind = 1;
8180 for(;;) {
8181 if (optind >= argc)
8182 break;
8183 r = argv[optind];
8184 if (r[0] != '-') {
8185 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8186 } else {
8187 const QEMUOption *popt;
8189 optind++;
8190 /* Treat --foo the same as -foo. */
8191 if (r[1] == '-')
8192 r++;
8193 popt = qemu_options;
8194 for(;;) {
8195 if (!popt->name) {
8196 fprintf(stderr, "%s: invalid option -- '%s'\n",
8197 argv[0], r);
8198 exit(1);
8200 if (!strcmp(popt->name, r + 1))
8201 break;
8202 popt++;
8204 if (popt->flags & HAS_ARG) {
8205 if (optind >= argc) {
8206 fprintf(stderr, "%s: option '%s' requires an argument\n",
8207 argv[0], r);
8208 exit(1);
8210 optarg = argv[optind++];
8211 } else {
8212 optarg = NULL;
8215 switch(popt->index) {
8216 case QEMU_OPTION_M:
8217 machine = find_machine(optarg);
8218 if (!machine) {
8219 QEMUMachine *m;
8220 printf("Supported machines are:\n");
8221 for(m = first_machine; m != NULL; m = m->next) {
8222 printf("%-10s %s%s\n",
8223 m->name, m->desc,
8224 m == first_machine ? " (default)" : "");
8226 exit(*optarg != '?');
8228 break;
8229 case QEMU_OPTION_cpu:
8230 /* hw initialization will check this */
8231 if (*optarg == '?') {
8232 /* XXX: implement xxx_cpu_list for targets that still miss it */
8233 #if defined(cpu_list)
8234 cpu_list(stdout, &fprintf);
8235 #endif
8236 exit(0);
8237 } else {
8238 cpu_model = optarg;
8240 break;
8241 case QEMU_OPTION_initrd:
8242 initrd_filename = optarg;
8243 break;
8244 case QEMU_OPTION_hda:
8245 if (cyls == 0)
8246 hda_index = drive_add(optarg, HD_ALIAS, 0);
8247 else
8248 hda_index = drive_add(optarg, HD_ALIAS
8249 ",cyls=%d,heads=%d,secs=%d%s",
8250 0, cyls, heads, secs,
8251 translation == BIOS_ATA_TRANSLATION_LBA ?
8252 ",trans=lba" :
8253 translation == BIOS_ATA_TRANSLATION_NONE ?
8254 ",trans=none" : "");
8255 break;
8256 case QEMU_OPTION_hdb:
8257 case QEMU_OPTION_hdc:
8258 case QEMU_OPTION_hdd:
8259 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8260 break;
8261 case QEMU_OPTION_drive:
8262 drive_add(NULL, "%s", optarg);
8263 break;
8264 case QEMU_OPTION_mtdblock:
8265 drive_add(optarg, MTD_ALIAS);
8266 break;
8267 case QEMU_OPTION_sd:
8268 drive_add(optarg, SD_ALIAS);
8269 break;
8270 case QEMU_OPTION_pflash:
8271 drive_add(optarg, PFLASH_ALIAS);
8272 break;
8273 case QEMU_OPTION_snapshot:
8274 snapshot = 1;
8275 break;
8276 case QEMU_OPTION_hdachs:
8278 const char *p;
8279 p = optarg;
8280 cyls = strtol(p, (char **)&p, 0);
8281 if (cyls < 1 || cyls > 16383)
8282 goto chs_fail;
8283 if (*p != ',')
8284 goto chs_fail;
8285 p++;
8286 heads = strtol(p, (char **)&p, 0);
8287 if (heads < 1 || heads > 16)
8288 goto chs_fail;
8289 if (*p != ',')
8290 goto chs_fail;
8291 p++;
8292 secs = strtol(p, (char **)&p, 0);
8293 if (secs < 1 || secs > 63)
8294 goto chs_fail;
8295 if (*p == ',') {
8296 p++;
8297 if (!strcmp(p, "none"))
8298 translation = BIOS_ATA_TRANSLATION_NONE;
8299 else if (!strcmp(p, "lba"))
8300 translation = BIOS_ATA_TRANSLATION_LBA;
8301 else if (!strcmp(p, "auto"))
8302 translation = BIOS_ATA_TRANSLATION_AUTO;
8303 else
8304 goto chs_fail;
8305 } else if (*p != '\0') {
8306 chs_fail:
8307 fprintf(stderr, "qemu: invalid physical CHS format\n");
8308 exit(1);
8310 if (hda_index != -1)
8311 snprintf(drives_opt[hda_index].opt,
8312 sizeof(drives_opt[hda_index].opt),
8313 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8314 0, cyls, heads, secs,
8315 translation == BIOS_ATA_TRANSLATION_LBA ?
8316 ",trans=lba" :
8317 translation == BIOS_ATA_TRANSLATION_NONE ?
8318 ",trans=none" : "");
8320 break;
8321 case QEMU_OPTION_nographic:
8322 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8323 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8324 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8325 nographic = 1;
8326 break;
8327 case QEMU_OPTION_portrait:
8328 graphic_rotate = 1;
8329 break;
8330 case QEMU_OPTION_kernel:
8331 kernel_filename = optarg;
8332 break;
8333 case QEMU_OPTION_append:
8334 kernel_cmdline = optarg;
8335 break;
8336 case QEMU_OPTION_cdrom:
8337 drive_add(optarg, CDROM_ALIAS);
8338 break;
8339 case QEMU_OPTION_boot:
8340 boot_devices = optarg;
8341 /* We just do some generic consistency checks */
8343 /* Could easily be extended to 64 devices if needed */
8344 const char *p;
8346 boot_devices_bitmap = 0;
8347 for (p = boot_devices; *p != '\0'; p++) {
8348 /* Allowed boot devices are:
8349 * a b : floppy disk drives
8350 * c ... f : IDE disk drives
8351 * g ... m : machine implementation dependant drives
8352 * n ... p : network devices
8353 * It's up to each machine implementation to check
8354 * if the given boot devices match the actual hardware
8355 * implementation and firmware features.
8357 if (*p < 'a' || *p > 'q') {
8358 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8359 exit(1);
8361 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8362 fprintf(stderr,
8363 "Boot device '%c' was given twice\n",*p);
8364 exit(1);
8366 boot_devices_bitmap |= 1 << (*p - 'a');
8369 break;
8370 case QEMU_OPTION_fda:
8371 case QEMU_OPTION_fdb:
8372 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8373 break;
8374 #ifdef TARGET_I386
8375 case QEMU_OPTION_no_fd_bootchk:
8376 fd_bootchk = 0;
8377 break;
8378 #endif
8379 case QEMU_OPTION_no_code_copy:
8380 code_copy_enabled = 0;
8381 break;
8382 case QEMU_OPTION_net:
8383 if (nb_net_clients >= MAX_NET_CLIENTS) {
8384 fprintf(stderr, "qemu: too many network clients\n");
8385 exit(1);
8387 pstrcpy(net_clients[nb_net_clients],
8388 sizeof(net_clients[0]),
8389 optarg);
8390 nb_net_clients++;
8391 break;
8392 #ifdef CONFIG_SLIRP
8393 case QEMU_OPTION_tftp:
8394 tftp_prefix = optarg;
8395 break;
8396 case QEMU_OPTION_bootp:
8397 bootp_filename = optarg;
8398 break;
8399 #ifndef _WIN32
8400 case QEMU_OPTION_smb:
8401 net_slirp_smb(optarg);
8402 break;
8403 #endif
8404 case QEMU_OPTION_redir:
8405 net_slirp_redir(optarg);
8406 break;
8407 #endif
8408 #ifdef HAS_AUDIO
8409 case QEMU_OPTION_audio_help:
8410 AUD_help ();
8411 exit (0);
8412 break;
8413 case QEMU_OPTION_soundhw:
8414 select_soundhw (optarg);
8415 break;
8416 #endif
8417 case QEMU_OPTION_h:
8418 help(0);
8419 break;
8420 case QEMU_OPTION_m:
8421 ram_size = atoi(optarg) * 1024 * 1024;
8422 if (ram_size <= 0)
8423 help(1);
8424 if (ram_size > PHYS_RAM_MAX_SIZE) {
8425 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8426 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8427 exit(1);
8429 break;
8430 case QEMU_OPTION_d:
8432 int mask;
8433 CPULogItem *item;
8435 mask = cpu_str_to_log_mask(optarg);
8436 if (!mask) {
8437 printf("Log items (comma separated):\n");
8438 for(item = cpu_log_items; item->mask != 0; item++) {
8439 printf("%-10s %s\n", item->name, item->help);
8441 exit(1);
8443 cpu_set_log(mask);
8445 break;
8446 #ifdef CONFIG_GDBSTUB
8447 case QEMU_OPTION_s:
8448 use_gdbstub = 1;
8449 break;
8450 case QEMU_OPTION_p:
8451 gdbstub_port = optarg;
8452 break;
8453 #endif
8454 case QEMU_OPTION_L:
8455 bios_dir = optarg;
8456 break;
8457 case QEMU_OPTION_bios:
8458 bios_name = optarg;
8459 break;
8460 case QEMU_OPTION_S:
8461 autostart = 0;
8462 break;
8463 case QEMU_OPTION_k:
8464 keyboard_layout = optarg;
8465 break;
8466 case QEMU_OPTION_localtime:
8467 rtc_utc = 0;
8468 break;
8469 case QEMU_OPTION_cirrusvga:
8470 cirrus_vga_enabled = 1;
8471 vmsvga_enabled = 0;
8472 break;
8473 case QEMU_OPTION_vmsvga:
8474 cirrus_vga_enabled = 0;
8475 vmsvga_enabled = 1;
8476 break;
8477 case QEMU_OPTION_std_vga:
8478 cirrus_vga_enabled = 0;
8479 vmsvga_enabled = 0;
8480 break;
8481 case QEMU_OPTION_g:
8483 const char *p;
8484 int w, h, depth;
8485 p = optarg;
8486 w = strtol(p, (char **)&p, 10);
8487 if (w <= 0) {
8488 graphic_error:
8489 fprintf(stderr, "qemu: invalid resolution or depth\n");
8490 exit(1);
8492 if (*p != 'x')
8493 goto graphic_error;
8494 p++;
8495 h = strtol(p, (char **)&p, 10);
8496 if (h <= 0)
8497 goto graphic_error;
8498 if (*p == 'x') {
8499 p++;
8500 depth = strtol(p, (char **)&p, 10);
8501 if (depth != 8 && depth != 15 && depth != 16 &&
8502 depth != 24 && depth != 32)
8503 goto graphic_error;
8504 } else if (*p == '\0') {
8505 depth = graphic_depth;
8506 } else {
8507 goto graphic_error;
8510 graphic_width = w;
8511 graphic_height = h;
8512 graphic_depth = depth;
8514 break;
8515 case QEMU_OPTION_echr:
8517 char *r;
8518 term_escape_char = strtol(optarg, &r, 0);
8519 if (r == optarg)
8520 printf("Bad argument to echr\n");
8521 break;
8523 case QEMU_OPTION_monitor:
8524 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8525 break;
8526 case QEMU_OPTION_serial:
8527 if (serial_device_index >= MAX_SERIAL_PORTS) {
8528 fprintf(stderr, "qemu: too many serial ports\n");
8529 exit(1);
8531 pstrcpy(serial_devices[serial_device_index],
8532 sizeof(serial_devices[0]), optarg);
8533 serial_device_index++;
8534 break;
8535 case QEMU_OPTION_parallel:
8536 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8537 fprintf(stderr, "qemu: too many parallel ports\n");
8538 exit(1);
8540 pstrcpy(parallel_devices[parallel_device_index],
8541 sizeof(parallel_devices[0]), optarg);
8542 parallel_device_index++;
8543 break;
8544 case QEMU_OPTION_loadvm:
8545 loadvm = optarg;
8546 break;
8547 case QEMU_OPTION_full_screen:
8548 full_screen = 1;
8549 break;
8550 #ifdef CONFIG_SDL
8551 case QEMU_OPTION_no_frame:
8552 no_frame = 1;
8553 break;
8554 case QEMU_OPTION_alt_grab:
8555 alt_grab = 1;
8556 break;
8557 case QEMU_OPTION_no_quit:
8558 no_quit = 1;
8559 break;
8560 #endif
8561 case QEMU_OPTION_pidfile:
8562 pid_file = optarg;
8563 break;
8564 #ifdef TARGET_I386
8565 case QEMU_OPTION_win2k_hack:
8566 win2k_install_hack = 1;
8567 break;
8568 #endif
8569 #ifdef USE_KQEMU
8570 case QEMU_OPTION_no_kqemu:
8571 kqemu_allowed = 0;
8572 break;
8573 case QEMU_OPTION_kernel_kqemu:
8574 kqemu_allowed = 2;
8575 break;
8576 #endif
8577 case QEMU_OPTION_usb:
8578 usb_enabled = 1;
8579 break;
8580 case QEMU_OPTION_usbdevice:
8581 usb_enabled = 1;
8582 if (usb_devices_index >= MAX_USB_CMDLINE) {
8583 fprintf(stderr, "Too many USB devices\n");
8584 exit(1);
8586 pstrcpy(usb_devices[usb_devices_index],
8587 sizeof(usb_devices[usb_devices_index]),
8588 optarg);
8589 usb_devices_index++;
8590 break;
8591 case QEMU_OPTION_smp:
8592 smp_cpus = atoi(optarg);
8593 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8594 fprintf(stderr, "Invalid number of CPUs\n");
8595 exit(1);
8597 break;
8598 case QEMU_OPTION_vnc:
8599 vnc_display = optarg;
8600 break;
8601 case QEMU_OPTION_no_acpi:
8602 acpi_enabled = 0;
8603 break;
8604 case QEMU_OPTION_no_reboot:
8605 no_reboot = 1;
8606 break;
8607 case QEMU_OPTION_show_cursor:
8608 cursor_hide = 0;
8609 break;
8610 case QEMU_OPTION_daemonize:
8611 daemonize = 1;
8612 break;
8613 case QEMU_OPTION_option_rom:
8614 if (nb_option_roms >= MAX_OPTION_ROMS) {
8615 fprintf(stderr, "Too many option ROMs\n");
8616 exit(1);
8618 option_rom[nb_option_roms] = optarg;
8619 nb_option_roms++;
8620 break;
8621 case QEMU_OPTION_semihosting:
8622 semihosting_enabled = 1;
8623 break;
8624 case QEMU_OPTION_name:
8625 qemu_name = optarg;
8626 break;
8627 #ifdef TARGET_SPARC
8628 case QEMU_OPTION_prom_env:
8629 if (nb_prom_envs >= MAX_PROM_ENVS) {
8630 fprintf(stderr, "Too many prom variables\n");
8631 exit(1);
8633 prom_envs[nb_prom_envs] = optarg;
8634 nb_prom_envs++;
8635 break;
8636 #endif
8637 #ifdef TARGET_ARM
8638 case QEMU_OPTION_old_param:
8639 old_param = 1;
8640 break;
8641 #endif
8642 case QEMU_OPTION_clock:
8643 configure_alarms(optarg);
8644 break;
8645 case QEMU_OPTION_startdate:
8647 struct tm tm;
8648 if (!strcmp(optarg, "now")) {
8649 rtc_start_date = -1;
8650 } else {
8651 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8652 &tm.tm_year,
8653 &tm.tm_mon,
8654 &tm.tm_mday,
8655 &tm.tm_hour,
8656 &tm.tm_min,
8657 &tm.tm_sec) == 6) {
8658 /* OK */
8659 } else if (sscanf(optarg, "%d-%d-%d",
8660 &tm.tm_year,
8661 &tm.tm_mon,
8662 &tm.tm_mday) == 3) {
8663 tm.tm_hour = 0;
8664 tm.tm_min = 0;
8665 tm.tm_sec = 0;
8666 } else {
8667 goto date_fail;
8669 tm.tm_year -= 1900;
8670 tm.tm_mon--;
8671 rtc_start_date = mktimegm(&tm);
8672 if (rtc_start_date == -1) {
8673 date_fail:
8674 fprintf(stderr, "Invalid date format. Valid format are:\n"
8675 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8676 exit(1);
8680 break;
8685 #ifndef _WIN32
8686 if (daemonize && !nographic && vnc_display == NULL) {
8687 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8688 daemonize = 0;
8691 if (daemonize) {
8692 pid_t pid;
8694 if (pipe(fds) == -1)
8695 exit(1);
8697 pid = fork();
8698 if (pid > 0) {
8699 uint8_t status;
8700 ssize_t len;
8702 close(fds[1]);
8704 again:
8705 len = read(fds[0], &status, 1);
8706 if (len == -1 && (errno == EINTR))
8707 goto again;
8709 if (len != 1)
8710 exit(1);
8711 else if (status == 1) {
8712 fprintf(stderr, "Could not acquire pidfile\n");
8713 exit(1);
8714 } else
8715 exit(0);
8716 } else if (pid < 0)
8717 exit(1);
8719 setsid();
8721 pid = fork();
8722 if (pid > 0)
8723 exit(0);
8724 else if (pid < 0)
8725 exit(1);
8727 umask(027);
8728 chdir("/");
8730 signal(SIGTSTP, SIG_IGN);
8731 signal(SIGTTOU, SIG_IGN);
8732 signal(SIGTTIN, SIG_IGN);
8734 #endif
8736 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8737 if (daemonize) {
8738 uint8_t status = 1;
8739 write(fds[1], &status, 1);
8740 } else
8741 fprintf(stderr, "Could not acquire pid file\n");
8742 exit(1);
8745 #ifdef USE_KQEMU
8746 if (smp_cpus > 1)
8747 kqemu_allowed = 0;
8748 #endif
8749 linux_boot = (kernel_filename != NULL);
8750 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8752 /* XXX: this should not be: some embedded targets just have flash */
8753 if (!linux_boot && net_boot == 0 &&
8754 nb_drives_opt == 0)
8755 help(1);
8757 /* boot to floppy or the default cd if no hard disk defined yet */
8758 if (!boot_devices[0]) {
8759 boot_devices = "cad";
8761 setvbuf(stdout, NULL, _IOLBF, 0);
8763 init_timers();
8764 init_timer_alarm();
8765 qemu_aio_init();
8767 #ifdef _WIN32
8768 socket_init();
8769 #endif
8771 /* init network clients */
8772 if (nb_net_clients == 0) {
8773 /* if no clients, we use a default config */
8774 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8775 "nic");
8776 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8777 "user");
8778 nb_net_clients = 2;
8781 for(i = 0;i < nb_net_clients; i++) {
8782 if (net_client_init(net_clients[i]) < 0)
8783 exit(1);
8785 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8786 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8787 continue;
8788 if (vlan->nb_guest_devs == 0) {
8789 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8790 exit(1);
8792 if (vlan->nb_host_devs == 0)
8793 fprintf(stderr,
8794 "Warning: vlan %d is not connected to host network\n",
8795 vlan->id);
8798 #ifdef TARGET_I386
8799 /* XXX: this should be moved in the PC machine instantiation code */
8800 if (net_boot != 0) {
8801 int netroms = 0;
8802 for (i = 0; i < nb_nics && i < 4; i++) {
8803 const char *model = nd_table[i].model;
8804 char buf[1024];
8805 if (net_boot & (1 << i)) {
8806 if (model == NULL)
8807 model = "ne2k_pci";
8808 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8809 if (get_image_size(buf) > 0) {
8810 if (nb_option_roms >= MAX_OPTION_ROMS) {
8811 fprintf(stderr, "Too many option ROMs\n");
8812 exit(1);
8814 option_rom[nb_option_roms] = strdup(buf);
8815 nb_option_roms++;
8816 netroms++;
8820 if (netroms == 0) {
8821 fprintf(stderr, "No valid PXE rom found for network device\n");
8822 exit(1);
8825 #endif
8827 /* init the memory */
8828 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8830 phys_ram_base = qemu_vmalloc(phys_ram_size);
8831 if (!phys_ram_base) {
8832 fprintf(stderr, "Could not allocate physical memory\n");
8833 exit(1);
8836 bdrv_init();
8838 /* we always create the cdrom drive, even if no disk is there */
8840 if (nb_drives_opt < MAX_DRIVES)
8841 drive_add(NULL, CDROM_ALIAS);
8843 /* we always create at least one floppy */
8845 if (nb_drives_opt < MAX_DRIVES)
8846 drive_add(NULL, FD_ALIAS, 0);
8848 /* we always create one sd slot, even if no card is in it */
8850 if (nb_drives_opt < MAX_DRIVES)
8851 drive_add(NULL, SD_ALIAS);
8853 /* open the virtual block devices */
8855 for(i = 0; i < nb_drives_opt; i++)
8856 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8857 exit(1);
8859 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8860 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8862 init_ioports();
8864 /* terminal init */
8865 memset(&display_state, 0, sizeof(display_state));
8866 if (nographic) {
8867 /* nearly nothing to do */
8868 dumb_display_init(ds);
8869 } else if (vnc_display != NULL) {
8870 vnc_display_init(ds);
8871 if (vnc_display_open(ds, vnc_display) < 0)
8872 exit(1);
8873 } else {
8874 #if defined(CONFIG_SDL)
8875 sdl_display_init(ds, full_screen, no_frame);
8876 #elif defined(CONFIG_COCOA)
8877 cocoa_display_init(ds, full_screen);
8878 #else
8879 dumb_display_init(ds);
8880 #endif
8883 /* Maintain compatibility with multiple stdio monitors */
8884 if (!strcmp(monitor_device,"stdio")) {
8885 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8886 if (!strcmp(serial_devices[i],"mon:stdio")) {
8887 monitor_device[0] = '\0';
8888 break;
8889 } else if (!strcmp(serial_devices[i],"stdio")) {
8890 monitor_device[0] = '\0';
8891 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8892 break;
8896 if (monitor_device[0] != '\0') {
8897 monitor_hd = qemu_chr_open(monitor_device);
8898 if (!monitor_hd) {
8899 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8900 exit(1);
8902 monitor_init(monitor_hd, !nographic);
8905 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8906 const char *devname = serial_devices[i];
8907 if (devname[0] != '\0' && strcmp(devname, "none")) {
8908 serial_hds[i] = qemu_chr_open(devname);
8909 if (!serial_hds[i]) {
8910 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8911 devname);
8912 exit(1);
8914 if (strstart(devname, "vc", 0))
8915 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8919 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8920 const char *devname = parallel_devices[i];
8921 if (devname[0] != '\0' && strcmp(devname, "none")) {
8922 parallel_hds[i] = qemu_chr_open(devname);
8923 if (!parallel_hds[i]) {
8924 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8925 devname);
8926 exit(1);
8928 if (strstart(devname, "vc", 0))
8929 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8933 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8934 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8936 /* init USB devices */
8937 if (usb_enabled) {
8938 for(i = 0; i < usb_devices_index; i++) {
8939 if (usb_device_add(usb_devices[i]) < 0) {
8940 fprintf(stderr, "Warning: could not add USB device %s\n",
8941 usb_devices[i]);
8946 if (display_state.dpy_refresh) {
8947 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8948 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8951 #ifdef CONFIG_GDBSTUB
8952 if (use_gdbstub) {
8953 /* XXX: use standard host:port notation and modify options
8954 accordingly. */
8955 if (gdbserver_start(gdbstub_port) < 0) {
8956 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8957 gdbstub_port);
8958 exit(1);
8961 #endif
8963 if (loadvm)
8964 do_loadvm(loadvm);
8967 /* XXX: simplify init */
8968 read_passwords();
8969 if (autostart) {
8970 vm_start();
8974 if (daemonize) {
8975 uint8_t status = 0;
8976 ssize_t len;
8977 int fd;
8979 again1:
8980 len = write(fds[1], &status, 1);
8981 if (len == -1 && (errno == EINTR))
8982 goto again1;
8984 if (len != 1)
8985 exit(1);
8987 TFR(fd = open("/dev/null", O_RDWR));
8988 if (fd == -1)
8989 exit(1);
8991 dup2(fd, 0);
8992 dup2(fd, 1);
8993 dup2(fd, 2);
8995 close(fd);
8998 main_loop();
8999 quit_timers();
9001 #if !defined(_WIN32)
9002 /* close network clients */
9003 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9004 VLANClientState *vc;
9006 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9007 if (vc->fd_read == tap_receive) {
9008 char ifname[64];
9009 TAPState *s = vc->opaque;
9011 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9012 s->down_script[0])
9013 launch_script(s->down_script, ifname, s->fd);
9017 #endif
9018 return 0;