Use a TCG global for pc and npc
[qemu-kvm/fedora.git] / vl.c
blob2019f9f026cc95a3ac9fa9a09c7860218c98c299
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 int curses;
176 const char* keyboard_layout = NULL;
177 int64_t ticks_per_sec;
178 int ram_size;
179 int pit_min_timer_count = 0;
180 int nb_nics;
181 NICInfo nd_table[MAX_NICS];
182 int vm_running;
183 static int rtc_utc = 1;
184 static int rtc_date_offset = -1; /* -1 means no change */
185 int cirrus_vga_enabled = 1;
186 int vmsvga_enabled = 0;
187 #ifdef TARGET_SPARC
188 int graphic_width = 1024;
189 int graphic_height = 768;
190 int graphic_depth = 8;
191 #else
192 int graphic_width = 800;
193 int graphic_height = 600;
194 int graphic_depth = 15;
195 #endif
196 int full_screen = 0;
197 int no_frame = 0;
198 int no_quit = 0;
199 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
200 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
201 #ifdef TARGET_I386
202 int win2k_install_hack = 0;
203 #endif
204 int usb_enabled = 0;
205 static VLANState *first_vlan;
206 int smp_cpus = 1;
207 const char *vnc_display;
208 #if defined(TARGET_SPARC)
209 #define MAX_CPUS 16
210 #elif defined(TARGET_I386)
211 #define MAX_CPUS 255
212 #else
213 #define MAX_CPUS 1
214 #endif
215 int acpi_enabled = 1;
216 int fd_bootchk = 1;
217 int no_reboot = 0;
218 int cursor_hide = 1;
219 int graphic_rotate = 0;
220 int daemonize = 0;
221 const char *option_rom[MAX_OPTION_ROMS];
222 int nb_option_roms;
223 int semihosting_enabled = 0;
224 int autostart = 1;
225 #ifdef TARGET_ARM
226 int old_param = 0;
227 #endif
228 const char *qemu_name;
229 int alt_grab = 0;
230 #ifdef TARGET_SPARC
231 unsigned int nb_prom_envs = 0;
232 const char *prom_envs[MAX_PROM_ENVS];
233 #endif
234 int nb_drives_opt;
235 struct drive_opt {
236 const char *file;
237 char opt[1024];
238 } drives_opt[MAX_DRIVES];
240 static CPUState *cur_cpu;
241 static CPUState *next_cpu;
242 static int event_pending = 1;
244 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
246 /***********************************************************/
247 /* x86 ISA bus support */
249 target_phys_addr_t isa_mem_base = 0;
250 PicState2 *isa_pic;
252 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
254 #ifdef DEBUG_UNUSED_IOPORT
255 fprintf(stderr, "unused inb: port=0x%04x\n", address);
256 #endif
257 return 0xff;
260 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
262 #ifdef DEBUG_UNUSED_IOPORT
263 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
264 #endif
267 /* default is to make two byte accesses */
268 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
270 uint32_t data;
271 data = ioport_read_table[0][address](ioport_opaque[address], address);
272 address = (address + 1) & (MAX_IOPORTS - 1);
273 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
274 return data;
277 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
279 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
280 address = (address + 1) & (MAX_IOPORTS - 1);
281 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
284 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
286 #ifdef DEBUG_UNUSED_IOPORT
287 fprintf(stderr, "unused inl: port=0x%04x\n", address);
288 #endif
289 return 0xffffffff;
292 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
294 #ifdef DEBUG_UNUSED_IOPORT
295 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
296 #endif
299 static void init_ioports(void)
301 int i;
303 for(i = 0; i < MAX_IOPORTS; i++) {
304 ioport_read_table[0][i] = default_ioport_readb;
305 ioport_write_table[0][i] = default_ioport_writeb;
306 ioport_read_table[1][i] = default_ioport_readw;
307 ioport_write_table[1][i] = default_ioport_writew;
308 ioport_read_table[2][i] = default_ioport_readl;
309 ioport_write_table[2][i] = default_ioport_writel;
313 /* size is the word size in byte */
314 int register_ioport_read(int start, int length, int size,
315 IOPortReadFunc *func, void *opaque)
317 int i, bsize;
319 if (size == 1) {
320 bsize = 0;
321 } else if (size == 2) {
322 bsize = 1;
323 } else if (size == 4) {
324 bsize = 2;
325 } else {
326 hw_error("register_ioport_read: invalid size");
327 return -1;
329 for(i = start; i < start + length; i += size) {
330 ioport_read_table[bsize][i] = func;
331 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
332 hw_error("register_ioport_read: invalid opaque");
333 ioport_opaque[i] = opaque;
335 return 0;
338 /* size is the word size in byte */
339 int register_ioport_write(int start, int length, int size,
340 IOPortWriteFunc *func, void *opaque)
342 int i, bsize;
344 if (size == 1) {
345 bsize = 0;
346 } else if (size == 2) {
347 bsize = 1;
348 } else if (size == 4) {
349 bsize = 2;
350 } else {
351 hw_error("register_ioport_write: invalid size");
352 return -1;
354 for(i = start; i < start + length; i += size) {
355 ioport_write_table[bsize][i] = func;
356 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
357 hw_error("register_ioport_write: invalid opaque");
358 ioport_opaque[i] = opaque;
360 return 0;
363 void isa_unassign_ioport(int start, int length)
365 int i;
367 for(i = start; i < start + length; i++) {
368 ioport_read_table[0][i] = default_ioport_readb;
369 ioport_read_table[1][i] = default_ioport_readw;
370 ioport_read_table[2][i] = default_ioport_readl;
372 ioport_write_table[0][i] = default_ioport_writeb;
373 ioport_write_table[1][i] = default_ioport_writew;
374 ioport_write_table[2][i] = default_ioport_writel;
378 /***********************************************************/
380 void cpu_outb(CPUState *env, int addr, int val)
382 #ifdef DEBUG_IOPORT
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "outb: %04x %02x\n", addr, val);
385 #endif
386 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
387 #ifdef USE_KQEMU
388 if (env)
389 env->last_io_time = cpu_get_time_fast();
390 #endif
393 void cpu_outw(CPUState *env, int addr, int val)
395 #ifdef DEBUG_IOPORT
396 if (loglevel & CPU_LOG_IOPORT)
397 fprintf(logfile, "outw: %04x %04x\n", addr, val);
398 #endif
399 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
400 #ifdef USE_KQEMU
401 if (env)
402 env->last_io_time = cpu_get_time_fast();
403 #endif
406 void cpu_outl(CPUState *env, int addr, int val)
408 #ifdef DEBUG_IOPORT
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "outl: %04x %08x\n", addr, val);
411 #endif
412 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
413 #ifdef USE_KQEMU
414 if (env)
415 env->last_io_time = cpu_get_time_fast();
416 #endif
419 int cpu_inb(CPUState *env, int addr)
421 int val;
422 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inb : %04x %02x\n", addr, val);
426 #endif
427 #ifdef USE_KQEMU
428 if (env)
429 env->last_io_time = cpu_get_time_fast();
430 #endif
431 return val;
434 int cpu_inw(CPUState *env, int addr)
436 int val;
437 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
438 #ifdef DEBUG_IOPORT
439 if (loglevel & CPU_LOG_IOPORT)
440 fprintf(logfile, "inw : %04x %04x\n", addr, val);
441 #endif
442 #ifdef USE_KQEMU
443 if (env)
444 env->last_io_time = cpu_get_time_fast();
445 #endif
446 return val;
449 int cpu_inl(CPUState *env, int addr)
451 int val;
452 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
453 #ifdef DEBUG_IOPORT
454 if (loglevel & CPU_LOG_IOPORT)
455 fprintf(logfile, "inl : %04x %08x\n", addr, val);
456 #endif
457 #ifdef USE_KQEMU
458 if (env)
459 env->last_io_time = cpu_get_time_fast();
460 #endif
461 return val;
464 /***********************************************************/
465 void hw_error(const char *fmt, ...)
467 va_list ap;
468 CPUState *env;
470 va_start(ap, fmt);
471 fprintf(stderr, "qemu: hardware error: ");
472 vfprintf(stderr, fmt, ap);
473 fprintf(stderr, "\n");
474 for(env = first_cpu; env != NULL; env = env->next_cpu) {
475 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
476 #ifdef TARGET_I386
477 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
478 #else
479 cpu_dump_state(env, stderr, fprintf, 0);
480 #endif
482 va_end(ap);
483 abort();
486 /***********************************************************/
487 /* keyboard/mouse */
489 static QEMUPutKBDEvent *qemu_put_kbd_event;
490 static void *qemu_put_kbd_event_opaque;
491 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
492 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
494 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
496 qemu_put_kbd_event_opaque = opaque;
497 qemu_put_kbd_event = func;
500 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
501 void *opaque, int absolute,
502 const char *name)
504 QEMUPutMouseEntry *s, *cursor;
506 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
507 if (!s)
508 return NULL;
510 s->qemu_put_mouse_event = func;
511 s->qemu_put_mouse_event_opaque = opaque;
512 s->qemu_put_mouse_event_absolute = absolute;
513 s->qemu_put_mouse_event_name = qemu_strdup(name);
514 s->next = NULL;
516 if (!qemu_put_mouse_event_head) {
517 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
518 return s;
521 cursor = qemu_put_mouse_event_head;
522 while (cursor->next != NULL)
523 cursor = cursor->next;
525 cursor->next = s;
526 qemu_put_mouse_event_current = s;
528 return s;
531 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
533 QEMUPutMouseEntry *prev = NULL, *cursor;
535 if (!qemu_put_mouse_event_head || entry == NULL)
536 return;
538 cursor = qemu_put_mouse_event_head;
539 while (cursor != NULL && cursor != entry) {
540 prev = cursor;
541 cursor = cursor->next;
544 if (cursor == NULL) // does not exist or list empty
545 return;
546 else if (prev == NULL) { // entry is head
547 qemu_put_mouse_event_head = cursor->next;
548 if (qemu_put_mouse_event_current == entry)
549 qemu_put_mouse_event_current = cursor->next;
550 qemu_free(entry->qemu_put_mouse_event_name);
551 qemu_free(entry);
552 return;
555 prev->next = entry->next;
557 if (qemu_put_mouse_event_current == entry)
558 qemu_put_mouse_event_current = prev;
560 qemu_free(entry->qemu_put_mouse_event_name);
561 qemu_free(entry);
564 void kbd_put_keycode(int keycode)
566 if (qemu_put_kbd_event) {
567 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
571 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
573 QEMUPutMouseEvent *mouse_event;
574 void *mouse_event_opaque;
575 int width;
577 if (!qemu_put_mouse_event_current) {
578 return;
581 mouse_event =
582 qemu_put_mouse_event_current->qemu_put_mouse_event;
583 mouse_event_opaque =
584 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
586 if (mouse_event) {
587 if (graphic_rotate) {
588 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
589 width = 0x7fff;
590 else
591 width = graphic_width - 1;
592 mouse_event(mouse_event_opaque,
593 width - dy, dx, dz, buttons_state);
594 } else
595 mouse_event(mouse_event_opaque,
596 dx, dy, dz, buttons_state);
600 int kbd_mouse_is_absolute(void)
602 if (!qemu_put_mouse_event_current)
603 return 0;
605 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
608 void do_info_mice(void)
610 QEMUPutMouseEntry *cursor;
611 int index = 0;
613 if (!qemu_put_mouse_event_head) {
614 term_printf("No mouse devices connected\n");
615 return;
618 term_printf("Mouse devices available:\n");
619 cursor = qemu_put_mouse_event_head;
620 while (cursor != NULL) {
621 term_printf("%c Mouse #%d: %s\n",
622 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
623 index, cursor->qemu_put_mouse_event_name);
624 index++;
625 cursor = cursor->next;
629 void do_mouse_set(int index)
631 QEMUPutMouseEntry *cursor;
632 int i = 0;
634 if (!qemu_put_mouse_event_head) {
635 term_printf("No mouse devices connected\n");
636 return;
639 cursor = qemu_put_mouse_event_head;
640 while (cursor != NULL && index != i) {
641 i++;
642 cursor = cursor->next;
645 if (cursor != NULL)
646 qemu_put_mouse_event_current = cursor;
647 else
648 term_printf("Mouse at given index not found\n");
651 /* compute with 96 bit intermediate result: (a*b)/c */
652 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
654 union {
655 uint64_t ll;
656 struct {
657 #ifdef WORDS_BIGENDIAN
658 uint32_t high, low;
659 #else
660 uint32_t low, high;
661 #endif
662 } l;
663 } u, res;
664 uint64_t rl, rh;
666 u.ll = a;
667 rl = (uint64_t)u.l.low * (uint64_t)b;
668 rh = (uint64_t)u.l.high * (uint64_t)b;
669 rh += (rl >> 32);
670 res.l.high = rh / c;
671 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
672 return res.ll;
675 /***********************************************************/
676 /* real time host monotonic timer */
678 #define QEMU_TIMER_BASE 1000000000LL
680 #ifdef WIN32
682 static int64_t clock_freq;
684 static void init_get_clock(void)
686 LARGE_INTEGER freq;
687 int ret;
688 ret = QueryPerformanceFrequency(&freq);
689 if (ret == 0) {
690 fprintf(stderr, "Could not calibrate ticks\n");
691 exit(1);
693 clock_freq = freq.QuadPart;
696 static int64_t get_clock(void)
698 LARGE_INTEGER ti;
699 QueryPerformanceCounter(&ti);
700 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
703 #else
705 static int use_rt_clock;
707 static void init_get_clock(void)
709 use_rt_clock = 0;
710 #if defined(__linux__)
712 struct timespec ts;
713 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
714 use_rt_clock = 1;
717 #endif
720 static int64_t get_clock(void)
722 #if defined(__linux__)
723 if (use_rt_clock) {
724 struct timespec ts;
725 clock_gettime(CLOCK_MONOTONIC, &ts);
726 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
727 } else
728 #endif
730 /* XXX: using gettimeofday leads to problems if the date
731 changes, so it should be avoided. */
732 struct timeval tv;
733 gettimeofday(&tv, NULL);
734 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
738 #endif
740 /***********************************************************/
741 /* guest cycle counter */
743 static int64_t cpu_ticks_prev;
744 static int64_t cpu_ticks_offset;
745 static int64_t cpu_clock_offset;
746 static int cpu_ticks_enabled;
748 /* return the host CPU cycle counter and handle stop/restart */
749 int64_t cpu_get_ticks(void)
751 if (!cpu_ticks_enabled) {
752 return cpu_ticks_offset;
753 } else {
754 int64_t ticks;
755 ticks = cpu_get_real_ticks();
756 if (cpu_ticks_prev > ticks) {
757 /* Note: non increasing ticks may happen if the host uses
758 software suspend */
759 cpu_ticks_offset += cpu_ticks_prev - ticks;
761 cpu_ticks_prev = ticks;
762 return ticks + cpu_ticks_offset;
766 /* return the host CPU monotonic timer and handle stop/restart */
767 static int64_t cpu_get_clock(void)
769 int64_t ti;
770 if (!cpu_ticks_enabled) {
771 return cpu_clock_offset;
772 } else {
773 ti = get_clock();
774 return ti + cpu_clock_offset;
778 /* enable cpu_get_ticks() */
779 void cpu_enable_ticks(void)
781 if (!cpu_ticks_enabled) {
782 cpu_ticks_offset -= cpu_get_real_ticks();
783 cpu_clock_offset -= get_clock();
784 cpu_ticks_enabled = 1;
788 /* disable cpu_get_ticks() : the clock is stopped. You must not call
789 cpu_get_ticks() after that. */
790 void cpu_disable_ticks(void)
792 if (cpu_ticks_enabled) {
793 cpu_ticks_offset = cpu_get_ticks();
794 cpu_clock_offset = cpu_get_clock();
795 cpu_ticks_enabled = 0;
799 /***********************************************************/
800 /* timers */
802 #define QEMU_TIMER_REALTIME 0
803 #define QEMU_TIMER_VIRTUAL 1
805 struct QEMUClock {
806 int type;
807 /* XXX: add frequency */
810 struct QEMUTimer {
811 QEMUClock *clock;
812 int64_t expire_time;
813 QEMUTimerCB *cb;
814 void *opaque;
815 struct QEMUTimer *next;
818 struct qemu_alarm_timer {
819 char const *name;
820 unsigned int flags;
822 int (*start)(struct qemu_alarm_timer *t);
823 void (*stop)(struct qemu_alarm_timer *t);
824 void (*rearm)(struct qemu_alarm_timer *t);
825 void *priv;
828 #define ALARM_FLAG_DYNTICKS 0x1
829 #define ALARM_FLAG_EXPIRED 0x2
831 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
833 return t->flags & ALARM_FLAG_DYNTICKS;
836 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
838 if (!alarm_has_dynticks(t))
839 return;
841 t->rearm(t);
844 /* TODO: MIN_TIMER_REARM_US should be optimized */
845 #define MIN_TIMER_REARM_US 250
847 static struct qemu_alarm_timer *alarm_timer;
849 #ifdef _WIN32
851 struct qemu_alarm_win32 {
852 MMRESULT timerId;
853 HANDLE host_alarm;
854 unsigned int period;
855 } alarm_win32_data = {0, NULL, -1};
857 static int win32_start_timer(struct qemu_alarm_timer *t);
858 static void win32_stop_timer(struct qemu_alarm_timer *t);
859 static void win32_rearm_timer(struct qemu_alarm_timer *t);
861 #else
863 static int unix_start_timer(struct qemu_alarm_timer *t);
864 static void unix_stop_timer(struct qemu_alarm_timer *t);
866 #ifdef __linux__
868 static int dynticks_start_timer(struct qemu_alarm_timer *t);
869 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
870 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
872 static int hpet_start_timer(struct qemu_alarm_timer *t);
873 static void hpet_stop_timer(struct qemu_alarm_timer *t);
875 static int rtc_start_timer(struct qemu_alarm_timer *t);
876 static void rtc_stop_timer(struct qemu_alarm_timer *t);
878 #endif /* __linux__ */
880 #endif /* _WIN32 */
882 static struct qemu_alarm_timer alarm_timers[] = {
883 #ifndef _WIN32
884 #ifdef __linux__
885 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
886 dynticks_stop_timer, dynticks_rearm_timer, NULL},
887 /* HPET - if available - is preferred */
888 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
889 /* ...otherwise try RTC */
890 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
891 #endif
892 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
893 #else
894 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
895 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
896 {"win32", 0, win32_start_timer,
897 win32_stop_timer, NULL, &alarm_win32_data},
898 #endif
899 {NULL, }
902 static void show_available_alarms(void)
904 int i;
906 printf("Available alarm timers, in order of precedence:\n");
907 for (i = 0; alarm_timers[i].name; i++)
908 printf("%s\n", alarm_timers[i].name);
911 static void configure_alarms(char const *opt)
913 int i;
914 int cur = 0;
915 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
916 char *arg;
917 char *name;
919 if (!strcmp(opt, "?")) {
920 show_available_alarms();
921 exit(0);
924 arg = strdup(opt);
926 /* Reorder the array */
927 name = strtok(arg, ",");
928 while (name) {
929 struct qemu_alarm_timer tmp;
931 for (i = 0; i < count && alarm_timers[i].name; i++) {
932 if (!strcmp(alarm_timers[i].name, name))
933 break;
936 if (i == count) {
937 fprintf(stderr, "Unknown clock %s\n", name);
938 goto next;
941 if (i < cur)
942 /* Ignore */
943 goto next;
945 /* Swap */
946 tmp = alarm_timers[i];
947 alarm_timers[i] = alarm_timers[cur];
948 alarm_timers[cur] = tmp;
950 cur++;
951 next:
952 name = strtok(NULL, ",");
955 free(arg);
957 if (cur) {
958 /* Disable remaining timers */
959 for (i = cur; i < count; i++)
960 alarm_timers[i].name = NULL;
961 } else {
962 show_available_alarms();
963 exit(1);
967 QEMUClock *rt_clock;
968 QEMUClock *vm_clock;
970 static QEMUTimer *active_timers[2];
972 static QEMUClock *qemu_new_clock(int type)
974 QEMUClock *clock;
975 clock = qemu_mallocz(sizeof(QEMUClock));
976 if (!clock)
977 return NULL;
978 clock->type = type;
979 return clock;
982 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
984 QEMUTimer *ts;
986 ts = qemu_mallocz(sizeof(QEMUTimer));
987 ts->clock = clock;
988 ts->cb = cb;
989 ts->opaque = opaque;
990 return ts;
993 void qemu_free_timer(QEMUTimer *ts)
995 qemu_free(ts);
998 /* stop a timer, but do not dealloc it */
999 void qemu_del_timer(QEMUTimer *ts)
1001 QEMUTimer **pt, *t;
1003 /* NOTE: this code must be signal safe because
1004 qemu_timer_expired() can be called from a signal. */
1005 pt = &active_timers[ts->clock->type];
1006 for(;;) {
1007 t = *pt;
1008 if (!t)
1009 break;
1010 if (t == ts) {
1011 *pt = t->next;
1012 break;
1014 pt = &t->next;
1018 /* modify the current timer so that it will be fired when current_time
1019 >= expire_time. The corresponding callback will be called. */
1020 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1022 QEMUTimer **pt, *t;
1024 qemu_del_timer(ts);
1026 /* add the timer in the sorted list */
1027 /* NOTE: this code must be signal safe because
1028 qemu_timer_expired() can be called from a signal. */
1029 pt = &active_timers[ts->clock->type];
1030 for(;;) {
1031 t = *pt;
1032 if (!t)
1033 break;
1034 if (t->expire_time > expire_time)
1035 break;
1036 pt = &t->next;
1038 ts->expire_time = expire_time;
1039 ts->next = *pt;
1040 *pt = ts;
1042 /* Rearm if necessary */
1043 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1044 pt == &active_timers[ts->clock->type])
1045 qemu_rearm_alarm_timer(alarm_timer);
1048 int qemu_timer_pending(QEMUTimer *ts)
1050 QEMUTimer *t;
1051 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1052 if (t == ts)
1053 return 1;
1055 return 0;
1058 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1060 if (!timer_head)
1061 return 0;
1062 return (timer_head->expire_time <= current_time);
1065 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1067 QEMUTimer *ts;
1069 for(;;) {
1070 ts = *ptimer_head;
1071 if (!ts || ts->expire_time > current_time)
1072 break;
1073 /* remove timer from the list before calling the callback */
1074 *ptimer_head = ts->next;
1075 ts->next = NULL;
1077 /* run the callback (the timer list can be modified) */
1078 ts->cb(ts->opaque);
1082 int64_t qemu_get_clock(QEMUClock *clock)
1084 switch(clock->type) {
1085 case QEMU_TIMER_REALTIME:
1086 return get_clock() / 1000000;
1087 default:
1088 case QEMU_TIMER_VIRTUAL:
1089 return cpu_get_clock();
1093 static void init_timers(void)
1095 init_get_clock();
1096 ticks_per_sec = QEMU_TIMER_BASE;
1097 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1098 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1101 /* save a timer */
1102 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1104 uint64_t expire_time;
1106 if (qemu_timer_pending(ts)) {
1107 expire_time = ts->expire_time;
1108 } else {
1109 expire_time = -1;
1111 qemu_put_be64(f, expire_time);
1114 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1116 uint64_t expire_time;
1118 expire_time = qemu_get_be64(f);
1119 if (expire_time != -1) {
1120 qemu_mod_timer(ts, expire_time);
1121 } else {
1122 qemu_del_timer(ts);
1126 static void timer_save(QEMUFile *f, void *opaque)
1128 if (cpu_ticks_enabled) {
1129 hw_error("cannot save state if virtual timers are running");
1131 qemu_put_be64(f, cpu_ticks_offset);
1132 qemu_put_be64(f, ticks_per_sec);
1133 qemu_put_be64(f, cpu_clock_offset);
1136 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1138 if (version_id != 1 && version_id != 2)
1139 return -EINVAL;
1140 if (cpu_ticks_enabled) {
1141 return -EINVAL;
1143 cpu_ticks_offset=qemu_get_be64(f);
1144 ticks_per_sec=qemu_get_be64(f);
1145 if (version_id == 2) {
1146 cpu_clock_offset=qemu_get_be64(f);
1148 return 0;
1151 #ifdef _WIN32
1152 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1153 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1154 #else
1155 static void host_alarm_handler(int host_signum)
1156 #endif
1158 #if 0
1159 #define DISP_FREQ 1000
1161 static int64_t delta_min = INT64_MAX;
1162 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1163 static int count;
1164 ti = qemu_get_clock(vm_clock);
1165 if (last_clock != 0) {
1166 delta = ti - last_clock;
1167 if (delta < delta_min)
1168 delta_min = delta;
1169 if (delta > delta_max)
1170 delta_max = delta;
1171 delta_cum += delta;
1172 if (++count == DISP_FREQ) {
1173 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1174 muldiv64(delta_min, 1000000, ticks_per_sec),
1175 muldiv64(delta_max, 1000000, ticks_per_sec),
1176 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1177 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1178 count = 0;
1179 delta_min = INT64_MAX;
1180 delta_max = 0;
1181 delta_cum = 0;
1184 last_clock = ti;
1186 #endif
1187 if (alarm_has_dynticks(alarm_timer) ||
1188 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1189 qemu_get_clock(vm_clock)) ||
1190 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1191 qemu_get_clock(rt_clock))) {
1192 #ifdef _WIN32
1193 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1194 SetEvent(data->host_alarm);
1195 #endif
1196 CPUState *env = next_cpu;
1198 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1200 if (env) {
1201 /* stop the currently executing cpu because a timer occured */
1202 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1203 #ifdef USE_KQEMU
1204 if (env->kqemu_enabled) {
1205 kqemu_cpu_interrupt(env);
1207 #endif
1209 event_pending = 1;
1213 static uint64_t qemu_next_deadline(void)
1215 int64_t nearest_delta_us = INT64_MAX;
1216 int64_t vmdelta_us;
1218 if (active_timers[QEMU_TIMER_REALTIME])
1219 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1220 qemu_get_clock(rt_clock))*1000;
1222 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1223 /* round up */
1224 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1225 qemu_get_clock(vm_clock)+999)/1000;
1226 if (vmdelta_us < nearest_delta_us)
1227 nearest_delta_us = vmdelta_us;
1230 /* Avoid arming the timer to negative, zero, or too low values */
1231 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1232 nearest_delta_us = MIN_TIMER_REARM_US;
1234 return nearest_delta_us;
1237 #ifndef _WIN32
1239 #if defined(__linux__)
1241 #define RTC_FREQ 1024
1243 static void enable_sigio_timer(int fd)
1245 struct sigaction act;
1247 /* timer signal */
1248 sigfillset(&act.sa_mask);
1249 act.sa_flags = 0;
1250 act.sa_handler = host_alarm_handler;
1252 sigaction(SIGIO, &act, NULL);
1253 fcntl(fd, F_SETFL, O_ASYNC);
1254 fcntl(fd, F_SETOWN, getpid());
1257 static int hpet_start_timer(struct qemu_alarm_timer *t)
1259 struct hpet_info info;
1260 int r, fd;
1262 fd = open("/dev/hpet", O_RDONLY);
1263 if (fd < 0)
1264 return -1;
1266 /* Set frequency */
1267 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1268 if (r < 0) {
1269 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1270 "error, but for better emulation accuracy type:\n"
1271 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1272 goto fail;
1275 /* Check capabilities */
1276 r = ioctl(fd, HPET_INFO, &info);
1277 if (r < 0)
1278 goto fail;
1280 /* Enable periodic mode */
1281 r = ioctl(fd, HPET_EPI, 0);
1282 if (info.hi_flags && (r < 0))
1283 goto fail;
1285 /* Enable interrupt */
1286 r = ioctl(fd, HPET_IE_ON, 0);
1287 if (r < 0)
1288 goto fail;
1290 enable_sigio_timer(fd);
1291 t->priv = (void *)(long)fd;
1293 return 0;
1294 fail:
1295 close(fd);
1296 return -1;
1299 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1301 int fd = (long)t->priv;
1303 close(fd);
1306 static int rtc_start_timer(struct qemu_alarm_timer *t)
1308 int rtc_fd;
1309 unsigned long current_rtc_freq = 0;
1311 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1312 if (rtc_fd < 0)
1313 return -1;
1314 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1315 if (current_rtc_freq != RTC_FREQ &&
1316 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1317 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1318 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1319 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1320 goto fail;
1322 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1323 fail:
1324 close(rtc_fd);
1325 return -1;
1328 enable_sigio_timer(rtc_fd);
1330 t->priv = (void *)(long)rtc_fd;
1332 return 0;
1335 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1337 int rtc_fd = (long)t->priv;
1339 close(rtc_fd);
1342 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1344 struct sigevent ev;
1345 timer_t host_timer;
1346 struct sigaction act;
1348 sigfillset(&act.sa_mask);
1349 act.sa_flags = 0;
1350 act.sa_handler = host_alarm_handler;
1352 sigaction(SIGALRM, &act, NULL);
1354 ev.sigev_value.sival_int = 0;
1355 ev.sigev_notify = SIGEV_SIGNAL;
1356 ev.sigev_signo = SIGALRM;
1358 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1359 perror("timer_create");
1361 /* disable dynticks */
1362 fprintf(stderr, "Dynamic Ticks disabled\n");
1364 return -1;
1367 t->priv = (void *)host_timer;
1369 return 0;
1372 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1374 timer_t host_timer = (timer_t)t->priv;
1376 timer_delete(host_timer);
1379 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1381 timer_t host_timer = (timer_t)t->priv;
1382 struct itimerspec timeout;
1383 int64_t nearest_delta_us = INT64_MAX;
1384 int64_t current_us;
1386 if (!active_timers[QEMU_TIMER_REALTIME] &&
1387 !active_timers[QEMU_TIMER_VIRTUAL])
1388 return;
1390 nearest_delta_us = qemu_next_deadline();
1392 /* check whether a timer is already running */
1393 if (timer_gettime(host_timer, &timeout)) {
1394 perror("gettime");
1395 fprintf(stderr, "Internal timer error: aborting\n");
1396 exit(1);
1398 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1399 if (current_us && current_us <= nearest_delta_us)
1400 return;
1402 timeout.it_interval.tv_sec = 0;
1403 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1404 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1405 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1406 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1407 perror("settime");
1408 fprintf(stderr, "Internal timer error: aborting\n");
1409 exit(1);
1413 #endif /* defined(__linux__) */
1415 static int unix_start_timer(struct qemu_alarm_timer *t)
1417 struct sigaction act;
1418 struct itimerval itv;
1419 int err;
1421 /* timer signal */
1422 sigfillset(&act.sa_mask);
1423 act.sa_flags = 0;
1424 act.sa_handler = host_alarm_handler;
1426 sigaction(SIGALRM, &act, NULL);
1428 itv.it_interval.tv_sec = 0;
1429 /* for i386 kernel 2.6 to get 1 ms */
1430 itv.it_interval.tv_usec = 999;
1431 itv.it_value.tv_sec = 0;
1432 itv.it_value.tv_usec = 10 * 1000;
1434 err = setitimer(ITIMER_REAL, &itv, NULL);
1435 if (err)
1436 return -1;
1438 return 0;
1441 static void unix_stop_timer(struct qemu_alarm_timer *t)
1443 struct itimerval itv;
1445 memset(&itv, 0, sizeof(itv));
1446 setitimer(ITIMER_REAL, &itv, NULL);
1449 #endif /* !defined(_WIN32) */
1451 #ifdef _WIN32
1453 static int win32_start_timer(struct qemu_alarm_timer *t)
1455 TIMECAPS tc;
1456 struct qemu_alarm_win32 *data = t->priv;
1457 UINT flags;
1459 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1460 if (!data->host_alarm) {
1461 perror("Failed CreateEvent");
1462 return -1;
1465 memset(&tc, 0, sizeof(tc));
1466 timeGetDevCaps(&tc, sizeof(tc));
1468 if (data->period < tc.wPeriodMin)
1469 data->period = tc.wPeriodMin;
1471 timeBeginPeriod(data->period);
1473 flags = TIME_CALLBACK_FUNCTION;
1474 if (alarm_has_dynticks(t))
1475 flags |= TIME_ONESHOT;
1476 else
1477 flags |= TIME_PERIODIC;
1479 data->timerId = timeSetEvent(1, // interval (ms)
1480 data->period, // resolution
1481 host_alarm_handler, // function
1482 (DWORD)t, // parameter
1483 flags);
1485 if (!data->timerId) {
1486 perror("Failed to initialize win32 alarm timer");
1488 timeEndPeriod(data->period);
1489 CloseHandle(data->host_alarm);
1490 return -1;
1493 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1495 return 0;
1498 static void win32_stop_timer(struct qemu_alarm_timer *t)
1500 struct qemu_alarm_win32 *data = t->priv;
1502 timeKillEvent(data->timerId);
1503 timeEndPeriod(data->period);
1505 CloseHandle(data->host_alarm);
1508 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1510 struct qemu_alarm_win32 *data = t->priv;
1511 uint64_t nearest_delta_us;
1513 if (!active_timers[QEMU_TIMER_REALTIME] &&
1514 !active_timers[QEMU_TIMER_VIRTUAL])
1515 return;
1517 nearest_delta_us = qemu_next_deadline();
1518 nearest_delta_us /= 1000;
1520 timeKillEvent(data->timerId);
1522 data->timerId = timeSetEvent(1,
1523 data->period,
1524 host_alarm_handler,
1525 (DWORD)t,
1526 TIME_ONESHOT | TIME_PERIODIC);
1528 if (!data->timerId) {
1529 perror("Failed to re-arm win32 alarm timer");
1531 timeEndPeriod(data->period);
1532 CloseHandle(data->host_alarm);
1533 exit(1);
1537 #endif /* _WIN32 */
1539 static void init_timer_alarm(void)
1541 struct qemu_alarm_timer *t;
1542 int i, err = -1;
1544 for (i = 0; alarm_timers[i].name; i++) {
1545 t = &alarm_timers[i];
1547 err = t->start(t);
1548 if (!err)
1549 break;
1552 if (err) {
1553 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1554 fprintf(stderr, "Terminating\n");
1555 exit(1);
1558 alarm_timer = t;
1561 static void quit_timers(void)
1563 alarm_timer->stop(alarm_timer);
1564 alarm_timer = NULL;
1567 /***********************************************************/
1568 /* host time/date access */
1569 void qemu_get_timedate(struct tm *tm, int offset)
1571 time_t ti;
1572 struct tm *ret;
1574 time(&ti);
1575 ti += offset;
1576 if (rtc_date_offset == -1) {
1577 if (rtc_utc)
1578 ret = gmtime(&ti);
1579 else
1580 ret = localtime(&ti);
1581 } else {
1582 ti -= rtc_date_offset;
1583 ret = gmtime(&ti);
1586 memcpy(tm, ret, sizeof(struct tm));
1589 int qemu_timedate_diff(struct tm *tm)
1591 time_t seconds;
1593 if (rtc_date_offset == -1)
1594 if (rtc_utc)
1595 seconds = mktimegm(tm);
1596 else
1597 seconds = mktime(tm);
1598 else
1599 seconds = mktimegm(tm) + rtc_date_offset;
1601 return seconds - time(NULL);
1604 /***********************************************************/
1605 /* character device */
1607 static void qemu_chr_event(CharDriverState *s, int event)
1609 if (!s->chr_event)
1610 return;
1611 s->chr_event(s->handler_opaque, event);
1614 static void qemu_chr_reset_bh(void *opaque)
1616 CharDriverState *s = opaque;
1617 qemu_chr_event(s, CHR_EVENT_RESET);
1618 qemu_bh_delete(s->bh);
1619 s->bh = NULL;
1622 void qemu_chr_reset(CharDriverState *s)
1624 if (s->bh == NULL) {
1625 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1626 qemu_bh_schedule(s->bh);
1630 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1632 return s->chr_write(s, buf, len);
1635 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1637 if (!s->chr_ioctl)
1638 return -ENOTSUP;
1639 return s->chr_ioctl(s, cmd, arg);
1642 int qemu_chr_can_read(CharDriverState *s)
1644 if (!s->chr_can_read)
1645 return 0;
1646 return s->chr_can_read(s->handler_opaque);
1649 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1651 s->chr_read(s->handler_opaque, buf, len);
1654 void qemu_chr_accept_input(CharDriverState *s)
1656 if (s->chr_accept_input)
1657 s->chr_accept_input(s);
1660 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1662 char buf[4096];
1663 va_list ap;
1664 va_start(ap, fmt);
1665 vsnprintf(buf, sizeof(buf), fmt, ap);
1666 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1667 va_end(ap);
1670 void qemu_chr_send_event(CharDriverState *s, int event)
1672 if (s->chr_send_event)
1673 s->chr_send_event(s, event);
1676 void qemu_chr_add_handlers(CharDriverState *s,
1677 IOCanRWHandler *fd_can_read,
1678 IOReadHandler *fd_read,
1679 IOEventHandler *fd_event,
1680 void *opaque)
1682 s->chr_can_read = fd_can_read;
1683 s->chr_read = fd_read;
1684 s->chr_event = fd_event;
1685 s->handler_opaque = opaque;
1686 if (s->chr_update_read_handler)
1687 s->chr_update_read_handler(s);
1690 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1692 return len;
1695 static CharDriverState *qemu_chr_open_null(void)
1697 CharDriverState *chr;
1699 chr = qemu_mallocz(sizeof(CharDriverState));
1700 if (!chr)
1701 return NULL;
1702 chr->chr_write = null_chr_write;
1703 return chr;
1706 /* MUX driver for serial I/O splitting */
1707 static int term_timestamps;
1708 static int64_t term_timestamps_start;
1709 #define MAX_MUX 4
1710 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1711 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1712 typedef struct {
1713 IOCanRWHandler *chr_can_read[MAX_MUX];
1714 IOReadHandler *chr_read[MAX_MUX];
1715 IOEventHandler *chr_event[MAX_MUX];
1716 void *ext_opaque[MAX_MUX];
1717 CharDriverState *drv;
1718 unsigned char buffer[MUX_BUFFER_SIZE];
1719 int prod;
1720 int cons;
1721 int mux_cnt;
1722 int term_got_escape;
1723 int max_size;
1724 } MuxDriver;
1727 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1729 MuxDriver *d = chr->opaque;
1730 int ret;
1731 if (!term_timestamps) {
1732 ret = d->drv->chr_write(d->drv, buf, len);
1733 } else {
1734 int i;
1736 ret = 0;
1737 for(i = 0; i < len; i++) {
1738 ret += d->drv->chr_write(d->drv, buf+i, 1);
1739 if (buf[i] == '\n') {
1740 char buf1[64];
1741 int64_t ti;
1742 int secs;
1744 ti = get_clock();
1745 if (term_timestamps_start == -1)
1746 term_timestamps_start = ti;
1747 ti -= term_timestamps_start;
1748 secs = ti / 1000000000;
1749 snprintf(buf1, sizeof(buf1),
1750 "[%02d:%02d:%02d.%03d] ",
1751 secs / 3600,
1752 (secs / 60) % 60,
1753 secs % 60,
1754 (int)((ti / 1000000) % 1000));
1755 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1759 return ret;
1762 static char *mux_help[] = {
1763 "% h print this help\n\r",
1764 "% x exit emulator\n\r",
1765 "% s save disk data back to file (if -snapshot)\n\r",
1766 "% t toggle console timestamps\n\r"
1767 "% b send break (magic sysrq)\n\r",
1768 "% c switch between console and monitor\n\r",
1769 "% % sends %\n\r",
1770 NULL
1773 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1774 static void mux_print_help(CharDriverState *chr)
1776 int i, j;
1777 char ebuf[15] = "Escape-Char";
1778 char cbuf[50] = "\n\r";
1780 if (term_escape_char > 0 && term_escape_char < 26) {
1781 sprintf(cbuf,"\n\r");
1782 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1783 } else {
1784 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1785 term_escape_char);
1787 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1788 for (i = 0; mux_help[i] != NULL; i++) {
1789 for (j=0; mux_help[i][j] != '\0'; j++) {
1790 if (mux_help[i][j] == '%')
1791 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1792 else
1793 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1798 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1800 if (d->term_got_escape) {
1801 d->term_got_escape = 0;
1802 if (ch == term_escape_char)
1803 goto send_char;
1804 switch(ch) {
1805 case '?':
1806 case 'h':
1807 mux_print_help(chr);
1808 break;
1809 case 'x':
1811 char *term = "QEMU: Terminated\n\r";
1812 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1813 exit(0);
1814 break;
1816 case 's':
1818 int i;
1819 for (i = 0; i < nb_drives; i++) {
1820 bdrv_commit(drives_table[i].bdrv);
1823 break;
1824 case 'b':
1825 qemu_chr_event(chr, CHR_EVENT_BREAK);
1826 break;
1827 case 'c':
1828 /* Switch to the next registered device */
1829 chr->focus++;
1830 if (chr->focus >= d->mux_cnt)
1831 chr->focus = 0;
1832 break;
1833 case 't':
1834 term_timestamps = !term_timestamps;
1835 term_timestamps_start = -1;
1836 break;
1838 } else if (ch == term_escape_char) {
1839 d->term_got_escape = 1;
1840 } else {
1841 send_char:
1842 return 1;
1844 return 0;
1847 static void mux_chr_accept_input(CharDriverState *chr)
1849 int m = chr->focus;
1850 MuxDriver *d = chr->opaque;
1852 while (d->prod != d->cons &&
1853 d->chr_can_read[m] &&
1854 d->chr_can_read[m](d->ext_opaque[m])) {
1855 d->chr_read[m](d->ext_opaque[m],
1856 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1860 static int mux_chr_can_read(void *opaque)
1862 CharDriverState *chr = opaque;
1863 MuxDriver *d = chr->opaque;
1865 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1866 return 1;
1867 if (d->chr_can_read[chr->focus])
1868 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1869 return 0;
1872 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1874 CharDriverState *chr = opaque;
1875 MuxDriver *d = chr->opaque;
1876 int m = chr->focus;
1877 int i;
1879 mux_chr_accept_input (opaque);
1881 for(i = 0; i < size; i++)
1882 if (mux_proc_byte(chr, d, buf[i])) {
1883 if (d->prod == d->cons &&
1884 d->chr_can_read[m] &&
1885 d->chr_can_read[m](d->ext_opaque[m]))
1886 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1887 else
1888 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1892 static void mux_chr_event(void *opaque, int event)
1894 CharDriverState *chr = opaque;
1895 MuxDriver *d = chr->opaque;
1896 int i;
1898 /* Send the event to all registered listeners */
1899 for (i = 0; i < d->mux_cnt; i++)
1900 if (d->chr_event[i])
1901 d->chr_event[i](d->ext_opaque[i], event);
1904 static void mux_chr_update_read_handler(CharDriverState *chr)
1906 MuxDriver *d = chr->opaque;
1908 if (d->mux_cnt >= MAX_MUX) {
1909 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1910 return;
1912 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1913 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1914 d->chr_read[d->mux_cnt] = chr->chr_read;
1915 d->chr_event[d->mux_cnt] = chr->chr_event;
1916 /* Fix up the real driver with mux routines */
1917 if (d->mux_cnt == 0) {
1918 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1919 mux_chr_event, chr);
1921 chr->focus = d->mux_cnt;
1922 d->mux_cnt++;
1925 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1927 CharDriverState *chr;
1928 MuxDriver *d;
1930 chr = qemu_mallocz(sizeof(CharDriverState));
1931 if (!chr)
1932 return NULL;
1933 d = qemu_mallocz(sizeof(MuxDriver));
1934 if (!d) {
1935 free(chr);
1936 return NULL;
1939 chr->opaque = d;
1940 d->drv = drv;
1941 chr->focus = -1;
1942 chr->chr_write = mux_chr_write;
1943 chr->chr_update_read_handler = mux_chr_update_read_handler;
1944 chr->chr_accept_input = mux_chr_accept_input;
1945 return chr;
1949 #ifdef _WIN32
1951 static void socket_cleanup(void)
1953 WSACleanup();
1956 static int socket_init(void)
1958 WSADATA Data;
1959 int ret, err;
1961 ret = WSAStartup(MAKEWORD(2,2), &Data);
1962 if (ret != 0) {
1963 err = WSAGetLastError();
1964 fprintf(stderr, "WSAStartup: %d\n", err);
1965 return -1;
1967 atexit(socket_cleanup);
1968 return 0;
1971 static int send_all(int fd, const uint8_t *buf, int len1)
1973 int ret, len;
1975 len = len1;
1976 while (len > 0) {
1977 ret = send(fd, buf, len, 0);
1978 if (ret < 0) {
1979 int errno;
1980 errno = WSAGetLastError();
1981 if (errno != WSAEWOULDBLOCK) {
1982 return -1;
1984 } else if (ret == 0) {
1985 break;
1986 } else {
1987 buf += ret;
1988 len -= ret;
1991 return len1 - len;
1994 void socket_set_nonblock(int fd)
1996 unsigned long opt = 1;
1997 ioctlsocket(fd, FIONBIO, &opt);
2000 #else
2002 static int unix_write(int fd, const uint8_t *buf, int len1)
2004 int ret, len;
2006 len = len1;
2007 while (len > 0) {
2008 ret = write(fd, buf, len);
2009 if (ret < 0) {
2010 if (errno != EINTR && errno != EAGAIN)
2011 return -1;
2012 } else if (ret == 0) {
2013 break;
2014 } else {
2015 buf += ret;
2016 len -= ret;
2019 return len1 - len;
2022 static inline int send_all(int fd, const uint8_t *buf, int len1)
2024 return unix_write(fd, buf, len1);
2027 void socket_set_nonblock(int fd)
2029 fcntl(fd, F_SETFL, O_NONBLOCK);
2031 #endif /* !_WIN32 */
2033 #ifndef _WIN32
2035 typedef struct {
2036 int fd_in, fd_out;
2037 int max_size;
2038 } FDCharDriver;
2040 #define STDIO_MAX_CLIENTS 1
2041 static int stdio_nb_clients = 0;
2043 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2045 FDCharDriver *s = chr->opaque;
2046 return unix_write(s->fd_out, buf, len);
2049 static int fd_chr_read_poll(void *opaque)
2051 CharDriverState *chr = opaque;
2052 FDCharDriver *s = chr->opaque;
2054 s->max_size = qemu_chr_can_read(chr);
2055 return s->max_size;
2058 static void fd_chr_read(void *opaque)
2060 CharDriverState *chr = opaque;
2061 FDCharDriver *s = chr->opaque;
2062 int size, len;
2063 uint8_t buf[1024];
2065 len = sizeof(buf);
2066 if (len > s->max_size)
2067 len = s->max_size;
2068 if (len == 0)
2069 return;
2070 size = read(s->fd_in, buf, len);
2071 if (size == 0) {
2072 /* FD has been closed. Remove it from the active list. */
2073 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2074 return;
2076 if (size > 0) {
2077 qemu_chr_read(chr, buf, size);
2081 static void fd_chr_update_read_handler(CharDriverState *chr)
2083 FDCharDriver *s = chr->opaque;
2085 if (s->fd_in >= 0) {
2086 if (nographic && s->fd_in == 0) {
2087 } else {
2088 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2089 fd_chr_read, NULL, chr);
2094 static void fd_chr_close(struct CharDriverState *chr)
2096 FDCharDriver *s = chr->opaque;
2098 if (s->fd_in >= 0) {
2099 if (nographic && s->fd_in == 0) {
2100 } else {
2101 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2105 qemu_free(s);
2108 /* open a character device to a unix fd */
2109 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2111 CharDriverState *chr;
2112 FDCharDriver *s;
2114 chr = qemu_mallocz(sizeof(CharDriverState));
2115 if (!chr)
2116 return NULL;
2117 s = qemu_mallocz(sizeof(FDCharDriver));
2118 if (!s) {
2119 free(chr);
2120 return NULL;
2122 s->fd_in = fd_in;
2123 s->fd_out = fd_out;
2124 chr->opaque = s;
2125 chr->chr_write = fd_chr_write;
2126 chr->chr_update_read_handler = fd_chr_update_read_handler;
2127 chr->chr_close = fd_chr_close;
2129 qemu_chr_reset(chr);
2131 return chr;
2134 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2136 int fd_out;
2138 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2139 if (fd_out < 0)
2140 return NULL;
2141 return qemu_chr_open_fd(-1, fd_out);
2144 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2146 int fd_in, fd_out;
2147 char filename_in[256], filename_out[256];
2149 snprintf(filename_in, 256, "%s.in", filename);
2150 snprintf(filename_out, 256, "%s.out", filename);
2151 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2152 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2153 if (fd_in < 0 || fd_out < 0) {
2154 if (fd_in >= 0)
2155 close(fd_in);
2156 if (fd_out >= 0)
2157 close(fd_out);
2158 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2159 if (fd_in < 0)
2160 return NULL;
2162 return qemu_chr_open_fd(fd_in, fd_out);
2166 /* for STDIO, we handle the case where several clients use it
2167 (nographic mode) */
2169 #define TERM_FIFO_MAX_SIZE 1
2171 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2172 static int term_fifo_size;
2174 static int stdio_read_poll(void *opaque)
2176 CharDriverState *chr = opaque;
2178 /* try to flush the queue if needed */
2179 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2180 qemu_chr_read(chr, term_fifo, 1);
2181 term_fifo_size = 0;
2183 /* see if we can absorb more chars */
2184 if (term_fifo_size == 0)
2185 return 1;
2186 else
2187 return 0;
2190 static void stdio_read(void *opaque)
2192 int size;
2193 uint8_t buf[1];
2194 CharDriverState *chr = opaque;
2196 size = read(0, buf, 1);
2197 if (size == 0) {
2198 /* stdin has been closed. Remove it from the active list. */
2199 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2200 return;
2202 if (size > 0) {
2203 if (qemu_chr_can_read(chr) > 0) {
2204 qemu_chr_read(chr, buf, 1);
2205 } else if (term_fifo_size == 0) {
2206 term_fifo[term_fifo_size++] = buf[0];
2211 /* init terminal so that we can grab keys */
2212 static struct termios oldtty;
2213 static int old_fd0_flags;
2214 static int term_atexit_done;
2216 static void term_exit(void)
2218 tcsetattr (0, TCSANOW, &oldtty);
2219 fcntl(0, F_SETFL, old_fd0_flags);
2222 static void term_init(void)
2224 struct termios tty;
2226 tcgetattr (0, &tty);
2227 oldtty = tty;
2228 old_fd0_flags = fcntl(0, F_GETFL);
2230 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2231 |INLCR|IGNCR|ICRNL|IXON);
2232 tty.c_oflag |= OPOST;
2233 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2234 /* if graphical mode, we allow Ctrl-C handling */
2235 if (nographic)
2236 tty.c_lflag &= ~ISIG;
2237 tty.c_cflag &= ~(CSIZE|PARENB);
2238 tty.c_cflag |= CS8;
2239 tty.c_cc[VMIN] = 1;
2240 tty.c_cc[VTIME] = 0;
2242 tcsetattr (0, TCSANOW, &tty);
2244 if (!term_atexit_done++)
2245 atexit(term_exit);
2247 fcntl(0, F_SETFL, O_NONBLOCK);
2250 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2252 term_exit();
2253 stdio_nb_clients--;
2254 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2255 fd_chr_close(chr);
2258 static CharDriverState *qemu_chr_open_stdio(void)
2260 CharDriverState *chr;
2262 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2263 return NULL;
2264 chr = qemu_chr_open_fd(0, 1);
2265 chr->chr_close = qemu_chr_close_stdio;
2266 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2267 stdio_nb_clients++;
2268 term_init();
2270 return chr;
2273 #if defined(__linux__) || defined(__sun__)
2274 static CharDriverState *qemu_chr_open_pty(void)
2276 struct termios tty;
2277 char slave_name[1024];
2278 int master_fd, slave_fd;
2280 #if defined(__linux__)
2281 /* Not satisfying */
2282 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2283 return NULL;
2285 #endif
2287 /* Disabling local echo and line-buffered output */
2288 tcgetattr (master_fd, &tty);
2289 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2290 tty.c_cc[VMIN] = 1;
2291 tty.c_cc[VTIME] = 0;
2292 tcsetattr (master_fd, TCSAFLUSH, &tty);
2294 fprintf(stderr, "char device redirected to %s\n", slave_name);
2295 return qemu_chr_open_fd(master_fd, master_fd);
2298 static void tty_serial_init(int fd, int speed,
2299 int parity, int data_bits, int stop_bits)
2301 struct termios tty;
2302 speed_t spd;
2304 #if 0
2305 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2306 speed, parity, data_bits, stop_bits);
2307 #endif
2308 tcgetattr (fd, &tty);
2310 #define MARGIN 1.1
2311 if (speed <= 50 * MARGIN)
2312 spd = B50;
2313 else if (speed <= 75 * MARGIN)
2314 spd = B75;
2315 else if (speed <= 300 * MARGIN)
2316 spd = B300;
2317 else if (speed <= 600 * MARGIN)
2318 spd = B600;
2319 else if (speed <= 1200 * MARGIN)
2320 spd = B1200;
2321 else if (speed <= 2400 * MARGIN)
2322 spd = B2400;
2323 else if (speed <= 4800 * MARGIN)
2324 spd = B4800;
2325 else if (speed <= 9600 * MARGIN)
2326 spd = B9600;
2327 else if (speed <= 19200 * MARGIN)
2328 spd = B19200;
2329 else if (speed <= 38400 * MARGIN)
2330 spd = B38400;
2331 else if (speed <= 57600 * MARGIN)
2332 spd = B57600;
2333 else if (speed <= 115200 * MARGIN)
2334 spd = B115200;
2335 else
2336 spd = B115200;
2338 cfsetispeed(&tty, spd);
2339 cfsetospeed(&tty, spd);
2341 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2342 |INLCR|IGNCR|ICRNL|IXON);
2343 tty.c_oflag |= OPOST;
2344 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2345 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2346 switch(data_bits) {
2347 default:
2348 case 8:
2349 tty.c_cflag |= CS8;
2350 break;
2351 case 7:
2352 tty.c_cflag |= CS7;
2353 break;
2354 case 6:
2355 tty.c_cflag |= CS6;
2356 break;
2357 case 5:
2358 tty.c_cflag |= CS5;
2359 break;
2361 switch(parity) {
2362 default:
2363 case 'N':
2364 break;
2365 case 'E':
2366 tty.c_cflag |= PARENB;
2367 break;
2368 case 'O':
2369 tty.c_cflag |= PARENB | PARODD;
2370 break;
2372 if (stop_bits == 2)
2373 tty.c_cflag |= CSTOPB;
2375 tcsetattr (fd, TCSANOW, &tty);
2378 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2380 FDCharDriver *s = chr->opaque;
2382 switch(cmd) {
2383 case CHR_IOCTL_SERIAL_SET_PARAMS:
2385 QEMUSerialSetParams *ssp = arg;
2386 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2387 ssp->data_bits, ssp->stop_bits);
2389 break;
2390 case CHR_IOCTL_SERIAL_SET_BREAK:
2392 int enable = *(int *)arg;
2393 if (enable)
2394 tcsendbreak(s->fd_in, 1);
2396 break;
2397 default:
2398 return -ENOTSUP;
2400 return 0;
2403 static CharDriverState *qemu_chr_open_tty(const char *filename)
2405 CharDriverState *chr;
2406 int fd;
2408 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2409 fcntl(fd, F_SETFL, O_NONBLOCK);
2410 tty_serial_init(fd, 115200, 'N', 8, 1);
2411 chr = qemu_chr_open_fd(fd, fd);
2412 if (!chr) {
2413 close(fd);
2414 return NULL;
2416 chr->chr_ioctl = tty_serial_ioctl;
2417 qemu_chr_reset(chr);
2418 return chr;
2420 #else /* ! __linux__ && ! __sun__ */
2421 static CharDriverState *qemu_chr_open_pty(void)
2423 return NULL;
2425 #endif /* __linux__ || __sun__ */
2427 #if defined(__linux__)
2428 typedef struct {
2429 int fd;
2430 int mode;
2431 } ParallelCharDriver;
2433 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2435 if (s->mode != mode) {
2436 int m = mode;
2437 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2438 return 0;
2439 s->mode = mode;
2441 return 1;
2444 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2446 ParallelCharDriver *drv = chr->opaque;
2447 int fd = drv->fd;
2448 uint8_t b;
2450 switch(cmd) {
2451 case CHR_IOCTL_PP_READ_DATA:
2452 if (ioctl(fd, PPRDATA, &b) < 0)
2453 return -ENOTSUP;
2454 *(uint8_t *)arg = b;
2455 break;
2456 case CHR_IOCTL_PP_WRITE_DATA:
2457 b = *(uint8_t *)arg;
2458 if (ioctl(fd, PPWDATA, &b) < 0)
2459 return -ENOTSUP;
2460 break;
2461 case CHR_IOCTL_PP_READ_CONTROL:
2462 if (ioctl(fd, PPRCONTROL, &b) < 0)
2463 return -ENOTSUP;
2464 /* Linux gives only the lowest bits, and no way to know data
2465 direction! For better compatibility set the fixed upper
2466 bits. */
2467 *(uint8_t *)arg = b | 0xc0;
2468 break;
2469 case CHR_IOCTL_PP_WRITE_CONTROL:
2470 b = *(uint8_t *)arg;
2471 if (ioctl(fd, PPWCONTROL, &b) < 0)
2472 return -ENOTSUP;
2473 break;
2474 case CHR_IOCTL_PP_READ_STATUS:
2475 if (ioctl(fd, PPRSTATUS, &b) < 0)
2476 return -ENOTSUP;
2477 *(uint8_t *)arg = b;
2478 break;
2479 case CHR_IOCTL_PP_EPP_READ_ADDR:
2480 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2481 struct ParallelIOArg *parg = arg;
2482 int n = read(fd, parg->buffer, parg->count);
2483 if (n != parg->count) {
2484 return -EIO;
2487 break;
2488 case CHR_IOCTL_PP_EPP_READ:
2489 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2490 struct ParallelIOArg *parg = arg;
2491 int n = read(fd, parg->buffer, parg->count);
2492 if (n != parg->count) {
2493 return -EIO;
2496 break;
2497 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2498 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2499 struct ParallelIOArg *parg = arg;
2500 int n = write(fd, parg->buffer, parg->count);
2501 if (n != parg->count) {
2502 return -EIO;
2505 break;
2506 case CHR_IOCTL_PP_EPP_WRITE:
2507 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2508 struct ParallelIOArg *parg = arg;
2509 int n = write(fd, parg->buffer, parg->count);
2510 if (n != parg->count) {
2511 return -EIO;
2514 break;
2515 default:
2516 return -ENOTSUP;
2518 return 0;
2521 static void pp_close(CharDriverState *chr)
2523 ParallelCharDriver *drv = chr->opaque;
2524 int fd = drv->fd;
2526 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2527 ioctl(fd, PPRELEASE);
2528 close(fd);
2529 qemu_free(drv);
2532 static CharDriverState *qemu_chr_open_pp(const char *filename)
2534 CharDriverState *chr;
2535 ParallelCharDriver *drv;
2536 int fd;
2538 TFR(fd = open(filename, O_RDWR));
2539 if (fd < 0)
2540 return NULL;
2542 if (ioctl(fd, PPCLAIM) < 0) {
2543 close(fd);
2544 return NULL;
2547 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2548 if (!drv) {
2549 close(fd);
2550 return NULL;
2552 drv->fd = fd;
2553 drv->mode = IEEE1284_MODE_COMPAT;
2555 chr = qemu_mallocz(sizeof(CharDriverState));
2556 if (!chr) {
2557 qemu_free(drv);
2558 close(fd);
2559 return NULL;
2561 chr->chr_write = null_chr_write;
2562 chr->chr_ioctl = pp_ioctl;
2563 chr->chr_close = pp_close;
2564 chr->opaque = drv;
2566 qemu_chr_reset(chr);
2568 return chr;
2570 #endif /* __linux__ */
2572 #else /* _WIN32 */
2574 typedef struct {
2575 int max_size;
2576 HANDLE hcom, hrecv, hsend;
2577 OVERLAPPED orecv, osend;
2578 BOOL fpipe;
2579 DWORD len;
2580 } WinCharState;
2582 #define NSENDBUF 2048
2583 #define NRECVBUF 2048
2584 #define MAXCONNECT 1
2585 #define NTIMEOUT 5000
2587 static int win_chr_poll(void *opaque);
2588 static int win_chr_pipe_poll(void *opaque);
2590 static void win_chr_close(CharDriverState *chr)
2592 WinCharState *s = chr->opaque;
2594 if (s->hsend) {
2595 CloseHandle(s->hsend);
2596 s->hsend = NULL;
2598 if (s->hrecv) {
2599 CloseHandle(s->hrecv);
2600 s->hrecv = NULL;
2602 if (s->hcom) {
2603 CloseHandle(s->hcom);
2604 s->hcom = NULL;
2606 if (s->fpipe)
2607 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2608 else
2609 qemu_del_polling_cb(win_chr_poll, chr);
2612 static int win_chr_init(CharDriverState *chr, const char *filename)
2614 WinCharState *s = chr->opaque;
2615 COMMCONFIG comcfg;
2616 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2617 COMSTAT comstat;
2618 DWORD size;
2619 DWORD err;
2621 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2622 if (!s->hsend) {
2623 fprintf(stderr, "Failed CreateEvent\n");
2624 goto fail;
2626 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2627 if (!s->hrecv) {
2628 fprintf(stderr, "Failed CreateEvent\n");
2629 goto fail;
2632 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2633 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2634 if (s->hcom == INVALID_HANDLE_VALUE) {
2635 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2636 s->hcom = NULL;
2637 goto fail;
2640 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2641 fprintf(stderr, "Failed SetupComm\n");
2642 goto fail;
2645 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2646 size = sizeof(COMMCONFIG);
2647 GetDefaultCommConfig(filename, &comcfg, &size);
2648 comcfg.dcb.DCBlength = sizeof(DCB);
2649 CommConfigDialog(filename, NULL, &comcfg);
2651 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2652 fprintf(stderr, "Failed SetCommState\n");
2653 goto fail;
2656 if (!SetCommMask(s->hcom, EV_ERR)) {
2657 fprintf(stderr, "Failed SetCommMask\n");
2658 goto fail;
2661 cto.ReadIntervalTimeout = MAXDWORD;
2662 if (!SetCommTimeouts(s->hcom, &cto)) {
2663 fprintf(stderr, "Failed SetCommTimeouts\n");
2664 goto fail;
2667 if (!ClearCommError(s->hcom, &err, &comstat)) {
2668 fprintf(stderr, "Failed ClearCommError\n");
2669 goto fail;
2671 qemu_add_polling_cb(win_chr_poll, chr);
2672 return 0;
2674 fail:
2675 win_chr_close(chr);
2676 return -1;
2679 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2681 WinCharState *s = chr->opaque;
2682 DWORD len, ret, size, err;
2684 len = len1;
2685 ZeroMemory(&s->osend, sizeof(s->osend));
2686 s->osend.hEvent = s->hsend;
2687 while (len > 0) {
2688 if (s->hsend)
2689 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2690 else
2691 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2692 if (!ret) {
2693 err = GetLastError();
2694 if (err == ERROR_IO_PENDING) {
2695 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2696 if (ret) {
2697 buf += size;
2698 len -= size;
2699 } else {
2700 break;
2702 } else {
2703 break;
2705 } else {
2706 buf += size;
2707 len -= size;
2710 return len1 - len;
2713 static int win_chr_read_poll(CharDriverState *chr)
2715 WinCharState *s = chr->opaque;
2717 s->max_size = qemu_chr_can_read(chr);
2718 return s->max_size;
2721 static void win_chr_readfile(CharDriverState *chr)
2723 WinCharState *s = chr->opaque;
2724 int ret, err;
2725 uint8_t buf[1024];
2726 DWORD size;
2728 ZeroMemory(&s->orecv, sizeof(s->orecv));
2729 s->orecv.hEvent = s->hrecv;
2730 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2731 if (!ret) {
2732 err = GetLastError();
2733 if (err == ERROR_IO_PENDING) {
2734 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2738 if (size > 0) {
2739 qemu_chr_read(chr, buf, size);
2743 static void win_chr_read(CharDriverState *chr)
2745 WinCharState *s = chr->opaque;
2747 if (s->len > s->max_size)
2748 s->len = s->max_size;
2749 if (s->len == 0)
2750 return;
2752 win_chr_readfile(chr);
2755 static int win_chr_poll(void *opaque)
2757 CharDriverState *chr = opaque;
2758 WinCharState *s = chr->opaque;
2759 COMSTAT status;
2760 DWORD comerr;
2762 ClearCommError(s->hcom, &comerr, &status);
2763 if (status.cbInQue > 0) {
2764 s->len = status.cbInQue;
2765 win_chr_read_poll(chr);
2766 win_chr_read(chr);
2767 return 1;
2769 return 0;
2772 static CharDriverState *qemu_chr_open_win(const char *filename)
2774 CharDriverState *chr;
2775 WinCharState *s;
2777 chr = qemu_mallocz(sizeof(CharDriverState));
2778 if (!chr)
2779 return NULL;
2780 s = qemu_mallocz(sizeof(WinCharState));
2781 if (!s) {
2782 free(chr);
2783 return NULL;
2785 chr->opaque = s;
2786 chr->chr_write = win_chr_write;
2787 chr->chr_close = win_chr_close;
2789 if (win_chr_init(chr, filename) < 0) {
2790 free(s);
2791 free(chr);
2792 return NULL;
2794 qemu_chr_reset(chr);
2795 return chr;
2798 static int win_chr_pipe_poll(void *opaque)
2800 CharDriverState *chr = opaque;
2801 WinCharState *s = chr->opaque;
2802 DWORD size;
2804 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2805 if (size > 0) {
2806 s->len = size;
2807 win_chr_read_poll(chr);
2808 win_chr_read(chr);
2809 return 1;
2811 return 0;
2814 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2816 WinCharState *s = chr->opaque;
2817 OVERLAPPED ov;
2818 int ret;
2819 DWORD size;
2820 char openname[256];
2822 s->fpipe = TRUE;
2824 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2825 if (!s->hsend) {
2826 fprintf(stderr, "Failed CreateEvent\n");
2827 goto fail;
2829 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2830 if (!s->hrecv) {
2831 fprintf(stderr, "Failed CreateEvent\n");
2832 goto fail;
2835 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2836 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2837 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2838 PIPE_WAIT,
2839 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2840 if (s->hcom == INVALID_HANDLE_VALUE) {
2841 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2842 s->hcom = NULL;
2843 goto fail;
2846 ZeroMemory(&ov, sizeof(ov));
2847 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2848 ret = ConnectNamedPipe(s->hcom, &ov);
2849 if (ret) {
2850 fprintf(stderr, "Failed ConnectNamedPipe\n");
2851 goto fail;
2854 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2855 if (!ret) {
2856 fprintf(stderr, "Failed GetOverlappedResult\n");
2857 if (ov.hEvent) {
2858 CloseHandle(ov.hEvent);
2859 ov.hEvent = NULL;
2861 goto fail;
2864 if (ov.hEvent) {
2865 CloseHandle(ov.hEvent);
2866 ov.hEvent = NULL;
2868 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2869 return 0;
2871 fail:
2872 win_chr_close(chr);
2873 return -1;
2877 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2879 CharDriverState *chr;
2880 WinCharState *s;
2882 chr = qemu_mallocz(sizeof(CharDriverState));
2883 if (!chr)
2884 return NULL;
2885 s = qemu_mallocz(sizeof(WinCharState));
2886 if (!s) {
2887 free(chr);
2888 return NULL;
2890 chr->opaque = s;
2891 chr->chr_write = win_chr_write;
2892 chr->chr_close = win_chr_close;
2894 if (win_chr_pipe_init(chr, filename) < 0) {
2895 free(s);
2896 free(chr);
2897 return NULL;
2899 qemu_chr_reset(chr);
2900 return chr;
2903 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2905 CharDriverState *chr;
2906 WinCharState *s;
2908 chr = qemu_mallocz(sizeof(CharDriverState));
2909 if (!chr)
2910 return NULL;
2911 s = qemu_mallocz(sizeof(WinCharState));
2912 if (!s) {
2913 free(chr);
2914 return NULL;
2916 s->hcom = fd_out;
2917 chr->opaque = s;
2918 chr->chr_write = win_chr_write;
2919 qemu_chr_reset(chr);
2920 return chr;
2923 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2925 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2928 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2930 HANDLE fd_out;
2932 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2933 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2934 if (fd_out == INVALID_HANDLE_VALUE)
2935 return NULL;
2937 return qemu_chr_open_win_file(fd_out);
2939 #endif /* !_WIN32 */
2941 /***********************************************************/
2942 /* UDP Net console */
2944 typedef struct {
2945 int fd;
2946 struct sockaddr_in daddr;
2947 uint8_t buf[1024];
2948 int bufcnt;
2949 int bufptr;
2950 int max_size;
2951 } NetCharDriver;
2953 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2955 NetCharDriver *s = chr->opaque;
2957 return sendto(s->fd, buf, len, 0,
2958 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2961 static int udp_chr_read_poll(void *opaque)
2963 CharDriverState *chr = opaque;
2964 NetCharDriver *s = chr->opaque;
2966 s->max_size = qemu_chr_can_read(chr);
2968 /* If there were any stray characters in the queue process them
2969 * first
2971 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2972 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2973 s->bufptr++;
2974 s->max_size = qemu_chr_can_read(chr);
2976 return s->max_size;
2979 static void udp_chr_read(void *opaque)
2981 CharDriverState *chr = opaque;
2982 NetCharDriver *s = chr->opaque;
2984 if (s->max_size == 0)
2985 return;
2986 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2987 s->bufptr = s->bufcnt;
2988 if (s->bufcnt <= 0)
2989 return;
2991 s->bufptr = 0;
2992 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2993 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2994 s->bufptr++;
2995 s->max_size = qemu_chr_can_read(chr);
2999 static void udp_chr_update_read_handler(CharDriverState *chr)
3001 NetCharDriver *s = chr->opaque;
3003 if (s->fd >= 0) {
3004 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3005 udp_chr_read, NULL, chr);
3009 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3010 #ifndef _WIN32
3011 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3012 #endif
3013 int parse_host_src_port(struct sockaddr_in *haddr,
3014 struct sockaddr_in *saddr,
3015 const char *str);
3017 static CharDriverState *qemu_chr_open_udp(const char *def)
3019 CharDriverState *chr = NULL;
3020 NetCharDriver *s = NULL;
3021 int fd = -1;
3022 struct sockaddr_in saddr;
3024 chr = qemu_mallocz(sizeof(CharDriverState));
3025 if (!chr)
3026 goto return_err;
3027 s = qemu_mallocz(sizeof(NetCharDriver));
3028 if (!s)
3029 goto return_err;
3031 fd = socket(PF_INET, SOCK_DGRAM, 0);
3032 if (fd < 0) {
3033 perror("socket(PF_INET, SOCK_DGRAM)");
3034 goto return_err;
3037 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3038 printf("Could not parse: %s\n", def);
3039 goto return_err;
3042 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3044 perror("bind");
3045 goto return_err;
3048 s->fd = fd;
3049 s->bufcnt = 0;
3050 s->bufptr = 0;
3051 chr->opaque = s;
3052 chr->chr_write = udp_chr_write;
3053 chr->chr_update_read_handler = udp_chr_update_read_handler;
3054 return chr;
3056 return_err:
3057 if (chr)
3058 free(chr);
3059 if (s)
3060 free(s);
3061 if (fd >= 0)
3062 closesocket(fd);
3063 return NULL;
3066 /***********************************************************/
3067 /* TCP Net console */
3069 typedef struct {
3070 int fd, listen_fd;
3071 int connected;
3072 int max_size;
3073 int do_telnetopt;
3074 int do_nodelay;
3075 int is_unix;
3076 } TCPCharDriver;
3078 static void tcp_chr_accept(void *opaque);
3080 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3082 TCPCharDriver *s = chr->opaque;
3083 if (s->connected) {
3084 return send_all(s->fd, buf, len);
3085 } else {
3086 /* XXX: indicate an error ? */
3087 return len;
3091 static int tcp_chr_read_poll(void *opaque)
3093 CharDriverState *chr = opaque;
3094 TCPCharDriver *s = chr->opaque;
3095 if (!s->connected)
3096 return 0;
3097 s->max_size = qemu_chr_can_read(chr);
3098 return s->max_size;
3101 #define IAC 255
3102 #define IAC_BREAK 243
3103 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3104 TCPCharDriver *s,
3105 uint8_t *buf, int *size)
3107 /* Handle any telnet client's basic IAC options to satisfy char by
3108 * char mode with no echo. All IAC options will be removed from
3109 * the buf and the do_telnetopt variable will be used to track the
3110 * state of the width of the IAC information.
3112 * IAC commands come in sets of 3 bytes with the exception of the
3113 * "IAC BREAK" command and the double IAC.
3116 int i;
3117 int j = 0;
3119 for (i = 0; i < *size; i++) {
3120 if (s->do_telnetopt > 1) {
3121 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3122 /* Double IAC means send an IAC */
3123 if (j != i)
3124 buf[j] = buf[i];
3125 j++;
3126 s->do_telnetopt = 1;
3127 } else {
3128 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3129 /* Handle IAC break commands by sending a serial break */
3130 qemu_chr_event(chr, CHR_EVENT_BREAK);
3131 s->do_telnetopt++;
3133 s->do_telnetopt++;
3135 if (s->do_telnetopt >= 4) {
3136 s->do_telnetopt = 1;
3138 } else {
3139 if ((unsigned char)buf[i] == IAC) {
3140 s->do_telnetopt = 2;
3141 } else {
3142 if (j != i)
3143 buf[j] = buf[i];
3144 j++;
3148 *size = j;
3151 static void tcp_chr_read(void *opaque)
3153 CharDriverState *chr = opaque;
3154 TCPCharDriver *s = chr->opaque;
3155 uint8_t buf[1024];
3156 int len, size;
3158 if (!s->connected || s->max_size <= 0)
3159 return;
3160 len = sizeof(buf);
3161 if (len > s->max_size)
3162 len = s->max_size;
3163 size = recv(s->fd, buf, len, 0);
3164 if (size == 0) {
3165 /* connection closed */
3166 s->connected = 0;
3167 if (s->listen_fd >= 0) {
3168 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3170 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3171 closesocket(s->fd);
3172 s->fd = -1;
3173 } else if (size > 0) {
3174 if (s->do_telnetopt)
3175 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3176 if (size > 0)
3177 qemu_chr_read(chr, buf, size);
3181 static void tcp_chr_connect(void *opaque)
3183 CharDriverState *chr = opaque;
3184 TCPCharDriver *s = chr->opaque;
3186 s->connected = 1;
3187 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3188 tcp_chr_read, NULL, chr);
3189 qemu_chr_reset(chr);
3192 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3193 static void tcp_chr_telnet_init(int fd)
3195 char buf[3];
3196 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3197 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3198 send(fd, (char *)buf, 3, 0);
3199 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3200 send(fd, (char *)buf, 3, 0);
3201 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3202 send(fd, (char *)buf, 3, 0);
3203 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3204 send(fd, (char *)buf, 3, 0);
3207 static void socket_set_nodelay(int fd)
3209 int val = 1;
3210 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3213 static void tcp_chr_accept(void *opaque)
3215 CharDriverState *chr = opaque;
3216 TCPCharDriver *s = chr->opaque;
3217 struct sockaddr_in saddr;
3218 #ifndef _WIN32
3219 struct sockaddr_un uaddr;
3220 #endif
3221 struct sockaddr *addr;
3222 socklen_t len;
3223 int fd;
3225 for(;;) {
3226 #ifndef _WIN32
3227 if (s->is_unix) {
3228 len = sizeof(uaddr);
3229 addr = (struct sockaddr *)&uaddr;
3230 } else
3231 #endif
3233 len = sizeof(saddr);
3234 addr = (struct sockaddr *)&saddr;
3236 fd = accept(s->listen_fd, addr, &len);
3237 if (fd < 0 && errno != EINTR) {
3238 return;
3239 } else if (fd >= 0) {
3240 if (s->do_telnetopt)
3241 tcp_chr_telnet_init(fd);
3242 break;
3245 socket_set_nonblock(fd);
3246 if (s->do_nodelay)
3247 socket_set_nodelay(fd);
3248 s->fd = fd;
3249 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3250 tcp_chr_connect(chr);
3253 static void tcp_chr_close(CharDriverState *chr)
3255 TCPCharDriver *s = chr->opaque;
3256 if (s->fd >= 0)
3257 closesocket(s->fd);
3258 if (s->listen_fd >= 0)
3259 closesocket(s->listen_fd);
3260 qemu_free(s);
3263 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3264 int is_telnet,
3265 int is_unix)
3267 CharDriverState *chr = NULL;
3268 TCPCharDriver *s = NULL;
3269 int fd = -1, ret, err, val;
3270 int is_listen = 0;
3271 int is_waitconnect = 1;
3272 int do_nodelay = 0;
3273 const char *ptr;
3274 struct sockaddr_in saddr;
3275 #ifndef _WIN32
3276 struct sockaddr_un uaddr;
3277 #endif
3278 struct sockaddr *addr;
3279 socklen_t addrlen;
3281 #ifndef _WIN32
3282 if (is_unix) {
3283 addr = (struct sockaddr *)&uaddr;
3284 addrlen = sizeof(uaddr);
3285 if (parse_unix_path(&uaddr, host_str) < 0)
3286 goto fail;
3287 } else
3288 #endif
3290 addr = (struct sockaddr *)&saddr;
3291 addrlen = sizeof(saddr);
3292 if (parse_host_port(&saddr, host_str) < 0)
3293 goto fail;
3296 ptr = host_str;
3297 while((ptr = strchr(ptr,','))) {
3298 ptr++;
3299 if (!strncmp(ptr,"server",6)) {
3300 is_listen = 1;
3301 } else if (!strncmp(ptr,"nowait",6)) {
3302 is_waitconnect = 0;
3303 } else if (!strncmp(ptr,"nodelay",6)) {
3304 do_nodelay = 1;
3305 } else {
3306 printf("Unknown option: %s\n", ptr);
3307 goto fail;
3310 if (!is_listen)
3311 is_waitconnect = 0;
3313 chr = qemu_mallocz(sizeof(CharDriverState));
3314 if (!chr)
3315 goto fail;
3316 s = qemu_mallocz(sizeof(TCPCharDriver));
3317 if (!s)
3318 goto fail;
3320 #ifndef _WIN32
3321 if (is_unix)
3322 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3323 else
3324 #endif
3325 fd = socket(PF_INET, SOCK_STREAM, 0);
3327 if (fd < 0)
3328 goto fail;
3330 if (!is_waitconnect)
3331 socket_set_nonblock(fd);
3333 s->connected = 0;
3334 s->fd = -1;
3335 s->listen_fd = -1;
3336 s->is_unix = is_unix;
3337 s->do_nodelay = do_nodelay && !is_unix;
3339 chr->opaque = s;
3340 chr->chr_write = tcp_chr_write;
3341 chr->chr_close = tcp_chr_close;
3343 if (is_listen) {
3344 /* allow fast reuse */
3345 #ifndef _WIN32
3346 if (is_unix) {
3347 char path[109];
3348 strncpy(path, uaddr.sun_path, 108);
3349 path[108] = 0;
3350 unlink(path);
3351 } else
3352 #endif
3354 val = 1;
3355 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3358 ret = bind(fd, addr, addrlen);
3359 if (ret < 0)
3360 goto fail;
3362 ret = listen(fd, 0);
3363 if (ret < 0)
3364 goto fail;
3366 s->listen_fd = fd;
3367 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3368 if (is_telnet)
3369 s->do_telnetopt = 1;
3370 } else {
3371 for(;;) {
3372 ret = connect(fd, addr, addrlen);
3373 if (ret < 0) {
3374 err = socket_error();
3375 if (err == EINTR || err == EWOULDBLOCK) {
3376 } else if (err == EINPROGRESS) {
3377 break;
3378 #ifdef _WIN32
3379 } else if (err == WSAEALREADY) {
3380 break;
3381 #endif
3382 } else {
3383 goto fail;
3385 } else {
3386 s->connected = 1;
3387 break;
3390 s->fd = fd;
3391 socket_set_nodelay(fd);
3392 if (s->connected)
3393 tcp_chr_connect(chr);
3394 else
3395 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3398 if (is_listen && is_waitconnect) {
3399 printf("QEMU waiting for connection on: %s\n", host_str);
3400 tcp_chr_accept(chr);
3401 socket_set_nonblock(s->listen_fd);
3404 return chr;
3405 fail:
3406 if (fd >= 0)
3407 closesocket(fd);
3408 qemu_free(s);
3409 qemu_free(chr);
3410 return NULL;
3413 CharDriverState *qemu_chr_open(const char *filename)
3415 const char *p;
3417 if (!strcmp(filename, "vc")) {
3418 return text_console_init(&display_state, 0);
3419 } else if (strstart(filename, "vc:", &p)) {
3420 return text_console_init(&display_state, p);
3421 } else if (!strcmp(filename, "null")) {
3422 return qemu_chr_open_null();
3423 } else
3424 if (strstart(filename, "tcp:", &p)) {
3425 return qemu_chr_open_tcp(p, 0, 0);
3426 } else
3427 if (strstart(filename, "telnet:", &p)) {
3428 return qemu_chr_open_tcp(p, 1, 0);
3429 } else
3430 if (strstart(filename, "udp:", &p)) {
3431 return qemu_chr_open_udp(p);
3432 } else
3433 if (strstart(filename, "mon:", &p)) {
3434 CharDriverState *drv = qemu_chr_open(p);
3435 if (drv) {
3436 drv = qemu_chr_open_mux(drv);
3437 monitor_init(drv, !nographic);
3438 return drv;
3440 printf("Unable to open driver: %s\n", p);
3441 return 0;
3442 } else
3443 #ifndef _WIN32
3444 if (strstart(filename, "unix:", &p)) {
3445 return qemu_chr_open_tcp(p, 0, 1);
3446 } else if (strstart(filename, "file:", &p)) {
3447 return qemu_chr_open_file_out(p);
3448 } else if (strstart(filename, "pipe:", &p)) {
3449 return qemu_chr_open_pipe(p);
3450 } else if (!strcmp(filename, "pty")) {
3451 return qemu_chr_open_pty();
3452 } else if (!strcmp(filename, "stdio")) {
3453 return qemu_chr_open_stdio();
3454 } else
3455 #if defined(__linux__)
3456 if (strstart(filename, "/dev/parport", NULL)) {
3457 return qemu_chr_open_pp(filename);
3458 } else
3459 #endif
3460 #if defined(__linux__) || defined(__sun__)
3461 if (strstart(filename, "/dev/", NULL)) {
3462 return qemu_chr_open_tty(filename);
3463 } else
3464 #endif
3465 #else /* !_WIN32 */
3466 if (strstart(filename, "COM", NULL)) {
3467 return qemu_chr_open_win(filename);
3468 } else
3469 if (strstart(filename, "pipe:", &p)) {
3470 return qemu_chr_open_win_pipe(p);
3471 } else
3472 if (strstart(filename, "con:", NULL)) {
3473 return qemu_chr_open_win_con(filename);
3474 } else
3475 if (strstart(filename, "file:", &p)) {
3476 return qemu_chr_open_win_file_out(p);
3478 #endif
3480 return NULL;
3484 void qemu_chr_close(CharDriverState *chr)
3486 if (chr->chr_close)
3487 chr->chr_close(chr);
3488 qemu_free(chr);
3491 /***********************************************************/
3492 /* network device redirectors */
3494 __attribute__ (( unused ))
3495 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3497 int len, i, j, c;
3499 for(i=0;i<size;i+=16) {
3500 len = size - i;
3501 if (len > 16)
3502 len = 16;
3503 fprintf(f, "%08x ", i);
3504 for(j=0;j<16;j++) {
3505 if (j < len)
3506 fprintf(f, " %02x", buf[i+j]);
3507 else
3508 fprintf(f, " ");
3510 fprintf(f, " ");
3511 for(j=0;j<len;j++) {
3512 c = buf[i+j];
3513 if (c < ' ' || c > '~')
3514 c = '.';
3515 fprintf(f, "%c", c);
3517 fprintf(f, "\n");
3521 static int parse_macaddr(uint8_t *macaddr, const char *p)
3523 int i;
3524 char *last_char;
3525 long int offset;
3527 errno = 0;
3528 offset = strtol(p, &last_char, 0);
3529 if (0 == errno && '\0' == *last_char &&
3530 offset >= 0 && offset <= 0xFFFFFF) {
3531 macaddr[3] = (offset & 0xFF0000) >> 16;
3532 macaddr[4] = (offset & 0xFF00) >> 8;
3533 macaddr[5] = offset & 0xFF;
3534 return 0;
3535 } else {
3536 for(i = 0; i < 6; i++) {
3537 macaddr[i] = strtol(p, (char **)&p, 16);
3538 if (i == 5) {
3539 if (*p != '\0')
3540 return -1;
3541 } else {
3542 if (*p != ':' && *p != '-')
3543 return -1;
3544 p++;
3547 return 0;
3550 return -1;
3553 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3555 const char *p, *p1;
3556 int len;
3557 p = *pp;
3558 p1 = strchr(p, sep);
3559 if (!p1)
3560 return -1;
3561 len = p1 - p;
3562 p1++;
3563 if (buf_size > 0) {
3564 if (len > buf_size - 1)
3565 len = buf_size - 1;
3566 memcpy(buf, p, len);
3567 buf[len] = '\0';
3569 *pp = p1;
3570 return 0;
3573 int parse_host_src_port(struct sockaddr_in *haddr,
3574 struct sockaddr_in *saddr,
3575 const char *input_str)
3577 char *str = strdup(input_str);
3578 char *host_str = str;
3579 char *src_str;
3580 char *ptr;
3583 * Chop off any extra arguments at the end of the string which
3584 * would start with a comma, then fill in the src port information
3585 * if it was provided else use the "any address" and "any port".
3587 if ((ptr = strchr(str,',')))
3588 *ptr = '\0';
3590 if ((src_str = strchr(input_str,'@'))) {
3591 *src_str = '\0';
3592 src_str++;
3595 if (parse_host_port(haddr, host_str) < 0)
3596 goto fail;
3598 if (!src_str || *src_str == '\0')
3599 src_str = ":0";
3601 if (parse_host_port(saddr, src_str) < 0)
3602 goto fail;
3604 free(str);
3605 return(0);
3607 fail:
3608 free(str);
3609 return -1;
3612 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3614 char buf[512];
3615 struct hostent *he;
3616 const char *p, *r;
3617 int port;
3619 p = str;
3620 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3621 return -1;
3622 saddr->sin_family = AF_INET;
3623 if (buf[0] == '\0') {
3624 saddr->sin_addr.s_addr = 0;
3625 } else {
3626 if (isdigit(buf[0])) {
3627 if (!inet_aton(buf, &saddr->sin_addr))
3628 return -1;
3629 } else {
3630 if ((he = gethostbyname(buf)) == NULL)
3631 return - 1;
3632 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3635 port = strtol(p, (char **)&r, 0);
3636 if (r == p)
3637 return -1;
3638 saddr->sin_port = htons(port);
3639 return 0;
3642 #ifndef _WIN32
3643 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3645 const char *p;
3646 int len;
3648 len = MIN(108, strlen(str));
3649 p = strchr(str, ',');
3650 if (p)
3651 len = MIN(len, p - str);
3653 memset(uaddr, 0, sizeof(*uaddr));
3655 uaddr->sun_family = AF_UNIX;
3656 memcpy(uaddr->sun_path, str, len);
3658 return 0;
3660 #endif
3662 /* find or alloc a new VLAN */
3663 VLANState *qemu_find_vlan(int id)
3665 VLANState **pvlan, *vlan;
3666 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3667 if (vlan->id == id)
3668 return vlan;
3670 vlan = qemu_mallocz(sizeof(VLANState));
3671 if (!vlan)
3672 return NULL;
3673 vlan->id = id;
3674 vlan->next = NULL;
3675 pvlan = &first_vlan;
3676 while (*pvlan != NULL)
3677 pvlan = &(*pvlan)->next;
3678 *pvlan = vlan;
3679 return vlan;
3682 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3683 IOReadHandler *fd_read,
3684 IOCanRWHandler *fd_can_read,
3685 void *opaque)
3687 VLANClientState *vc, **pvc;
3688 vc = qemu_mallocz(sizeof(VLANClientState));
3689 if (!vc)
3690 return NULL;
3691 vc->fd_read = fd_read;
3692 vc->fd_can_read = fd_can_read;
3693 vc->opaque = opaque;
3694 vc->vlan = vlan;
3696 vc->next = NULL;
3697 pvc = &vlan->first_client;
3698 while (*pvc != NULL)
3699 pvc = &(*pvc)->next;
3700 *pvc = vc;
3701 return vc;
3704 int qemu_can_send_packet(VLANClientState *vc1)
3706 VLANState *vlan = vc1->vlan;
3707 VLANClientState *vc;
3709 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3710 if (vc != vc1) {
3711 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3712 return 1;
3715 return 0;
3718 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3720 VLANState *vlan = vc1->vlan;
3721 VLANClientState *vc;
3723 #if 0
3724 printf("vlan %d send:\n", vlan->id);
3725 hex_dump(stdout, buf, size);
3726 #endif
3727 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3728 if (vc != vc1) {
3729 vc->fd_read(vc->opaque, buf, size);
3734 #if defined(CONFIG_SLIRP)
3736 /* slirp network adapter */
3738 static int slirp_inited;
3739 static VLANClientState *slirp_vc;
3741 int slirp_can_output(void)
3743 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3746 void slirp_output(const uint8_t *pkt, int pkt_len)
3748 #if 0
3749 printf("slirp output:\n");
3750 hex_dump(stdout, pkt, pkt_len);
3751 #endif
3752 if (!slirp_vc)
3753 return;
3754 qemu_send_packet(slirp_vc, pkt, pkt_len);
3757 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3759 #if 0
3760 printf("slirp input:\n");
3761 hex_dump(stdout, buf, size);
3762 #endif
3763 slirp_input(buf, size);
3766 static int net_slirp_init(VLANState *vlan)
3768 if (!slirp_inited) {
3769 slirp_inited = 1;
3770 slirp_init();
3772 slirp_vc = qemu_new_vlan_client(vlan,
3773 slirp_receive, NULL, NULL);
3774 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3775 return 0;
3778 static void net_slirp_redir(const char *redir_str)
3780 int is_udp;
3781 char buf[256], *r;
3782 const char *p;
3783 struct in_addr guest_addr;
3784 int host_port, guest_port;
3786 if (!slirp_inited) {
3787 slirp_inited = 1;
3788 slirp_init();
3791 p = redir_str;
3792 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3793 goto fail;
3794 if (!strcmp(buf, "tcp")) {
3795 is_udp = 0;
3796 } else if (!strcmp(buf, "udp")) {
3797 is_udp = 1;
3798 } else {
3799 goto fail;
3802 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3803 goto fail;
3804 host_port = strtol(buf, &r, 0);
3805 if (r == buf)
3806 goto fail;
3808 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3809 goto fail;
3810 if (buf[0] == '\0') {
3811 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3813 if (!inet_aton(buf, &guest_addr))
3814 goto fail;
3816 guest_port = strtol(p, &r, 0);
3817 if (r == p)
3818 goto fail;
3820 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3821 fprintf(stderr, "qemu: could not set up redirection\n");
3822 exit(1);
3824 return;
3825 fail:
3826 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3827 exit(1);
3830 #ifndef _WIN32
3832 char smb_dir[1024];
3834 static void erase_dir(char *dir_name)
3836 DIR *d;
3837 struct dirent *de;
3838 char filename[1024];
3840 /* erase all the files in the directory */
3841 if ((d = opendir(dir_name)) != 0) {
3842 for(;;) {
3843 de = readdir(d);
3844 if (!de)
3845 break;
3846 if (strcmp(de->d_name, ".") != 0 &&
3847 strcmp(de->d_name, "..") != 0) {
3848 snprintf(filename, sizeof(filename), "%s/%s",
3849 smb_dir, de->d_name);
3850 if (unlink(filename) != 0) /* is it a directory? */
3851 erase_dir(filename);
3854 closedir(d);
3855 rmdir(dir_name);
3859 /* automatic user mode samba server configuration */
3860 static void smb_exit(void)
3862 erase_dir(smb_dir);
3865 /* automatic user mode samba server configuration */
3866 static void net_slirp_smb(const char *exported_dir)
3868 char smb_conf[1024];
3869 char smb_cmdline[1024];
3870 FILE *f;
3872 if (!slirp_inited) {
3873 slirp_inited = 1;
3874 slirp_init();
3877 /* XXX: better tmp dir construction */
3878 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3879 if (mkdir(smb_dir, 0700) < 0) {
3880 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3881 exit(1);
3883 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3885 f = fopen(smb_conf, "w");
3886 if (!f) {
3887 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3888 exit(1);
3890 fprintf(f,
3891 "[global]\n"
3892 "private dir=%s\n"
3893 "smb ports=0\n"
3894 "socket address=127.0.0.1\n"
3895 "pid directory=%s\n"
3896 "lock directory=%s\n"
3897 "log file=%s/log.smbd\n"
3898 "smb passwd file=%s/smbpasswd\n"
3899 "security = share\n"
3900 "[qemu]\n"
3901 "path=%s\n"
3902 "read only=no\n"
3903 "guest ok=yes\n",
3904 smb_dir,
3905 smb_dir,
3906 smb_dir,
3907 smb_dir,
3908 smb_dir,
3909 exported_dir
3911 fclose(f);
3912 atexit(smb_exit);
3914 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3915 SMBD_COMMAND, smb_conf);
3917 slirp_add_exec(0, smb_cmdline, 4, 139);
3920 #endif /* !defined(_WIN32) */
3921 void do_info_slirp(void)
3923 slirp_stats();
3926 #endif /* CONFIG_SLIRP */
3928 #if !defined(_WIN32)
3930 typedef struct TAPState {
3931 VLANClientState *vc;
3932 int fd;
3933 char down_script[1024];
3934 } TAPState;
3936 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3938 TAPState *s = opaque;
3939 int ret;
3940 for(;;) {
3941 ret = write(s->fd, buf, size);
3942 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3943 } else {
3944 break;
3949 static void tap_send(void *opaque)
3951 TAPState *s = opaque;
3952 uint8_t buf[4096];
3953 int size;
3955 #ifdef __sun__
3956 struct strbuf sbuf;
3957 int f = 0;
3958 sbuf.maxlen = sizeof(buf);
3959 sbuf.buf = buf;
3960 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3961 #else
3962 size = read(s->fd, buf, sizeof(buf));
3963 #endif
3964 if (size > 0) {
3965 qemu_send_packet(s->vc, buf, size);
3969 /* fd support */
3971 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3973 TAPState *s;
3975 s = qemu_mallocz(sizeof(TAPState));
3976 if (!s)
3977 return NULL;
3978 s->fd = fd;
3979 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3980 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3981 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3982 return s;
3985 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3986 static int tap_open(char *ifname, int ifname_size)
3988 int fd;
3989 char *dev;
3990 struct stat s;
3992 TFR(fd = open("/dev/tap", O_RDWR));
3993 if (fd < 0) {
3994 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3995 return -1;
3998 fstat(fd, &s);
3999 dev = devname(s.st_rdev, S_IFCHR);
4000 pstrcpy(ifname, ifname_size, dev);
4002 fcntl(fd, F_SETFL, O_NONBLOCK);
4003 return fd;
4005 #elif defined(__sun__)
4006 #define TUNNEWPPA (('T'<<16) | 0x0001)
4008 * Allocate TAP device, returns opened fd.
4009 * Stores dev name in the first arg(must be large enough).
4011 int tap_alloc(char *dev)
4013 int tap_fd, if_fd, ppa = -1;
4014 static int ip_fd = 0;
4015 char *ptr;
4017 static int arp_fd = 0;
4018 int ip_muxid, arp_muxid;
4019 struct strioctl strioc_if, strioc_ppa;
4020 int link_type = I_PLINK;;
4021 struct lifreq ifr;
4022 char actual_name[32] = "";
4024 memset(&ifr, 0x0, sizeof(ifr));
4026 if( *dev ){
4027 ptr = dev;
4028 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4029 ppa = atoi(ptr);
4032 /* Check if IP device was opened */
4033 if( ip_fd )
4034 close(ip_fd);
4036 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4037 if (ip_fd < 0) {
4038 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4039 return -1;
4042 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4043 if (tap_fd < 0) {
4044 syslog(LOG_ERR, "Can't open /dev/tap");
4045 return -1;
4048 /* Assign a new PPA and get its unit number. */
4049 strioc_ppa.ic_cmd = TUNNEWPPA;
4050 strioc_ppa.ic_timout = 0;
4051 strioc_ppa.ic_len = sizeof(ppa);
4052 strioc_ppa.ic_dp = (char *)&ppa;
4053 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4054 syslog (LOG_ERR, "Can't assign new interface");
4056 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4057 if (if_fd < 0) {
4058 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4059 return -1;
4061 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4062 syslog(LOG_ERR, "Can't push IP module");
4063 return -1;
4066 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4067 syslog(LOG_ERR, "Can't get flags\n");
4069 snprintf (actual_name, 32, "tap%d", ppa);
4070 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4072 ifr.lifr_ppa = ppa;
4073 /* Assign ppa according to the unit number returned by tun device */
4075 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4076 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4077 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4078 syslog (LOG_ERR, "Can't get flags\n");
4079 /* Push arp module to if_fd */
4080 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4081 syslog (LOG_ERR, "Can't push ARP module (2)");
4083 /* Push arp module to ip_fd */
4084 if (ioctl (ip_fd, I_POP, NULL) < 0)
4085 syslog (LOG_ERR, "I_POP failed\n");
4086 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4087 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4088 /* Open arp_fd */
4089 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4090 if (arp_fd < 0)
4091 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4093 /* Set ifname to arp */
4094 strioc_if.ic_cmd = SIOCSLIFNAME;
4095 strioc_if.ic_timout = 0;
4096 strioc_if.ic_len = sizeof(ifr);
4097 strioc_if.ic_dp = (char *)&ifr;
4098 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4099 syslog (LOG_ERR, "Can't set ifname to arp\n");
4102 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4103 syslog(LOG_ERR, "Can't link TAP device to IP");
4104 return -1;
4107 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4108 syslog (LOG_ERR, "Can't link TAP device to ARP");
4110 close (if_fd);
4112 memset(&ifr, 0x0, sizeof(ifr));
4113 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4114 ifr.lifr_ip_muxid = ip_muxid;
4115 ifr.lifr_arp_muxid = arp_muxid;
4117 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4119 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4120 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4121 syslog (LOG_ERR, "Can't set multiplexor id");
4124 sprintf(dev, "tap%d", ppa);
4125 return tap_fd;
4128 static int tap_open(char *ifname, int ifname_size)
4130 char dev[10]="";
4131 int fd;
4132 if( (fd = tap_alloc(dev)) < 0 ){
4133 fprintf(stderr, "Cannot allocate TAP device\n");
4134 return -1;
4136 pstrcpy(ifname, ifname_size, dev);
4137 fcntl(fd, F_SETFL, O_NONBLOCK);
4138 return fd;
4140 #else
4141 static int tap_open(char *ifname, int ifname_size)
4143 struct ifreq ifr;
4144 int fd, ret;
4146 TFR(fd = open("/dev/net/tun", O_RDWR));
4147 if (fd < 0) {
4148 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4149 return -1;
4151 memset(&ifr, 0, sizeof(ifr));
4152 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4153 if (ifname[0] != '\0')
4154 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4155 else
4156 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4157 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4158 if (ret != 0) {
4159 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4160 close(fd);
4161 return -1;
4163 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4164 fcntl(fd, F_SETFL, O_NONBLOCK);
4165 return fd;
4167 #endif
4169 static int launch_script(const char *setup_script, const char *ifname, int fd)
4171 int pid, status;
4172 char *args[3];
4173 char **parg;
4175 /* try to launch network script */
4176 pid = fork();
4177 if (pid >= 0) {
4178 if (pid == 0) {
4179 int open_max = sysconf (_SC_OPEN_MAX), i;
4180 for (i = 0; i < open_max; i++)
4181 if (i != STDIN_FILENO &&
4182 i != STDOUT_FILENO &&
4183 i != STDERR_FILENO &&
4184 i != fd)
4185 close(i);
4187 parg = args;
4188 *parg++ = (char *)setup_script;
4189 *parg++ = (char *)ifname;
4190 *parg++ = NULL;
4191 execv(setup_script, args);
4192 _exit(1);
4194 while (waitpid(pid, &status, 0) != pid);
4195 if (!WIFEXITED(status) ||
4196 WEXITSTATUS(status) != 0) {
4197 fprintf(stderr, "%s: could not launch network script\n",
4198 setup_script);
4199 return -1;
4202 return 0;
4205 static int net_tap_init(VLANState *vlan, const char *ifname1,
4206 const char *setup_script, const char *down_script)
4208 TAPState *s;
4209 int fd;
4210 char ifname[128];
4212 if (ifname1 != NULL)
4213 pstrcpy(ifname, sizeof(ifname), ifname1);
4214 else
4215 ifname[0] = '\0';
4216 TFR(fd = tap_open(ifname, sizeof(ifname)));
4217 if (fd < 0)
4218 return -1;
4220 if (!setup_script || !strcmp(setup_script, "no"))
4221 setup_script = "";
4222 if (setup_script[0] != '\0') {
4223 if (launch_script(setup_script, ifname, fd))
4224 return -1;
4226 s = net_tap_fd_init(vlan, fd);
4227 if (!s)
4228 return -1;
4229 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4230 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4231 if (down_script && strcmp(down_script, "no"))
4232 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4233 return 0;
4236 #endif /* !_WIN32 */
4238 /* network connection */
4239 typedef struct NetSocketState {
4240 VLANClientState *vc;
4241 int fd;
4242 int state; /* 0 = getting length, 1 = getting data */
4243 int index;
4244 int packet_len;
4245 uint8_t buf[4096];
4246 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4247 } NetSocketState;
4249 typedef struct NetSocketListenState {
4250 VLANState *vlan;
4251 int fd;
4252 } NetSocketListenState;
4254 /* XXX: we consider we can send the whole packet without blocking */
4255 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4257 NetSocketState *s = opaque;
4258 uint32_t len;
4259 len = htonl(size);
4261 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4262 send_all(s->fd, buf, size);
4265 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4267 NetSocketState *s = opaque;
4268 sendto(s->fd, buf, size, 0,
4269 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4272 static void net_socket_send(void *opaque)
4274 NetSocketState *s = opaque;
4275 int l, size, err;
4276 uint8_t buf1[4096];
4277 const uint8_t *buf;
4279 size = recv(s->fd, buf1, sizeof(buf1), 0);
4280 if (size < 0) {
4281 err = socket_error();
4282 if (err != EWOULDBLOCK)
4283 goto eoc;
4284 } else if (size == 0) {
4285 /* end of connection */
4286 eoc:
4287 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4288 closesocket(s->fd);
4289 return;
4291 buf = buf1;
4292 while (size > 0) {
4293 /* reassemble a packet from the network */
4294 switch(s->state) {
4295 case 0:
4296 l = 4 - s->index;
4297 if (l > size)
4298 l = size;
4299 memcpy(s->buf + s->index, buf, l);
4300 buf += l;
4301 size -= l;
4302 s->index += l;
4303 if (s->index == 4) {
4304 /* got length */
4305 s->packet_len = ntohl(*(uint32_t *)s->buf);
4306 s->index = 0;
4307 s->state = 1;
4309 break;
4310 case 1:
4311 l = s->packet_len - s->index;
4312 if (l > size)
4313 l = size;
4314 memcpy(s->buf + s->index, buf, l);
4315 s->index += l;
4316 buf += l;
4317 size -= l;
4318 if (s->index >= s->packet_len) {
4319 qemu_send_packet(s->vc, s->buf, s->packet_len);
4320 s->index = 0;
4321 s->state = 0;
4323 break;
4328 static void net_socket_send_dgram(void *opaque)
4330 NetSocketState *s = opaque;
4331 int size;
4333 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4334 if (size < 0)
4335 return;
4336 if (size == 0) {
4337 /* end of connection */
4338 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4339 return;
4341 qemu_send_packet(s->vc, s->buf, size);
4344 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4346 struct ip_mreq imr;
4347 int fd;
4348 int val, ret;
4349 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4350 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4351 inet_ntoa(mcastaddr->sin_addr),
4352 (int)ntohl(mcastaddr->sin_addr.s_addr));
4353 return -1;
4356 fd = socket(PF_INET, SOCK_DGRAM, 0);
4357 if (fd < 0) {
4358 perror("socket(PF_INET, SOCK_DGRAM)");
4359 return -1;
4362 val = 1;
4363 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4364 (const char *)&val, sizeof(val));
4365 if (ret < 0) {
4366 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4367 goto fail;
4370 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4371 if (ret < 0) {
4372 perror("bind");
4373 goto fail;
4376 /* Add host to multicast group */
4377 imr.imr_multiaddr = mcastaddr->sin_addr;
4378 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4380 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4381 (const char *)&imr, sizeof(struct ip_mreq));
4382 if (ret < 0) {
4383 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4384 goto fail;
4387 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4388 val = 1;
4389 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4390 (const char *)&val, sizeof(val));
4391 if (ret < 0) {
4392 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4393 goto fail;
4396 socket_set_nonblock(fd);
4397 return fd;
4398 fail:
4399 if (fd >= 0)
4400 closesocket(fd);
4401 return -1;
4404 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4405 int is_connected)
4407 struct sockaddr_in saddr;
4408 int newfd;
4409 socklen_t saddr_len;
4410 NetSocketState *s;
4412 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4413 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4414 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4417 if (is_connected) {
4418 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4419 /* must be bound */
4420 if (saddr.sin_addr.s_addr==0) {
4421 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4422 fd);
4423 return NULL;
4425 /* clone dgram socket */
4426 newfd = net_socket_mcast_create(&saddr);
4427 if (newfd < 0) {
4428 /* error already reported by net_socket_mcast_create() */
4429 close(fd);
4430 return NULL;
4432 /* clone newfd to fd, close newfd */
4433 dup2(newfd, fd);
4434 close(newfd);
4436 } else {
4437 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4438 fd, strerror(errno));
4439 return NULL;
4443 s = qemu_mallocz(sizeof(NetSocketState));
4444 if (!s)
4445 return NULL;
4446 s->fd = fd;
4448 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4449 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4451 /* mcast: save bound address as dst */
4452 if (is_connected) s->dgram_dst=saddr;
4454 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4455 "socket: fd=%d (%s mcast=%s:%d)",
4456 fd, is_connected? "cloned" : "",
4457 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4458 return s;
4461 static void net_socket_connect(void *opaque)
4463 NetSocketState *s = opaque;
4464 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4467 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4468 int is_connected)
4470 NetSocketState *s;
4471 s = qemu_mallocz(sizeof(NetSocketState));
4472 if (!s)
4473 return NULL;
4474 s->fd = fd;
4475 s->vc = qemu_new_vlan_client(vlan,
4476 net_socket_receive, NULL, s);
4477 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4478 "socket: fd=%d", fd);
4479 if (is_connected) {
4480 net_socket_connect(s);
4481 } else {
4482 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4484 return s;
4487 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4488 int is_connected)
4490 int so_type=-1, optlen=sizeof(so_type);
4492 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4493 (socklen_t *)&optlen)< 0) {
4494 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4495 return NULL;
4497 switch(so_type) {
4498 case SOCK_DGRAM:
4499 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4500 case SOCK_STREAM:
4501 return net_socket_fd_init_stream(vlan, fd, is_connected);
4502 default:
4503 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4504 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4505 return net_socket_fd_init_stream(vlan, fd, is_connected);
4507 return NULL;
4510 static void net_socket_accept(void *opaque)
4512 NetSocketListenState *s = opaque;
4513 NetSocketState *s1;
4514 struct sockaddr_in saddr;
4515 socklen_t len;
4516 int fd;
4518 for(;;) {
4519 len = sizeof(saddr);
4520 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4521 if (fd < 0 && errno != EINTR) {
4522 return;
4523 } else if (fd >= 0) {
4524 break;
4527 s1 = net_socket_fd_init(s->vlan, fd, 1);
4528 if (!s1) {
4529 closesocket(fd);
4530 } else {
4531 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4532 "socket: connection from %s:%d",
4533 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4537 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4539 NetSocketListenState *s;
4540 int fd, val, ret;
4541 struct sockaddr_in saddr;
4543 if (parse_host_port(&saddr, host_str) < 0)
4544 return -1;
4546 s = qemu_mallocz(sizeof(NetSocketListenState));
4547 if (!s)
4548 return -1;
4550 fd = socket(PF_INET, SOCK_STREAM, 0);
4551 if (fd < 0) {
4552 perror("socket");
4553 return -1;
4555 socket_set_nonblock(fd);
4557 /* allow fast reuse */
4558 val = 1;
4559 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4561 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4562 if (ret < 0) {
4563 perror("bind");
4564 return -1;
4566 ret = listen(fd, 0);
4567 if (ret < 0) {
4568 perror("listen");
4569 return -1;
4571 s->vlan = vlan;
4572 s->fd = fd;
4573 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4574 return 0;
4577 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4579 NetSocketState *s;
4580 int fd, connected, ret, err;
4581 struct sockaddr_in saddr;
4583 if (parse_host_port(&saddr, host_str) < 0)
4584 return -1;
4586 fd = socket(PF_INET, SOCK_STREAM, 0);
4587 if (fd < 0) {
4588 perror("socket");
4589 return -1;
4591 socket_set_nonblock(fd);
4593 connected = 0;
4594 for(;;) {
4595 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4596 if (ret < 0) {
4597 err = socket_error();
4598 if (err == EINTR || err == EWOULDBLOCK) {
4599 } else if (err == EINPROGRESS) {
4600 break;
4601 #ifdef _WIN32
4602 } else if (err == WSAEALREADY) {
4603 break;
4604 #endif
4605 } else {
4606 perror("connect");
4607 closesocket(fd);
4608 return -1;
4610 } else {
4611 connected = 1;
4612 break;
4615 s = net_socket_fd_init(vlan, fd, connected);
4616 if (!s)
4617 return -1;
4618 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4619 "socket: connect to %s:%d",
4620 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4621 return 0;
4624 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4626 NetSocketState *s;
4627 int fd;
4628 struct sockaddr_in saddr;
4630 if (parse_host_port(&saddr, host_str) < 0)
4631 return -1;
4634 fd = net_socket_mcast_create(&saddr);
4635 if (fd < 0)
4636 return -1;
4638 s = net_socket_fd_init(vlan, fd, 0);
4639 if (!s)
4640 return -1;
4642 s->dgram_dst = saddr;
4644 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4645 "socket: mcast=%s:%d",
4646 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4647 return 0;
4651 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4653 char *q;
4655 q = buf;
4656 while (*p != '\0' && *p != '=') {
4657 if (q && (q - buf) < buf_size - 1)
4658 *q++ = *p;
4659 p++;
4661 if (q)
4662 *q = '\0';
4664 return p;
4667 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4669 char *q;
4671 q = buf;
4672 while (*p != '\0') {
4673 if (*p == ',') {
4674 if (*(p + 1) != ',')
4675 break;
4676 p++;
4678 if (q && (q - buf) < buf_size - 1)
4679 *q++ = *p;
4680 p++;
4682 if (q)
4683 *q = '\0';
4685 return p;
4688 static int get_param_value(char *buf, int buf_size,
4689 const char *tag, const char *str)
4691 const char *p;
4692 char option[128];
4694 p = str;
4695 for(;;) {
4696 p = get_opt_name(option, sizeof(option), p);
4697 if (*p != '=')
4698 break;
4699 p++;
4700 if (!strcmp(tag, option)) {
4701 (void)get_opt_value(buf, buf_size, p);
4702 return strlen(buf);
4703 } else {
4704 p = get_opt_value(NULL, 0, p);
4706 if (*p != ',')
4707 break;
4708 p++;
4710 return 0;
4713 static int check_params(char *buf, int buf_size,
4714 char **params, const char *str)
4716 const char *p;
4717 int i;
4719 p = str;
4720 for(;;) {
4721 p = get_opt_name(buf, buf_size, p);
4722 if (*p != '=')
4723 return -1;
4724 p++;
4725 for(i = 0; params[i] != NULL; i++)
4726 if (!strcmp(params[i], buf))
4727 break;
4728 if (params[i] == NULL)
4729 return -1;
4730 p = get_opt_value(NULL, 0, p);
4731 if (*p != ',')
4732 break;
4733 p++;
4735 return 0;
4739 static int net_client_init(const char *str)
4741 const char *p;
4742 char *q;
4743 char device[64];
4744 char buf[1024];
4745 int vlan_id, ret;
4746 VLANState *vlan;
4748 p = str;
4749 q = device;
4750 while (*p != '\0' && *p != ',') {
4751 if ((q - device) < sizeof(device) - 1)
4752 *q++ = *p;
4753 p++;
4755 *q = '\0';
4756 if (*p == ',')
4757 p++;
4758 vlan_id = 0;
4759 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4760 vlan_id = strtol(buf, NULL, 0);
4762 vlan = qemu_find_vlan(vlan_id);
4763 if (!vlan) {
4764 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4765 return -1;
4767 if (!strcmp(device, "nic")) {
4768 NICInfo *nd;
4769 uint8_t *macaddr;
4771 if (nb_nics >= MAX_NICS) {
4772 fprintf(stderr, "Too Many NICs\n");
4773 return -1;
4775 nd = &nd_table[nb_nics];
4776 macaddr = nd->macaddr;
4777 macaddr[0] = 0x52;
4778 macaddr[1] = 0x54;
4779 macaddr[2] = 0x00;
4780 macaddr[3] = 0x12;
4781 macaddr[4] = 0x34;
4782 macaddr[5] = 0x56 + nb_nics;
4784 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4785 if (parse_macaddr(macaddr, buf) < 0) {
4786 fprintf(stderr, "invalid syntax for ethernet address\n");
4787 return -1;
4790 if (get_param_value(buf, sizeof(buf), "model", p)) {
4791 nd->model = strdup(buf);
4793 nd->vlan = vlan;
4794 nb_nics++;
4795 vlan->nb_guest_devs++;
4796 ret = 0;
4797 } else
4798 if (!strcmp(device, "none")) {
4799 /* does nothing. It is needed to signal that no network cards
4800 are wanted */
4801 ret = 0;
4802 } else
4803 #ifdef CONFIG_SLIRP
4804 if (!strcmp(device, "user")) {
4805 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4806 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4808 vlan->nb_host_devs++;
4809 ret = net_slirp_init(vlan);
4810 } else
4811 #endif
4812 #ifdef _WIN32
4813 if (!strcmp(device, "tap")) {
4814 char ifname[64];
4815 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4816 fprintf(stderr, "tap: no interface name\n");
4817 return -1;
4819 vlan->nb_host_devs++;
4820 ret = tap_win32_init(vlan, ifname);
4821 } else
4822 #else
4823 if (!strcmp(device, "tap")) {
4824 char ifname[64];
4825 char setup_script[1024], down_script[1024];
4826 int fd;
4827 vlan->nb_host_devs++;
4828 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4829 fd = strtol(buf, NULL, 0);
4830 ret = -1;
4831 if (net_tap_fd_init(vlan, fd))
4832 ret = 0;
4833 } else {
4834 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4835 ifname[0] = '\0';
4837 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4838 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4840 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4841 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4843 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4845 } else
4846 #endif
4847 if (!strcmp(device, "socket")) {
4848 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4849 int fd;
4850 fd = strtol(buf, NULL, 0);
4851 ret = -1;
4852 if (net_socket_fd_init(vlan, fd, 1))
4853 ret = 0;
4854 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4855 ret = net_socket_listen_init(vlan, buf);
4856 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4857 ret = net_socket_connect_init(vlan, buf);
4858 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4859 ret = net_socket_mcast_init(vlan, buf);
4860 } else {
4861 fprintf(stderr, "Unknown socket options: %s\n", p);
4862 return -1;
4864 vlan->nb_host_devs++;
4865 } else
4867 fprintf(stderr, "Unknown network device: %s\n", device);
4868 return -1;
4870 if (ret < 0) {
4871 fprintf(stderr, "Could not initialize device '%s'\n", device);
4874 return ret;
4877 void do_info_network(void)
4879 VLANState *vlan;
4880 VLANClientState *vc;
4882 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4883 term_printf("VLAN %d devices:\n", vlan->id);
4884 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4885 term_printf(" %s\n", vc->info_str);
4889 #define HD_ALIAS "index=%d,media=disk"
4890 #ifdef TARGET_PPC
4891 #define CDROM_ALIAS "index=1,media=cdrom"
4892 #else
4893 #define CDROM_ALIAS "index=2,media=cdrom"
4894 #endif
4895 #define FD_ALIAS "index=%d,if=floppy"
4896 #define PFLASH_ALIAS "if=pflash"
4897 #define MTD_ALIAS "if=mtd"
4898 #define SD_ALIAS "index=0,if=sd"
4900 static int drive_add(const char *file, const char *fmt, ...)
4902 va_list ap;
4904 if (nb_drives_opt >= MAX_DRIVES) {
4905 fprintf(stderr, "qemu: too many drives\n");
4906 exit(1);
4909 drives_opt[nb_drives_opt].file = file;
4910 va_start(ap, fmt);
4911 vsnprintf(drives_opt[nb_drives_opt].opt,
4912 sizeof(drives_opt[0].opt), fmt, ap);
4913 va_end(ap);
4915 return nb_drives_opt++;
4918 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4920 int index;
4922 /* seek interface, bus and unit */
4924 for (index = 0; index < nb_drives; index++)
4925 if (drives_table[index].type == type &&
4926 drives_table[index].bus == bus &&
4927 drives_table[index].unit == unit)
4928 return index;
4930 return -1;
4933 int drive_get_max_bus(BlockInterfaceType type)
4935 int max_bus;
4936 int index;
4938 max_bus = -1;
4939 for (index = 0; index < nb_drives; index++) {
4940 if(drives_table[index].type == type &&
4941 drives_table[index].bus > max_bus)
4942 max_bus = drives_table[index].bus;
4944 return max_bus;
4947 static int drive_init(struct drive_opt *arg, int snapshot,
4948 QEMUMachine *machine)
4950 char buf[128];
4951 char file[1024];
4952 char devname[128];
4953 const char *mediastr = "";
4954 BlockInterfaceType type;
4955 enum { MEDIA_DISK, MEDIA_CDROM } media;
4956 int bus_id, unit_id;
4957 int cyls, heads, secs, translation;
4958 BlockDriverState *bdrv;
4959 int max_devs;
4960 int index;
4961 int cache;
4962 int bdrv_flags;
4963 char *str = arg->opt;
4964 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4965 "secs", "trans", "media", "snapshot", "file",
4966 "cache", NULL };
4968 if (check_params(buf, sizeof(buf), params, str) < 0) {
4969 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
4970 buf, str);
4971 return -1;
4974 file[0] = 0;
4975 cyls = heads = secs = 0;
4976 bus_id = 0;
4977 unit_id = -1;
4978 translation = BIOS_ATA_TRANSLATION_AUTO;
4979 index = -1;
4980 cache = 1;
4982 if (!strcmp(machine->name, "realview") ||
4983 !strcmp(machine->name, "SS-5") ||
4984 !strcmp(machine->name, "SS-10") ||
4985 !strcmp(machine->name, "SS-600MP") ||
4986 !strcmp(machine->name, "versatilepb") ||
4987 !strcmp(machine->name, "versatileab")) {
4988 type = IF_SCSI;
4989 max_devs = MAX_SCSI_DEVS;
4990 strcpy(devname, "scsi");
4991 } else {
4992 type = IF_IDE;
4993 max_devs = MAX_IDE_DEVS;
4994 strcpy(devname, "ide");
4996 media = MEDIA_DISK;
4998 /* extract parameters */
5000 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5001 bus_id = strtol(buf, NULL, 0);
5002 if (bus_id < 0) {
5003 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5004 return -1;
5008 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5009 unit_id = strtol(buf, NULL, 0);
5010 if (unit_id < 0) {
5011 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5012 return -1;
5016 if (get_param_value(buf, sizeof(buf), "if", str)) {
5017 strncpy(devname, buf, sizeof(devname));
5018 if (!strcmp(buf, "ide")) {
5019 type = IF_IDE;
5020 max_devs = MAX_IDE_DEVS;
5021 } else if (!strcmp(buf, "scsi")) {
5022 type = IF_SCSI;
5023 max_devs = MAX_SCSI_DEVS;
5024 } else if (!strcmp(buf, "floppy")) {
5025 type = IF_FLOPPY;
5026 max_devs = 0;
5027 } else if (!strcmp(buf, "pflash")) {
5028 type = IF_PFLASH;
5029 max_devs = 0;
5030 } else if (!strcmp(buf, "mtd")) {
5031 type = IF_MTD;
5032 max_devs = 0;
5033 } else if (!strcmp(buf, "sd")) {
5034 type = IF_SD;
5035 max_devs = 0;
5036 } else {
5037 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5038 return -1;
5042 if (get_param_value(buf, sizeof(buf), "index", str)) {
5043 index = strtol(buf, NULL, 0);
5044 if (index < 0) {
5045 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5046 return -1;
5050 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5051 cyls = strtol(buf, NULL, 0);
5054 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5055 heads = strtol(buf, NULL, 0);
5058 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5059 secs = strtol(buf, NULL, 0);
5062 if (cyls || heads || secs) {
5063 if (cyls < 1 || cyls > 16383) {
5064 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5065 return -1;
5067 if (heads < 1 || heads > 16) {
5068 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5069 return -1;
5071 if (secs < 1 || secs > 63) {
5072 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5073 return -1;
5077 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5078 if (!cyls) {
5079 fprintf(stderr,
5080 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5081 str);
5082 return -1;
5084 if (!strcmp(buf, "none"))
5085 translation = BIOS_ATA_TRANSLATION_NONE;
5086 else if (!strcmp(buf, "lba"))
5087 translation = BIOS_ATA_TRANSLATION_LBA;
5088 else if (!strcmp(buf, "auto"))
5089 translation = BIOS_ATA_TRANSLATION_AUTO;
5090 else {
5091 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5092 return -1;
5096 if (get_param_value(buf, sizeof(buf), "media", str)) {
5097 if (!strcmp(buf, "disk")) {
5098 media = MEDIA_DISK;
5099 } else if (!strcmp(buf, "cdrom")) {
5100 if (cyls || secs || heads) {
5101 fprintf(stderr,
5102 "qemu: '%s' invalid physical CHS format\n", str);
5103 return -1;
5105 media = MEDIA_CDROM;
5106 } else {
5107 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5108 return -1;
5112 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5113 if (!strcmp(buf, "on"))
5114 snapshot = 1;
5115 else if (!strcmp(buf, "off"))
5116 snapshot = 0;
5117 else {
5118 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5119 return -1;
5123 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5124 if (!strcmp(buf, "off"))
5125 cache = 0;
5126 else if (!strcmp(buf, "on"))
5127 cache = 1;
5128 else {
5129 fprintf(stderr, "qemu: invalid cache option\n");
5130 return -1;
5134 if (arg->file == NULL)
5135 get_param_value(file, sizeof(file), "file", str);
5136 else
5137 pstrcpy(file, sizeof(file), arg->file);
5139 /* compute bus and unit according index */
5141 if (index != -1) {
5142 if (bus_id != 0 || unit_id != -1) {
5143 fprintf(stderr,
5144 "qemu: '%s' index cannot be used with bus and unit\n", str);
5145 return -1;
5147 if (max_devs == 0)
5149 unit_id = index;
5150 bus_id = 0;
5151 } else {
5152 unit_id = index % max_devs;
5153 bus_id = index / max_devs;
5157 /* if user doesn't specify a unit_id,
5158 * try to find the first free
5161 if (unit_id == -1) {
5162 unit_id = 0;
5163 while (drive_get_index(type, bus_id, unit_id) != -1) {
5164 unit_id++;
5165 if (max_devs && unit_id >= max_devs) {
5166 unit_id -= max_devs;
5167 bus_id++;
5172 /* check unit id */
5174 if (max_devs && unit_id >= max_devs) {
5175 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5176 str, unit_id, max_devs - 1);
5177 return -1;
5181 * ignore multiple definitions
5184 if (drive_get_index(type, bus_id, unit_id) != -1)
5185 return 0;
5187 /* init */
5189 if (type == IF_IDE || type == IF_SCSI)
5190 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5191 if (max_devs)
5192 snprintf(buf, sizeof(buf), "%s%i%s%i",
5193 devname, bus_id, mediastr, unit_id);
5194 else
5195 snprintf(buf, sizeof(buf), "%s%s%i",
5196 devname, mediastr, unit_id);
5197 bdrv = bdrv_new(buf);
5198 drives_table[nb_drives].bdrv = bdrv;
5199 drives_table[nb_drives].type = type;
5200 drives_table[nb_drives].bus = bus_id;
5201 drives_table[nb_drives].unit = unit_id;
5202 nb_drives++;
5204 switch(type) {
5205 case IF_IDE:
5206 case IF_SCSI:
5207 switch(media) {
5208 case MEDIA_DISK:
5209 if (cyls != 0) {
5210 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5211 bdrv_set_translation_hint(bdrv, translation);
5213 break;
5214 case MEDIA_CDROM:
5215 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5216 break;
5218 break;
5219 case IF_SD:
5220 /* FIXME: This isn't really a floppy, but it's a reasonable
5221 approximation. */
5222 case IF_FLOPPY:
5223 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5224 break;
5225 case IF_PFLASH:
5226 case IF_MTD:
5227 break;
5229 if (!file[0])
5230 return 0;
5231 bdrv_flags = 0;
5232 if (snapshot)
5233 bdrv_flags |= BDRV_O_SNAPSHOT;
5234 if (!cache)
5235 bdrv_flags |= BDRV_O_DIRECT;
5236 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5237 fprintf(stderr, "qemu: could not open disk image %s\n",
5238 file);
5239 return -1;
5241 return 0;
5244 /***********************************************************/
5245 /* USB devices */
5247 static USBPort *used_usb_ports;
5248 static USBPort *free_usb_ports;
5250 /* ??? Maybe change this to register a hub to keep track of the topology. */
5251 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5252 usb_attachfn attach)
5254 port->opaque = opaque;
5255 port->index = index;
5256 port->attach = attach;
5257 port->next = free_usb_ports;
5258 free_usb_ports = port;
5261 static int usb_device_add(const char *devname)
5263 const char *p;
5264 USBDevice *dev;
5265 USBPort *port;
5267 if (!free_usb_ports)
5268 return -1;
5270 if (strstart(devname, "host:", &p)) {
5271 dev = usb_host_device_open(p);
5272 } else if (!strcmp(devname, "mouse")) {
5273 dev = usb_mouse_init();
5274 } else if (!strcmp(devname, "tablet")) {
5275 dev = usb_tablet_init();
5276 } else if (!strcmp(devname, "keyboard")) {
5277 dev = usb_keyboard_init();
5278 } else if (strstart(devname, "disk:", &p)) {
5279 dev = usb_msd_init(p);
5280 } else if (!strcmp(devname, "wacom-tablet")) {
5281 dev = usb_wacom_init();
5282 } else if (strstart(devname, "serial:", &p)) {
5283 dev = usb_serial_init(p);
5284 } else {
5285 return -1;
5287 if (!dev)
5288 return -1;
5290 /* Find a USB port to add the device to. */
5291 port = free_usb_ports;
5292 if (!port->next) {
5293 USBDevice *hub;
5295 /* Create a new hub and chain it on. */
5296 free_usb_ports = NULL;
5297 port->next = used_usb_ports;
5298 used_usb_ports = port;
5300 hub = usb_hub_init(VM_USB_HUB_SIZE);
5301 usb_attach(port, hub);
5302 port = free_usb_ports;
5305 free_usb_ports = port->next;
5306 port->next = used_usb_ports;
5307 used_usb_ports = port;
5308 usb_attach(port, dev);
5309 return 0;
5312 static int usb_device_del(const char *devname)
5314 USBPort *port;
5315 USBPort **lastp;
5316 USBDevice *dev;
5317 int bus_num, addr;
5318 const char *p;
5320 if (!used_usb_ports)
5321 return -1;
5323 p = strchr(devname, '.');
5324 if (!p)
5325 return -1;
5326 bus_num = strtoul(devname, NULL, 0);
5327 addr = strtoul(p + 1, NULL, 0);
5328 if (bus_num != 0)
5329 return -1;
5331 lastp = &used_usb_ports;
5332 port = used_usb_ports;
5333 while (port && port->dev->addr != addr) {
5334 lastp = &port->next;
5335 port = port->next;
5338 if (!port)
5339 return -1;
5341 dev = port->dev;
5342 *lastp = port->next;
5343 usb_attach(port, NULL);
5344 dev->handle_destroy(dev);
5345 port->next = free_usb_ports;
5346 free_usb_ports = port;
5347 return 0;
5350 void do_usb_add(const char *devname)
5352 int ret;
5353 ret = usb_device_add(devname);
5354 if (ret < 0)
5355 term_printf("Could not add USB device '%s'\n", devname);
5358 void do_usb_del(const char *devname)
5360 int ret;
5361 ret = usb_device_del(devname);
5362 if (ret < 0)
5363 term_printf("Could not remove USB device '%s'\n", devname);
5366 void usb_info(void)
5368 USBDevice *dev;
5369 USBPort *port;
5370 const char *speed_str;
5372 if (!usb_enabled) {
5373 term_printf("USB support not enabled\n");
5374 return;
5377 for (port = used_usb_ports; port; port = port->next) {
5378 dev = port->dev;
5379 if (!dev)
5380 continue;
5381 switch(dev->speed) {
5382 case USB_SPEED_LOW:
5383 speed_str = "1.5";
5384 break;
5385 case USB_SPEED_FULL:
5386 speed_str = "12";
5387 break;
5388 case USB_SPEED_HIGH:
5389 speed_str = "480";
5390 break;
5391 default:
5392 speed_str = "?";
5393 break;
5395 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5396 0, dev->addr, speed_str, dev->devname);
5400 /***********************************************************/
5401 /* PCMCIA/Cardbus */
5403 static struct pcmcia_socket_entry_s {
5404 struct pcmcia_socket_s *socket;
5405 struct pcmcia_socket_entry_s *next;
5406 } *pcmcia_sockets = 0;
5408 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5410 struct pcmcia_socket_entry_s *entry;
5412 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5413 entry->socket = socket;
5414 entry->next = pcmcia_sockets;
5415 pcmcia_sockets = entry;
5418 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5420 struct pcmcia_socket_entry_s *entry, **ptr;
5422 ptr = &pcmcia_sockets;
5423 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5424 if (entry->socket == socket) {
5425 *ptr = entry->next;
5426 qemu_free(entry);
5430 void pcmcia_info(void)
5432 struct pcmcia_socket_entry_s *iter;
5433 if (!pcmcia_sockets)
5434 term_printf("No PCMCIA sockets\n");
5436 for (iter = pcmcia_sockets; iter; iter = iter->next)
5437 term_printf("%s: %s\n", iter->socket->slot_string,
5438 iter->socket->attached ? iter->socket->card_string :
5439 "Empty");
5442 /***********************************************************/
5443 /* dumb display */
5445 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5449 static void dumb_resize(DisplayState *ds, int w, int h)
5453 static void dumb_refresh(DisplayState *ds)
5455 #if defined(CONFIG_SDL)
5456 vga_hw_update();
5457 #endif
5460 static void dumb_display_init(DisplayState *ds)
5462 ds->data = NULL;
5463 ds->linesize = 0;
5464 ds->depth = 0;
5465 ds->dpy_update = dumb_update;
5466 ds->dpy_resize = dumb_resize;
5467 ds->dpy_refresh = dumb_refresh;
5470 /***********************************************************/
5471 /* I/O handling */
5473 #define MAX_IO_HANDLERS 64
5475 typedef struct IOHandlerRecord {
5476 int fd;
5477 IOCanRWHandler *fd_read_poll;
5478 IOHandler *fd_read;
5479 IOHandler *fd_write;
5480 int deleted;
5481 void *opaque;
5482 /* temporary data */
5483 struct pollfd *ufd;
5484 struct IOHandlerRecord *next;
5485 } IOHandlerRecord;
5487 static IOHandlerRecord *first_io_handler;
5489 /* XXX: fd_read_poll should be suppressed, but an API change is
5490 necessary in the character devices to suppress fd_can_read(). */
5491 int qemu_set_fd_handler2(int fd,
5492 IOCanRWHandler *fd_read_poll,
5493 IOHandler *fd_read,
5494 IOHandler *fd_write,
5495 void *opaque)
5497 IOHandlerRecord **pioh, *ioh;
5499 if (!fd_read && !fd_write) {
5500 pioh = &first_io_handler;
5501 for(;;) {
5502 ioh = *pioh;
5503 if (ioh == NULL)
5504 break;
5505 if (ioh->fd == fd) {
5506 ioh->deleted = 1;
5507 break;
5509 pioh = &ioh->next;
5511 } else {
5512 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5513 if (ioh->fd == fd)
5514 goto found;
5516 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5517 if (!ioh)
5518 return -1;
5519 ioh->next = first_io_handler;
5520 first_io_handler = ioh;
5521 found:
5522 ioh->fd = fd;
5523 ioh->fd_read_poll = fd_read_poll;
5524 ioh->fd_read = fd_read;
5525 ioh->fd_write = fd_write;
5526 ioh->opaque = opaque;
5527 ioh->deleted = 0;
5529 return 0;
5532 int qemu_set_fd_handler(int fd,
5533 IOHandler *fd_read,
5534 IOHandler *fd_write,
5535 void *opaque)
5537 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5540 /***********************************************************/
5541 /* Polling handling */
5543 typedef struct PollingEntry {
5544 PollingFunc *func;
5545 void *opaque;
5546 struct PollingEntry *next;
5547 } PollingEntry;
5549 static PollingEntry *first_polling_entry;
5551 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5553 PollingEntry **ppe, *pe;
5554 pe = qemu_mallocz(sizeof(PollingEntry));
5555 if (!pe)
5556 return -1;
5557 pe->func = func;
5558 pe->opaque = opaque;
5559 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5560 *ppe = pe;
5561 return 0;
5564 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5566 PollingEntry **ppe, *pe;
5567 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5568 pe = *ppe;
5569 if (pe->func == func && pe->opaque == opaque) {
5570 *ppe = pe->next;
5571 qemu_free(pe);
5572 break;
5577 #ifdef _WIN32
5578 /***********************************************************/
5579 /* Wait objects support */
5580 typedef struct WaitObjects {
5581 int num;
5582 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5583 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5584 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5585 } WaitObjects;
5587 static WaitObjects wait_objects = {0};
5589 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5591 WaitObjects *w = &wait_objects;
5593 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5594 return -1;
5595 w->events[w->num] = handle;
5596 w->func[w->num] = func;
5597 w->opaque[w->num] = opaque;
5598 w->num++;
5599 return 0;
5602 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5604 int i, found;
5605 WaitObjects *w = &wait_objects;
5607 found = 0;
5608 for (i = 0; i < w->num; i++) {
5609 if (w->events[i] == handle)
5610 found = 1;
5611 if (found) {
5612 w->events[i] = w->events[i + 1];
5613 w->func[i] = w->func[i + 1];
5614 w->opaque[i] = w->opaque[i + 1];
5617 if (found)
5618 w->num--;
5620 #endif
5622 /***********************************************************/
5623 /* savevm/loadvm support */
5625 #define IO_BUF_SIZE 32768
5627 struct QEMUFile {
5628 FILE *outfile;
5629 BlockDriverState *bs;
5630 int is_file;
5631 int is_writable;
5632 int64_t base_offset;
5633 int64_t buf_offset; /* start of buffer when writing, end of buffer
5634 when reading */
5635 int buf_index;
5636 int buf_size; /* 0 when writing */
5637 uint8_t buf[IO_BUF_SIZE];
5640 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5642 QEMUFile *f;
5644 f = qemu_mallocz(sizeof(QEMUFile));
5645 if (!f)
5646 return NULL;
5647 if (!strcmp(mode, "wb")) {
5648 f->is_writable = 1;
5649 } else if (!strcmp(mode, "rb")) {
5650 f->is_writable = 0;
5651 } else {
5652 goto fail;
5654 f->outfile = fopen(filename, mode);
5655 if (!f->outfile)
5656 goto fail;
5657 f->is_file = 1;
5658 return f;
5659 fail:
5660 if (f->outfile)
5661 fclose(f->outfile);
5662 qemu_free(f);
5663 return NULL;
5666 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5668 QEMUFile *f;
5670 f = qemu_mallocz(sizeof(QEMUFile));
5671 if (!f)
5672 return NULL;
5673 f->is_file = 0;
5674 f->bs = bs;
5675 f->is_writable = is_writable;
5676 f->base_offset = offset;
5677 return f;
5680 void qemu_fflush(QEMUFile *f)
5682 if (!f->is_writable)
5683 return;
5684 if (f->buf_index > 0) {
5685 if (f->is_file) {
5686 fseek(f->outfile, f->buf_offset, SEEK_SET);
5687 fwrite(f->buf, 1, f->buf_index, f->outfile);
5688 } else {
5689 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5690 f->buf, f->buf_index);
5692 f->buf_offset += f->buf_index;
5693 f->buf_index = 0;
5697 static void qemu_fill_buffer(QEMUFile *f)
5699 int len;
5701 if (f->is_writable)
5702 return;
5703 if (f->is_file) {
5704 fseek(f->outfile, f->buf_offset, SEEK_SET);
5705 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5706 if (len < 0)
5707 len = 0;
5708 } else {
5709 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5710 f->buf, IO_BUF_SIZE);
5711 if (len < 0)
5712 len = 0;
5714 f->buf_index = 0;
5715 f->buf_size = len;
5716 f->buf_offset += len;
5719 void qemu_fclose(QEMUFile *f)
5721 if (f->is_writable)
5722 qemu_fflush(f);
5723 if (f->is_file) {
5724 fclose(f->outfile);
5726 qemu_free(f);
5729 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5731 int l;
5732 while (size > 0) {
5733 l = IO_BUF_SIZE - f->buf_index;
5734 if (l > size)
5735 l = size;
5736 memcpy(f->buf + f->buf_index, buf, l);
5737 f->buf_index += l;
5738 buf += l;
5739 size -= l;
5740 if (f->buf_index >= IO_BUF_SIZE)
5741 qemu_fflush(f);
5745 void qemu_put_byte(QEMUFile *f, int v)
5747 f->buf[f->buf_index++] = v;
5748 if (f->buf_index >= IO_BUF_SIZE)
5749 qemu_fflush(f);
5752 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5754 int size, l;
5756 size = size1;
5757 while (size > 0) {
5758 l = f->buf_size - f->buf_index;
5759 if (l == 0) {
5760 qemu_fill_buffer(f);
5761 l = f->buf_size - f->buf_index;
5762 if (l == 0)
5763 break;
5765 if (l > size)
5766 l = size;
5767 memcpy(buf, f->buf + f->buf_index, l);
5768 f->buf_index += l;
5769 buf += l;
5770 size -= l;
5772 return size1 - size;
5775 int qemu_get_byte(QEMUFile *f)
5777 if (f->buf_index >= f->buf_size) {
5778 qemu_fill_buffer(f);
5779 if (f->buf_index >= f->buf_size)
5780 return 0;
5782 return f->buf[f->buf_index++];
5785 int64_t qemu_ftell(QEMUFile *f)
5787 return f->buf_offset - f->buf_size + f->buf_index;
5790 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5792 if (whence == SEEK_SET) {
5793 /* nothing to do */
5794 } else if (whence == SEEK_CUR) {
5795 pos += qemu_ftell(f);
5796 } else {
5797 /* SEEK_END not supported */
5798 return -1;
5800 if (f->is_writable) {
5801 qemu_fflush(f);
5802 f->buf_offset = pos;
5803 } else {
5804 f->buf_offset = pos;
5805 f->buf_index = 0;
5806 f->buf_size = 0;
5808 return pos;
5811 void qemu_put_be16(QEMUFile *f, unsigned int v)
5813 qemu_put_byte(f, v >> 8);
5814 qemu_put_byte(f, v);
5817 void qemu_put_be32(QEMUFile *f, unsigned int v)
5819 qemu_put_byte(f, v >> 24);
5820 qemu_put_byte(f, v >> 16);
5821 qemu_put_byte(f, v >> 8);
5822 qemu_put_byte(f, v);
5825 void qemu_put_be64(QEMUFile *f, uint64_t v)
5827 qemu_put_be32(f, v >> 32);
5828 qemu_put_be32(f, v);
5831 unsigned int qemu_get_be16(QEMUFile *f)
5833 unsigned int v;
5834 v = qemu_get_byte(f) << 8;
5835 v |= qemu_get_byte(f);
5836 return v;
5839 unsigned int qemu_get_be32(QEMUFile *f)
5841 unsigned int v;
5842 v = qemu_get_byte(f) << 24;
5843 v |= qemu_get_byte(f) << 16;
5844 v |= qemu_get_byte(f) << 8;
5845 v |= qemu_get_byte(f);
5846 return v;
5849 uint64_t qemu_get_be64(QEMUFile *f)
5851 uint64_t v;
5852 v = (uint64_t)qemu_get_be32(f) << 32;
5853 v |= qemu_get_be32(f);
5854 return v;
5857 typedef struct SaveStateEntry {
5858 char idstr[256];
5859 int instance_id;
5860 int version_id;
5861 SaveStateHandler *save_state;
5862 LoadStateHandler *load_state;
5863 void *opaque;
5864 struct SaveStateEntry *next;
5865 } SaveStateEntry;
5867 static SaveStateEntry *first_se;
5869 int register_savevm(const char *idstr,
5870 int instance_id,
5871 int version_id,
5872 SaveStateHandler *save_state,
5873 LoadStateHandler *load_state,
5874 void *opaque)
5876 SaveStateEntry *se, **pse;
5878 se = qemu_malloc(sizeof(SaveStateEntry));
5879 if (!se)
5880 return -1;
5881 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5882 se->instance_id = instance_id;
5883 se->version_id = version_id;
5884 se->save_state = save_state;
5885 se->load_state = load_state;
5886 se->opaque = opaque;
5887 se->next = NULL;
5889 /* add at the end of list */
5890 pse = &first_se;
5891 while (*pse != NULL)
5892 pse = &(*pse)->next;
5893 *pse = se;
5894 return 0;
5897 #define QEMU_VM_FILE_MAGIC 0x5145564d
5898 #define QEMU_VM_FILE_VERSION 0x00000002
5900 static int qemu_savevm_state(QEMUFile *f)
5902 SaveStateEntry *se;
5903 int len, ret;
5904 int64_t cur_pos, len_pos, total_len_pos;
5906 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5907 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5908 total_len_pos = qemu_ftell(f);
5909 qemu_put_be64(f, 0); /* total size */
5911 for(se = first_se; se != NULL; se = se->next) {
5912 /* ID string */
5913 len = strlen(se->idstr);
5914 qemu_put_byte(f, len);
5915 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5917 qemu_put_be32(f, se->instance_id);
5918 qemu_put_be32(f, se->version_id);
5920 /* record size: filled later */
5921 len_pos = qemu_ftell(f);
5922 qemu_put_be32(f, 0);
5923 se->save_state(f, se->opaque);
5925 /* fill record size */
5926 cur_pos = qemu_ftell(f);
5927 len = cur_pos - len_pos - 4;
5928 qemu_fseek(f, len_pos, SEEK_SET);
5929 qemu_put_be32(f, len);
5930 qemu_fseek(f, cur_pos, SEEK_SET);
5932 cur_pos = qemu_ftell(f);
5933 qemu_fseek(f, total_len_pos, SEEK_SET);
5934 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5935 qemu_fseek(f, cur_pos, SEEK_SET);
5937 ret = 0;
5938 return ret;
5941 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5943 SaveStateEntry *se;
5945 for(se = first_se; se != NULL; se = se->next) {
5946 if (!strcmp(se->idstr, idstr) &&
5947 instance_id == se->instance_id)
5948 return se;
5950 return NULL;
5953 static int qemu_loadvm_state(QEMUFile *f)
5955 SaveStateEntry *se;
5956 int len, ret, instance_id, record_len, version_id;
5957 int64_t total_len, end_pos, cur_pos;
5958 unsigned int v;
5959 char idstr[256];
5961 v = qemu_get_be32(f);
5962 if (v != QEMU_VM_FILE_MAGIC)
5963 goto fail;
5964 v = qemu_get_be32(f);
5965 if (v != QEMU_VM_FILE_VERSION) {
5966 fail:
5967 ret = -1;
5968 goto the_end;
5970 total_len = qemu_get_be64(f);
5971 end_pos = total_len + qemu_ftell(f);
5972 for(;;) {
5973 if (qemu_ftell(f) >= end_pos)
5974 break;
5975 len = qemu_get_byte(f);
5976 qemu_get_buffer(f, (uint8_t *)idstr, len);
5977 idstr[len] = '\0';
5978 instance_id = qemu_get_be32(f);
5979 version_id = qemu_get_be32(f);
5980 record_len = qemu_get_be32(f);
5981 #if 0
5982 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5983 idstr, instance_id, version_id, record_len);
5984 #endif
5985 cur_pos = qemu_ftell(f);
5986 se = find_se(idstr, instance_id);
5987 if (!se) {
5988 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5989 instance_id, idstr);
5990 } else {
5991 ret = se->load_state(f, se->opaque, version_id);
5992 if (ret < 0) {
5993 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5994 instance_id, idstr);
5997 /* always seek to exact end of record */
5998 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6000 ret = 0;
6001 the_end:
6002 return ret;
6005 /* device can contain snapshots */
6006 static int bdrv_can_snapshot(BlockDriverState *bs)
6008 return (bs &&
6009 !bdrv_is_removable(bs) &&
6010 !bdrv_is_read_only(bs));
6013 /* device must be snapshots in order to have a reliable snapshot */
6014 static int bdrv_has_snapshot(BlockDriverState *bs)
6016 return (bs &&
6017 !bdrv_is_removable(bs) &&
6018 !bdrv_is_read_only(bs));
6021 static BlockDriverState *get_bs_snapshots(void)
6023 BlockDriverState *bs;
6024 int i;
6026 if (bs_snapshots)
6027 return bs_snapshots;
6028 for(i = 0; i <= nb_drives; i++) {
6029 bs = drives_table[i].bdrv;
6030 if (bdrv_can_snapshot(bs))
6031 goto ok;
6033 return NULL;
6035 bs_snapshots = bs;
6036 return bs;
6039 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6040 const char *name)
6042 QEMUSnapshotInfo *sn_tab, *sn;
6043 int nb_sns, i, ret;
6045 ret = -ENOENT;
6046 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6047 if (nb_sns < 0)
6048 return ret;
6049 for(i = 0; i < nb_sns; i++) {
6050 sn = &sn_tab[i];
6051 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6052 *sn_info = *sn;
6053 ret = 0;
6054 break;
6057 qemu_free(sn_tab);
6058 return ret;
6061 void do_savevm(const char *name)
6063 BlockDriverState *bs, *bs1;
6064 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6065 int must_delete, ret, i;
6066 BlockDriverInfo bdi1, *bdi = &bdi1;
6067 QEMUFile *f;
6068 int saved_vm_running;
6069 #ifdef _WIN32
6070 struct _timeb tb;
6071 #else
6072 struct timeval tv;
6073 #endif
6075 bs = get_bs_snapshots();
6076 if (!bs) {
6077 term_printf("No block device can accept snapshots\n");
6078 return;
6081 /* ??? Should this occur after vm_stop? */
6082 qemu_aio_flush();
6084 saved_vm_running = vm_running;
6085 vm_stop(0);
6087 must_delete = 0;
6088 if (name) {
6089 ret = bdrv_snapshot_find(bs, old_sn, name);
6090 if (ret >= 0) {
6091 must_delete = 1;
6094 memset(sn, 0, sizeof(*sn));
6095 if (must_delete) {
6096 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6097 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6098 } else {
6099 if (name)
6100 pstrcpy(sn->name, sizeof(sn->name), name);
6103 /* fill auxiliary fields */
6104 #ifdef _WIN32
6105 _ftime(&tb);
6106 sn->date_sec = tb.time;
6107 sn->date_nsec = tb.millitm * 1000000;
6108 #else
6109 gettimeofday(&tv, NULL);
6110 sn->date_sec = tv.tv_sec;
6111 sn->date_nsec = tv.tv_usec * 1000;
6112 #endif
6113 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6115 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6116 term_printf("Device %s does not support VM state snapshots\n",
6117 bdrv_get_device_name(bs));
6118 goto the_end;
6121 /* save the VM state */
6122 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6123 if (!f) {
6124 term_printf("Could not open VM state file\n");
6125 goto the_end;
6127 ret = qemu_savevm_state(f);
6128 sn->vm_state_size = qemu_ftell(f);
6129 qemu_fclose(f);
6130 if (ret < 0) {
6131 term_printf("Error %d while writing VM\n", ret);
6132 goto the_end;
6135 /* create the snapshots */
6137 for(i = 0; i < nb_drives; i++) {
6138 bs1 = drives_table[i].bdrv;
6139 if (bdrv_has_snapshot(bs1)) {
6140 if (must_delete) {
6141 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6142 if (ret < 0) {
6143 term_printf("Error while deleting snapshot on '%s'\n",
6144 bdrv_get_device_name(bs1));
6147 ret = bdrv_snapshot_create(bs1, sn);
6148 if (ret < 0) {
6149 term_printf("Error while creating snapshot on '%s'\n",
6150 bdrv_get_device_name(bs1));
6155 the_end:
6156 if (saved_vm_running)
6157 vm_start();
6160 void do_loadvm(const char *name)
6162 BlockDriverState *bs, *bs1;
6163 BlockDriverInfo bdi1, *bdi = &bdi1;
6164 QEMUFile *f;
6165 int i, ret;
6166 int saved_vm_running;
6168 bs = get_bs_snapshots();
6169 if (!bs) {
6170 term_printf("No block device supports snapshots\n");
6171 return;
6174 /* Flush all IO requests so they don't interfere with the new state. */
6175 qemu_aio_flush();
6177 saved_vm_running = vm_running;
6178 vm_stop(0);
6180 for(i = 0; i <= nb_drives; i++) {
6181 bs1 = drives_table[i].bdrv;
6182 if (bdrv_has_snapshot(bs1)) {
6183 ret = bdrv_snapshot_goto(bs1, name);
6184 if (ret < 0) {
6185 if (bs != bs1)
6186 term_printf("Warning: ");
6187 switch(ret) {
6188 case -ENOTSUP:
6189 term_printf("Snapshots not supported on device '%s'\n",
6190 bdrv_get_device_name(bs1));
6191 break;
6192 case -ENOENT:
6193 term_printf("Could not find snapshot '%s' on device '%s'\n",
6194 name, bdrv_get_device_name(bs1));
6195 break;
6196 default:
6197 term_printf("Error %d while activating snapshot on '%s'\n",
6198 ret, bdrv_get_device_name(bs1));
6199 break;
6201 /* fatal on snapshot block device */
6202 if (bs == bs1)
6203 goto the_end;
6208 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6209 term_printf("Device %s does not support VM state snapshots\n",
6210 bdrv_get_device_name(bs));
6211 return;
6214 /* restore the VM state */
6215 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6216 if (!f) {
6217 term_printf("Could not open VM state file\n");
6218 goto the_end;
6220 ret = qemu_loadvm_state(f);
6221 qemu_fclose(f);
6222 if (ret < 0) {
6223 term_printf("Error %d while loading VM state\n", ret);
6225 the_end:
6226 if (saved_vm_running)
6227 vm_start();
6230 void do_delvm(const char *name)
6232 BlockDriverState *bs, *bs1;
6233 int i, ret;
6235 bs = get_bs_snapshots();
6236 if (!bs) {
6237 term_printf("No block device supports snapshots\n");
6238 return;
6241 for(i = 0; i <= nb_drives; i++) {
6242 bs1 = drives_table[i].bdrv;
6243 if (bdrv_has_snapshot(bs1)) {
6244 ret = bdrv_snapshot_delete(bs1, name);
6245 if (ret < 0) {
6246 if (ret == -ENOTSUP)
6247 term_printf("Snapshots not supported on device '%s'\n",
6248 bdrv_get_device_name(bs1));
6249 else
6250 term_printf("Error %d while deleting snapshot on '%s'\n",
6251 ret, bdrv_get_device_name(bs1));
6257 void do_info_snapshots(void)
6259 BlockDriverState *bs, *bs1;
6260 QEMUSnapshotInfo *sn_tab, *sn;
6261 int nb_sns, i;
6262 char buf[256];
6264 bs = get_bs_snapshots();
6265 if (!bs) {
6266 term_printf("No available block device supports snapshots\n");
6267 return;
6269 term_printf("Snapshot devices:");
6270 for(i = 0; i <= nb_drives; i++) {
6271 bs1 = drives_table[i].bdrv;
6272 if (bdrv_has_snapshot(bs1)) {
6273 if (bs == bs1)
6274 term_printf(" %s", bdrv_get_device_name(bs1));
6277 term_printf("\n");
6279 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6280 if (nb_sns < 0) {
6281 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6282 return;
6284 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6285 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6286 for(i = 0; i < nb_sns; i++) {
6287 sn = &sn_tab[i];
6288 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6290 qemu_free(sn_tab);
6293 /***********************************************************/
6294 /* cpu save/restore */
6296 #if defined(TARGET_I386)
6298 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6300 qemu_put_be32(f, dt->selector);
6301 qemu_put_betl(f, dt->base);
6302 qemu_put_be32(f, dt->limit);
6303 qemu_put_be32(f, dt->flags);
6306 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6308 dt->selector = qemu_get_be32(f);
6309 dt->base = qemu_get_betl(f);
6310 dt->limit = qemu_get_be32(f);
6311 dt->flags = qemu_get_be32(f);
6314 void cpu_save(QEMUFile *f, void *opaque)
6316 CPUState *env = opaque;
6317 uint16_t fptag, fpus, fpuc, fpregs_format;
6318 uint32_t hflags;
6319 int i;
6321 for(i = 0; i < CPU_NB_REGS; i++)
6322 qemu_put_betls(f, &env->regs[i]);
6323 qemu_put_betls(f, &env->eip);
6324 qemu_put_betls(f, &env->eflags);
6325 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6326 qemu_put_be32s(f, &hflags);
6328 /* FPU */
6329 fpuc = env->fpuc;
6330 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6331 fptag = 0;
6332 for(i = 0; i < 8; i++) {
6333 fptag |= ((!env->fptags[i]) << i);
6336 qemu_put_be16s(f, &fpuc);
6337 qemu_put_be16s(f, &fpus);
6338 qemu_put_be16s(f, &fptag);
6340 #ifdef USE_X86LDOUBLE
6341 fpregs_format = 0;
6342 #else
6343 fpregs_format = 1;
6344 #endif
6345 qemu_put_be16s(f, &fpregs_format);
6347 for(i = 0; i < 8; i++) {
6348 #ifdef USE_X86LDOUBLE
6350 uint64_t mant;
6351 uint16_t exp;
6352 /* we save the real CPU data (in case of MMX usage only 'mant'
6353 contains the MMX register */
6354 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6355 qemu_put_be64(f, mant);
6356 qemu_put_be16(f, exp);
6358 #else
6359 /* if we use doubles for float emulation, we save the doubles to
6360 avoid losing information in case of MMX usage. It can give
6361 problems if the image is restored on a CPU where long
6362 doubles are used instead. */
6363 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6364 #endif
6367 for(i = 0; i < 6; i++)
6368 cpu_put_seg(f, &env->segs[i]);
6369 cpu_put_seg(f, &env->ldt);
6370 cpu_put_seg(f, &env->tr);
6371 cpu_put_seg(f, &env->gdt);
6372 cpu_put_seg(f, &env->idt);
6374 qemu_put_be32s(f, &env->sysenter_cs);
6375 qemu_put_be32s(f, &env->sysenter_esp);
6376 qemu_put_be32s(f, &env->sysenter_eip);
6378 qemu_put_betls(f, &env->cr[0]);
6379 qemu_put_betls(f, &env->cr[2]);
6380 qemu_put_betls(f, &env->cr[3]);
6381 qemu_put_betls(f, &env->cr[4]);
6383 for(i = 0; i < 8; i++)
6384 qemu_put_betls(f, &env->dr[i]);
6386 /* MMU */
6387 qemu_put_be32s(f, &env->a20_mask);
6389 /* XMM */
6390 qemu_put_be32s(f, &env->mxcsr);
6391 for(i = 0; i < CPU_NB_REGS; i++) {
6392 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6393 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6396 #ifdef TARGET_X86_64
6397 qemu_put_be64s(f, &env->efer);
6398 qemu_put_be64s(f, &env->star);
6399 qemu_put_be64s(f, &env->lstar);
6400 qemu_put_be64s(f, &env->cstar);
6401 qemu_put_be64s(f, &env->fmask);
6402 qemu_put_be64s(f, &env->kernelgsbase);
6403 #endif
6404 qemu_put_be32s(f, &env->smbase);
6407 #ifdef USE_X86LDOUBLE
6408 /* XXX: add that in a FPU generic layer */
6409 union x86_longdouble {
6410 uint64_t mant;
6411 uint16_t exp;
6414 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6415 #define EXPBIAS1 1023
6416 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6417 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6419 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6421 int e;
6422 /* mantissa */
6423 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6424 /* exponent + sign */
6425 e = EXPD1(temp) - EXPBIAS1 + 16383;
6426 e |= SIGND1(temp) >> 16;
6427 p->exp = e;
6429 #endif
6431 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6433 CPUState *env = opaque;
6434 int i, guess_mmx;
6435 uint32_t hflags;
6436 uint16_t fpus, fpuc, fptag, fpregs_format;
6438 if (version_id != 3 && version_id != 4)
6439 return -EINVAL;
6440 for(i = 0; i < CPU_NB_REGS; i++)
6441 qemu_get_betls(f, &env->regs[i]);
6442 qemu_get_betls(f, &env->eip);
6443 qemu_get_betls(f, &env->eflags);
6444 qemu_get_be32s(f, &hflags);
6446 qemu_get_be16s(f, &fpuc);
6447 qemu_get_be16s(f, &fpus);
6448 qemu_get_be16s(f, &fptag);
6449 qemu_get_be16s(f, &fpregs_format);
6451 /* NOTE: we cannot always restore the FPU state if the image come
6452 from a host with a different 'USE_X86LDOUBLE' define. We guess
6453 if we are in an MMX state to restore correctly in that case. */
6454 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6455 for(i = 0; i < 8; i++) {
6456 uint64_t mant;
6457 uint16_t exp;
6459 switch(fpregs_format) {
6460 case 0:
6461 mant = qemu_get_be64(f);
6462 exp = qemu_get_be16(f);
6463 #ifdef USE_X86LDOUBLE
6464 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6465 #else
6466 /* difficult case */
6467 if (guess_mmx)
6468 env->fpregs[i].mmx.MMX_Q(0) = mant;
6469 else
6470 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6471 #endif
6472 break;
6473 case 1:
6474 mant = qemu_get_be64(f);
6475 #ifdef USE_X86LDOUBLE
6477 union x86_longdouble *p;
6478 /* difficult case */
6479 p = (void *)&env->fpregs[i];
6480 if (guess_mmx) {
6481 p->mant = mant;
6482 p->exp = 0xffff;
6483 } else {
6484 fp64_to_fp80(p, mant);
6487 #else
6488 env->fpregs[i].mmx.MMX_Q(0) = mant;
6489 #endif
6490 break;
6491 default:
6492 return -EINVAL;
6496 env->fpuc = fpuc;
6497 /* XXX: restore FPU round state */
6498 env->fpstt = (fpus >> 11) & 7;
6499 env->fpus = fpus & ~0x3800;
6500 fptag ^= 0xff;
6501 for(i = 0; i < 8; i++) {
6502 env->fptags[i] = (fptag >> i) & 1;
6505 for(i = 0; i < 6; i++)
6506 cpu_get_seg(f, &env->segs[i]);
6507 cpu_get_seg(f, &env->ldt);
6508 cpu_get_seg(f, &env->tr);
6509 cpu_get_seg(f, &env->gdt);
6510 cpu_get_seg(f, &env->idt);
6512 qemu_get_be32s(f, &env->sysenter_cs);
6513 qemu_get_be32s(f, &env->sysenter_esp);
6514 qemu_get_be32s(f, &env->sysenter_eip);
6516 qemu_get_betls(f, &env->cr[0]);
6517 qemu_get_betls(f, &env->cr[2]);
6518 qemu_get_betls(f, &env->cr[3]);
6519 qemu_get_betls(f, &env->cr[4]);
6521 for(i = 0; i < 8; i++)
6522 qemu_get_betls(f, &env->dr[i]);
6524 /* MMU */
6525 qemu_get_be32s(f, &env->a20_mask);
6527 qemu_get_be32s(f, &env->mxcsr);
6528 for(i = 0; i < CPU_NB_REGS; i++) {
6529 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6530 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6533 #ifdef TARGET_X86_64
6534 qemu_get_be64s(f, &env->efer);
6535 qemu_get_be64s(f, &env->star);
6536 qemu_get_be64s(f, &env->lstar);
6537 qemu_get_be64s(f, &env->cstar);
6538 qemu_get_be64s(f, &env->fmask);
6539 qemu_get_be64s(f, &env->kernelgsbase);
6540 #endif
6541 if (version_id >= 4)
6542 qemu_get_be32s(f, &env->smbase);
6544 /* XXX: compute hflags from scratch, except for CPL and IIF */
6545 env->hflags = hflags;
6546 tlb_flush(env, 1);
6547 return 0;
6550 #elif defined(TARGET_PPC)
6551 void cpu_save(QEMUFile *f, void *opaque)
6555 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6557 return 0;
6560 #elif defined(TARGET_MIPS)
6561 void cpu_save(QEMUFile *f, void *opaque)
6565 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6567 return 0;
6570 #elif defined(TARGET_SPARC)
6571 void cpu_save(QEMUFile *f, void *opaque)
6573 CPUState *env = opaque;
6574 int i;
6575 uint32_t tmp;
6577 for(i = 0; i < 8; i++)
6578 qemu_put_betls(f, &env->gregs[i]);
6579 for(i = 0; i < NWINDOWS * 16; i++)
6580 qemu_put_betls(f, &env->regbase[i]);
6582 /* FPU */
6583 for(i = 0; i < TARGET_FPREGS; i++) {
6584 union {
6585 float32 f;
6586 uint32_t i;
6587 } u;
6588 u.f = env->fpr[i];
6589 qemu_put_be32(f, u.i);
6592 qemu_put_betls(f, &env->pc);
6593 qemu_put_betls(f, &env->npc);
6594 qemu_put_betls(f, &env->y);
6595 tmp = GET_PSR(env);
6596 qemu_put_be32(f, tmp);
6597 qemu_put_betls(f, &env->fsr);
6598 qemu_put_betls(f, &env->tbr);
6599 #ifndef TARGET_SPARC64
6600 qemu_put_be32s(f, &env->wim);
6601 /* MMU */
6602 for(i = 0; i < 16; i++)
6603 qemu_put_be32s(f, &env->mmuregs[i]);
6604 #endif
6607 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6609 CPUState *env = opaque;
6610 int i;
6611 uint32_t tmp;
6613 for(i = 0; i < 8; i++)
6614 qemu_get_betls(f, &env->gregs[i]);
6615 for(i = 0; i < NWINDOWS * 16; i++)
6616 qemu_get_betls(f, &env->regbase[i]);
6618 /* FPU */
6619 for(i = 0; i < TARGET_FPREGS; i++) {
6620 union {
6621 float32 f;
6622 uint32_t i;
6623 } u;
6624 u.i = qemu_get_be32(f);
6625 env->fpr[i] = u.f;
6628 qemu_get_betls(f, &env->pc);
6629 qemu_get_betls(f, &env->npc);
6630 qemu_get_betls(f, &env->y);
6631 tmp = qemu_get_be32(f);
6632 env->cwp = 0; /* needed to ensure that the wrapping registers are
6633 correctly updated */
6634 PUT_PSR(env, tmp);
6635 qemu_get_betls(f, &env->fsr);
6636 qemu_get_betls(f, &env->tbr);
6637 #ifndef TARGET_SPARC64
6638 qemu_get_be32s(f, &env->wim);
6639 /* MMU */
6640 for(i = 0; i < 16; i++)
6641 qemu_get_be32s(f, &env->mmuregs[i]);
6642 #endif
6643 tlb_flush(env, 1);
6644 return 0;
6647 #elif defined(TARGET_ARM)
6649 void cpu_save(QEMUFile *f, void *opaque)
6651 int i;
6652 CPUARMState *env = (CPUARMState *)opaque;
6654 for (i = 0; i < 16; i++) {
6655 qemu_put_be32(f, env->regs[i]);
6657 qemu_put_be32(f, cpsr_read(env));
6658 qemu_put_be32(f, env->spsr);
6659 for (i = 0; i < 6; i++) {
6660 qemu_put_be32(f, env->banked_spsr[i]);
6661 qemu_put_be32(f, env->banked_r13[i]);
6662 qemu_put_be32(f, env->banked_r14[i]);
6664 for (i = 0; i < 5; i++) {
6665 qemu_put_be32(f, env->usr_regs[i]);
6666 qemu_put_be32(f, env->fiq_regs[i]);
6668 qemu_put_be32(f, env->cp15.c0_cpuid);
6669 qemu_put_be32(f, env->cp15.c0_cachetype);
6670 qemu_put_be32(f, env->cp15.c1_sys);
6671 qemu_put_be32(f, env->cp15.c1_coproc);
6672 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6673 qemu_put_be32(f, env->cp15.c2_base0);
6674 qemu_put_be32(f, env->cp15.c2_base1);
6675 qemu_put_be32(f, env->cp15.c2_mask);
6676 qemu_put_be32(f, env->cp15.c2_data);
6677 qemu_put_be32(f, env->cp15.c2_insn);
6678 qemu_put_be32(f, env->cp15.c3);
6679 qemu_put_be32(f, env->cp15.c5_insn);
6680 qemu_put_be32(f, env->cp15.c5_data);
6681 for (i = 0; i < 8; i++) {
6682 qemu_put_be32(f, env->cp15.c6_region[i]);
6684 qemu_put_be32(f, env->cp15.c6_insn);
6685 qemu_put_be32(f, env->cp15.c6_data);
6686 qemu_put_be32(f, env->cp15.c9_insn);
6687 qemu_put_be32(f, env->cp15.c9_data);
6688 qemu_put_be32(f, env->cp15.c13_fcse);
6689 qemu_put_be32(f, env->cp15.c13_context);
6690 qemu_put_be32(f, env->cp15.c13_tls1);
6691 qemu_put_be32(f, env->cp15.c13_tls2);
6692 qemu_put_be32(f, env->cp15.c13_tls3);
6693 qemu_put_be32(f, env->cp15.c15_cpar);
6695 qemu_put_be32(f, env->features);
6697 if (arm_feature(env, ARM_FEATURE_VFP)) {
6698 for (i = 0; i < 16; i++) {
6699 CPU_DoubleU u;
6700 u.d = env->vfp.regs[i];
6701 qemu_put_be32(f, u.l.upper);
6702 qemu_put_be32(f, u.l.lower);
6704 for (i = 0; i < 16; i++) {
6705 qemu_put_be32(f, env->vfp.xregs[i]);
6708 /* TODO: Should use proper FPSCR access functions. */
6709 qemu_put_be32(f, env->vfp.vec_len);
6710 qemu_put_be32(f, env->vfp.vec_stride);
6712 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6713 for (i = 16; i < 32; i++) {
6714 CPU_DoubleU u;
6715 u.d = env->vfp.regs[i];
6716 qemu_put_be32(f, u.l.upper);
6717 qemu_put_be32(f, u.l.lower);
6722 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6723 for (i = 0; i < 16; i++) {
6724 qemu_put_be64(f, env->iwmmxt.regs[i]);
6726 for (i = 0; i < 16; i++) {
6727 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6731 if (arm_feature(env, ARM_FEATURE_M)) {
6732 qemu_put_be32(f, env->v7m.other_sp);
6733 qemu_put_be32(f, env->v7m.vecbase);
6734 qemu_put_be32(f, env->v7m.basepri);
6735 qemu_put_be32(f, env->v7m.control);
6736 qemu_put_be32(f, env->v7m.current_sp);
6737 qemu_put_be32(f, env->v7m.exception);
6741 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6743 CPUARMState *env = (CPUARMState *)opaque;
6744 int i;
6746 if (version_id != ARM_CPU_SAVE_VERSION)
6747 return -EINVAL;
6749 for (i = 0; i < 16; i++) {
6750 env->regs[i] = qemu_get_be32(f);
6752 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6753 env->spsr = qemu_get_be32(f);
6754 for (i = 0; i < 6; i++) {
6755 env->banked_spsr[i] = qemu_get_be32(f);
6756 env->banked_r13[i] = qemu_get_be32(f);
6757 env->banked_r14[i] = qemu_get_be32(f);
6759 for (i = 0; i < 5; i++) {
6760 env->usr_regs[i] = qemu_get_be32(f);
6761 env->fiq_regs[i] = qemu_get_be32(f);
6763 env->cp15.c0_cpuid = qemu_get_be32(f);
6764 env->cp15.c0_cachetype = qemu_get_be32(f);
6765 env->cp15.c1_sys = qemu_get_be32(f);
6766 env->cp15.c1_coproc = qemu_get_be32(f);
6767 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6768 env->cp15.c2_base0 = qemu_get_be32(f);
6769 env->cp15.c2_base1 = qemu_get_be32(f);
6770 env->cp15.c2_mask = qemu_get_be32(f);
6771 env->cp15.c2_data = qemu_get_be32(f);
6772 env->cp15.c2_insn = qemu_get_be32(f);
6773 env->cp15.c3 = qemu_get_be32(f);
6774 env->cp15.c5_insn = qemu_get_be32(f);
6775 env->cp15.c5_data = qemu_get_be32(f);
6776 for (i = 0; i < 8; i++) {
6777 env->cp15.c6_region[i] = qemu_get_be32(f);
6779 env->cp15.c6_insn = qemu_get_be32(f);
6780 env->cp15.c6_data = qemu_get_be32(f);
6781 env->cp15.c9_insn = qemu_get_be32(f);
6782 env->cp15.c9_data = qemu_get_be32(f);
6783 env->cp15.c13_fcse = qemu_get_be32(f);
6784 env->cp15.c13_context = qemu_get_be32(f);
6785 env->cp15.c13_tls1 = qemu_get_be32(f);
6786 env->cp15.c13_tls2 = qemu_get_be32(f);
6787 env->cp15.c13_tls3 = qemu_get_be32(f);
6788 env->cp15.c15_cpar = qemu_get_be32(f);
6790 env->features = qemu_get_be32(f);
6792 if (arm_feature(env, ARM_FEATURE_VFP)) {
6793 for (i = 0; i < 16; i++) {
6794 CPU_DoubleU u;
6795 u.l.upper = qemu_get_be32(f);
6796 u.l.lower = qemu_get_be32(f);
6797 env->vfp.regs[i] = u.d;
6799 for (i = 0; i < 16; i++) {
6800 env->vfp.xregs[i] = qemu_get_be32(f);
6803 /* TODO: Should use proper FPSCR access functions. */
6804 env->vfp.vec_len = qemu_get_be32(f);
6805 env->vfp.vec_stride = qemu_get_be32(f);
6807 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6808 for (i = 0; i < 16; i++) {
6809 CPU_DoubleU u;
6810 u.l.upper = qemu_get_be32(f);
6811 u.l.lower = qemu_get_be32(f);
6812 env->vfp.regs[i] = u.d;
6817 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6818 for (i = 0; i < 16; i++) {
6819 env->iwmmxt.regs[i] = qemu_get_be64(f);
6821 for (i = 0; i < 16; i++) {
6822 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6826 if (arm_feature(env, ARM_FEATURE_M)) {
6827 env->v7m.other_sp = qemu_get_be32(f);
6828 env->v7m.vecbase = qemu_get_be32(f);
6829 env->v7m.basepri = qemu_get_be32(f);
6830 env->v7m.control = qemu_get_be32(f);
6831 env->v7m.current_sp = qemu_get_be32(f);
6832 env->v7m.exception = qemu_get_be32(f);
6835 return 0;
6838 #else
6840 //#warning No CPU save/restore functions
6842 #endif
6844 /***********************************************************/
6845 /* ram save/restore */
6847 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6849 int v;
6851 v = qemu_get_byte(f);
6852 switch(v) {
6853 case 0:
6854 if (qemu_get_buffer(f, buf, len) != len)
6855 return -EIO;
6856 break;
6857 case 1:
6858 v = qemu_get_byte(f);
6859 memset(buf, v, len);
6860 break;
6861 default:
6862 return -EINVAL;
6864 return 0;
6867 static int ram_load_v1(QEMUFile *f, void *opaque)
6869 int i, ret;
6871 if (qemu_get_be32(f) != phys_ram_size)
6872 return -EINVAL;
6873 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6874 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6875 if (ret)
6876 return ret;
6878 return 0;
6881 #define BDRV_HASH_BLOCK_SIZE 1024
6882 #define IOBUF_SIZE 4096
6883 #define RAM_CBLOCK_MAGIC 0xfabe
6885 typedef struct RamCompressState {
6886 z_stream zstream;
6887 QEMUFile *f;
6888 uint8_t buf[IOBUF_SIZE];
6889 } RamCompressState;
6891 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6893 int ret;
6894 memset(s, 0, sizeof(*s));
6895 s->f = f;
6896 ret = deflateInit2(&s->zstream, 1,
6897 Z_DEFLATED, 15,
6898 9, Z_DEFAULT_STRATEGY);
6899 if (ret != Z_OK)
6900 return -1;
6901 s->zstream.avail_out = IOBUF_SIZE;
6902 s->zstream.next_out = s->buf;
6903 return 0;
6906 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6908 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6909 qemu_put_be16(s->f, len);
6910 qemu_put_buffer(s->f, buf, len);
6913 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6915 int ret;
6917 s->zstream.avail_in = len;
6918 s->zstream.next_in = (uint8_t *)buf;
6919 while (s->zstream.avail_in > 0) {
6920 ret = deflate(&s->zstream, Z_NO_FLUSH);
6921 if (ret != Z_OK)
6922 return -1;
6923 if (s->zstream.avail_out == 0) {
6924 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6925 s->zstream.avail_out = IOBUF_SIZE;
6926 s->zstream.next_out = s->buf;
6929 return 0;
6932 static void ram_compress_close(RamCompressState *s)
6934 int len, ret;
6936 /* compress last bytes */
6937 for(;;) {
6938 ret = deflate(&s->zstream, Z_FINISH);
6939 if (ret == Z_OK || ret == Z_STREAM_END) {
6940 len = IOBUF_SIZE - s->zstream.avail_out;
6941 if (len > 0) {
6942 ram_put_cblock(s, s->buf, len);
6944 s->zstream.avail_out = IOBUF_SIZE;
6945 s->zstream.next_out = s->buf;
6946 if (ret == Z_STREAM_END)
6947 break;
6948 } else {
6949 goto fail;
6952 fail:
6953 deflateEnd(&s->zstream);
6956 typedef struct RamDecompressState {
6957 z_stream zstream;
6958 QEMUFile *f;
6959 uint8_t buf[IOBUF_SIZE];
6960 } RamDecompressState;
6962 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6964 int ret;
6965 memset(s, 0, sizeof(*s));
6966 s->f = f;
6967 ret = inflateInit(&s->zstream);
6968 if (ret != Z_OK)
6969 return -1;
6970 return 0;
6973 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6975 int ret, clen;
6977 s->zstream.avail_out = len;
6978 s->zstream.next_out = buf;
6979 while (s->zstream.avail_out > 0) {
6980 if (s->zstream.avail_in == 0) {
6981 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6982 return -1;
6983 clen = qemu_get_be16(s->f);
6984 if (clen > IOBUF_SIZE)
6985 return -1;
6986 qemu_get_buffer(s->f, s->buf, clen);
6987 s->zstream.avail_in = clen;
6988 s->zstream.next_in = s->buf;
6990 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6991 if (ret != Z_OK && ret != Z_STREAM_END) {
6992 return -1;
6995 return 0;
6998 static void ram_decompress_close(RamDecompressState *s)
7000 inflateEnd(&s->zstream);
7003 static void ram_save(QEMUFile *f, void *opaque)
7005 int i;
7006 RamCompressState s1, *s = &s1;
7007 uint8_t buf[10];
7009 qemu_put_be32(f, phys_ram_size);
7010 if (ram_compress_open(s, f) < 0)
7011 return;
7012 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7013 #if 0
7014 if (tight_savevm_enabled) {
7015 int64_t sector_num;
7016 int j;
7018 /* find if the memory block is available on a virtual
7019 block device */
7020 sector_num = -1;
7021 for(j = 0; j < nb_drives; j++) {
7022 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7023 phys_ram_base + i,
7024 BDRV_HASH_BLOCK_SIZE);
7025 if (sector_num >= 0)
7026 break;
7028 if (j == nb_drives)
7029 goto normal_compress;
7030 buf[0] = 1;
7031 buf[1] = j;
7032 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7033 ram_compress_buf(s, buf, 10);
7034 } else
7035 #endif
7037 // normal_compress:
7038 buf[0] = 0;
7039 ram_compress_buf(s, buf, 1);
7040 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7043 ram_compress_close(s);
7046 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7048 RamDecompressState s1, *s = &s1;
7049 uint8_t buf[10];
7050 int i;
7052 if (version_id == 1)
7053 return ram_load_v1(f, opaque);
7054 if (version_id != 2)
7055 return -EINVAL;
7056 if (qemu_get_be32(f) != phys_ram_size)
7057 return -EINVAL;
7058 if (ram_decompress_open(s, f) < 0)
7059 return -EINVAL;
7060 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7061 if (ram_decompress_buf(s, buf, 1) < 0) {
7062 fprintf(stderr, "Error while reading ram block header\n");
7063 goto error;
7065 if (buf[0] == 0) {
7066 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7067 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7068 goto error;
7070 } else
7071 #if 0
7072 if (buf[0] == 1) {
7073 int bs_index;
7074 int64_t sector_num;
7076 ram_decompress_buf(s, buf + 1, 9);
7077 bs_index = buf[1];
7078 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7079 if (bs_index >= nb_drives) {
7080 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7081 goto error;
7083 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7084 phys_ram_base + i,
7085 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7086 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7087 bs_index, sector_num);
7088 goto error;
7090 } else
7091 #endif
7093 error:
7094 printf("Error block header\n");
7095 return -EINVAL;
7098 ram_decompress_close(s);
7099 return 0;
7102 /***********************************************************/
7103 /* bottom halves (can be seen as timers which expire ASAP) */
7105 struct QEMUBH {
7106 QEMUBHFunc *cb;
7107 void *opaque;
7108 int scheduled;
7109 QEMUBH *next;
7112 static QEMUBH *first_bh = NULL;
7114 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7116 QEMUBH *bh;
7117 bh = qemu_mallocz(sizeof(QEMUBH));
7118 if (!bh)
7119 return NULL;
7120 bh->cb = cb;
7121 bh->opaque = opaque;
7122 return bh;
7125 int qemu_bh_poll(void)
7127 QEMUBH *bh, **pbh;
7128 int ret;
7130 ret = 0;
7131 for(;;) {
7132 pbh = &first_bh;
7133 bh = *pbh;
7134 if (!bh)
7135 break;
7136 ret = 1;
7137 *pbh = bh->next;
7138 bh->scheduled = 0;
7139 bh->cb(bh->opaque);
7141 return ret;
7144 void qemu_bh_schedule(QEMUBH *bh)
7146 CPUState *env = cpu_single_env;
7147 if (bh->scheduled)
7148 return;
7149 bh->scheduled = 1;
7150 bh->next = first_bh;
7151 first_bh = bh;
7153 /* stop the currently executing CPU to execute the BH ASAP */
7154 if (env) {
7155 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7159 void qemu_bh_cancel(QEMUBH *bh)
7161 QEMUBH **pbh;
7162 if (bh->scheduled) {
7163 pbh = &first_bh;
7164 while (*pbh != bh)
7165 pbh = &(*pbh)->next;
7166 *pbh = bh->next;
7167 bh->scheduled = 0;
7171 void qemu_bh_delete(QEMUBH *bh)
7173 qemu_bh_cancel(bh);
7174 qemu_free(bh);
7177 /***********************************************************/
7178 /* machine registration */
7180 QEMUMachine *first_machine = NULL;
7182 int qemu_register_machine(QEMUMachine *m)
7184 QEMUMachine **pm;
7185 pm = &first_machine;
7186 while (*pm != NULL)
7187 pm = &(*pm)->next;
7188 m->next = NULL;
7189 *pm = m;
7190 return 0;
7193 static QEMUMachine *find_machine(const char *name)
7195 QEMUMachine *m;
7197 for(m = first_machine; m != NULL; m = m->next) {
7198 if (!strcmp(m->name, name))
7199 return m;
7201 return NULL;
7204 /***********************************************************/
7205 /* main execution loop */
7207 static void gui_update(void *opaque)
7209 DisplayState *ds = opaque;
7210 ds->dpy_refresh(ds);
7211 qemu_mod_timer(ds->gui_timer,
7212 (ds->gui_timer_interval ?
7213 ds->gui_timer_interval :
7214 GUI_REFRESH_INTERVAL)
7215 + qemu_get_clock(rt_clock));
7218 struct vm_change_state_entry {
7219 VMChangeStateHandler *cb;
7220 void *opaque;
7221 LIST_ENTRY (vm_change_state_entry) entries;
7224 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7226 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7227 void *opaque)
7229 VMChangeStateEntry *e;
7231 e = qemu_mallocz(sizeof (*e));
7232 if (!e)
7233 return NULL;
7235 e->cb = cb;
7236 e->opaque = opaque;
7237 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7238 return e;
7241 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7243 LIST_REMOVE (e, entries);
7244 qemu_free (e);
7247 static void vm_state_notify(int running)
7249 VMChangeStateEntry *e;
7251 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7252 e->cb(e->opaque, running);
7256 /* XXX: support several handlers */
7257 static VMStopHandler *vm_stop_cb;
7258 static void *vm_stop_opaque;
7260 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7262 vm_stop_cb = cb;
7263 vm_stop_opaque = opaque;
7264 return 0;
7267 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7269 vm_stop_cb = NULL;
7272 void vm_start(void)
7274 if (!vm_running) {
7275 cpu_enable_ticks();
7276 vm_running = 1;
7277 vm_state_notify(1);
7278 qemu_rearm_alarm_timer(alarm_timer);
7282 void vm_stop(int reason)
7284 if (vm_running) {
7285 cpu_disable_ticks();
7286 vm_running = 0;
7287 if (reason != 0) {
7288 if (vm_stop_cb) {
7289 vm_stop_cb(vm_stop_opaque, reason);
7292 vm_state_notify(0);
7296 /* reset/shutdown handler */
7298 typedef struct QEMUResetEntry {
7299 QEMUResetHandler *func;
7300 void *opaque;
7301 struct QEMUResetEntry *next;
7302 } QEMUResetEntry;
7304 static QEMUResetEntry *first_reset_entry;
7305 static int reset_requested;
7306 static int shutdown_requested;
7307 static int powerdown_requested;
7309 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7311 QEMUResetEntry **pre, *re;
7313 pre = &first_reset_entry;
7314 while (*pre != NULL)
7315 pre = &(*pre)->next;
7316 re = qemu_mallocz(sizeof(QEMUResetEntry));
7317 re->func = func;
7318 re->opaque = opaque;
7319 re->next = NULL;
7320 *pre = re;
7323 static void qemu_system_reset(void)
7325 QEMUResetEntry *re;
7327 /* reset all devices */
7328 for(re = first_reset_entry; re != NULL; re = re->next) {
7329 re->func(re->opaque);
7333 void qemu_system_reset_request(void)
7335 if (no_reboot) {
7336 shutdown_requested = 1;
7337 } else {
7338 reset_requested = 1;
7340 if (cpu_single_env)
7341 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7344 void qemu_system_shutdown_request(void)
7346 shutdown_requested = 1;
7347 if (cpu_single_env)
7348 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7351 void qemu_system_powerdown_request(void)
7353 powerdown_requested = 1;
7354 if (cpu_single_env)
7355 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7358 void main_loop_wait(int timeout)
7360 IOHandlerRecord *ioh;
7361 fd_set rfds, wfds, xfds;
7362 int ret, nfds;
7363 #ifdef _WIN32
7364 int ret2, i;
7365 #endif
7366 struct timeval tv;
7367 PollingEntry *pe;
7370 /* XXX: need to suppress polling by better using win32 events */
7371 ret = 0;
7372 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7373 ret |= pe->func(pe->opaque);
7375 #ifdef _WIN32
7376 if (ret == 0) {
7377 int err;
7378 WaitObjects *w = &wait_objects;
7380 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7381 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7382 if (w->func[ret - WAIT_OBJECT_0])
7383 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7385 /* Check for additional signaled events */
7386 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7388 /* Check if event is signaled */
7389 ret2 = WaitForSingleObject(w->events[i], 0);
7390 if(ret2 == WAIT_OBJECT_0) {
7391 if (w->func[i])
7392 w->func[i](w->opaque[i]);
7393 } else if (ret2 == WAIT_TIMEOUT) {
7394 } else {
7395 err = GetLastError();
7396 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7399 } else if (ret == WAIT_TIMEOUT) {
7400 } else {
7401 err = GetLastError();
7402 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7405 #endif
7406 /* poll any events */
7407 /* XXX: separate device handlers from system ones */
7408 nfds = -1;
7409 FD_ZERO(&rfds);
7410 FD_ZERO(&wfds);
7411 FD_ZERO(&xfds);
7412 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7413 if (ioh->deleted)
7414 continue;
7415 if (ioh->fd_read &&
7416 (!ioh->fd_read_poll ||
7417 ioh->fd_read_poll(ioh->opaque) != 0)) {
7418 FD_SET(ioh->fd, &rfds);
7419 if (ioh->fd > nfds)
7420 nfds = ioh->fd;
7422 if (ioh->fd_write) {
7423 FD_SET(ioh->fd, &wfds);
7424 if (ioh->fd > nfds)
7425 nfds = ioh->fd;
7429 tv.tv_sec = 0;
7430 #ifdef _WIN32
7431 tv.tv_usec = 0;
7432 #else
7433 tv.tv_usec = timeout * 1000;
7434 #endif
7435 #if defined(CONFIG_SLIRP)
7436 if (slirp_inited) {
7437 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7439 #endif
7440 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7441 if (ret > 0) {
7442 IOHandlerRecord **pioh;
7444 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7445 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7446 ioh->fd_read(ioh->opaque);
7448 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7449 ioh->fd_write(ioh->opaque);
7453 /* remove deleted IO handlers */
7454 pioh = &first_io_handler;
7455 while (*pioh) {
7456 ioh = *pioh;
7457 if (ioh->deleted) {
7458 *pioh = ioh->next;
7459 qemu_free(ioh);
7460 } else
7461 pioh = &ioh->next;
7464 #if defined(CONFIG_SLIRP)
7465 if (slirp_inited) {
7466 if (ret < 0) {
7467 FD_ZERO(&rfds);
7468 FD_ZERO(&wfds);
7469 FD_ZERO(&xfds);
7471 slirp_select_poll(&rfds, &wfds, &xfds);
7473 #endif
7474 qemu_aio_poll();
7476 if (vm_running) {
7477 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7478 qemu_get_clock(vm_clock));
7479 /* run dma transfers, if any */
7480 DMA_run();
7483 /* real time timers */
7484 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7485 qemu_get_clock(rt_clock));
7487 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7488 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7489 qemu_rearm_alarm_timer(alarm_timer);
7492 /* Check bottom-halves last in case any of the earlier events triggered
7493 them. */
7494 qemu_bh_poll();
7498 static int main_loop(void)
7500 int ret, timeout;
7501 #ifdef CONFIG_PROFILER
7502 int64_t ti;
7503 #endif
7504 CPUState *env;
7506 cur_cpu = first_cpu;
7507 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7508 for(;;) {
7509 if (vm_running) {
7511 for(;;) {
7512 /* get next cpu */
7513 env = next_cpu;
7514 #ifdef CONFIG_PROFILER
7515 ti = profile_getclock();
7516 #endif
7517 ret = cpu_exec(env);
7518 #ifdef CONFIG_PROFILER
7519 qemu_time += profile_getclock() - ti;
7520 #endif
7521 next_cpu = env->next_cpu ?: first_cpu;
7522 if (event_pending) {
7523 ret = EXCP_INTERRUPT;
7524 event_pending = 0;
7525 break;
7527 if (ret == EXCP_HLT) {
7528 /* Give the next CPU a chance to run. */
7529 cur_cpu = env;
7530 continue;
7532 if (ret != EXCP_HALTED)
7533 break;
7534 /* all CPUs are halted ? */
7535 if (env == cur_cpu)
7536 break;
7538 cur_cpu = env;
7540 if (shutdown_requested) {
7541 ret = EXCP_INTERRUPT;
7542 break;
7544 if (reset_requested) {
7545 reset_requested = 0;
7546 qemu_system_reset();
7547 ret = EXCP_INTERRUPT;
7549 if (powerdown_requested) {
7550 powerdown_requested = 0;
7551 qemu_system_powerdown();
7552 ret = EXCP_INTERRUPT;
7554 if (ret == EXCP_DEBUG) {
7555 vm_stop(EXCP_DEBUG);
7557 /* If all cpus are halted then wait until the next IRQ */
7558 /* XXX: use timeout computed from timers */
7559 if (ret == EXCP_HALTED)
7560 timeout = 10;
7561 else
7562 timeout = 0;
7563 } else {
7564 timeout = 10;
7566 #ifdef CONFIG_PROFILER
7567 ti = profile_getclock();
7568 #endif
7569 main_loop_wait(timeout);
7570 #ifdef CONFIG_PROFILER
7571 dev_time += profile_getclock() - ti;
7572 #endif
7574 cpu_disable_ticks();
7575 return ret;
7578 static void help(int exitcode)
7580 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7581 "usage: %s [options] [disk_image]\n"
7582 "\n"
7583 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7584 "\n"
7585 "Standard options:\n"
7586 "-M machine select emulated machine (-M ? for list)\n"
7587 "-cpu cpu select CPU (-cpu ? for list)\n"
7588 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7589 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7590 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7591 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7592 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7593 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7594 " [,cache=on|off]\n"
7595 " use 'file' as a drive image\n"
7596 "-mtdblock file use 'file' as on-board Flash memory image\n"
7597 "-sd file use 'file' as SecureDigital card image\n"
7598 "-pflash file use 'file' as a parallel flash image\n"
7599 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7600 "-snapshot write to temporary files instead of disk image files\n"
7601 #ifdef CONFIG_SDL
7602 "-no-frame open SDL window without a frame and window decorations\n"
7603 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7604 "-no-quit disable SDL window close capability\n"
7605 #endif
7606 #ifdef TARGET_I386
7607 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7608 #endif
7609 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7610 "-smp n set the number of CPUs to 'n' [default=1]\n"
7611 "-nographic disable graphical output and redirect serial I/Os to console\n"
7612 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7613 #ifndef _WIN32
7614 "-k language use keyboard layout (for example \"fr\" for French)\n"
7615 #endif
7616 #ifdef HAS_AUDIO
7617 "-audio-help print list of audio drivers and their options\n"
7618 "-soundhw c1,... enable audio support\n"
7619 " and only specified sound cards (comma separated list)\n"
7620 " use -soundhw ? to get the list of supported cards\n"
7621 " use -soundhw all to enable all of them\n"
7622 #endif
7623 "-localtime set the real time clock to local time [default=utc]\n"
7624 "-full-screen start in full screen\n"
7625 #ifdef TARGET_I386
7626 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7627 #endif
7628 "-usb enable the USB driver (will be the default soon)\n"
7629 "-usbdevice name add the host or guest USB device 'name'\n"
7630 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7631 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7632 #endif
7633 "-name string set the name of the guest\n"
7634 "\n"
7635 "Network options:\n"
7636 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7637 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7638 #ifdef CONFIG_SLIRP
7639 "-net user[,vlan=n][,hostname=host]\n"
7640 " connect the user mode network stack to VLAN 'n' and send\n"
7641 " hostname 'host' to DHCP clients\n"
7642 #endif
7643 #ifdef _WIN32
7644 "-net tap[,vlan=n],ifname=name\n"
7645 " connect the host TAP network interface to VLAN 'n'\n"
7646 #else
7647 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7648 " connect the host TAP network interface to VLAN 'n' and use the\n"
7649 " network scripts 'file' (default=%s)\n"
7650 " and 'dfile' (default=%s);\n"
7651 " use '[down]script=no' to disable script execution;\n"
7652 " use 'fd=h' to connect to an already opened TAP interface\n"
7653 #endif
7654 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7655 " connect the vlan 'n' to another VLAN using a socket connection\n"
7656 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7657 " connect the vlan 'n' to multicast maddr and port\n"
7658 "-net none use it alone to have zero network devices; if no -net option\n"
7659 " is provided, the default is '-net nic -net user'\n"
7660 "\n"
7661 #ifdef CONFIG_SLIRP
7662 "-tftp dir allow tftp access to files in dir [-net user]\n"
7663 "-bootp file advertise file in BOOTP replies\n"
7664 #ifndef _WIN32
7665 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7666 #endif
7667 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7668 " redirect TCP or UDP connections from host to guest [-net user]\n"
7669 #endif
7670 "\n"
7671 "Linux boot specific:\n"
7672 "-kernel bzImage use 'bzImage' as kernel image\n"
7673 "-append cmdline use 'cmdline' as kernel command line\n"
7674 "-initrd file use 'file' as initial ram disk\n"
7675 "\n"
7676 "Debug/Expert options:\n"
7677 "-monitor dev redirect the monitor to char device 'dev'\n"
7678 "-serial dev redirect the serial port to char device 'dev'\n"
7679 "-parallel dev redirect the parallel port to char device 'dev'\n"
7680 "-pidfile file Write PID to 'file'\n"
7681 "-S freeze CPU at startup (use 'c' to start execution)\n"
7682 "-s wait gdb connection to port\n"
7683 "-p port set gdb connection port [default=%s]\n"
7684 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7685 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7686 " translation (t=none or lba) (usually qemu can guess them)\n"
7687 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7688 #ifdef USE_KQEMU
7689 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7690 "-no-kqemu disable KQEMU kernel module usage\n"
7691 #endif
7692 #ifdef TARGET_I386
7693 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7694 " (default is CL-GD5446 PCI VGA)\n"
7695 "-no-acpi disable ACPI\n"
7696 #endif
7697 #ifdef CONFIG_CURSES
7698 "-curses use a curses/ncurses interface instead of SDL\n"
7699 #endif
7700 "-no-reboot exit instead of rebooting\n"
7701 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7702 "-vnc display start a VNC server on display\n"
7703 #ifndef _WIN32
7704 "-daemonize daemonize QEMU after initializing\n"
7705 #endif
7706 "-option-rom rom load a file, rom, into the option ROM space\n"
7707 #ifdef TARGET_SPARC
7708 "-prom-env variable=value set OpenBIOS nvram variables\n"
7709 #endif
7710 "-clock force the use of the given methods for timer alarm.\n"
7711 " To see what timers are available use -clock ?\n"
7712 "-startdate select initial date of the clock\n"
7713 "\n"
7714 "During emulation, the following keys are useful:\n"
7715 "ctrl-alt-f toggle full screen\n"
7716 "ctrl-alt-n switch to virtual console 'n'\n"
7717 "ctrl-alt toggle mouse and keyboard grab\n"
7718 "\n"
7719 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7721 "qemu",
7722 DEFAULT_RAM_SIZE,
7723 #ifndef _WIN32
7724 DEFAULT_NETWORK_SCRIPT,
7725 DEFAULT_NETWORK_DOWN_SCRIPT,
7726 #endif
7727 DEFAULT_GDBSTUB_PORT,
7728 "/tmp/qemu.log");
7729 exit(exitcode);
7732 #define HAS_ARG 0x0001
7734 enum {
7735 QEMU_OPTION_h,
7737 QEMU_OPTION_M,
7738 QEMU_OPTION_cpu,
7739 QEMU_OPTION_fda,
7740 QEMU_OPTION_fdb,
7741 QEMU_OPTION_hda,
7742 QEMU_OPTION_hdb,
7743 QEMU_OPTION_hdc,
7744 QEMU_OPTION_hdd,
7745 QEMU_OPTION_drive,
7746 QEMU_OPTION_cdrom,
7747 QEMU_OPTION_mtdblock,
7748 QEMU_OPTION_sd,
7749 QEMU_OPTION_pflash,
7750 QEMU_OPTION_boot,
7751 QEMU_OPTION_snapshot,
7752 #ifdef TARGET_I386
7753 QEMU_OPTION_no_fd_bootchk,
7754 #endif
7755 QEMU_OPTION_m,
7756 QEMU_OPTION_nographic,
7757 QEMU_OPTION_portrait,
7758 #ifdef HAS_AUDIO
7759 QEMU_OPTION_audio_help,
7760 QEMU_OPTION_soundhw,
7761 #endif
7763 QEMU_OPTION_net,
7764 QEMU_OPTION_tftp,
7765 QEMU_OPTION_bootp,
7766 QEMU_OPTION_smb,
7767 QEMU_OPTION_redir,
7769 QEMU_OPTION_kernel,
7770 QEMU_OPTION_append,
7771 QEMU_OPTION_initrd,
7773 QEMU_OPTION_S,
7774 QEMU_OPTION_s,
7775 QEMU_OPTION_p,
7776 QEMU_OPTION_d,
7777 QEMU_OPTION_hdachs,
7778 QEMU_OPTION_L,
7779 QEMU_OPTION_bios,
7780 QEMU_OPTION_no_code_copy,
7781 QEMU_OPTION_k,
7782 QEMU_OPTION_localtime,
7783 QEMU_OPTION_cirrusvga,
7784 QEMU_OPTION_vmsvga,
7785 QEMU_OPTION_g,
7786 QEMU_OPTION_std_vga,
7787 QEMU_OPTION_echr,
7788 QEMU_OPTION_monitor,
7789 QEMU_OPTION_serial,
7790 QEMU_OPTION_parallel,
7791 QEMU_OPTION_loadvm,
7792 QEMU_OPTION_full_screen,
7793 QEMU_OPTION_no_frame,
7794 QEMU_OPTION_alt_grab,
7795 QEMU_OPTION_no_quit,
7796 QEMU_OPTION_pidfile,
7797 QEMU_OPTION_no_kqemu,
7798 QEMU_OPTION_kernel_kqemu,
7799 QEMU_OPTION_win2k_hack,
7800 QEMU_OPTION_usb,
7801 QEMU_OPTION_usbdevice,
7802 QEMU_OPTION_smp,
7803 QEMU_OPTION_vnc,
7804 QEMU_OPTION_no_acpi,
7805 QEMU_OPTION_curses,
7806 QEMU_OPTION_no_reboot,
7807 QEMU_OPTION_show_cursor,
7808 QEMU_OPTION_daemonize,
7809 QEMU_OPTION_option_rom,
7810 QEMU_OPTION_semihosting,
7811 QEMU_OPTION_name,
7812 QEMU_OPTION_prom_env,
7813 QEMU_OPTION_old_param,
7814 QEMU_OPTION_clock,
7815 QEMU_OPTION_startdate,
7818 typedef struct QEMUOption {
7819 const char *name;
7820 int flags;
7821 int index;
7822 } QEMUOption;
7824 const QEMUOption qemu_options[] = {
7825 { "h", 0, QEMU_OPTION_h },
7826 { "help", 0, QEMU_OPTION_h },
7828 { "M", HAS_ARG, QEMU_OPTION_M },
7829 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7830 { "fda", HAS_ARG, QEMU_OPTION_fda },
7831 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7832 { "hda", HAS_ARG, QEMU_OPTION_hda },
7833 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7834 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7835 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7836 { "drive", HAS_ARG, QEMU_OPTION_drive },
7837 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7838 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7839 { "sd", HAS_ARG, QEMU_OPTION_sd },
7840 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7841 { "boot", HAS_ARG, QEMU_OPTION_boot },
7842 { "snapshot", 0, QEMU_OPTION_snapshot },
7843 #ifdef TARGET_I386
7844 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7845 #endif
7846 { "m", HAS_ARG, QEMU_OPTION_m },
7847 { "nographic", 0, QEMU_OPTION_nographic },
7848 { "portrait", 0, QEMU_OPTION_portrait },
7849 { "k", HAS_ARG, QEMU_OPTION_k },
7850 #ifdef HAS_AUDIO
7851 { "audio-help", 0, QEMU_OPTION_audio_help },
7852 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7853 #endif
7855 { "net", HAS_ARG, QEMU_OPTION_net},
7856 #ifdef CONFIG_SLIRP
7857 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7858 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7859 #ifndef _WIN32
7860 { "smb", HAS_ARG, QEMU_OPTION_smb },
7861 #endif
7862 { "redir", HAS_ARG, QEMU_OPTION_redir },
7863 #endif
7865 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7866 { "append", HAS_ARG, QEMU_OPTION_append },
7867 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7869 { "S", 0, QEMU_OPTION_S },
7870 { "s", 0, QEMU_OPTION_s },
7871 { "p", HAS_ARG, QEMU_OPTION_p },
7872 { "d", HAS_ARG, QEMU_OPTION_d },
7873 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7874 { "L", HAS_ARG, QEMU_OPTION_L },
7875 { "bios", HAS_ARG, QEMU_OPTION_bios },
7876 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7877 #ifdef USE_KQEMU
7878 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7879 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7880 #endif
7881 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7882 { "g", 1, QEMU_OPTION_g },
7883 #endif
7884 { "localtime", 0, QEMU_OPTION_localtime },
7885 { "std-vga", 0, QEMU_OPTION_std_vga },
7886 { "echr", HAS_ARG, QEMU_OPTION_echr },
7887 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7888 { "serial", HAS_ARG, QEMU_OPTION_serial },
7889 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7890 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7891 { "full-screen", 0, QEMU_OPTION_full_screen },
7892 #ifdef CONFIG_SDL
7893 { "no-frame", 0, QEMU_OPTION_no_frame },
7894 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7895 { "no-quit", 0, QEMU_OPTION_no_quit },
7896 #endif
7897 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7898 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7899 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7900 { "smp", HAS_ARG, QEMU_OPTION_smp },
7901 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7902 #ifdef CONFIG_CURSES
7903 { "curses", 0, QEMU_OPTION_curses },
7904 #endif
7906 /* temporary options */
7907 { "usb", 0, QEMU_OPTION_usb },
7908 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7909 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7910 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7911 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7912 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7913 { "daemonize", 0, QEMU_OPTION_daemonize },
7914 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7915 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7916 { "semihosting", 0, QEMU_OPTION_semihosting },
7917 #endif
7918 { "name", HAS_ARG, QEMU_OPTION_name },
7919 #if defined(TARGET_SPARC)
7920 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7921 #endif
7922 #if defined(TARGET_ARM)
7923 { "old-param", 0, QEMU_OPTION_old_param },
7924 #endif
7925 { "clock", HAS_ARG, QEMU_OPTION_clock },
7926 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7927 { NULL },
7930 /* password input */
7932 int qemu_key_check(BlockDriverState *bs, const char *name)
7934 char password[256];
7935 int i;
7937 if (!bdrv_is_encrypted(bs))
7938 return 0;
7940 term_printf("%s is encrypted.\n", name);
7941 for(i = 0; i < 3; i++) {
7942 monitor_readline("Password: ", 1, password, sizeof(password));
7943 if (bdrv_set_key(bs, password) == 0)
7944 return 0;
7945 term_printf("invalid password\n");
7947 return -EPERM;
7950 static BlockDriverState *get_bdrv(int index)
7952 if (index > nb_drives)
7953 return NULL;
7954 return drives_table[index].bdrv;
7957 static void read_passwords(void)
7959 BlockDriverState *bs;
7960 int i;
7962 for(i = 0; i < 6; i++) {
7963 bs = get_bdrv(i);
7964 if (bs)
7965 qemu_key_check(bs, bdrv_get_device_name(bs));
7969 /* XXX: currently we cannot use simultaneously different CPUs */
7970 static void register_machines(void)
7972 #if defined(TARGET_I386)
7973 qemu_register_machine(&pc_machine);
7974 qemu_register_machine(&isapc_machine);
7975 #elif defined(TARGET_PPC)
7976 qemu_register_machine(&heathrow_machine);
7977 qemu_register_machine(&core99_machine);
7978 qemu_register_machine(&prep_machine);
7979 qemu_register_machine(&ref405ep_machine);
7980 qemu_register_machine(&taihu_machine);
7981 #elif defined(TARGET_MIPS)
7982 qemu_register_machine(&mips_machine);
7983 qemu_register_machine(&mips_malta_machine);
7984 qemu_register_machine(&mips_pica61_machine);
7985 qemu_register_machine(&mips_mipssim_machine);
7986 #elif defined(TARGET_SPARC)
7987 #ifdef TARGET_SPARC64
7988 qemu_register_machine(&sun4u_machine);
7989 #else
7990 qemu_register_machine(&ss5_machine);
7991 qemu_register_machine(&ss10_machine);
7992 qemu_register_machine(&ss600mp_machine);
7993 qemu_register_machine(&ss20_machine);
7994 qemu_register_machine(&ss2_machine);
7995 qemu_register_machine(&voyager_machine);
7996 qemu_register_machine(&ss_lx_machine);
7997 qemu_register_machine(&ss4_machine);
7998 qemu_register_machine(&scls_machine);
7999 qemu_register_machine(&sbook_machine);
8000 qemu_register_machine(&ss1000_machine);
8001 qemu_register_machine(&ss2000_machine);
8002 #endif
8003 #elif defined(TARGET_ARM)
8004 qemu_register_machine(&integratorcp_machine);
8005 qemu_register_machine(&versatilepb_machine);
8006 qemu_register_machine(&versatileab_machine);
8007 qemu_register_machine(&realview_machine);
8008 qemu_register_machine(&akitapda_machine);
8009 qemu_register_machine(&spitzpda_machine);
8010 qemu_register_machine(&borzoipda_machine);
8011 qemu_register_machine(&terrierpda_machine);
8012 qemu_register_machine(&palmte_machine);
8013 qemu_register_machine(&lm3s811evb_machine);
8014 qemu_register_machine(&lm3s6965evb_machine);
8015 qemu_register_machine(&connex_machine);
8016 qemu_register_machine(&verdex_machine);
8017 qemu_register_machine(&mainstone2_machine);
8018 #elif defined(TARGET_SH4)
8019 qemu_register_machine(&shix_machine);
8020 qemu_register_machine(&r2d_machine);
8021 #elif defined(TARGET_ALPHA)
8022 /* XXX: TODO */
8023 #elif defined(TARGET_M68K)
8024 qemu_register_machine(&mcf5208evb_machine);
8025 qemu_register_machine(&an5206_machine);
8026 qemu_register_machine(&dummy_m68k_machine);
8027 #elif defined(TARGET_CRIS)
8028 qemu_register_machine(&bareetraxfs_machine);
8029 #else
8030 #error unsupported CPU
8031 #endif
8034 #ifdef HAS_AUDIO
8035 struct soundhw soundhw[] = {
8036 #ifdef HAS_AUDIO_CHOICE
8037 #ifdef TARGET_I386
8039 "pcspk",
8040 "PC speaker",
8043 { .init_isa = pcspk_audio_init }
8045 #endif
8047 "sb16",
8048 "Creative Sound Blaster 16",
8051 { .init_isa = SB16_init }
8054 #ifdef CONFIG_ADLIB
8056 "adlib",
8057 #ifdef HAS_YMF262
8058 "Yamaha YMF262 (OPL3)",
8059 #else
8060 "Yamaha YM3812 (OPL2)",
8061 #endif
8064 { .init_isa = Adlib_init }
8066 #endif
8068 #ifdef CONFIG_GUS
8070 "gus",
8071 "Gravis Ultrasound GF1",
8074 { .init_isa = GUS_init }
8076 #endif
8078 #ifdef CONFIG_AC97
8080 "ac97",
8081 "Intel 82801AA AC97 Audio",
8084 { .init_pci = ac97_init }
8086 #endif
8089 "es1370",
8090 "ENSONIQ AudioPCI ES1370",
8093 { .init_pci = es1370_init }
8095 #endif
8097 { NULL, NULL, 0, 0, { NULL } }
8100 static void select_soundhw (const char *optarg)
8102 struct soundhw *c;
8104 if (*optarg == '?') {
8105 show_valid_cards:
8107 printf ("Valid sound card names (comma separated):\n");
8108 for (c = soundhw; c->name; ++c) {
8109 printf ("%-11s %s\n", c->name, c->descr);
8111 printf ("\n-soundhw all will enable all of the above\n");
8112 exit (*optarg != '?');
8114 else {
8115 size_t l;
8116 const char *p;
8117 char *e;
8118 int bad_card = 0;
8120 if (!strcmp (optarg, "all")) {
8121 for (c = soundhw; c->name; ++c) {
8122 c->enabled = 1;
8124 return;
8127 p = optarg;
8128 while (*p) {
8129 e = strchr (p, ',');
8130 l = !e ? strlen (p) : (size_t) (e - p);
8132 for (c = soundhw; c->name; ++c) {
8133 if (!strncmp (c->name, p, l)) {
8134 c->enabled = 1;
8135 break;
8139 if (!c->name) {
8140 if (l > 80) {
8141 fprintf (stderr,
8142 "Unknown sound card name (too big to show)\n");
8144 else {
8145 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8146 (int) l, p);
8148 bad_card = 1;
8150 p += l + (e != NULL);
8153 if (bad_card)
8154 goto show_valid_cards;
8157 #endif
8159 #ifdef _WIN32
8160 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8162 exit(STATUS_CONTROL_C_EXIT);
8163 return TRUE;
8165 #endif
8167 #define MAX_NET_CLIENTS 32
8169 int main(int argc, char **argv)
8171 #ifdef CONFIG_GDBSTUB
8172 int use_gdbstub;
8173 const char *gdbstub_port;
8174 #endif
8175 uint32_t boot_devices_bitmap = 0;
8176 int i;
8177 int snapshot, linux_boot, net_boot;
8178 const char *initrd_filename;
8179 const char *kernel_filename, *kernel_cmdline;
8180 const char *boot_devices = "";
8181 DisplayState *ds = &display_state;
8182 int cyls, heads, secs, translation;
8183 char net_clients[MAX_NET_CLIENTS][256];
8184 int nb_net_clients;
8185 int hda_index;
8186 int optind;
8187 const char *r, *optarg;
8188 CharDriverState *monitor_hd;
8189 char monitor_device[128];
8190 char serial_devices[MAX_SERIAL_PORTS][128];
8191 int serial_device_index;
8192 char parallel_devices[MAX_PARALLEL_PORTS][128];
8193 int parallel_device_index;
8194 const char *loadvm = NULL;
8195 QEMUMachine *machine;
8196 const char *cpu_model;
8197 char usb_devices[MAX_USB_CMDLINE][128];
8198 int usb_devices_index;
8199 int fds[2];
8200 const char *pid_file = NULL;
8201 VLANState *vlan;
8203 LIST_INIT (&vm_change_state_head);
8204 #ifndef _WIN32
8206 struct sigaction act;
8207 sigfillset(&act.sa_mask);
8208 act.sa_flags = 0;
8209 act.sa_handler = SIG_IGN;
8210 sigaction(SIGPIPE, &act, NULL);
8212 #else
8213 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8214 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8215 QEMU to run on a single CPU */
8217 HANDLE h;
8218 DWORD mask, smask;
8219 int i;
8220 h = GetCurrentProcess();
8221 if (GetProcessAffinityMask(h, &mask, &smask)) {
8222 for(i = 0; i < 32; i++) {
8223 if (mask & (1 << i))
8224 break;
8226 if (i != 32) {
8227 mask = 1 << i;
8228 SetProcessAffinityMask(h, mask);
8232 #endif
8234 register_machines();
8235 machine = first_machine;
8236 cpu_model = NULL;
8237 initrd_filename = NULL;
8238 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8239 vga_ram_size = VGA_RAM_SIZE;
8240 #ifdef CONFIG_GDBSTUB
8241 use_gdbstub = 0;
8242 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8243 #endif
8244 snapshot = 0;
8245 nographic = 0;
8246 curses = 0;
8247 kernel_filename = NULL;
8248 kernel_cmdline = "";
8249 cyls = heads = secs = 0;
8250 translation = BIOS_ATA_TRANSLATION_AUTO;
8251 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8253 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8254 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8255 serial_devices[i][0] = '\0';
8256 serial_device_index = 0;
8258 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8259 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8260 parallel_devices[i][0] = '\0';
8261 parallel_device_index = 0;
8263 usb_devices_index = 0;
8265 nb_net_clients = 0;
8266 nb_drives = 0;
8267 nb_drives_opt = 0;
8268 hda_index = -1;
8270 nb_nics = 0;
8271 /* default mac address of the first network interface */
8273 optind = 1;
8274 for(;;) {
8275 if (optind >= argc)
8276 break;
8277 r = argv[optind];
8278 if (r[0] != '-') {
8279 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8280 } else {
8281 const QEMUOption *popt;
8283 optind++;
8284 /* Treat --foo the same as -foo. */
8285 if (r[1] == '-')
8286 r++;
8287 popt = qemu_options;
8288 for(;;) {
8289 if (!popt->name) {
8290 fprintf(stderr, "%s: invalid option -- '%s'\n",
8291 argv[0], r);
8292 exit(1);
8294 if (!strcmp(popt->name, r + 1))
8295 break;
8296 popt++;
8298 if (popt->flags & HAS_ARG) {
8299 if (optind >= argc) {
8300 fprintf(stderr, "%s: option '%s' requires an argument\n",
8301 argv[0], r);
8302 exit(1);
8304 optarg = argv[optind++];
8305 } else {
8306 optarg = NULL;
8309 switch(popt->index) {
8310 case QEMU_OPTION_M:
8311 machine = find_machine(optarg);
8312 if (!machine) {
8313 QEMUMachine *m;
8314 printf("Supported machines are:\n");
8315 for(m = first_machine; m != NULL; m = m->next) {
8316 printf("%-10s %s%s\n",
8317 m->name, m->desc,
8318 m == first_machine ? " (default)" : "");
8320 exit(*optarg != '?');
8322 break;
8323 case QEMU_OPTION_cpu:
8324 /* hw initialization will check this */
8325 if (*optarg == '?') {
8326 /* XXX: implement xxx_cpu_list for targets that still miss it */
8327 #if defined(cpu_list)
8328 cpu_list(stdout, &fprintf);
8329 #endif
8330 exit(0);
8331 } else {
8332 cpu_model = optarg;
8334 break;
8335 case QEMU_OPTION_initrd:
8336 initrd_filename = optarg;
8337 break;
8338 case QEMU_OPTION_hda:
8339 if (cyls == 0)
8340 hda_index = drive_add(optarg, HD_ALIAS, 0);
8341 else
8342 hda_index = drive_add(optarg, HD_ALIAS
8343 ",cyls=%d,heads=%d,secs=%d%s",
8344 0, cyls, heads, secs,
8345 translation == BIOS_ATA_TRANSLATION_LBA ?
8346 ",trans=lba" :
8347 translation == BIOS_ATA_TRANSLATION_NONE ?
8348 ",trans=none" : "");
8349 break;
8350 case QEMU_OPTION_hdb:
8351 case QEMU_OPTION_hdc:
8352 case QEMU_OPTION_hdd:
8353 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8354 break;
8355 case QEMU_OPTION_drive:
8356 drive_add(NULL, "%s", optarg);
8357 break;
8358 case QEMU_OPTION_mtdblock:
8359 drive_add(optarg, MTD_ALIAS);
8360 break;
8361 case QEMU_OPTION_sd:
8362 drive_add(optarg, SD_ALIAS);
8363 break;
8364 case QEMU_OPTION_pflash:
8365 drive_add(optarg, PFLASH_ALIAS);
8366 break;
8367 case QEMU_OPTION_snapshot:
8368 snapshot = 1;
8369 break;
8370 case QEMU_OPTION_hdachs:
8372 const char *p;
8373 p = optarg;
8374 cyls = strtol(p, (char **)&p, 0);
8375 if (cyls < 1 || cyls > 16383)
8376 goto chs_fail;
8377 if (*p != ',')
8378 goto chs_fail;
8379 p++;
8380 heads = strtol(p, (char **)&p, 0);
8381 if (heads < 1 || heads > 16)
8382 goto chs_fail;
8383 if (*p != ',')
8384 goto chs_fail;
8385 p++;
8386 secs = strtol(p, (char **)&p, 0);
8387 if (secs < 1 || secs > 63)
8388 goto chs_fail;
8389 if (*p == ',') {
8390 p++;
8391 if (!strcmp(p, "none"))
8392 translation = BIOS_ATA_TRANSLATION_NONE;
8393 else if (!strcmp(p, "lba"))
8394 translation = BIOS_ATA_TRANSLATION_LBA;
8395 else if (!strcmp(p, "auto"))
8396 translation = BIOS_ATA_TRANSLATION_AUTO;
8397 else
8398 goto chs_fail;
8399 } else if (*p != '\0') {
8400 chs_fail:
8401 fprintf(stderr, "qemu: invalid physical CHS format\n");
8402 exit(1);
8404 if (hda_index != -1)
8405 snprintf(drives_opt[hda_index].opt,
8406 sizeof(drives_opt[hda_index].opt),
8407 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8408 0, cyls, heads, secs,
8409 translation == BIOS_ATA_TRANSLATION_LBA ?
8410 ",trans=lba" :
8411 translation == BIOS_ATA_TRANSLATION_NONE ?
8412 ",trans=none" : "");
8414 break;
8415 case QEMU_OPTION_nographic:
8416 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8417 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8418 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8419 nographic = 1;
8420 break;
8421 #ifdef CONFIG_CURSES
8422 case QEMU_OPTION_curses:
8423 curses = 1;
8424 break;
8425 #endif
8426 case QEMU_OPTION_portrait:
8427 graphic_rotate = 1;
8428 break;
8429 case QEMU_OPTION_kernel:
8430 kernel_filename = optarg;
8431 break;
8432 case QEMU_OPTION_append:
8433 kernel_cmdline = optarg;
8434 break;
8435 case QEMU_OPTION_cdrom:
8436 drive_add(optarg, CDROM_ALIAS);
8437 break;
8438 case QEMU_OPTION_boot:
8439 boot_devices = optarg;
8440 /* We just do some generic consistency checks */
8442 /* Could easily be extended to 64 devices if needed */
8443 const char *p;
8445 boot_devices_bitmap = 0;
8446 for (p = boot_devices; *p != '\0'; p++) {
8447 /* Allowed boot devices are:
8448 * a b : floppy disk drives
8449 * c ... f : IDE disk drives
8450 * g ... m : machine implementation dependant drives
8451 * n ... p : network devices
8452 * It's up to each machine implementation to check
8453 * if the given boot devices match the actual hardware
8454 * implementation and firmware features.
8456 if (*p < 'a' || *p > 'q') {
8457 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8458 exit(1);
8460 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8461 fprintf(stderr,
8462 "Boot device '%c' was given twice\n",*p);
8463 exit(1);
8465 boot_devices_bitmap |= 1 << (*p - 'a');
8468 break;
8469 case QEMU_OPTION_fda:
8470 case QEMU_OPTION_fdb:
8471 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8472 break;
8473 #ifdef TARGET_I386
8474 case QEMU_OPTION_no_fd_bootchk:
8475 fd_bootchk = 0;
8476 break;
8477 #endif
8478 case QEMU_OPTION_no_code_copy:
8479 code_copy_enabled = 0;
8480 break;
8481 case QEMU_OPTION_net:
8482 if (nb_net_clients >= MAX_NET_CLIENTS) {
8483 fprintf(stderr, "qemu: too many network clients\n");
8484 exit(1);
8486 pstrcpy(net_clients[nb_net_clients],
8487 sizeof(net_clients[0]),
8488 optarg);
8489 nb_net_clients++;
8490 break;
8491 #ifdef CONFIG_SLIRP
8492 case QEMU_OPTION_tftp:
8493 tftp_prefix = optarg;
8494 break;
8495 case QEMU_OPTION_bootp:
8496 bootp_filename = optarg;
8497 break;
8498 #ifndef _WIN32
8499 case QEMU_OPTION_smb:
8500 net_slirp_smb(optarg);
8501 break;
8502 #endif
8503 case QEMU_OPTION_redir:
8504 net_slirp_redir(optarg);
8505 break;
8506 #endif
8507 #ifdef HAS_AUDIO
8508 case QEMU_OPTION_audio_help:
8509 AUD_help ();
8510 exit (0);
8511 break;
8512 case QEMU_OPTION_soundhw:
8513 select_soundhw (optarg);
8514 break;
8515 #endif
8516 case QEMU_OPTION_h:
8517 help(0);
8518 break;
8519 case QEMU_OPTION_m:
8520 ram_size = atoi(optarg) * 1024 * 1024;
8521 if (ram_size <= 0)
8522 help(1);
8523 if (ram_size > PHYS_RAM_MAX_SIZE) {
8524 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8525 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8526 exit(1);
8528 break;
8529 case QEMU_OPTION_d:
8531 int mask;
8532 CPULogItem *item;
8534 mask = cpu_str_to_log_mask(optarg);
8535 if (!mask) {
8536 printf("Log items (comma separated):\n");
8537 for(item = cpu_log_items; item->mask != 0; item++) {
8538 printf("%-10s %s\n", item->name, item->help);
8540 exit(1);
8542 cpu_set_log(mask);
8544 break;
8545 #ifdef CONFIG_GDBSTUB
8546 case QEMU_OPTION_s:
8547 use_gdbstub = 1;
8548 break;
8549 case QEMU_OPTION_p:
8550 gdbstub_port = optarg;
8551 break;
8552 #endif
8553 case QEMU_OPTION_L:
8554 bios_dir = optarg;
8555 break;
8556 case QEMU_OPTION_bios:
8557 bios_name = optarg;
8558 break;
8559 case QEMU_OPTION_S:
8560 autostart = 0;
8561 break;
8562 case QEMU_OPTION_k:
8563 keyboard_layout = optarg;
8564 break;
8565 case QEMU_OPTION_localtime:
8566 rtc_utc = 0;
8567 break;
8568 case QEMU_OPTION_cirrusvga:
8569 cirrus_vga_enabled = 1;
8570 vmsvga_enabled = 0;
8571 break;
8572 case QEMU_OPTION_vmsvga:
8573 cirrus_vga_enabled = 0;
8574 vmsvga_enabled = 1;
8575 break;
8576 case QEMU_OPTION_std_vga:
8577 cirrus_vga_enabled = 0;
8578 vmsvga_enabled = 0;
8579 break;
8580 case QEMU_OPTION_g:
8582 const char *p;
8583 int w, h, depth;
8584 p = optarg;
8585 w = strtol(p, (char **)&p, 10);
8586 if (w <= 0) {
8587 graphic_error:
8588 fprintf(stderr, "qemu: invalid resolution or depth\n");
8589 exit(1);
8591 if (*p != 'x')
8592 goto graphic_error;
8593 p++;
8594 h = strtol(p, (char **)&p, 10);
8595 if (h <= 0)
8596 goto graphic_error;
8597 if (*p == 'x') {
8598 p++;
8599 depth = strtol(p, (char **)&p, 10);
8600 if (depth != 8 && depth != 15 && depth != 16 &&
8601 depth != 24 && depth != 32)
8602 goto graphic_error;
8603 } else if (*p == '\0') {
8604 depth = graphic_depth;
8605 } else {
8606 goto graphic_error;
8609 graphic_width = w;
8610 graphic_height = h;
8611 graphic_depth = depth;
8613 break;
8614 case QEMU_OPTION_echr:
8616 char *r;
8617 term_escape_char = strtol(optarg, &r, 0);
8618 if (r == optarg)
8619 printf("Bad argument to echr\n");
8620 break;
8622 case QEMU_OPTION_monitor:
8623 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8624 break;
8625 case QEMU_OPTION_serial:
8626 if (serial_device_index >= MAX_SERIAL_PORTS) {
8627 fprintf(stderr, "qemu: too many serial ports\n");
8628 exit(1);
8630 pstrcpy(serial_devices[serial_device_index],
8631 sizeof(serial_devices[0]), optarg);
8632 serial_device_index++;
8633 break;
8634 case QEMU_OPTION_parallel:
8635 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8636 fprintf(stderr, "qemu: too many parallel ports\n");
8637 exit(1);
8639 pstrcpy(parallel_devices[parallel_device_index],
8640 sizeof(parallel_devices[0]), optarg);
8641 parallel_device_index++;
8642 break;
8643 case QEMU_OPTION_loadvm:
8644 loadvm = optarg;
8645 break;
8646 case QEMU_OPTION_full_screen:
8647 full_screen = 1;
8648 break;
8649 #ifdef CONFIG_SDL
8650 case QEMU_OPTION_no_frame:
8651 no_frame = 1;
8652 break;
8653 case QEMU_OPTION_alt_grab:
8654 alt_grab = 1;
8655 break;
8656 case QEMU_OPTION_no_quit:
8657 no_quit = 1;
8658 break;
8659 #endif
8660 case QEMU_OPTION_pidfile:
8661 pid_file = optarg;
8662 break;
8663 #ifdef TARGET_I386
8664 case QEMU_OPTION_win2k_hack:
8665 win2k_install_hack = 1;
8666 break;
8667 #endif
8668 #ifdef USE_KQEMU
8669 case QEMU_OPTION_no_kqemu:
8670 kqemu_allowed = 0;
8671 break;
8672 case QEMU_OPTION_kernel_kqemu:
8673 kqemu_allowed = 2;
8674 break;
8675 #endif
8676 case QEMU_OPTION_usb:
8677 usb_enabled = 1;
8678 break;
8679 case QEMU_OPTION_usbdevice:
8680 usb_enabled = 1;
8681 if (usb_devices_index >= MAX_USB_CMDLINE) {
8682 fprintf(stderr, "Too many USB devices\n");
8683 exit(1);
8685 pstrcpy(usb_devices[usb_devices_index],
8686 sizeof(usb_devices[usb_devices_index]),
8687 optarg);
8688 usb_devices_index++;
8689 break;
8690 case QEMU_OPTION_smp:
8691 smp_cpus = atoi(optarg);
8692 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8693 fprintf(stderr, "Invalid number of CPUs\n");
8694 exit(1);
8696 break;
8697 case QEMU_OPTION_vnc:
8698 vnc_display = optarg;
8699 break;
8700 case QEMU_OPTION_no_acpi:
8701 acpi_enabled = 0;
8702 break;
8703 case QEMU_OPTION_no_reboot:
8704 no_reboot = 1;
8705 break;
8706 case QEMU_OPTION_show_cursor:
8707 cursor_hide = 0;
8708 break;
8709 case QEMU_OPTION_daemonize:
8710 daemonize = 1;
8711 break;
8712 case QEMU_OPTION_option_rom:
8713 if (nb_option_roms >= MAX_OPTION_ROMS) {
8714 fprintf(stderr, "Too many option ROMs\n");
8715 exit(1);
8717 option_rom[nb_option_roms] = optarg;
8718 nb_option_roms++;
8719 break;
8720 case QEMU_OPTION_semihosting:
8721 semihosting_enabled = 1;
8722 break;
8723 case QEMU_OPTION_name:
8724 qemu_name = optarg;
8725 break;
8726 #ifdef TARGET_SPARC
8727 case QEMU_OPTION_prom_env:
8728 if (nb_prom_envs >= MAX_PROM_ENVS) {
8729 fprintf(stderr, "Too many prom variables\n");
8730 exit(1);
8732 prom_envs[nb_prom_envs] = optarg;
8733 nb_prom_envs++;
8734 break;
8735 #endif
8736 #ifdef TARGET_ARM
8737 case QEMU_OPTION_old_param:
8738 old_param = 1;
8739 break;
8740 #endif
8741 case QEMU_OPTION_clock:
8742 configure_alarms(optarg);
8743 break;
8744 case QEMU_OPTION_startdate:
8746 struct tm tm;
8747 time_t rtc_start_date;
8748 if (!strcmp(optarg, "now")) {
8749 rtc_date_offset = -1;
8750 } else {
8751 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8752 &tm.tm_year,
8753 &tm.tm_mon,
8754 &tm.tm_mday,
8755 &tm.tm_hour,
8756 &tm.tm_min,
8757 &tm.tm_sec) == 6) {
8758 /* OK */
8759 } else if (sscanf(optarg, "%d-%d-%d",
8760 &tm.tm_year,
8761 &tm.tm_mon,
8762 &tm.tm_mday) == 3) {
8763 tm.tm_hour = 0;
8764 tm.tm_min = 0;
8765 tm.tm_sec = 0;
8766 } else {
8767 goto date_fail;
8769 tm.tm_year -= 1900;
8770 tm.tm_mon--;
8771 rtc_start_date = mktimegm(&tm);
8772 if (rtc_start_date == -1) {
8773 date_fail:
8774 fprintf(stderr, "Invalid date format. Valid format are:\n"
8775 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8776 exit(1);
8778 rtc_date_offset = time(NULL) - rtc_start_date;
8781 break;
8786 #ifndef _WIN32
8787 if (daemonize && !nographic && vnc_display == NULL) {
8788 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8789 daemonize = 0;
8792 if (daemonize) {
8793 pid_t pid;
8795 if (pipe(fds) == -1)
8796 exit(1);
8798 pid = fork();
8799 if (pid > 0) {
8800 uint8_t status;
8801 ssize_t len;
8803 close(fds[1]);
8805 again:
8806 len = read(fds[0], &status, 1);
8807 if (len == -1 && (errno == EINTR))
8808 goto again;
8810 if (len != 1)
8811 exit(1);
8812 else if (status == 1) {
8813 fprintf(stderr, "Could not acquire pidfile\n");
8814 exit(1);
8815 } else
8816 exit(0);
8817 } else if (pid < 0)
8818 exit(1);
8820 setsid();
8822 pid = fork();
8823 if (pid > 0)
8824 exit(0);
8825 else if (pid < 0)
8826 exit(1);
8828 umask(027);
8829 chdir("/");
8831 signal(SIGTSTP, SIG_IGN);
8832 signal(SIGTTOU, SIG_IGN);
8833 signal(SIGTTIN, SIG_IGN);
8835 #endif
8837 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8838 if (daemonize) {
8839 uint8_t status = 1;
8840 write(fds[1], &status, 1);
8841 } else
8842 fprintf(stderr, "Could not acquire pid file\n");
8843 exit(1);
8846 #ifdef USE_KQEMU
8847 if (smp_cpus > 1)
8848 kqemu_allowed = 0;
8849 #endif
8850 linux_boot = (kernel_filename != NULL);
8851 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8853 /* XXX: this should not be: some embedded targets just have flash */
8854 if (!linux_boot && net_boot == 0 &&
8855 nb_drives_opt == 0)
8856 help(1);
8858 /* boot to floppy or the default cd if no hard disk defined yet */
8859 if (!boot_devices[0]) {
8860 boot_devices = "cad";
8862 setvbuf(stdout, NULL, _IOLBF, 0);
8864 init_timers();
8865 init_timer_alarm();
8866 qemu_aio_init();
8868 #ifdef _WIN32
8869 socket_init();
8870 #endif
8872 /* init network clients */
8873 if (nb_net_clients == 0) {
8874 /* if no clients, we use a default config */
8875 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8876 "nic");
8877 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8878 "user");
8879 nb_net_clients = 2;
8882 for(i = 0;i < nb_net_clients; i++) {
8883 if (net_client_init(net_clients[i]) < 0)
8884 exit(1);
8886 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8887 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8888 continue;
8889 if (vlan->nb_guest_devs == 0) {
8890 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8891 exit(1);
8893 if (vlan->nb_host_devs == 0)
8894 fprintf(stderr,
8895 "Warning: vlan %d is not connected to host network\n",
8896 vlan->id);
8899 #ifdef TARGET_I386
8900 /* XXX: this should be moved in the PC machine instantiation code */
8901 if (net_boot != 0) {
8902 int netroms = 0;
8903 for (i = 0; i < nb_nics && i < 4; i++) {
8904 const char *model = nd_table[i].model;
8905 char buf[1024];
8906 if (net_boot & (1 << i)) {
8907 if (model == NULL)
8908 model = "ne2k_pci";
8909 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8910 if (get_image_size(buf) > 0) {
8911 if (nb_option_roms >= MAX_OPTION_ROMS) {
8912 fprintf(stderr, "Too many option ROMs\n");
8913 exit(1);
8915 option_rom[nb_option_roms] = strdup(buf);
8916 nb_option_roms++;
8917 netroms++;
8921 if (netroms == 0) {
8922 fprintf(stderr, "No valid PXE rom found for network device\n");
8923 exit(1);
8926 #endif
8928 /* init the memory */
8929 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8931 phys_ram_base = qemu_vmalloc(phys_ram_size);
8932 if (!phys_ram_base) {
8933 fprintf(stderr, "Could not allocate physical memory\n");
8934 exit(1);
8937 bdrv_init();
8939 /* we always create the cdrom drive, even if no disk is there */
8941 if (nb_drives_opt < MAX_DRIVES)
8942 drive_add(NULL, CDROM_ALIAS);
8944 /* we always create at least one floppy */
8946 if (nb_drives_opt < MAX_DRIVES)
8947 drive_add(NULL, FD_ALIAS, 0);
8949 /* we always create one sd slot, even if no card is in it */
8951 if (nb_drives_opt < MAX_DRIVES)
8952 drive_add(NULL, SD_ALIAS);
8954 /* open the virtual block devices */
8956 for(i = 0; i < nb_drives_opt; i++)
8957 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8958 exit(1);
8960 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8961 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8963 init_ioports();
8965 /* terminal init */
8966 memset(&display_state, 0, sizeof(display_state));
8967 if (nographic) {
8968 if (curses) {
8969 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
8970 exit(1);
8972 /* nearly nothing to do */
8973 dumb_display_init(ds);
8974 } else if (vnc_display != NULL) {
8975 vnc_display_init(ds);
8976 if (vnc_display_open(ds, vnc_display) < 0)
8977 exit(1);
8978 } else
8979 #if defined(CONFIG_CURSES)
8980 if (curses) {
8981 curses_display_init(ds, full_screen);
8982 } else
8983 #endif
8985 #if defined(CONFIG_SDL)
8986 sdl_display_init(ds, full_screen, no_frame);
8987 #elif defined(CONFIG_COCOA)
8988 cocoa_display_init(ds, full_screen);
8989 #else
8990 dumb_display_init(ds);
8991 #endif
8994 /* Maintain compatibility with multiple stdio monitors */
8995 if (!strcmp(monitor_device,"stdio")) {
8996 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8997 if (!strcmp(serial_devices[i],"mon:stdio")) {
8998 monitor_device[0] = '\0';
8999 break;
9000 } else if (!strcmp(serial_devices[i],"stdio")) {
9001 monitor_device[0] = '\0';
9002 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9003 break;
9007 if (monitor_device[0] != '\0') {
9008 monitor_hd = qemu_chr_open(monitor_device);
9009 if (!monitor_hd) {
9010 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9011 exit(1);
9013 monitor_init(monitor_hd, !nographic);
9016 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9017 const char *devname = serial_devices[i];
9018 if (devname[0] != '\0' && strcmp(devname, "none")) {
9019 serial_hds[i] = qemu_chr_open(devname);
9020 if (!serial_hds[i]) {
9021 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9022 devname);
9023 exit(1);
9025 if (strstart(devname, "vc", 0))
9026 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9030 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9031 const char *devname = parallel_devices[i];
9032 if (devname[0] != '\0' && strcmp(devname, "none")) {
9033 parallel_hds[i] = qemu_chr_open(devname);
9034 if (!parallel_hds[i]) {
9035 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9036 devname);
9037 exit(1);
9039 if (strstart(devname, "vc", 0))
9040 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9044 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9045 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9047 /* init USB devices */
9048 if (usb_enabled) {
9049 for(i = 0; i < usb_devices_index; i++) {
9050 if (usb_device_add(usb_devices[i]) < 0) {
9051 fprintf(stderr, "Warning: could not add USB device %s\n",
9052 usb_devices[i]);
9057 if (display_state.dpy_refresh) {
9058 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9059 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9062 #ifdef CONFIG_GDBSTUB
9063 if (use_gdbstub) {
9064 /* XXX: use standard host:port notation and modify options
9065 accordingly. */
9066 if (gdbserver_start(gdbstub_port) < 0) {
9067 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9068 gdbstub_port);
9069 exit(1);
9072 #endif
9074 if (loadvm)
9075 do_loadvm(loadvm);
9078 /* XXX: simplify init */
9079 read_passwords();
9080 if (autostart) {
9081 vm_start();
9085 if (daemonize) {
9086 uint8_t status = 0;
9087 ssize_t len;
9088 int fd;
9090 again1:
9091 len = write(fds[1], &status, 1);
9092 if (len == -1 && (errno == EINTR))
9093 goto again1;
9095 if (len != 1)
9096 exit(1);
9098 TFR(fd = open("/dev/null", O_RDWR));
9099 if (fd == -1)
9100 exit(1);
9102 dup2(fd, 0);
9103 dup2(fd, 1);
9104 dup2(fd, 2);
9106 close(fd);
9109 main_loop();
9110 quit_timers();
9112 #if !defined(_WIN32)
9113 /* close network clients */
9114 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9115 VLANClientState *vc;
9117 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9118 if (vc->fd_read == tap_receive) {
9119 char ifname[64];
9120 TAPState *s = vc->opaque;
9122 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9123 s->down_script[0])
9124 launch_script(s->down_script, ifname, s->fd);
9128 #endif
9129 return 0;