Don't race while creating a VCPU
[qemu-kvm/fedora.git] / vl.c
blob74be0590bdf06700e40ab61d5926ad03b9432453
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/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.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"
40 #include "migration.h"
41 #include "qemu-kvm.h"
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <time.h>
47 #include <errno.h>
48 #include <sys/time.h>
49 #include <zlib.h>
51 #ifndef _WIN32
52 #include <sys/times.h>
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <sys/poll.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <dirent.h>
61 #include <netdb.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
64 #ifdef _BSD
65 #include <sys/stat.h>
66 #ifndef __APPLE__
67 #include <libutil.h>
68 #endif
69 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
70 #include <freebsd/stdlib.h>
71 #else
72 #ifndef __sun__
73 #include <linux/if.h>
74 #include <linux/if_tun.h>
75 #include <pty.h>
76 #include <malloc.h>
77 #include <linux/rtc.h>
79 /* For the benefit of older linux systems which don't supply it,
80 we use a local copy of hpet.h. */
81 /* #include <linux/hpet.h> */
82 #include "hpet.h"
84 #include <linux/ppdev.h>
85 #include <linux/parport.h>
86 #else
87 #include <sys/stat.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
97 #include <net/if.h>
98 #include <syslog.h>
99 #include <stropts.h>
100 #endif
101 #endif
102 #else
103 #include <winsock2.h>
104 int inet_aton(const char *cp, struct in_addr *ia);
105 #endif
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
109 #endif
111 #ifdef _WIN32
112 #include <malloc.h>
113 #include <sys/timeb.h>
114 #include <mmsystem.h>
115 #define getopt_long_only getopt_long
116 #define memalign(align, size) malloc(size)
117 #endif
119 #include "qemu_socket.h"
121 #ifdef CONFIG_SDL
122 #ifdef __APPLE__
123 #include <SDL/SDL.h>
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "disas.h"
134 #include "exec-all.h"
136 #include "qemu-kvm.h"
138 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
140 #ifdef __sun__
141 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
142 #else
143 #define SMBD_COMMAND "/usr/sbin/smbd"
144 #endif
146 //#define DEBUG_UNUSED_IOPORT
147 //#define DEBUG_IOPORT
149 #if HOST_LONG_BITS < 64
150 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
151 #else
152 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024 * 1024ULL)
153 #endif
155 #ifdef TARGET_PPC
156 #define DEFAULT_RAM_SIZE 144
157 #else
158 #define DEFAULT_RAM_SIZE 128
159 #endif
160 /* in ms */
161 #define GUI_REFRESH_INTERVAL 30
163 /* Max number of USB devices that can be specified on the commandline. */
164 #define MAX_USB_CMDLINE 8
166 /* XXX: use a two level table to limit memory usage */
167 #define MAX_IOPORTS 65536
169 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
170 const char *bios_name = NULL;
171 void *ioport_opaque[MAX_IOPORTS];
172 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
173 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 DriveInfo drives_table[MAX_DRIVES+1];
177 int nb_drives;
178 int extboot_drive = -1;
179 /* point to the block driver where the snapshots are managed */
180 BlockDriverState *bs_snapshots;
181 int vga_ram_size;
182 static DisplayState display_state;
183 int nographic;
184 int curses;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
187 int64_t ram_size;
188 int pit_min_timer_count = 0;
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int cirrus_vga_enabled = 1;
195 int vmsvga_enabled = 0;
196 #ifdef TARGET_SPARC
197 int graphic_width = 1024;
198 int graphic_height = 768;
199 int graphic_depth = 8;
200 #else
201 int graphic_width = 800;
202 int graphic_height = 600;
203 int graphic_depth = 15;
204 #endif
205 int full_screen = 0;
206 int no_frame = 0;
207 int no_quit = 0;
208 int balloon_used = 0;
209 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
210 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
211 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
212 #ifdef TARGET_I386
213 int win2k_install_hack = 0;
214 #endif
215 int usb_enabled = 0;
216 static VLANState *first_vlan;
217 int smp_cpus = 1;
218 const char *vnc_display;
219 #if defined(TARGET_SPARC)
220 #define MAX_CPUS 16
221 #elif defined(TARGET_I386)
222 #define MAX_CPUS 255
223 #elif defined(TARGET_IA64)
224 #define MAX_CPUS 4
225 #else
226 #define MAX_CPUS 1
227 #endif
228 int acpi_enabled = 1;
229 int fd_bootchk = 1;
230 int no_reboot = 0;
231 int no_shutdown = 0;
232 int cursor_hide = 1;
233 int graphic_rotate = 0;
234 int daemonize = 0;
235 const char *incoming;
236 const char *option_rom[MAX_OPTION_ROMS];
237 int nb_option_roms;
238 int semihosting_enabled = 0;
239 int autostart = 1;
240 int time_drift_fix = 0;
241 unsigned int kvm_shadow_memory = 0;
242 const char *mem_path = NULL;
243 int hpagesize = 0;
244 const char *cpu_vendor_string;
245 #ifdef TARGET_ARM
246 int old_param = 0;
247 #endif
248 const char *qemu_name;
249 int alt_grab = 0;
250 #ifdef TARGET_SPARC
251 unsigned int nb_prom_envs = 0;
252 const char *prom_envs[MAX_PROM_ENVS];
253 #endif
254 int nb_drives_opt;
255 struct drive_opt drives_opt[MAX_DRIVES];
257 static CPUState *cur_cpu;
258 static CPUState *next_cpu;
259 static int event_pending = 1;
261 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
263 void decorate_application_name(char *appname, int max_len)
265 if (kvm_enabled())
267 int remain = max_len - strlen(appname) - 1;
269 if (remain > 0)
270 strncat(appname, "/KVM", remain);
274 /***********************************************************/
275 /* x86 ISA bus support */
277 target_phys_addr_t isa_mem_base = 0;
278 PicState2 *isa_pic;
280 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
282 #ifdef DEBUG_UNUSED_IOPORT
283 fprintf(stderr, "unused inb: port=0x%04x\n", address);
284 #endif
285 return 0xff;
288 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
290 #ifdef DEBUG_UNUSED_IOPORT
291 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
292 #endif
295 /* default is to make two byte accesses */
296 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
298 uint32_t data;
299 data = ioport_read_table[0][address](ioport_opaque[address], address);
300 address = (address + 1) & (MAX_IOPORTS - 1);
301 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
302 return data;
305 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
307 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
308 address = (address + 1) & (MAX_IOPORTS - 1);
309 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
312 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
314 #ifdef DEBUG_UNUSED_IOPORT
315 fprintf(stderr, "unused inl: port=0x%04x\n", address);
316 #endif
317 return 0xffffffff;
320 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
322 #ifdef DEBUG_UNUSED_IOPORT
323 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
324 #endif
327 static void init_ioports(void)
329 int i;
331 for(i = 0; i < MAX_IOPORTS; i++) {
332 ioport_read_table[0][i] = default_ioport_readb;
333 ioport_write_table[0][i] = default_ioport_writeb;
334 ioport_read_table[1][i] = default_ioport_readw;
335 ioport_write_table[1][i] = default_ioport_writew;
336 ioport_read_table[2][i] = default_ioport_readl;
337 ioport_write_table[2][i] = default_ioport_writel;
341 /* size is the word size in byte */
342 int register_ioport_read(int start, int length, int size,
343 IOPortReadFunc *func, void *opaque)
345 int i, bsize;
347 if (size == 1) {
348 bsize = 0;
349 } else if (size == 2) {
350 bsize = 1;
351 } else if (size == 4) {
352 bsize = 2;
353 } else {
354 hw_error("register_ioport_read: invalid size");
355 return -1;
357 for(i = start; i < start + length; i += size) {
358 ioport_read_table[bsize][i] = func;
359 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
360 hw_error("register_ioport_read: invalid opaque");
361 ioport_opaque[i] = opaque;
363 return 0;
366 /* size is the word size in byte */
367 int register_ioport_write(int start, int length, int size,
368 IOPortWriteFunc *func, void *opaque)
370 int i, bsize;
372 if (size == 1) {
373 bsize = 0;
374 } else if (size == 2) {
375 bsize = 1;
376 } else if (size == 4) {
377 bsize = 2;
378 } else {
379 hw_error("register_ioport_write: invalid size");
380 return -1;
382 for(i = start; i < start + length; i += size) {
383 ioport_write_table[bsize][i] = func;
384 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
385 hw_error("register_ioport_write: invalid opaque");
386 ioport_opaque[i] = opaque;
388 return 0;
391 void isa_unassign_ioport(int start, int length)
393 int i;
395 for(i = start; i < start + length; i++) {
396 ioport_read_table[0][i] = default_ioport_readb;
397 ioport_read_table[1][i] = default_ioport_readw;
398 ioport_read_table[2][i] = default_ioport_readl;
400 ioport_write_table[0][i] = default_ioport_writeb;
401 ioport_write_table[1][i] = default_ioport_writew;
402 ioport_write_table[2][i] = default_ioport_writel;
404 ioport_opaque[i] = NULL;
408 /***********************************************************/
410 void cpu_outb(CPUState *env, int addr, int val)
412 #ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "outb: %04x %02x\n", addr, val);
415 #endif
416 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
417 #ifdef USE_KQEMU
418 if (env)
419 env->last_io_time = cpu_get_time_fast();
420 #endif
423 void cpu_outw(CPUState *env, int addr, int val)
425 #ifdef DEBUG_IOPORT
426 if (loglevel & CPU_LOG_IOPORT)
427 fprintf(logfile, "outw: %04x %04x\n", addr, val);
428 #endif
429 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
430 #ifdef USE_KQEMU
431 if (env)
432 env->last_io_time = cpu_get_time_fast();
433 #endif
436 void cpu_outl(CPUState *env, int addr, int val)
438 #ifdef DEBUG_IOPORT
439 if (loglevel & CPU_LOG_IOPORT)
440 fprintf(logfile, "outl: %04x %08x\n", addr, val);
441 #endif
442 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
443 #ifdef USE_KQEMU
444 if (env)
445 env->last_io_time = cpu_get_time_fast();
446 #endif
449 int cpu_inb(CPUState *env, int addr)
451 int val;
452 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
453 #ifdef DEBUG_IOPORT
454 if (loglevel & CPU_LOG_IOPORT)
455 fprintf(logfile, "inb : %04x %02x\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 int cpu_inw(CPUState *env, int addr)
466 int val;
467 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
468 #ifdef DEBUG_IOPORT
469 if (loglevel & CPU_LOG_IOPORT)
470 fprintf(logfile, "inw : %04x %04x\n", addr, val);
471 #endif
472 #ifdef USE_KQEMU
473 if (env)
474 env->last_io_time = cpu_get_time_fast();
475 #endif
476 return val;
479 int cpu_inl(CPUState *env, int addr)
481 int val;
482 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
483 #ifdef DEBUG_IOPORT
484 if (loglevel & CPU_LOG_IOPORT)
485 fprintf(logfile, "inl : %04x %08x\n", addr, val);
486 #endif
487 #ifdef USE_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
491 return val;
494 /***********************************************************/
495 void hw_error(const char *fmt, ...)
497 va_list ap;
498 CPUState *env;
500 va_start(ap, fmt);
501 fprintf(stderr, "qemu: hardware error: ");
502 vfprintf(stderr, fmt, ap);
503 fprintf(stderr, "\n");
504 for(env = first_cpu; env != NULL; env = env->next_cpu) {
505 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
506 #ifdef TARGET_I386
507 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
508 #else
509 cpu_dump_state(env, stderr, fprintf, 0);
510 #endif
512 va_end(ap);
513 abort();
516 /***********************************************************/
517 /* keyboard/mouse */
519 static QEMUPutKBDEvent *qemu_put_kbd_event;
520 static void *qemu_put_kbd_event_opaque;
521 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
522 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
524 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
526 qemu_put_kbd_event_opaque = opaque;
527 qemu_put_kbd_event = func;
530 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
531 void *opaque, int absolute,
532 const char *name)
534 QEMUPutMouseEntry *s, *cursor;
536 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
537 if (!s)
538 return NULL;
540 s->qemu_put_mouse_event = func;
541 s->qemu_put_mouse_event_opaque = opaque;
542 s->qemu_put_mouse_event_absolute = absolute;
543 s->qemu_put_mouse_event_name = qemu_strdup(name);
544 s->next = NULL;
546 if (!qemu_put_mouse_event_head) {
547 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
548 return s;
551 cursor = qemu_put_mouse_event_head;
552 while (cursor->next != NULL)
553 cursor = cursor->next;
555 cursor->next = s;
556 qemu_put_mouse_event_current = s;
558 return s;
561 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
563 QEMUPutMouseEntry *prev = NULL, *cursor;
565 if (!qemu_put_mouse_event_head || entry == NULL)
566 return;
568 cursor = qemu_put_mouse_event_head;
569 while (cursor != NULL && cursor != entry) {
570 prev = cursor;
571 cursor = cursor->next;
574 if (cursor == NULL) // does not exist or list empty
575 return;
576 else if (prev == NULL) { // entry is head
577 qemu_put_mouse_event_head = cursor->next;
578 if (qemu_put_mouse_event_current == entry)
579 qemu_put_mouse_event_current = cursor->next;
580 qemu_free(entry->qemu_put_mouse_event_name);
581 qemu_free(entry);
582 return;
585 prev->next = entry->next;
587 if (qemu_put_mouse_event_current == entry)
588 qemu_put_mouse_event_current = prev;
590 qemu_free(entry->qemu_put_mouse_event_name);
591 qemu_free(entry);
594 void kbd_put_keycode(int keycode)
596 if (qemu_put_kbd_event) {
597 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
601 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
603 QEMUPutMouseEvent *mouse_event;
604 void *mouse_event_opaque;
605 int width;
607 if (!qemu_put_mouse_event_current) {
608 return;
611 mouse_event =
612 qemu_put_mouse_event_current->qemu_put_mouse_event;
613 mouse_event_opaque =
614 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
616 if (mouse_event) {
617 if (graphic_rotate) {
618 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
619 width = 0x7fff;
620 else
621 width = graphic_width - 1;
622 mouse_event(mouse_event_opaque,
623 width - dy, dx, dz, buttons_state);
624 } else
625 mouse_event(mouse_event_opaque,
626 dx, dy, dz, buttons_state);
630 int kbd_mouse_is_absolute(void)
632 if (!qemu_put_mouse_event_current)
633 return 0;
635 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
638 void do_info_mice(void)
640 QEMUPutMouseEntry *cursor;
641 int index = 0;
643 if (!qemu_put_mouse_event_head) {
644 term_printf("No mouse devices connected\n");
645 return;
648 term_printf("Mouse devices available:\n");
649 cursor = qemu_put_mouse_event_head;
650 while (cursor != NULL) {
651 term_printf("%c Mouse #%d: %s\n",
652 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
653 index, cursor->qemu_put_mouse_event_name);
654 index++;
655 cursor = cursor->next;
659 void do_mouse_set(int index)
661 QEMUPutMouseEntry *cursor;
662 int i = 0;
664 if (!qemu_put_mouse_event_head) {
665 term_printf("No mouse devices connected\n");
666 return;
669 cursor = qemu_put_mouse_event_head;
670 while (cursor != NULL && index != i) {
671 i++;
672 cursor = cursor->next;
675 if (cursor != NULL)
676 qemu_put_mouse_event_current = cursor;
677 else
678 term_printf("Mouse at given index not found\n");
681 /* compute with 96 bit intermediate result: (a*b)/c */
682 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
684 union {
685 uint64_t ll;
686 struct {
687 #ifdef WORDS_BIGENDIAN
688 uint32_t high, low;
689 #else
690 uint32_t low, high;
691 #endif
692 } l;
693 } u, res;
694 uint64_t rl, rh;
696 u.ll = a;
697 rl = (uint64_t)u.l.low * (uint64_t)b;
698 rh = (uint64_t)u.l.high * (uint64_t)b;
699 rh += (rl >> 32);
700 res.l.high = rh / c;
701 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
702 return res.ll;
705 /***********************************************************/
706 /* real time host monotonic timer */
708 #define QEMU_TIMER_BASE 1000000000LL
710 #ifdef WIN32
712 static int64_t clock_freq;
714 static void init_get_clock(void)
716 LARGE_INTEGER freq;
717 int ret;
718 ret = QueryPerformanceFrequency(&freq);
719 if (ret == 0) {
720 fprintf(stderr, "Could not calibrate ticks\n");
721 exit(1);
723 clock_freq = freq.QuadPart;
726 static int64_t get_clock(void)
728 LARGE_INTEGER ti;
729 QueryPerformanceCounter(&ti);
730 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
733 #else
735 static int use_rt_clock;
737 static void init_get_clock(void)
739 use_rt_clock = 0;
740 #if defined(__linux__)
742 struct timespec ts;
743 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
744 use_rt_clock = 1;
747 #endif
750 static int64_t get_clock(void)
752 #if defined(__linux__)
753 if (use_rt_clock) {
754 struct timespec ts;
755 clock_gettime(CLOCK_MONOTONIC, &ts);
756 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
757 } else
758 #endif
760 /* XXX: using gettimeofday leads to problems if the date
761 changes, so it should be avoided. */
762 struct timeval tv;
763 gettimeofday(&tv, NULL);
764 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
768 #endif
770 /***********************************************************/
771 /* guest cycle counter */
773 static int64_t cpu_ticks_prev;
774 static int64_t cpu_ticks_offset;
775 static int64_t cpu_clock_offset;
776 static int cpu_ticks_enabled;
778 /* return the host CPU cycle counter and handle stop/restart */
779 int64_t cpu_get_ticks(void)
781 if (!cpu_ticks_enabled) {
782 return cpu_ticks_offset;
783 } else {
784 int64_t ticks;
785 ticks = cpu_get_real_ticks();
786 if (cpu_ticks_prev > ticks) {
787 /* Note: non increasing ticks may happen if the host uses
788 software suspend */
789 cpu_ticks_offset += cpu_ticks_prev - ticks;
791 cpu_ticks_prev = ticks;
792 return ticks + cpu_ticks_offset;
796 /* return the host CPU monotonic timer and handle stop/restart */
797 static int64_t cpu_get_clock(void)
799 int64_t ti;
800 if (!cpu_ticks_enabled) {
801 return cpu_clock_offset;
802 } else {
803 ti = get_clock();
804 return ti + cpu_clock_offset;
808 /* enable cpu_get_ticks() */
809 void cpu_enable_ticks(void)
811 if (!cpu_ticks_enabled) {
812 cpu_ticks_offset -= cpu_get_real_ticks();
813 cpu_clock_offset -= get_clock();
814 cpu_ticks_enabled = 1;
818 /* disable cpu_get_ticks() : the clock is stopped. You must not call
819 cpu_get_ticks() after that. */
820 void cpu_disable_ticks(void)
822 if (cpu_ticks_enabled) {
823 cpu_ticks_offset = cpu_get_ticks();
824 cpu_clock_offset = cpu_get_clock();
825 cpu_ticks_enabled = 0;
829 /***********************************************************/
830 /* timers */
832 #define QEMU_TIMER_REALTIME 0
833 #define QEMU_TIMER_VIRTUAL 1
835 struct QEMUClock {
836 int type;
837 /* XXX: add frequency */
840 struct QEMUTimer {
841 QEMUClock *clock;
842 int64_t expire_time;
843 QEMUTimerCB *cb;
844 void *opaque;
845 struct QEMUTimer *next;
848 struct qemu_alarm_timer {
849 char const *name;
850 unsigned int flags;
852 int (*start)(struct qemu_alarm_timer *t);
853 void (*stop)(struct qemu_alarm_timer *t);
854 void (*rearm)(struct qemu_alarm_timer *t);
855 void *priv;
858 #define ALARM_FLAG_DYNTICKS 0x1
859 #define ALARM_FLAG_EXPIRED 0x2
861 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
863 return t->flags & ALARM_FLAG_DYNTICKS;
866 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
868 if (!alarm_has_dynticks(t))
869 return;
871 t->rearm(t);
874 /* TODO: MIN_TIMER_REARM_US should be optimized */
875 #define MIN_TIMER_REARM_US 250
877 static struct qemu_alarm_timer *alarm_timer;
879 #ifdef _WIN32
881 struct qemu_alarm_win32 {
882 MMRESULT timerId;
883 HANDLE host_alarm;
884 unsigned int period;
885 } alarm_win32_data = {0, NULL, -1};
887 static int win32_start_timer(struct qemu_alarm_timer *t);
888 static void win32_stop_timer(struct qemu_alarm_timer *t);
889 static void win32_rearm_timer(struct qemu_alarm_timer *t);
891 #else
893 static int unix_start_timer(struct qemu_alarm_timer *t);
894 static void unix_stop_timer(struct qemu_alarm_timer *t);
896 #ifdef __linux__
898 static int dynticks_start_timer(struct qemu_alarm_timer *t);
899 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
900 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
902 static int hpet_start_timer(struct qemu_alarm_timer *t);
903 static void hpet_stop_timer(struct qemu_alarm_timer *t);
905 static int rtc_start_timer(struct qemu_alarm_timer *t);
906 static void rtc_stop_timer(struct qemu_alarm_timer *t);
908 #endif /* __linux__ */
910 #endif /* _WIN32 */
912 static struct qemu_alarm_timer alarm_timers[] = {
913 #ifndef _WIN32
914 #ifdef __linux__
915 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
916 dynticks_stop_timer, dynticks_rearm_timer, NULL},
917 /* HPET - if available - is preferred */
918 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
919 /* ...otherwise try RTC */
920 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
921 #endif
922 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
923 #else
924 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
925 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
926 {"win32", 0, win32_start_timer,
927 win32_stop_timer, NULL, &alarm_win32_data},
928 #endif
929 {NULL, }
932 static void show_available_alarms(void)
934 int i;
936 printf("Available alarm timers, in order of precedence:\n");
937 for (i = 0; alarm_timers[i].name; i++)
938 printf("%s\n", alarm_timers[i].name);
941 static void configure_alarms(char const *opt)
943 int i;
944 int cur = 0;
945 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
946 char *arg;
947 char *name;
949 if (!strcmp(opt, "?")) {
950 show_available_alarms();
951 exit(0);
954 arg = strdup(opt);
956 /* Reorder the array */
957 name = strtok(arg, ",");
958 while (name) {
959 struct qemu_alarm_timer tmp;
961 for (i = 0; i < count && alarm_timers[i].name; i++) {
962 if (!strcmp(alarm_timers[i].name, name))
963 break;
966 if (i == count) {
967 fprintf(stderr, "Unknown clock %s\n", name);
968 goto next;
971 if (i < cur)
972 /* Ignore */
973 goto next;
975 /* Swap */
976 tmp = alarm_timers[i];
977 alarm_timers[i] = alarm_timers[cur];
978 alarm_timers[cur] = tmp;
980 cur++;
981 next:
982 name = strtok(NULL, ",");
985 free(arg);
987 if (cur) {
988 /* Disable remaining timers */
989 for (i = cur; i < count; i++)
990 alarm_timers[i].name = NULL;
991 } else {
992 show_available_alarms();
993 exit(1);
997 QEMUClock *rt_clock;
998 QEMUClock *vm_clock;
1000 static QEMUTimer *active_timers[2];
1002 static QEMUClock *qemu_new_clock(int type)
1004 QEMUClock *clock;
1005 clock = qemu_mallocz(sizeof(QEMUClock));
1006 if (!clock)
1007 return NULL;
1008 clock->type = type;
1009 return clock;
1012 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1014 QEMUTimer *ts;
1016 ts = qemu_mallocz(sizeof(QEMUTimer));
1017 ts->clock = clock;
1018 ts->cb = cb;
1019 ts->opaque = opaque;
1020 return ts;
1023 void qemu_free_timer(QEMUTimer *ts)
1025 qemu_free(ts);
1028 /* stop a timer, but do not dealloc it */
1029 void qemu_del_timer(QEMUTimer *ts)
1031 QEMUTimer **pt, *t;
1033 /* NOTE: this code must be signal safe because
1034 qemu_timer_expired() can be called from a signal. */
1035 pt = &active_timers[ts->clock->type];
1036 for(;;) {
1037 t = *pt;
1038 if (!t)
1039 break;
1040 if (t == ts) {
1041 *pt = t->next;
1042 break;
1044 pt = &t->next;
1048 /* modify the current timer so that it will be fired when current_time
1049 >= expire_time. The corresponding callback will be called. */
1050 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1052 QEMUTimer **pt, *t;
1054 qemu_del_timer(ts);
1056 /* add the timer in the sorted list */
1057 /* NOTE: this code must be signal safe because
1058 qemu_timer_expired() can be called from a signal. */
1059 pt = &active_timers[ts->clock->type];
1060 for(;;) {
1061 t = *pt;
1062 if (!t)
1063 break;
1064 if (t->expire_time > expire_time)
1065 break;
1066 pt = &t->next;
1068 ts->expire_time = expire_time;
1069 ts->next = *pt;
1070 *pt = ts;
1072 /* Rearm if necessary */
1073 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1074 pt == &active_timers[ts->clock->type])
1075 qemu_rearm_alarm_timer(alarm_timer);
1078 int qemu_timer_pending(QEMUTimer *ts)
1080 QEMUTimer *t;
1081 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1082 if (t == ts)
1083 return 1;
1085 return 0;
1088 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1090 if (!timer_head)
1091 return 0;
1092 return (timer_head->expire_time <= current_time);
1095 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1097 QEMUTimer *ts;
1099 for(;;) {
1100 ts = *ptimer_head;
1101 if (!ts || ts->expire_time > current_time)
1102 break;
1103 /* remove timer from the list before calling the callback */
1104 *ptimer_head = ts->next;
1105 ts->next = NULL;
1107 /* run the callback (the timer list can be modified) */
1108 ts->cb(ts->opaque);
1112 int64_t qemu_get_clock(QEMUClock *clock)
1114 switch(clock->type) {
1115 case QEMU_TIMER_REALTIME:
1116 return get_clock() / 1000000;
1117 default:
1118 case QEMU_TIMER_VIRTUAL:
1119 return cpu_get_clock();
1123 static void init_timers(void)
1125 init_get_clock();
1126 ticks_per_sec = QEMU_TIMER_BASE;
1127 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1128 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1131 /* save a timer */
1132 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1134 uint64_t expire_time;
1136 if (qemu_timer_pending(ts)) {
1137 expire_time = ts->expire_time;
1138 } else {
1139 expire_time = -1;
1141 qemu_put_be64(f, expire_time);
1144 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1146 uint64_t expire_time;
1148 expire_time = qemu_get_be64(f);
1149 if (expire_time != -1) {
1150 qemu_mod_timer(ts, expire_time);
1151 } else {
1152 qemu_del_timer(ts);
1156 static void timer_save(QEMUFile *f, void *opaque)
1158 if (cpu_ticks_enabled) {
1159 hw_error("cannot save state if virtual timers are running");
1161 qemu_put_be64(f, cpu_ticks_offset);
1162 qemu_put_be64(f, ticks_per_sec);
1163 qemu_put_be64(f, cpu_clock_offset);
1166 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1168 if (version_id != 1 && version_id != 2)
1169 return -EINVAL;
1170 if (cpu_ticks_enabled) {
1171 return -EINVAL;
1173 cpu_ticks_offset=qemu_get_be64(f);
1174 ticks_per_sec=qemu_get_be64(f);
1175 if (version_id == 2) {
1176 cpu_clock_offset=qemu_get_be64(f);
1178 return 0;
1181 #ifdef _WIN32
1182 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1183 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1184 #else
1185 static void host_alarm_handler(int host_signum)
1186 #endif
1188 #if 0
1189 #define DISP_FREQ 1000
1191 static int64_t delta_min = INT64_MAX;
1192 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1193 static int count;
1194 ti = qemu_get_clock(vm_clock);
1195 if (last_clock != 0) {
1196 delta = ti - last_clock;
1197 if (delta < delta_min)
1198 delta_min = delta;
1199 if (delta > delta_max)
1200 delta_max = delta;
1201 delta_cum += delta;
1202 if (++count == DISP_FREQ) {
1203 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1204 muldiv64(delta_min, 1000000, ticks_per_sec),
1205 muldiv64(delta_max, 1000000, ticks_per_sec),
1206 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1207 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1208 count = 0;
1209 delta_min = INT64_MAX;
1210 delta_max = 0;
1211 delta_cum = 0;
1214 last_clock = ti;
1216 #endif
1217 if (1 ||
1218 alarm_has_dynticks(alarm_timer) ||
1219 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1220 qemu_get_clock(vm_clock)) ||
1221 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1222 qemu_get_clock(rt_clock))) {
1223 #ifdef _WIN32
1224 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1225 SetEvent(data->host_alarm);
1226 #endif
1227 CPUState *env = next_cpu;
1229 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1231 if (env) {
1232 /* stop the currently executing cpu because a timer occured */
1233 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1234 #ifdef USE_KQEMU
1235 if (env->kqemu_enabled) {
1236 kqemu_cpu_interrupt(env);
1238 #endif
1240 event_pending = 1;
1244 static uint64_t qemu_next_deadline(void)
1246 int64_t nearest_delta_us = INT64_MAX;
1247 int64_t vmdelta_us;
1249 if (active_timers[QEMU_TIMER_REALTIME])
1250 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1251 qemu_get_clock(rt_clock))*1000;
1253 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1254 /* round up */
1255 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1256 qemu_get_clock(vm_clock)+999)/1000;
1257 if (vmdelta_us < nearest_delta_us)
1258 nearest_delta_us = vmdelta_us;
1261 /* Avoid arming the timer to negative, zero, or too low values */
1262 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1263 nearest_delta_us = MIN_TIMER_REARM_US;
1265 return nearest_delta_us;
1268 #ifndef _WIN32
1270 #if defined(__linux__)
1272 #define RTC_FREQ 1024
1274 static void enable_sigio_timer(int fd)
1276 struct sigaction act;
1278 /* timer signal */
1279 sigfillset(&act.sa_mask);
1280 act.sa_flags = 0;
1281 act.sa_handler = host_alarm_handler;
1283 sigaction(SIGIO, &act, NULL);
1284 fcntl(fd, F_SETFL, O_ASYNC);
1285 fcntl(fd, F_SETOWN, getpid());
1288 static int hpet_start_timer(struct qemu_alarm_timer *t)
1290 struct hpet_info info;
1291 int r, fd;
1293 fd = open("/dev/hpet", O_RDONLY);
1294 if (fd < 0)
1295 return -1;
1297 /* Set frequency */
1298 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1299 if (r < 0) {
1300 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1301 "error, but for better emulation accuracy type:\n"
1302 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1303 goto fail;
1306 /* Check capabilities */
1307 r = ioctl(fd, HPET_INFO, &info);
1308 if (r < 0)
1309 goto fail;
1311 /* Enable periodic mode */
1312 r = ioctl(fd, HPET_EPI, 0);
1313 if (info.hi_flags && (r < 0))
1314 goto fail;
1316 /* Enable interrupt */
1317 r = ioctl(fd, HPET_IE_ON, 0);
1318 if (r < 0)
1319 goto fail;
1321 enable_sigio_timer(fd);
1322 t->priv = (void *)(long)fd;
1324 return 0;
1325 fail:
1326 close(fd);
1327 return -1;
1330 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1332 int fd = (long)t->priv;
1334 close(fd);
1337 static int rtc_start_timer(struct qemu_alarm_timer *t)
1339 int rtc_fd;
1340 unsigned long current_rtc_freq = 0;
1342 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1343 if (rtc_fd < 0)
1344 return -1;
1345 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1346 if (current_rtc_freq != RTC_FREQ &&
1347 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1348 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1349 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1350 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1351 goto fail;
1353 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1354 fail:
1355 close(rtc_fd);
1356 return -1;
1359 enable_sigio_timer(rtc_fd);
1361 t->priv = (void *)(long)rtc_fd;
1363 return 0;
1366 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1368 int rtc_fd = (long)t->priv;
1370 close(rtc_fd);
1373 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1375 struct sigevent ev;
1376 timer_t host_timer;
1377 struct sigaction act;
1379 sigfillset(&act.sa_mask);
1380 act.sa_flags = 0;
1381 act.sa_handler = host_alarm_handler;
1383 sigaction(SIGALRM, &act, NULL);
1385 ev.sigev_value.sival_int = 0;
1386 ev.sigev_notify = SIGEV_SIGNAL;
1387 ev.sigev_signo = SIGALRM;
1389 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1390 perror("timer_create");
1392 /* disable dynticks */
1393 fprintf(stderr, "Dynamic Ticks disabled\n");
1395 return -1;
1398 t->priv = (void *)host_timer;
1400 return 0;
1403 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1405 timer_t host_timer = (timer_t)t->priv;
1407 timer_delete(host_timer);
1410 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1412 timer_t host_timer = (timer_t)t->priv;
1413 struct itimerspec timeout;
1414 int64_t nearest_delta_us = INT64_MAX;
1415 int64_t current_us;
1417 if (!active_timers[QEMU_TIMER_REALTIME] &&
1418 !active_timers[QEMU_TIMER_VIRTUAL])
1419 return;
1421 nearest_delta_us = qemu_next_deadline();
1423 /* check whether a timer is already running */
1424 if (timer_gettime(host_timer, &timeout)) {
1425 perror("gettime");
1426 fprintf(stderr, "Internal timer error: aborting\n");
1427 exit(1);
1429 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1430 if (current_us && current_us <= nearest_delta_us)
1431 return;
1433 timeout.it_interval.tv_sec = 0;
1434 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1435 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1436 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1437 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1438 perror("settime");
1439 fprintf(stderr, "Internal timer error: aborting\n");
1440 exit(1);
1444 #endif /* defined(__linux__) */
1446 static int unix_start_timer(struct qemu_alarm_timer *t)
1448 struct sigaction act;
1449 struct itimerval itv;
1450 int err;
1452 /* timer signal */
1453 sigfillset(&act.sa_mask);
1454 act.sa_flags = 0;
1455 act.sa_handler = host_alarm_handler;
1457 sigaction(SIGALRM, &act, NULL);
1459 itv.it_interval.tv_sec = 0;
1460 /* for i386 kernel 2.6 to get 1 ms */
1461 itv.it_interval.tv_usec = 999;
1462 itv.it_value.tv_sec = 0;
1463 itv.it_value.tv_usec = 10 * 1000;
1465 err = setitimer(ITIMER_REAL, &itv, NULL);
1466 if (err)
1467 return -1;
1469 return 0;
1472 static void unix_stop_timer(struct qemu_alarm_timer *t)
1474 struct itimerval itv;
1476 memset(&itv, 0, sizeof(itv));
1477 setitimer(ITIMER_REAL, &itv, NULL);
1480 #endif /* !defined(_WIN32) */
1482 #ifdef _WIN32
1484 static int win32_start_timer(struct qemu_alarm_timer *t)
1486 TIMECAPS tc;
1487 struct qemu_alarm_win32 *data = t->priv;
1488 UINT flags;
1490 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1491 if (!data->host_alarm) {
1492 perror("Failed CreateEvent");
1493 return -1;
1496 memset(&tc, 0, sizeof(tc));
1497 timeGetDevCaps(&tc, sizeof(tc));
1499 if (data->period < tc.wPeriodMin)
1500 data->period = tc.wPeriodMin;
1502 timeBeginPeriod(data->period);
1504 flags = TIME_CALLBACK_FUNCTION;
1505 if (alarm_has_dynticks(t))
1506 flags |= TIME_ONESHOT;
1507 else
1508 flags |= TIME_PERIODIC;
1510 data->timerId = timeSetEvent(1, // interval (ms)
1511 data->period, // resolution
1512 host_alarm_handler, // function
1513 (DWORD)t, // parameter
1514 flags);
1516 if (!data->timerId) {
1517 perror("Failed to initialize win32 alarm timer");
1519 timeEndPeriod(data->period);
1520 CloseHandle(data->host_alarm);
1521 return -1;
1524 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1526 return 0;
1529 static void win32_stop_timer(struct qemu_alarm_timer *t)
1531 struct qemu_alarm_win32 *data = t->priv;
1533 timeKillEvent(data->timerId);
1534 timeEndPeriod(data->period);
1536 CloseHandle(data->host_alarm);
1539 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1541 struct qemu_alarm_win32 *data = t->priv;
1542 uint64_t nearest_delta_us;
1544 if (!active_timers[QEMU_TIMER_REALTIME] &&
1545 !active_timers[QEMU_TIMER_VIRTUAL])
1546 return;
1548 nearest_delta_us = qemu_next_deadline();
1549 nearest_delta_us /= 1000;
1551 timeKillEvent(data->timerId);
1553 data->timerId = timeSetEvent(1,
1554 data->period,
1555 host_alarm_handler,
1556 (DWORD)t,
1557 TIME_ONESHOT | TIME_PERIODIC);
1559 if (!data->timerId) {
1560 perror("Failed to re-arm win32 alarm timer");
1562 timeEndPeriod(data->period);
1563 CloseHandle(data->host_alarm);
1564 exit(1);
1568 #endif /* _WIN32 */
1570 static void init_timer_alarm(void)
1572 struct qemu_alarm_timer *t;
1573 int i, err = -1;
1575 for (i = 0; alarm_timers[i].name; i++) {
1576 t = &alarm_timers[i];
1578 err = t->start(t);
1579 if (!err)
1580 break;
1583 if (err) {
1584 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1585 fprintf(stderr, "Terminating\n");
1586 exit(1);
1589 alarm_timer = t;
1592 static void quit_timers(void)
1594 alarm_timer->stop(alarm_timer);
1595 alarm_timer = NULL;
1598 /***********************************************************/
1599 /* host time/date access */
1600 void qemu_get_timedate(struct tm *tm, int offset)
1602 time_t ti;
1603 struct tm *ret;
1605 time(&ti);
1606 ti += offset;
1607 if (rtc_date_offset == -1) {
1608 if (rtc_utc)
1609 ret = gmtime(&ti);
1610 else
1611 ret = localtime(&ti);
1612 } else {
1613 ti -= rtc_date_offset;
1614 ret = gmtime(&ti);
1617 memcpy(tm, ret, sizeof(struct tm));
1620 int qemu_timedate_diff(struct tm *tm)
1622 time_t seconds;
1624 if (rtc_date_offset == -1)
1625 if (rtc_utc)
1626 seconds = mktimegm(tm);
1627 else
1628 seconds = mktime(tm);
1629 else
1630 seconds = mktimegm(tm) + rtc_date_offset;
1632 return seconds - time(NULL);
1635 /***********************************************************/
1636 /* character device */
1638 static void qemu_chr_event(CharDriverState *s, int event)
1640 if (!s->chr_event)
1641 return;
1642 s->chr_event(s->handler_opaque, event);
1645 static void qemu_chr_reset_bh(void *opaque)
1647 CharDriverState *s = opaque;
1648 qemu_chr_event(s, CHR_EVENT_RESET);
1649 qemu_bh_delete(s->bh);
1650 s->bh = NULL;
1653 void qemu_chr_reset(CharDriverState *s)
1655 if (s->bh == NULL) {
1656 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1657 qemu_bh_schedule(s->bh);
1661 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1663 return s->chr_write(s, buf, len);
1666 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1668 if (!s->chr_ioctl)
1669 return -ENOTSUP;
1670 return s->chr_ioctl(s, cmd, arg);
1673 int qemu_chr_can_read(CharDriverState *s)
1675 if (!s->chr_can_read)
1676 return 0;
1677 return s->chr_can_read(s->handler_opaque);
1680 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1682 s->chr_read(s->handler_opaque, buf, len);
1685 void qemu_chr_accept_input(CharDriverState *s)
1687 if (s->chr_accept_input)
1688 s->chr_accept_input(s);
1691 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1693 char buf[4096];
1694 va_list ap;
1695 va_start(ap, fmt);
1696 vsnprintf(buf, sizeof(buf), fmt, ap);
1697 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1698 va_end(ap);
1701 void qemu_chr_send_event(CharDriverState *s, int event)
1703 if (s->chr_send_event)
1704 s->chr_send_event(s, event);
1707 void qemu_chr_add_handlers(CharDriverState *s,
1708 IOCanRWHandler *fd_can_read,
1709 IOReadHandler *fd_read,
1710 IOEventHandler *fd_event,
1711 void *opaque)
1713 s->chr_can_read = fd_can_read;
1714 s->chr_read = fd_read;
1715 s->chr_event = fd_event;
1716 s->handler_opaque = opaque;
1717 if (s->chr_update_read_handler)
1718 s->chr_update_read_handler(s);
1721 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1723 return len;
1726 static CharDriverState *qemu_chr_open_null(void)
1728 CharDriverState *chr;
1730 chr = qemu_mallocz(sizeof(CharDriverState));
1731 if (!chr)
1732 return NULL;
1733 chr->chr_write = null_chr_write;
1734 return chr;
1737 /* MUX driver for serial I/O splitting */
1738 static int term_timestamps;
1739 static int64_t term_timestamps_start;
1740 #define MAX_MUX 4
1741 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1742 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1743 typedef struct {
1744 IOCanRWHandler *chr_can_read[MAX_MUX];
1745 IOReadHandler *chr_read[MAX_MUX];
1746 IOEventHandler *chr_event[MAX_MUX];
1747 void *ext_opaque[MAX_MUX];
1748 CharDriverState *drv;
1749 unsigned char buffer[MUX_BUFFER_SIZE];
1750 int prod;
1751 int cons;
1752 int mux_cnt;
1753 int term_got_escape;
1754 int max_size;
1755 } MuxDriver;
1758 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1760 MuxDriver *d = chr->opaque;
1761 int ret;
1762 if (!term_timestamps) {
1763 ret = d->drv->chr_write(d->drv, buf, len);
1764 } else {
1765 int i;
1767 ret = 0;
1768 for(i = 0; i < len; i++) {
1769 ret += d->drv->chr_write(d->drv, buf+i, 1);
1770 if (buf[i] == '\n') {
1771 char buf1[64];
1772 int64_t ti;
1773 int secs;
1775 ti = get_clock();
1776 if (term_timestamps_start == -1)
1777 term_timestamps_start = ti;
1778 ti -= term_timestamps_start;
1779 secs = ti / 1000000000;
1780 snprintf(buf1, sizeof(buf1),
1781 "[%02d:%02d:%02d.%03d] ",
1782 secs / 3600,
1783 (secs / 60) % 60,
1784 secs % 60,
1785 (int)((ti / 1000000) % 1000));
1786 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1790 return ret;
1793 static char *mux_help[] = {
1794 "% h print this help\n\r",
1795 "% x exit emulator\n\r",
1796 "% s save disk data back to file (if -snapshot)\n\r",
1797 "% t toggle console timestamps\n\r"
1798 "% b send break (magic sysrq)\n\r",
1799 "% c switch between console and monitor\n\r",
1800 "% % sends %\n\r",
1801 NULL
1804 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1805 static void mux_print_help(CharDriverState *chr)
1807 int i, j;
1808 char ebuf[15] = "Escape-Char";
1809 char cbuf[50] = "\n\r";
1811 if (term_escape_char > 0 && term_escape_char < 26) {
1812 sprintf(cbuf,"\n\r");
1813 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1814 } else {
1815 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1816 term_escape_char);
1818 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1819 for (i = 0; mux_help[i] != NULL; i++) {
1820 for (j=0; mux_help[i][j] != '\0'; j++) {
1821 if (mux_help[i][j] == '%')
1822 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1823 else
1824 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1829 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1831 if (d->term_got_escape) {
1832 d->term_got_escape = 0;
1833 if (ch == term_escape_char)
1834 goto send_char;
1835 switch(ch) {
1836 case '?':
1837 case 'h':
1838 mux_print_help(chr);
1839 break;
1840 case 'x':
1842 char *term = "QEMU: Terminated\n\r";
1843 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1844 exit(0);
1845 break;
1847 case 's':
1849 int i;
1850 for (i = 0; i < nb_drives; i++) {
1851 bdrv_commit(drives_table[i].bdrv);
1854 break;
1855 case 'b':
1856 qemu_chr_event(chr, CHR_EVENT_BREAK);
1857 break;
1858 case 'c':
1859 /* Switch to the next registered device */
1860 chr->focus++;
1861 if (chr->focus >= d->mux_cnt)
1862 chr->focus = 0;
1863 break;
1864 case 't':
1865 term_timestamps = !term_timestamps;
1866 term_timestamps_start = -1;
1867 break;
1869 } else if (ch == term_escape_char) {
1870 d->term_got_escape = 1;
1871 } else {
1872 send_char:
1873 return 1;
1875 return 0;
1878 static void mux_chr_accept_input(CharDriverState *chr)
1880 int m = chr->focus;
1881 MuxDriver *d = chr->opaque;
1883 while (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],
1887 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1891 static int mux_chr_can_read(void *opaque)
1893 CharDriverState *chr = opaque;
1894 MuxDriver *d = chr->opaque;
1896 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1897 return 1;
1898 if (d->chr_can_read[chr->focus])
1899 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1900 return 0;
1903 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1905 CharDriverState *chr = opaque;
1906 MuxDriver *d = chr->opaque;
1907 int m = chr->focus;
1908 int i;
1910 mux_chr_accept_input (opaque);
1912 for(i = 0; i < size; i++)
1913 if (mux_proc_byte(chr, d, buf[i])) {
1914 if (d->prod == d->cons &&
1915 d->chr_can_read[m] &&
1916 d->chr_can_read[m](d->ext_opaque[m]))
1917 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1918 else
1919 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1923 static void mux_chr_event(void *opaque, int event)
1925 CharDriverState *chr = opaque;
1926 MuxDriver *d = chr->opaque;
1927 int i;
1929 /* Send the event to all registered listeners */
1930 for (i = 0; i < d->mux_cnt; i++)
1931 if (d->chr_event[i])
1932 d->chr_event[i](d->ext_opaque[i], event);
1935 static void mux_chr_update_read_handler(CharDriverState *chr)
1937 MuxDriver *d = chr->opaque;
1939 if (d->mux_cnt >= MAX_MUX) {
1940 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1941 return;
1943 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1944 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1945 d->chr_read[d->mux_cnt] = chr->chr_read;
1946 d->chr_event[d->mux_cnt] = chr->chr_event;
1947 /* Fix up the real driver with mux routines */
1948 if (d->mux_cnt == 0) {
1949 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1950 mux_chr_event, chr);
1952 chr->focus = d->mux_cnt;
1953 d->mux_cnt++;
1956 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1958 CharDriverState *chr;
1959 MuxDriver *d;
1961 chr = qemu_mallocz(sizeof(CharDriverState));
1962 if (!chr)
1963 return NULL;
1964 d = qemu_mallocz(sizeof(MuxDriver));
1965 if (!d) {
1966 free(chr);
1967 return NULL;
1970 chr->opaque = d;
1971 d->drv = drv;
1972 chr->focus = -1;
1973 chr->chr_write = mux_chr_write;
1974 chr->chr_update_read_handler = mux_chr_update_read_handler;
1975 chr->chr_accept_input = mux_chr_accept_input;
1976 return chr;
1980 #ifdef _WIN32
1982 static void socket_cleanup(void)
1984 WSACleanup();
1987 static int socket_init(void)
1989 WSADATA Data;
1990 int ret, err;
1992 ret = WSAStartup(MAKEWORD(2,2), &Data);
1993 if (ret != 0) {
1994 err = WSAGetLastError();
1995 fprintf(stderr, "WSAStartup: %d\n", err);
1996 return -1;
1998 atexit(socket_cleanup);
1999 return 0;
2002 static int send_all(int fd, const uint8_t *buf, int len1)
2004 int ret, len;
2006 len = len1;
2007 while (len > 0) {
2008 ret = send(fd, buf, len, 0);
2009 if (ret < 0) {
2010 int errno;
2011 errno = WSAGetLastError();
2012 if (errno != WSAEWOULDBLOCK) {
2013 return -1;
2015 } else if (ret == 0) {
2016 break;
2017 } else {
2018 buf += ret;
2019 len -= ret;
2022 return len1 - len;
2025 void socket_set_nonblock(int fd)
2027 unsigned long opt = 1;
2028 ioctlsocket(fd, FIONBIO, &opt);
2031 #else
2033 static int unix_write(int fd, const uint8_t *buf, int len1)
2035 int ret, len;
2037 len = len1;
2038 while (len > 0) {
2039 ret = write(fd, buf, len);
2040 if (ret < 0) {
2041 if (errno != EINTR && errno != EAGAIN)
2042 return -1;
2043 } else if (ret == 0) {
2044 break;
2045 } else {
2046 buf += ret;
2047 len -= ret;
2050 return len1 - len;
2053 static inline int send_all(int fd, const uint8_t *buf, int len1)
2055 return unix_write(fd, buf, len1);
2058 void socket_set_nonblock(int fd)
2060 fcntl(fd, F_SETFL, O_NONBLOCK);
2062 #endif /* !_WIN32 */
2064 #ifndef _WIN32
2066 typedef struct {
2067 int fd_in, fd_out;
2068 int max_size;
2069 } FDCharDriver;
2071 #define STDIO_MAX_CLIENTS 1
2072 static int stdio_nb_clients = 0;
2074 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2076 FDCharDriver *s = chr->opaque;
2077 return unix_write(s->fd_out, buf, len);
2080 static int fd_chr_read_poll(void *opaque)
2082 CharDriverState *chr = opaque;
2083 FDCharDriver *s = chr->opaque;
2085 s->max_size = qemu_chr_can_read(chr);
2086 return s->max_size;
2089 static void fd_chr_read(void *opaque)
2091 CharDriverState *chr = opaque;
2092 FDCharDriver *s = chr->opaque;
2093 int size, len;
2094 uint8_t buf[1024];
2096 len = sizeof(buf);
2097 if (len > s->max_size)
2098 len = s->max_size;
2099 if (len == 0)
2100 return;
2101 size = read(s->fd_in, buf, len);
2102 if (size == 0) {
2103 /* FD has been closed. Remove it from the active list. */
2104 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2105 return;
2107 if (size > 0) {
2108 qemu_chr_read(chr, buf, size);
2112 static void fd_chr_update_read_handler(CharDriverState *chr)
2114 FDCharDriver *s = chr->opaque;
2116 if (s->fd_in >= 0) {
2117 if (nographic && s->fd_in == 0) {
2118 } else {
2119 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2120 fd_chr_read, NULL, chr);
2125 static void fd_chr_close(struct CharDriverState *chr)
2127 FDCharDriver *s = chr->opaque;
2129 if (s->fd_in >= 0) {
2130 if (nographic && s->fd_in == 0) {
2131 } else {
2132 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2136 qemu_free(s);
2139 /* open a character device to a unix fd */
2140 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2142 CharDriverState *chr;
2143 FDCharDriver *s;
2145 chr = qemu_mallocz(sizeof(CharDriverState));
2146 if (!chr)
2147 return NULL;
2148 s = qemu_mallocz(sizeof(FDCharDriver));
2149 if (!s) {
2150 free(chr);
2151 return NULL;
2153 s->fd_in = fd_in;
2154 s->fd_out = fd_out;
2155 chr->opaque = s;
2156 chr->chr_write = fd_chr_write;
2157 chr->chr_update_read_handler = fd_chr_update_read_handler;
2158 chr->chr_close = fd_chr_close;
2160 qemu_chr_reset(chr);
2162 return chr;
2165 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2167 int fd_out;
2169 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2170 if (fd_out < 0)
2171 return NULL;
2172 return qemu_chr_open_fd(-1, fd_out);
2175 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2177 int fd_in, fd_out;
2178 char filename_in[256], filename_out[256];
2180 snprintf(filename_in, 256, "%s.in", filename);
2181 snprintf(filename_out, 256, "%s.out", filename);
2182 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2183 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2184 if (fd_in < 0 || fd_out < 0) {
2185 if (fd_in >= 0)
2186 close(fd_in);
2187 if (fd_out >= 0)
2188 close(fd_out);
2189 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2190 if (fd_in < 0)
2191 return NULL;
2193 return qemu_chr_open_fd(fd_in, fd_out);
2197 /* for STDIO, we handle the case where several clients use it
2198 (nographic mode) */
2200 #define TERM_FIFO_MAX_SIZE 1
2202 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2203 static int term_fifo_size;
2205 static int stdio_read_poll(void *opaque)
2207 CharDriverState *chr = opaque;
2209 /* try to flush the queue if needed */
2210 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2211 qemu_chr_read(chr, term_fifo, 1);
2212 term_fifo_size = 0;
2214 /* see if we can absorb more chars */
2215 if (term_fifo_size == 0)
2216 return 1;
2217 else
2218 return 0;
2221 static void stdio_read(void *opaque)
2223 int size;
2224 uint8_t buf[1];
2225 CharDriverState *chr = opaque;
2227 size = read(0, buf, 1);
2228 if (size == 0) {
2229 /* stdin has been closed. Remove it from the active list. */
2230 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2231 return;
2233 if (size > 0) {
2234 if (qemu_chr_can_read(chr) > 0) {
2235 qemu_chr_read(chr, buf, 1);
2236 } else if (term_fifo_size == 0) {
2237 term_fifo[term_fifo_size++] = buf[0];
2242 /* init terminal so that we can grab keys */
2243 static struct termios oldtty;
2244 static int old_fd0_flags;
2245 static int term_atexit_done;
2247 static void term_exit(void)
2249 tcsetattr (0, TCSANOW, &oldtty);
2250 fcntl(0, F_SETFL, old_fd0_flags);
2253 static void term_init(void)
2255 struct termios tty;
2257 tcgetattr (0, &tty);
2258 oldtty = tty;
2259 old_fd0_flags = fcntl(0, F_GETFL);
2261 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2262 |INLCR|IGNCR|ICRNL|IXON);
2263 tty.c_oflag |= OPOST;
2264 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2265 /* if graphical mode, we allow Ctrl-C handling */
2266 if (nographic)
2267 tty.c_lflag &= ~ISIG;
2268 tty.c_cflag &= ~(CSIZE|PARENB);
2269 tty.c_cflag |= CS8;
2270 tty.c_cc[VMIN] = 1;
2271 tty.c_cc[VTIME] = 0;
2273 tcsetattr (0, TCSANOW, &tty);
2275 if (!term_atexit_done++)
2276 atexit(term_exit);
2278 fcntl(0, F_SETFL, O_NONBLOCK);
2281 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2283 term_exit();
2284 stdio_nb_clients--;
2285 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2286 fd_chr_close(chr);
2289 static CharDriverState *qemu_chr_open_stdio(void)
2291 CharDriverState *chr;
2293 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2294 return NULL;
2295 chr = qemu_chr_open_fd(0, 1);
2296 chr->chr_close = qemu_chr_close_stdio;
2297 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2298 stdio_nb_clients++;
2299 term_init();
2301 return chr;
2304 #if defined(__linux__) || defined(__sun__)
2305 static CharDriverState *qemu_chr_open_pty(void)
2307 struct termios tty;
2308 char slave_name[1024];
2309 int master_fd, slave_fd;
2311 #if defined(__linux__)
2312 /* Not satisfying */
2313 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2314 return NULL;
2316 #endif
2318 /* Disabling local echo and line-buffered output */
2319 tcgetattr (master_fd, &tty);
2320 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2321 tty.c_cc[VMIN] = 1;
2322 tty.c_cc[VTIME] = 0;
2323 tcsetattr (master_fd, TCSAFLUSH, &tty);
2325 fprintf(stderr, "char device redirected to %s\n", slave_name);
2326 return qemu_chr_open_fd(master_fd, master_fd);
2329 static void tty_serial_init(int fd, int speed,
2330 int parity, int data_bits, int stop_bits)
2332 struct termios tty;
2333 speed_t spd;
2335 #if 0
2336 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2337 speed, parity, data_bits, stop_bits);
2338 #endif
2339 tcgetattr (fd, &tty);
2341 #define MARGIN 1.1
2342 if (speed <= 50 * MARGIN)
2343 spd = B50;
2344 else if (speed <= 75 * MARGIN)
2345 spd = B75;
2346 else if (speed <= 300 * MARGIN)
2347 spd = B300;
2348 else if (speed <= 600 * MARGIN)
2349 spd = B600;
2350 else if (speed <= 1200 * MARGIN)
2351 spd = B1200;
2352 else if (speed <= 2400 * MARGIN)
2353 spd = B2400;
2354 else if (speed <= 4800 * MARGIN)
2355 spd = B4800;
2356 else if (speed <= 9600 * MARGIN)
2357 spd = B9600;
2358 else if (speed <= 19200 * MARGIN)
2359 spd = B19200;
2360 else if (speed <= 38400 * MARGIN)
2361 spd = B38400;
2362 else if (speed <= 57600 * MARGIN)
2363 spd = B57600;
2364 else if (speed <= 115200 * MARGIN)
2365 spd = B115200;
2366 else
2367 spd = B115200;
2369 cfsetispeed(&tty, spd);
2370 cfsetospeed(&tty, spd);
2372 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2373 |INLCR|IGNCR|ICRNL|IXON);
2374 tty.c_oflag |= OPOST;
2375 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2376 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2377 switch(data_bits) {
2378 default:
2379 case 8:
2380 tty.c_cflag |= CS8;
2381 break;
2382 case 7:
2383 tty.c_cflag |= CS7;
2384 break;
2385 case 6:
2386 tty.c_cflag |= CS6;
2387 break;
2388 case 5:
2389 tty.c_cflag |= CS5;
2390 break;
2392 switch(parity) {
2393 default:
2394 case 'N':
2395 break;
2396 case 'E':
2397 tty.c_cflag |= PARENB;
2398 break;
2399 case 'O':
2400 tty.c_cflag |= PARENB | PARODD;
2401 break;
2403 if (stop_bits == 2)
2404 tty.c_cflag |= CSTOPB;
2406 tcsetattr (fd, TCSANOW, &tty);
2409 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2411 FDCharDriver *s = chr->opaque;
2413 switch(cmd) {
2414 case CHR_IOCTL_SERIAL_SET_PARAMS:
2416 QEMUSerialSetParams *ssp = arg;
2417 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2418 ssp->data_bits, ssp->stop_bits);
2420 break;
2421 case CHR_IOCTL_SERIAL_SET_BREAK:
2423 int enable = *(int *)arg;
2424 if (enable)
2425 tcsendbreak(s->fd_in, 1);
2427 break;
2428 default:
2429 return -ENOTSUP;
2431 return 0;
2434 static CharDriverState *qemu_chr_open_tty(const char *filename)
2436 CharDriverState *chr;
2437 int fd;
2439 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2440 fcntl(fd, F_SETFL, O_NONBLOCK);
2441 tty_serial_init(fd, 115200, 'N', 8, 1);
2442 chr = qemu_chr_open_fd(fd, fd);
2443 if (!chr) {
2444 close(fd);
2445 return NULL;
2447 chr->chr_ioctl = tty_serial_ioctl;
2448 qemu_chr_reset(chr);
2449 return chr;
2451 #else /* ! __linux__ && ! __sun__ */
2452 static CharDriverState *qemu_chr_open_pty(void)
2454 return NULL;
2456 #endif /* __linux__ || __sun__ */
2458 #if defined(__linux__)
2459 typedef struct {
2460 int fd;
2461 int mode;
2462 } ParallelCharDriver;
2464 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2466 if (s->mode != mode) {
2467 int m = mode;
2468 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2469 return 0;
2470 s->mode = mode;
2472 return 1;
2475 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2477 ParallelCharDriver *drv = chr->opaque;
2478 int fd = drv->fd;
2479 uint8_t b;
2481 switch(cmd) {
2482 case CHR_IOCTL_PP_READ_DATA:
2483 if (ioctl(fd, PPRDATA, &b) < 0)
2484 return -ENOTSUP;
2485 *(uint8_t *)arg = b;
2486 break;
2487 case CHR_IOCTL_PP_WRITE_DATA:
2488 b = *(uint8_t *)arg;
2489 if (ioctl(fd, PPWDATA, &b) < 0)
2490 return -ENOTSUP;
2491 break;
2492 case CHR_IOCTL_PP_READ_CONTROL:
2493 if (ioctl(fd, PPRCONTROL, &b) < 0)
2494 return -ENOTSUP;
2495 /* Linux gives only the lowest bits, and no way to know data
2496 direction! For better compatibility set the fixed upper
2497 bits. */
2498 *(uint8_t *)arg = b | 0xc0;
2499 break;
2500 case CHR_IOCTL_PP_WRITE_CONTROL:
2501 b = *(uint8_t *)arg;
2502 if (ioctl(fd, PPWCONTROL, &b) < 0)
2503 return -ENOTSUP;
2504 break;
2505 case CHR_IOCTL_PP_READ_STATUS:
2506 if (ioctl(fd, PPRSTATUS, &b) < 0)
2507 return -ENOTSUP;
2508 *(uint8_t *)arg = b;
2509 break;
2510 case CHR_IOCTL_PP_EPP_READ_ADDR:
2511 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2512 struct ParallelIOArg *parg = arg;
2513 int n = read(fd, parg->buffer, parg->count);
2514 if (n != parg->count) {
2515 return -EIO;
2518 break;
2519 case CHR_IOCTL_PP_EPP_READ:
2520 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2521 struct ParallelIOArg *parg = arg;
2522 int n = read(fd, parg->buffer, parg->count);
2523 if (n != parg->count) {
2524 return -EIO;
2527 break;
2528 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2529 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2530 struct ParallelIOArg *parg = arg;
2531 int n = write(fd, parg->buffer, parg->count);
2532 if (n != parg->count) {
2533 return -EIO;
2536 break;
2537 case CHR_IOCTL_PP_EPP_WRITE:
2538 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2539 struct ParallelIOArg *parg = arg;
2540 int n = write(fd, parg->buffer, parg->count);
2541 if (n != parg->count) {
2542 return -EIO;
2545 break;
2546 default:
2547 return -ENOTSUP;
2549 return 0;
2552 static void pp_close(CharDriverState *chr)
2554 ParallelCharDriver *drv = chr->opaque;
2555 int fd = drv->fd;
2557 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2558 ioctl(fd, PPRELEASE);
2559 close(fd);
2560 qemu_free(drv);
2563 static CharDriverState *qemu_chr_open_pp(const char *filename)
2565 CharDriverState *chr;
2566 ParallelCharDriver *drv;
2567 int fd;
2569 TFR(fd = open(filename, O_RDWR));
2570 if (fd < 0)
2571 return NULL;
2573 if (ioctl(fd, PPCLAIM) < 0) {
2574 close(fd);
2575 return NULL;
2578 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2579 if (!drv) {
2580 close(fd);
2581 return NULL;
2583 drv->fd = fd;
2584 drv->mode = IEEE1284_MODE_COMPAT;
2586 chr = qemu_mallocz(sizeof(CharDriverState));
2587 if (!chr) {
2588 qemu_free(drv);
2589 close(fd);
2590 return NULL;
2592 chr->chr_write = null_chr_write;
2593 chr->chr_ioctl = pp_ioctl;
2594 chr->chr_close = pp_close;
2595 chr->opaque = drv;
2597 qemu_chr_reset(chr);
2599 return chr;
2601 #endif /* __linux__ */
2603 #else /* _WIN32 */
2605 typedef struct {
2606 int max_size;
2607 HANDLE hcom, hrecv, hsend;
2608 OVERLAPPED orecv, osend;
2609 BOOL fpipe;
2610 DWORD len;
2611 } WinCharState;
2613 #define NSENDBUF 2048
2614 #define NRECVBUF 2048
2615 #define MAXCONNECT 1
2616 #define NTIMEOUT 5000
2618 static int win_chr_poll(void *opaque);
2619 static int win_chr_pipe_poll(void *opaque);
2621 static void win_chr_close(CharDriverState *chr)
2623 WinCharState *s = chr->opaque;
2625 if (s->hsend) {
2626 CloseHandle(s->hsend);
2627 s->hsend = NULL;
2629 if (s->hrecv) {
2630 CloseHandle(s->hrecv);
2631 s->hrecv = NULL;
2633 if (s->hcom) {
2634 CloseHandle(s->hcom);
2635 s->hcom = NULL;
2637 if (s->fpipe)
2638 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2639 else
2640 qemu_del_polling_cb(win_chr_poll, chr);
2643 static int win_chr_init(CharDriverState *chr, const char *filename)
2645 WinCharState *s = chr->opaque;
2646 COMMCONFIG comcfg;
2647 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2648 COMSTAT comstat;
2649 DWORD size;
2650 DWORD err;
2652 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2653 if (!s->hsend) {
2654 fprintf(stderr, "Failed CreateEvent\n");
2655 goto fail;
2657 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2658 if (!s->hrecv) {
2659 fprintf(stderr, "Failed CreateEvent\n");
2660 goto fail;
2663 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2664 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2665 if (s->hcom == INVALID_HANDLE_VALUE) {
2666 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2667 s->hcom = NULL;
2668 goto fail;
2671 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2672 fprintf(stderr, "Failed SetupComm\n");
2673 goto fail;
2676 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2677 size = sizeof(COMMCONFIG);
2678 GetDefaultCommConfig(filename, &comcfg, &size);
2679 comcfg.dcb.DCBlength = sizeof(DCB);
2680 CommConfigDialog(filename, NULL, &comcfg);
2682 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2683 fprintf(stderr, "Failed SetCommState\n");
2684 goto fail;
2687 if (!SetCommMask(s->hcom, EV_ERR)) {
2688 fprintf(stderr, "Failed SetCommMask\n");
2689 goto fail;
2692 cto.ReadIntervalTimeout = MAXDWORD;
2693 if (!SetCommTimeouts(s->hcom, &cto)) {
2694 fprintf(stderr, "Failed SetCommTimeouts\n");
2695 goto fail;
2698 if (!ClearCommError(s->hcom, &err, &comstat)) {
2699 fprintf(stderr, "Failed ClearCommError\n");
2700 goto fail;
2702 qemu_add_polling_cb(win_chr_poll, chr);
2703 return 0;
2705 fail:
2706 win_chr_close(chr);
2707 return -1;
2710 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2712 WinCharState *s = chr->opaque;
2713 DWORD len, ret, size, err;
2715 len = len1;
2716 ZeroMemory(&s->osend, sizeof(s->osend));
2717 s->osend.hEvent = s->hsend;
2718 while (len > 0) {
2719 if (s->hsend)
2720 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2721 else
2722 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2723 if (!ret) {
2724 err = GetLastError();
2725 if (err == ERROR_IO_PENDING) {
2726 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2727 if (ret) {
2728 buf += size;
2729 len -= size;
2730 } else {
2731 break;
2733 } else {
2734 break;
2736 } else {
2737 buf += size;
2738 len -= size;
2741 return len1 - len;
2744 static int win_chr_read_poll(CharDriverState *chr)
2746 WinCharState *s = chr->opaque;
2748 s->max_size = qemu_chr_can_read(chr);
2749 return s->max_size;
2752 static void win_chr_readfile(CharDriverState *chr)
2754 WinCharState *s = chr->opaque;
2755 int ret, err;
2756 uint8_t buf[1024];
2757 DWORD size;
2759 ZeroMemory(&s->orecv, sizeof(s->orecv));
2760 s->orecv.hEvent = s->hrecv;
2761 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2762 if (!ret) {
2763 err = GetLastError();
2764 if (err == ERROR_IO_PENDING) {
2765 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2769 if (size > 0) {
2770 qemu_chr_read(chr, buf, size);
2774 static void win_chr_read(CharDriverState *chr)
2776 WinCharState *s = chr->opaque;
2778 if (s->len > s->max_size)
2779 s->len = s->max_size;
2780 if (s->len == 0)
2781 return;
2783 win_chr_readfile(chr);
2786 static int win_chr_poll(void *opaque)
2788 CharDriverState *chr = opaque;
2789 WinCharState *s = chr->opaque;
2790 COMSTAT status;
2791 DWORD comerr;
2793 ClearCommError(s->hcom, &comerr, &status);
2794 if (status.cbInQue > 0) {
2795 s->len = status.cbInQue;
2796 win_chr_read_poll(chr);
2797 win_chr_read(chr);
2798 return 1;
2800 return 0;
2803 static CharDriverState *qemu_chr_open_win(const char *filename)
2805 CharDriverState *chr;
2806 WinCharState *s;
2808 chr = qemu_mallocz(sizeof(CharDriverState));
2809 if (!chr)
2810 return NULL;
2811 s = qemu_mallocz(sizeof(WinCharState));
2812 if (!s) {
2813 free(chr);
2814 return NULL;
2816 chr->opaque = s;
2817 chr->chr_write = win_chr_write;
2818 chr->chr_close = win_chr_close;
2820 if (win_chr_init(chr, filename) < 0) {
2821 free(s);
2822 free(chr);
2823 return NULL;
2825 qemu_chr_reset(chr);
2826 return chr;
2829 static int win_chr_pipe_poll(void *opaque)
2831 CharDriverState *chr = opaque;
2832 WinCharState *s = chr->opaque;
2833 DWORD size;
2835 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2836 if (size > 0) {
2837 s->len = size;
2838 win_chr_read_poll(chr);
2839 win_chr_read(chr);
2840 return 1;
2842 return 0;
2845 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2847 WinCharState *s = chr->opaque;
2848 OVERLAPPED ov;
2849 int ret;
2850 DWORD size;
2851 char openname[256];
2853 s->fpipe = TRUE;
2855 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2856 if (!s->hsend) {
2857 fprintf(stderr, "Failed CreateEvent\n");
2858 goto fail;
2860 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2861 if (!s->hrecv) {
2862 fprintf(stderr, "Failed CreateEvent\n");
2863 goto fail;
2866 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2867 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2868 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2869 PIPE_WAIT,
2870 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2871 if (s->hcom == INVALID_HANDLE_VALUE) {
2872 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2873 s->hcom = NULL;
2874 goto fail;
2877 ZeroMemory(&ov, sizeof(ov));
2878 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2879 ret = ConnectNamedPipe(s->hcom, &ov);
2880 if (ret) {
2881 fprintf(stderr, "Failed ConnectNamedPipe\n");
2882 goto fail;
2885 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2886 if (!ret) {
2887 fprintf(stderr, "Failed GetOverlappedResult\n");
2888 if (ov.hEvent) {
2889 CloseHandle(ov.hEvent);
2890 ov.hEvent = NULL;
2892 goto fail;
2895 if (ov.hEvent) {
2896 CloseHandle(ov.hEvent);
2897 ov.hEvent = NULL;
2899 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2900 return 0;
2902 fail:
2903 win_chr_close(chr);
2904 return -1;
2908 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2910 CharDriverState *chr;
2911 WinCharState *s;
2913 chr = qemu_mallocz(sizeof(CharDriverState));
2914 if (!chr)
2915 return NULL;
2916 s = qemu_mallocz(sizeof(WinCharState));
2917 if (!s) {
2918 free(chr);
2919 return NULL;
2921 chr->opaque = s;
2922 chr->chr_write = win_chr_write;
2923 chr->chr_close = win_chr_close;
2925 if (win_chr_pipe_init(chr, filename) < 0) {
2926 free(s);
2927 free(chr);
2928 return NULL;
2930 qemu_chr_reset(chr);
2931 return chr;
2934 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2936 CharDriverState *chr;
2937 WinCharState *s;
2939 chr = qemu_mallocz(sizeof(CharDriverState));
2940 if (!chr)
2941 return NULL;
2942 s = qemu_mallocz(sizeof(WinCharState));
2943 if (!s) {
2944 free(chr);
2945 return NULL;
2947 s->hcom = fd_out;
2948 chr->opaque = s;
2949 chr->chr_write = win_chr_write;
2950 qemu_chr_reset(chr);
2951 return chr;
2954 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2956 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2959 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2961 HANDLE fd_out;
2963 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2964 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2965 if (fd_out == INVALID_HANDLE_VALUE)
2966 return NULL;
2968 return qemu_chr_open_win_file(fd_out);
2970 #endif /* !_WIN32 */
2972 /***********************************************************/
2973 /* UDP Net console */
2975 typedef struct {
2976 int fd;
2977 struct sockaddr_in daddr;
2978 uint8_t buf[1024];
2979 int bufcnt;
2980 int bufptr;
2981 int max_size;
2982 } NetCharDriver;
2984 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2986 NetCharDriver *s = chr->opaque;
2988 return sendto(s->fd, buf, len, 0,
2989 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2992 static int udp_chr_read_poll(void *opaque)
2994 CharDriverState *chr = opaque;
2995 NetCharDriver *s = chr->opaque;
2997 s->max_size = qemu_chr_can_read(chr);
2999 /* If there were any stray characters in the queue process them
3000 * first
3002 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3003 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3004 s->bufptr++;
3005 s->max_size = qemu_chr_can_read(chr);
3007 return s->max_size;
3010 static void udp_chr_read(void *opaque)
3012 CharDriverState *chr = opaque;
3013 NetCharDriver *s = chr->opaque;
3015 if (s->max_size == 0)
3016 return;
3017 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3018 s->bufptr = s->bufcnt;
3019 if (s->bufcnt <= 0)
3020 return;
3022 s->bufptr = 0;
3023 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3024 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3025 s->bufptr++;
3026 s->max_size = qemu_chr_can_read(chr);
3030 static void udp_chr_update_read_handler(CharDriverState *chr)
3032 NetCharDriver *s = chr->opaque;
3034 if (s->fd >= 0) {
3035 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3036 udp_chr_read, NULL, chr);
3040 #ifndef _WIN32
3041 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3042 #endif
3043 int parse_host_src_port(struct sockaddr_in *haddr,
3044 struct sockaddr_in *saddr,
3045 const char *str);
3047 static CharDriverState *qemu_chr_open_udp(const char *def)
3049 CharDriverState *chr = NULL;
3050 NetCharDriver *s = NULL;
3051 int fd = -1;
3052 struct sockaddr_in saddr;
3054 chr = qemu_mallocz(sizeof(CharDriverState));
3055 if (!chr)
3056 goto return_err;
3057 s = qemu_mallocz(sizeof(NetCharDriver));
3058 if (!s)
3059 goto return_err;
3061 fd = socket(PF_INET, SOCK_DGRAM, 0);
3062 if (fd < 0) {
3063 perror("socket(PF_INET, SOCK_DGRAM)");
3064 goto return_err;
3067 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3068 printf("Could not parse: %s\n", def);
3069 goto return_err;
3072 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3074 perror("bind");
3075 goto return_err;
3078 s->fd = fd;
3079 s->bufcnt = 0;
3080 s->bufptr = 0;
3081 chr->opaque = s;
3082 chr->chr_write = udp_chr_write;
3083 chr->chr_update_read_handler = udp_chr_update_read_handler;
3084 return chr;
3086 return_err:
3087 if (chr)
3088 free(chr);
3089 if (s)
3090 free(s);
3091 if (fd >= 0)
3092 closesocket(fd);
3093 return NULL;
3096 /***********************************************************/
3097 /* TCP Net console */
3099 typedef struct {
3100 int fd, listen_fd;
3101 int connected;
3102 int max_size;
3103 int do_telnetopt;
3104 int do_nodelay;
3105 int is_unix;
3106 } TCPCharDriver;
3108 static void tcp_chr_accept(void *opaque);
3110 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3112 TCPCharDriver *s = chr->opaque;
3113 if (s->connected) {
3114 return send_all(s->fd, buf, len);
3115 } else {
3116 /* XXX: indicate an error ? */
3117 return len;
3121 static int tcp_chr_read_poll(void *opaque)
3123 CharDriverState *chr = opaque;
3124 TCPCharDriver *s = chr->opaque;
3125 if (!s->connected)
3126 return 0;
3127 s->max_size = qemu_chr_can_read(chr);
3128 return s->max_size;
3131 #define IAC 255
3132 #define IAC_BREAK 243
3133 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3134 TCPCharDriver *s,
3135 uint8_t *buf, int *size)
3137 /* Handle any telnet client's basic IAC options to satisfy char by
3138 * char mode with no echo. All IAC options will be removed from
3139 * the buf and the do_telnetopt variable will be used to track the
3140 * state of the width of the IAC information.
3142 * IAC commands come in sets of 3 bytes with the exception of the
3143 * "IAC BREAK" command and the double IAC.
3146 int i;
3147 int j = 0;
3149 for (i = 0; i < *size; i++) {
3150 if (s->do_telnetopt > 1) {
3151 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3152 /* Double IAC means send an IAC */
3153 if (j != i)
3154 buf[j] = buf[i];
3155 j++;
3156 s->do_telnetopt = 1;
3157 } else {
3158 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3159 /* Handle IAC break commands by sending a serial break */
3160 qemu_chr_event(chr, CHR_EVENT_BREAK);
3161 s->do_telnetopt++;
3163 s->do_telnetopt++;
3165 if (s->do_telnetopt >= 4) {
3166 s->do_telnetopt = 1;
3168 } else {
3169 if ((unsigned char)buf[i] == IAC) {
3170 s->do_telnetopt = 2;
3171 } else {
3172 if (j != i)
3173 buf[j] = buf[i];
3174 j++;
3178 *size = j;
3181 static void tcp_chr_read(void *opaque)
3183 CharDriverState *chr = opaque;
3184 TCPCharDriver *s = chr->opaque;
3185 uint8_t buf[1024];
3186 int len, size;
3188 if (!s->connected || s->max_size <= 0)
3189 return;
3190 len = sizeof(buf);
3191 if (len > s->max_size)
3192 len = s->max_size;
3193 size = recv(s->fd, buf, len, 0);
3194 if (size == 0) {
3195 /* connection closed */
3196 s->connected = 0;
3197 if (s->listen_fd >= 0) {
3198 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3200 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3201 closesocket(s->fd);
3202 s->fd = -1;
3203 } else if (size > 0) {
3204 if (s->do_telnetopt)
3205 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3206 if (size > 0)
3207 qemu_chr_read(chr, buf, size);
3211 static void tcp_chr_connect(void *opaque)
3213 CharDriverState *chr = opaque;
3214 TCPCharDriver *s = chr->opaque;
3216 s->connected = 1;
3217 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3218 tcp_chr_read, NULL, chr);
3219 qemu_chr_reset(chr);
3222 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3223 static void tcp_chr_telnet_init(int fd)
3225 char buf[3];
3226 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3227 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3228 send(fd, (char *)buf, 3, 0);
3229 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3230 send(fd, (char *)buf, 3, 0);
3231 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3232 send(fd, (char *)buf, 3, 0);
3233 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3234 send(fd, (char *)buf, 3, 0);
3237 static void socket_set_nodelay(int fd)
3239 int val = 1;
3240 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3243 static void tcp_chr_accept(void *opaque)
3245 CharDriverState *chr = opaque;
3246 TCPCharDriver *s = chr->opaque;
3247 struct sockaddr_in saddr;
3248 #ifndef _WIN32
3249 struct sockaddr_un uaddr;
3250 #endif
3251 struct sockaddr *addr;
3252 socklen_t len;
3253 int fd;
3255 for(;;) {
3256 #ifndef _WIN32
3257 if (s->is_unix) {
3258 len = sizeof(uaddr);
3259 addr = (struct sockaddr *)&uaddr;
3260 } else
3261 #endif
3263 len = sizeof(saddr);
3264 addr = (struct sockaddr *)&saddr;
3266 fd = accept(s->listen_fd, addr, &len);
3267 if (fd < 0 && errno != EINTR) {
3268 return;
3269 } else if (fd >= 0) {
3270 if (s->do_telnetopt)
3271 tcp_chr_telnet_init(fd);
3272 break;
3275 socket_set_nonblock(fd);
3276 if (s->do_nodelay)
3277 socket_set_nodelay(fd);
3278 s->fd = fd;
3279 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3280 tcp_chr_connect(chr);
3283 static void tcp_chr_close(CharDriverState *chr)
3285 TCPCharDriver *s = chr->opaque;
3286 if (s->fd >= 0)
3287 closesocket(s->fd);
3288 if (s->listen_fd >= 0)
3289 closesocket(s->listen_fd);
3290 qemu_free(s);
3293 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3294 int is_telnet,
3295 int is_unix)
3297 CharDriverState *chr = NULL;
3298 TCPCharDriver *s = NULL;
3299 int fd = -1, ret, err, val;
3300 int is_listen = 0;
3301 int is_waitconnect = 1;
3302 int do_nodelay = 0;
3303 const char *ptr;
3304 struct sockaddr_in saddr;
3305 #ifndef _WIN32
3306 struct sockaddr_un uaddr;
3307 #endif
3308 struct sockaddr *addr;
3309 socklen_t addrlen;
3311 #ifndef _WIN32
3312 if (is_unix) {
3313 addr = (struct sockaddr *)&uaddr;
3314 addrlen = sizeof(uaddr);
3315 if (parse_unix_path(&uaddr, host_str) < 0)
3316 goto fail;
3317 } else
3318 #endif
3320 addr = (struct sockaddr *)&saddr;
3321 addrlen = sizeof(saddr);
3322 if (parse_host_port(&saddr, host_str) < 0)
3323 goto fail;
3326 ptr = host_str;
3327 while((ptr = strchr(ptr,','))) {
3328 ptr++;
3329 if (!strncmp(ptr,"server",6)) {
3330 is_listen = 1;
3331 } else if (!strncmp(ptr,"nowait",6)) {
3332 is_waitconnect = 0;
3333 } else if (!strncmp(ptr,"nodelay",6)) {
3334 do_nodelay = 1;
3335 } else {
3336 printf("Unknown option: %s\n", ptr);
3337 goto fail;
3340 if (!is_listen)
3341 is_waitconnect = 0;
3343 chr = qemu_mallocz(sizeof(CharDriverState));
3344 if (!chr)
3345 goto fail;
3346 s = qemu_mallocz(sizeof(TCPCharDriver));
3347 if (!s)
3348 goto fail;
3350 #ifndef _WIN32
3351 if (is_unix)
3352 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3353 else
3354 #endif
3355 fd = socket(PF_INET, SOCK_STREAM, 0);
3357 if (fd < 0)
3358 goto fail;
3360 if (!is_waitconnect)
3361 socket_set_nonblock(fd);
3363 s->connected = 0;
3364 s->fd = -1;
3365 s->listen_fd = -1;
3366 s->is_unix = is_unix;
3367 s->do_nodelay = do_nodelay && !is_unix;
3369 chr->opaque = s;
3370 chr->chr_write = tcp_chr_write;
3371 chr->chr_close = tcp_chr_close;
3373 if (is_listen) {
3374 /* allow fast reuse */
3375 #ifndef _WIN32
3376 if (is_unix) {
3377 char path[109];
3378 strncpy(path, uaddr.sun_path, 108);
3379 path[108] = 0;
3380 unlink(path);
3381 } else
3382 #endif
3384 val = 1;
3385 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3388 ret = bind(fd, addr, addrlen);
3389 if (ret < 0)
3390 goto fail;
3392 ret = listen(fd, 0);
3393 if (ret < 0)
3394 goto fail;
3396 s->listen_fd = fd;
3397 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3398 if (is_telnet)
3399 s->do_telnetopt = 1;
3400 } else {
3401 for(;;) {
3402 ret = connect(fd, addr, addrlen);
3403 if (ret < 0) {
3404 err = socket_error();
3405 if (err == EINTR || err == EWOULDBLOCK) {
3406 } else if (err == EINPROGRESS) {
3407 break;
3408 #ifdef _WIN32
3409 } else if (err == WSAEALREADY) {
3410 break;
3411 #endif
3412 } else {
3413 goto fail;
3415 } else {
3416 s->connected = 1;
3417 break;
3420 s->fd = fd;
3421 socket_set_nodelay(fd);
3422 if (s->connected)
3423 tcp_chr_connect(chr);
3424 else
3425 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3428 if (is_listen && is_waitconnect) {
3429 printf("QEMU waiting for connection on: %s\n", host_str);
3430 tcp_chr_accept(chr);
3431 socket_set_nonblock(s->listen_fd);
3434 return chr;
3435 fail:
3436 if (fd >= 0)
3437 closesocket(fd);
3438 qemu_free(s);
3439 qemu_free(chr);
3440 return NULL;
3443 CharDriverState *qemu_chr_open(const char *filename)
3445 const char *p;
3447 if (!strcmp(filename, "vc")) {
3448 return text_console_init(&display_state, 0);
3449 } else if (strstart(filename, "vc:", &p)) {
3450 return text_console_init(&display_state, p);
3451 } else if (!strcmp(filename, "null")) {
3452 return qemu_chr_open_null();
3453 } else
3454 if (strstart(filename, "tcp:", &p)) {
3455 return qemu_chr_open_tcp(p, 0, 0);
3456 } else
3457 if (strstart(filename, "telnet:", &p)) {
3458 return qemu_chr_open_tcp(p, 1, 0);
3459 } else
3460 if (strstart(filename, "udp:", &p)) {
3461 return qemu_chr_open_udp(p);
3462 } else
3463 if (strstart(filename, "mon:", &p)) {
3464 CharDriverState *drv = qemu_chr_open(p);
3465 if (drv) {
3466 drv = qemu_chr_open_mux(drv);
3467 monitor_init(drv, !nographic);
3468 return drv;
3470 printf("Unable to open driver: %s\n", p);
3471 return 0;
3472 } else
3473 #ifndef _WIN32
3474 if (strstart(filename, "unix:", &p)) {
3475 return qemu_chr_open_tcp(p, 0, 1);
3476 } else if (strstart(filename, "file:", &p)) {
3477 return qemu_chr_open_file_out(p);
3478 } else if (strstart(filename, "pipe:", &p)) {
3479 return qemu_chr_open_pipe(p);
3480 } else if (!strcmp(filename, "pty")) {
3481 return qemu_chr_open_pty();
3482 } else if (!strcmp(filename, "stdio")) {
3483 return qemu_chr_open_stdio();
3484 } else
3485 #if defined(__linux__)
3486 if (strstart(filename, "/dev/parport", NULL)) {
3487 return qemu_chr_open_pp(filename);
3488 } else
3489 #endif
3490 #if defined(__linux__) || defined(__sun__)
3491 if (strstart(filename, "/dev/", NULL)) {
3492 return qemu_chr_open_tty(filename);
3493 } else
3494 #endif
3495 #else /* !_WIN32 */
3496 if (strstart(filename, "COM", NULL)) {
3497 return qemu_chr_open_win(filename);
3498 } else
3499 if (strstart(filename, "pipe:", &p)) {
3500 return qemu_chr_open_win_pipe(p);
3501 } else
3502 if (strstart(filename, "con:", NULL)) {
3503 return qemu_chr_open_win_con(filename);
3504 } else
3505 if (strstart(filename, "file:", &p)) {
3506 return qemu_chr_open_win_file_out(p);
3507 } else
3508 #endif
3509 #ifdef CONFIG_BRLAPI
3510 if (!strcmp(filename, "braille")) {
3511 return chr_baum_init();
3512 } else
3513 #endif
3515 return NULL;
3519 void qemu_chr_close(CharDriverState *chr)
3521 if (chr->chr_close)
3522 chr->chr_close(chr);
3523 qemu_free(chr);
3526 /***********************************************************/
3527 /* network device redirectors */
3529 __attribute__ (( unused ))
3530 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3532 int len, i, j, c;
3534 for(i=0;i<size;i+=16) {
3535 len = size - i;
3536 if (len > 16)
3537 len = 16;
3538 fprintf(f, "%08x ", i);
3539 for(j=0;j<16;j++) {
3540 if (j < len)
3541 fprintf(f, " %02x", buf[i+j]);
3542 else
3543 fprintf(f, " ");
3545 fprintf(f, " ");
3546 for(j=0;j<len;j++) {
3547 c = buf[i+j];
3548 if (c < ' ' || c > '~')
3549 c = '.';
3550 fprintf(f, "%c", c);
3552 fprintf(f, "\n");
3556 static int parse_macaddr(uint8_t *macaddr, const char *p)
3558 int i;
3559 char *last_char;
3560 long int offset;
3562 errno = 0;
3563 offset = strtol(p, &last_char, 0);
3564 if (0 == errno && '\0' == *last_char &&
3565 offset >= 0 && offset <= 0xFFFFFF) {
3566 macaddr[3] = (offset & 0xFF0000) >> 16;
3567 macaddr[4] = (offset & 0xFF00) >> 8;
3568 macaddr[5] = offset & 0xFF;
3569 return 0;
3570 } else {
3571 for(i = 0; i < 6; i++) {
3572 macaddr[i] = strtol(p, (char **)&p, 16);
3573 if (i == 5) {
3574 if (*p != '\0')
3575 return -1;
3576 } else {
3577 if (*p != ':' && *p != '-')
3578 return -1;
3579 p++;
3582 return 0;
3585 return -1;
3588 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3590 const char *p, *p1;
3591 int len;
3592 p = *pp;
3593 p1 = strchr(p, sep);
3594 if (!p1)
3595 return -1;
3596 len = p1 - p;
3597 p1++;
3598 if (buf_size > 0) {
3599 if (len > buf_size - 1)
3600 len = buf_size - 1;
3601 memcpy(buf, p, len);
3602 buf[len] = '\0';
3604 *pp = p1;
3605 return 0;
3608 int parse_host_src_port(struct sockaddr_in *haddr,
3609 struct sockaddr_in *saddr,
3610 const char *input_str)
3612 char *str = strdup(input_str);
3613 char *host_str = str;
3614 char *src_str;
3615 char *ptr;
3618 * Chop off any extra arguments at the end of the string which
3619 * would start with a comma, then fill in the src port information
3620 * if it was provided else use the "any address" and "any port".
3622 if ((ptr = strchr(str,',')))
3623 *ptr = '\0';
3625 if ((src_str = strchr(input_str,'@'))) {
3626 *src_str = '\0';
3627 src_str++;
3630 if (parse_host_port(haddr, host_str) < 0)
3631 goto fail;
3633 if (!src_str || *src_str == '\0')
3634 src_str = ":0";
3636 if (parse_host_port(saddr, src_str) < 0)
3637 goto fail;
3639 free(str);
3640 return(0);
3642 fail:
3643 free(str);
3644 return -1;
3647 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3649 char buf[512];
3650 struct hostent *he;
3651 const char *p, *r;
3652 int port;
3654 p = str;
3655 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3656 return -1;
3657 saddr->sin_family = AF_INET;
3658 if (buf[0] == '\0') {
3659 saddr->sin_addr.s_addr = 0;
3660 } else {
3661 if (isdigit(buf[0])) {
3662 if (!inet_aton(buf, &saddr->sin_addr))
3663 return -1;
3664 } else {
3665 if ((he = gethostbyname(buf)) == NULL)
3666 return - 1;
3667 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3670 port = strtol(p, (char **)&r, 0);
3671 if (r == p)
3672 return -1;
3673 saddr->sin_port = htons(port);
3674 return 0;
3677 #ifndef _WIN32
3678 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3680 const char *p;
3681 int len;
3683 len = MIN(108, strlen(str));
3684 p = strchr(str, ',');
3685 if (p)
3686 len = MIN(len, p - str);
3688 memset(uaddr, 0, sizeof(*uaddr));
3690 uaddr->sun_family = AF_UNIX;
3691 memcpy(uaddr->sun_path, str, len);
3693 return 0;
3695 #endif
3697 /* find or alloc a new VLAN */
3698 VLANState *qemu_find_vlan(int id)
3700 VLANState **pvlan, *vlan;
3701 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3702 if (vlan->id == id)
3703 return vlan;
3705 vlan = qemu_mallocz(sizeof(VLANState));
3706 if (!vlan)
3707 return NULL;
3708 vlan->id = id;
3709 vlan->next = NULL;
3710 pvlan = &first_vlan;
3711 while (*pvlan != NULL)
3712 pvlan = &(*pvlan)->next;
3713 *pvlan = vlan;
3714 return vlan;
3717 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3718 IOReadHandler *fd_read,
3719 IOCanRWHandler *fd_can_read,
3720 void *opaque)
3722 VLANClientState *vc, **pvc;
3723 vc = qemu_mallocz(sizeof(VLANClientState));
3724 if (!vc)
3725 return NULL;
3726 vc->fd_read = fd_read;
3727 vc->fd_can_read = fd_can_read;
3728 vc->opaque = opaque;
3729 vc->vlan = vlan;
3731 vc->next = NULL;
3732 pvc = &vlan->first_client;
3733 while (*pvc != NULL)
3734 pvc = &(*pvc)->next;
3735 *pvc = vc;
3736 return vc;
3739 int qemu_can_send_packet(VLANClientState *vc1)
3741 VLANState *vlan = vc1->vlan;
3742 VLANClientState *vc;
3744 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3745 if (vc != vc1) {
3746 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3747 return 1;
3750 return 0;
3753 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3755 VLANState *vlan = vc1->vlan;
3756 VLANClientState *vc;
3758 #if 0
3759 printf("vlan %d send:\n", vlan->id);
3760 hex_dump(stdout, buf, size);
3761 #endif
3762 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3763 if (vc != vc1) {
3764 vc->fd_read(vc->opaque, buf, size);
3769 #if defined(CONFIG_SLIRP)
3771 /* slirp network adapter */
3773 static int slirp_inited;
3774 static VLANClientState *slirp_vc;
3776 int slirp_can_output(void)
3778 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3781 void slirp_output(const uint8_t *pkt, int pkt_len)
3783 #if 0
3784 printf("slirp output:\n");
3785 hex_dump(stdout, pkt, pkt_len);
3786 #endif
3787 if (!slirp_vc)
3788 return;
3789 qemu_send_packet(slirp_vc, pkt, pkt_len);
3792 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3794 #if 0
3795 printf("slirp input:\n");
3796 hex_dump(stdout, buf, size);
3797 #endif
3798 slirp_input(buf, size);
3801 static int net_slirp_init(VLANState *vlan)
3803 if (!slirp_inited) {
3804 slirp_inited = 1;
3805 slirp_init();
3807 slirp_vc = qemu_new_vlan_client(vlan,
3808 slirp_receive, NULL, NULL);
3809 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3810 return 0;
3813 static void net_slirp_redir(const char *redir_str)
3815 int is_udp;
3816 char buf[256], *r;
3817 const char *p;
3818 struct in_addr guest_addr;
3819 int host_port, guest_port;
3821 if (!slirp_inited) {
3822 slirp_inited = 1;
3823 slirp_init();
3826 p = redir_str;
3827 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3828 goto fail;
3829 if (!strcmp(buf, "tcp")) {
3830 is_udp = 0;
3831 } else if (!strcmp(buf, "udp")) {
3832 is_udp = 1;
3833 } else {
3834 goto fail;
3837 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3838 goto fail;
3839 host_port = strtol(buf, &r, 0);
3840 if (r == buf)
3841 goto fail;
3843 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3844 goto fail;
3845 if (buf[0] == '\0') {
3846 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3848 if (!inet_aton(buf, &guest_addr))
3849 goto fail;
3851 guest_port = strtol(p, &r, 0);
3852 if (r == p)
3853 goto fail;
3855 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3856 fprintf(stderr, "qemu: could not set up redirection\n");
3857 exit(1);
3859 return;
3860 fail:
3861 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3862 exit(1);
3865 #ifndef _WIN32
3867 char smb_dir[1024];
3869 static void erase_dir(char *dir_name)
3871 DIR *d;
3872 struct dirent *de;
3873 char filename[1024];
3875 /* erase all the files in the directory */
3876 if ((d = opendir(dir_name)) != 0) {
3877 for(;;) {
3878 de = readdir(d);
3879 if (!de)
3880 break;
3881 if (strcmp(de->d_name, ".") != 0 &&
3882 strcmp(de->d_name, "..") != 0) {
3883 snprintf(filename, sizeof(filename), "%s/%s",
3884 smb_dir, de->d_name);
3885 if (unlink(filename) != 0) /* is it a directory? */
3886 erase_dir(filename);
3889 closedir(d);
3890 rmdir(dir_name);
3894 /* automatic user mode samba server configuration */
3895 static void smb_exit(void)
3897 erase_dir(smb_dir);
3900 /* automatic user mode samba server configuration */
3901 static void net_slirp_smb(const char *exported_dir)
3903 char smb_conf[1024];
3904 char smb_cmdline[1024];
3905 FILE *f;
3907 if (!slirp_inited) {
3908 slirp_inited = 1;
3909 slirp_init();
3912 /* XXX: better tmp dir construction */
3913 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3914 if (mkdir(smb_dir, 0700) < 0) {
3915 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3916 exit(1);
3918 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3920 f = fopen(smb_conf, "w");
3921 if (!f) {
3922 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3923 exit(1);
3925 fprintf(f,
3926 "[global]\n"
3927 "private dir=%s\n"
3928 "smb ports=0\n"
3929 "socket address=127.0.0.1\n"
3930 "pid directory=%s\n"
3931 "lock directory=%s\n"
3932 "log file=%s/log.smbd\n"
3933 "smb passwd file=%s/smbpasswd\n"
3934 "security = share\n"
3935 "[qemu]\n"
3936 "path=%s\n"
3937 "read only=no\n"
3938 "guest ok=yes\n",
3939 smb_dir,
3940 smb_dir,
3941 smb_dir,
3942 smb_dir,
3943 smb_dir,
3944 exported_dir
3946 fclose(f);
3947 atexit(smb_exit);
3949 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3950 SMBD_COMMAND, smb_conf);
3952 slirp_add_exec(0, smb_cmdline, 4, 139);
3955 #endif /* !defined(_WIN32) */
3956 void do_info_slirp(void)
3958 slirp_stats();
3961 #endif /* CONFIG_SLIRP */
3963 #if !defined(_WIN32)
3965 typedef struct TAPState {
3966 VLANClientState *vc;
3967 int fd;
3968 char down_script[1024];
3969 int no_poll;
3970 } TAPState;
3972 static int tap_read_poll(void *opaque)
3974 TAPState *s = opaque;
3975 return (!s->no_poll);
3978 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3980 TAPState *s = opaque;
3981 int ret;
3982 for(;;) {
3983 ret = write(s->fd, buf, size);
3984 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3985 } else {
3986 break;
3991 static void tap_send(void *opaque)
3993 TAPState *s = opaque;
3994 uint8_t buf[4096];
3995 int size;
3997 #ifdef __sun__
3998 struct strbuf sbuf;
3999 int f = 0;
4000 sbuf.maxlen = sizeof(buf);
4001 sbuf.buf = buf;
4002 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4003 #else
4004 size = read(s->fd, buf, sizeof(buf));
4005 #endif
4006 if (size > 0) {
4007 qemu_send_packet(s->vc, buf, size);
4011 int hack_around_tap(void *opaque)
4013 VLANClientState *vc = opaque;
4014 TAPState *ts = vc->opaque;
4016 if (vc->fd_read != tap_receive)
4017 return -1;
4019 if (ts) {
4020 ts->no_poll = 1;
4021 return ts->fd;
4024 return -1;
4027 /* fd support */
4029 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4031 TAPState *s;
4033 s = qemu_mallocz(sizeof(TAPState));
4034 if (!s)
4035 return NULL;
4036 s->fd = fd;
4037 s->no_poll = 0;
4038 enable_sigio_timer(fd);
4039 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4040 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
4041 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4042 return s;
4045 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4046 static int tap_open(char *ifname, int ifname_size)
4048 int fd;
4049 char *dev;
4050 struct stat s;
4052 TFR(fd = open("/dev/tap", O_RDWR));
4053 if (fd < 0) {
4054 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4055 return -1;
4058 fstat(fd, &s);
4059 dev = devname(s.st_rdev, S_IFCHR);
4060 pstrcpy(ifname, ifname_size, dev);
4062 fcntl(fd, F_SETFL, O_NONBLOCK);
4063 return fd;
4065 #elif defined(__sun__)
4066 #define TUNNEWPPA (('T'<<16) | 0x0001)
4068 * Allocate TAP device, returns opened fd.
4069 * Stores dev name in the first arg(must be large enough).
4071 int tap_alloc(char *dev)
4073 int tap_fd, if_fd, ppa = -1;
4074 static int ip_fd = 0;
4075 char *ptr;
4077 static int arp_fd = 0;
4078 int ip_muxid, arp_muxid;
4079 struct strioctl strioc_if, strioc_ppa;
4080 int link_type = I_PLINK;;
4081 struct lifreq ifr;
4082 char actual_name[32] = "";
4084 memset(&ifr, 0x0, sizeof(ifr));
4086 if( *dev ){
4087 ptr = dev;
4088 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4089 ppa = atoi(ptr);
4092 /* Check if IP device was opened */
4093 if( ip_fd )
4094 close(ip_fd);
4096 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4097 if (ip_fd < 0) {
4098 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4099 return -1;
4102 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4103 if (tap_fd < 0) {
4104 syslog(LOG_ERR, "Can't open /dev/tap");
4105 return -1;
4108 /* Assign a new PPA and get its unit number. */
4109 strioc_ppa.ic_cmd = TUNNEWPPA;
4110 strioc_ppa.ic_timout = 0;
4111 strioc_ppa.ic_len = sizeof(ppa);
4112 strioc_ppa.ic_dp = (char *)&ppa;
4113 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4114 syslog (LOG_ERR, "Can't assign new interface");
4116 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4117 if (if_fd < 0) {
4118 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4119 return -1;
4121 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4122 syslog(LOG_ERR, "Can't push IP module");
4123 return -1;
4126 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4127 syslog(LOG_ERR, "Can't get flags\n");
4129 snprintf (actual_name, 32, "tap%d", ppa);
4130 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4132 ifr.lifr_ppa = ppa;
4133 /* Assign ppa according to the unit number returned by tun device */
4135 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4136 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4137 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4138 syslog (LOG_ERR, "Can't get flags\n");
4139 /* Push arp module to if_fd */
4140 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4141 syslog (LOG_ERR, "Can't push ARP module (2)");
4143 /* Push arp module to ip_fd */
4144 if (ioctl (ip_fd, I_POP, NULL) < 0)
4145 syslog (LOG_ERR, "I_POP failed\n");
4146 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4147 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4148 /* Open arp_fd */
4149 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4150 if (arp_fd < 0)
4151 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4153 /* Set ifname to arp */
4154 strioc_if.ic_cmd = SIOCSLIFNAME;
4155 strioc_if.ic_timout = 0;
4156 strioc_if.ic_len = sizeof(ifr);
4157 strioc_if.ic_dp = (char *)&ifr;
4158 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4159 syslog (LOG_ERR, "Can't set ifname to arp\n");
4162 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4163 syslog(LOG_ERR, "Can't link TAP device to IP");
4164 return -1;
4167 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4168 syslog (LOG_ERR, "Can't link TAP device to ARP");
4170 close (if_fd);
4172 memset(&ifr, 0x0, sizeof(ifr));
4173 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4174 ifr.lifr_ip_muxid = ip_muxid;
4175 ifr.lifr_arp_muxid = arp_muxid;
4177 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4179 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4180 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4181 syslog (LOG_ERR, "Can't set multiplexor id");
4184 sprintf(dev, "tap%d", ppa);
4185 return tap_fd;
4188 static int tap_open(char *ifname, int ifname_size)
4190 char dev[10]="";
4191 int fd;
4192 if( (fd = tap_alloc(dev)) < 0 ){
4193 fprintf(stderr, "Cannot allocate TAP device\n");
4194 return -1;
4196 pstrcpy(ifname, ifname_size, dev);
4197 fcntl(fd, F_SETFL, O_NONBLOCK);
4198 return fd;
4200 #else
4201 static int tap_open(char *ifname, int ifname_size)
4203 struct ifreq ifr;
4204 int fd, ret;
4206 TFR(fd = open("/dev/net/tun", O_RDWR));
4207 if (fd < 0) {
4208 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4209 return -1;
4211 memset(&ifr, 0, sizeof(ifr));
4212 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4213 if (ifname[0] != '\0')
4214 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4215 else
4216 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4217 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4218 if (ret != 0) {
4219 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4220 close(fd);
4221 return -1;
4223 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4224 fcntl(fd, F_SETFL, O_NONBLOCK);
4225 return fd;
4227 #endif
4229 static int launch_script(const char *setup_script, const char *ifname, int fd)
4231 int pid, status;
4232 char *args[3];
4233 char **parg;
4235 /* try to launch network script */
4236 pid = fork();
4237 if (pid >= 0) {
4238 if (pid == 0) {
4239 int open_max = sysconf (_SC_OPEN_MAX), i;
4240 for (i = 0; i < open_max; i++)
4241 if (i != STDIN_FILENO &&
4242 i != STDOUT_FILENO &&
4243 i != STDERR_FILENO &&
4244 i != fd)
4245 close(i);
4247 parg = args;
4248 *parg++ = (char *)setup_script;
4249 *parg++ = (char *)ifname;
4250 *parg++ = NULL;
4251 execv(setup_script, args);
4252 _exit(1);
4254 while (waitpid(pid, &status, 0) != pid);
4255 if (!WIFEXITED(status) ||
4256 WEXITSTATUS(status) != 0) {
4257 fprintf(stderr, "%s: could not launch network script\n",
4258 setup_script);
4259 return -1;
4262 return 0;
4265 static int net_tap_init(VLANState *vlan, const char *ifname1,
4266 const char *setup_script, const char *down_script)
4268 TAPState *s;
4269 int fd;
4270 char ifname[128];
4272 if (ifname1 != NULL)
4273 pstrcpy(ifname, sizeof(ifname), ifname1);
4274 else
4275 ifname[0] = '\0';
4276 TFR(fd = tap_open(ifname, sizeof(ifname)));
4277 if (fd < 0)
4278 return -1;
4280 if (!setup_script || !strcmp(setup_script, "no"))
4281 setup_script = "";
4282 if (setup_script[0] != '\0') {
4283 if (launch_script(setup_script, ifname, fd))
4284 return -1;
4286 s = net_tap_fd_init(vlan, fd);
4287 if (!s)
4288 return -1;
4289 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4290 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4291 if (down_script && strcmp(down_script, "no"))
4292 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4293 return 0;
4296 #endif /* !_WIN32 */
4298 /* network connection */
4299 typedef struct NetSocketState {
4300 VLANClientState *vc;
4301 int fd;
4302 int state; /* 0 = getting length, 1 = getting data */
4303 int index;
4304 int packet_len;
4305 uint8_t buf[4096];
4306 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4307 } NetSocketState;
4309 typedef struct NetSocketListenState {
4310 VLANState *vlan;
4311 int fd;
4312 } NetSocketListenState;
4314 /* XXX: we consider we can send the whole packet without blocking */
4315 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4317 NetSocketState *s = opaque;
4318 uint32_t len;
4319 len = htonl(size);
4321 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4322 send_all(s->fd, buf, size);
4325 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4327 NetSocketState *s = opaque;
4328 sendto(s->fd, buf, size, 0,
4329 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4332 static void net_socket_send(void *opaque)
4334 NetSocketState *s = opaque;
4335 int l, size, err;
4336 uint8_t buf1[4096];
4337 const uint8_t *buf;
4339 size = recv(s->fd, buf1, sizeof(buf1), 0);
4340 if (size < 0) {
4341 err = socket_error();
4342 if (err != EWOULDBLOCK)
4343 goto eoc;
4344 } else if (size == 0) {
4345 /* end of connection */
4346 eoc:
4347 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4348 closesocket(s->fd);
4349 return;
4351 buf = buf1;
4352 while (size > 0) {
4353 /* reassemble a packet from the network */
4354 switch(s->state) {
4355 case 0:
4356 l = 4 - s->index;
4357 if (l > size)
4358 l = size;
4359 memcpy(s->buf + s->index, buf, l);
4360 buf += l;
4361 size -= l;
4362 s->index += l;
4363 if (s->index == 4) {
4364 /* got length */
4365 s->packet_len = ntohl(*(uint32_t *)s->buf);
4366 s->index = 0;
4367 s->state = 1;
4369 break;
4370 case 1:
4371 l = s->packet_len - s->index;
4372 if (l > size)
4373 l = size;
4374 memcpy(s->buf + s->index, buf, l);
4375 s->index += l;
4376 buf += l;
4377 size -= l;
4378 if (s->index >= s->packet_len) {
4379 qemu_send_packet(s->vc, s->buf, s->packet_len);
4380 s->index = 0;
4381 s->state = 0;
4383 break;
4388 static void net_socket_send_dgram(void *opaque)
4390 NetSocketState *s = opaque;
4391 int size;
4393 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4394 if (size < 0)
4395 return;
4396 if (size == 0) {
4397 /* end of connection */
4398 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4399 return;
4401 qemu_send_packet(s->vc, s->buf, size);
4404 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4406 struct ip_mreq imr;
4407 int fd;
4408 int val, ret;
4409 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4410 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4411 inet_ntoa(mcastaddr->sin_addr),
4412 (int)ntohl(mcastaddr->sin_addr.s_addr));
4413 return -1;
4416 fd = socket(PF_INET, SOCK_DGRAM, 0);
4417 if (fd < 0) {
4418 perror("socket(PF_INET, SOCK_DGRAM)");
4419 return -1;
4422 val = 1;
4423 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4424 (const char *)&val, sizeof(val));
4425 if (ret < 0) {
4426 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4427 goto fail;
4430 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4431 if (ret < 0) {
4432 perror("bind");
4433 goto fail;
4436 /* Add host to multicast group */
4437 imr.imr_multiaddr = mcastaddr->sin_addr;
4438 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4440 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4441 (const char *)&imr, sizeof(struct ip_mreq));
4442 if (ret < 0) {
4443 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4444 goto fail;
4447 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4448 val = 1;
4449 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4450 (const char *)&val, sizeof(val));
4451 if (ret < 0) {
4452 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4453 goto fail;
4456 socket_set_nonblock(fd);
4457 return fd;
4458 fail:
4459 if (fd >= 0)
4460 closesocket(fd);
4461 return -1;
4464 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4465 int is_connected)
4467 struct sockaddr_in saddr;
4468 int newfd;
4469 socklen_t saddr_len;
4470 NetSocketState *s;
4472 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4473 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4474 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4477 if (is_connected) {
4478 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4479 /* must be bound */
4480 if (saddr.sin_addr.s_addr==0) {
4481 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4482 fd);
4483 return NULL;
4485 /* clone dgram socket */
4486 newfd = net_socket_mcast_create(&saddr);
4487 if (newfd < 0) {
4488 /* error already reported by net_socket_mcast_create() */
4489 close(fd);
4490 return NULL;
4492 /* clone newfd to fd, close newfd */
4493 dup2(newfd, fd);
4494 close(newfd);
4496 } else {
4497 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4498 fd, strerror(errno));
4499 return NULL;
4503 s = qemu_mallocz(sizeof(NetSocketState));
4504 if (!s)
4505 return NULL;
4506 s->fd = fd;
4508 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4509 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4511 /* mcast: save bound address as dst */
4512 if (is_connected) s->dgram_dst=saddr;
4514 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4515 "socket: fd=%d (%s mcast=%s:%d)",
4516 fd, is_connected? "cloned" : "",
4517 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4518 return s;
4521 static void net_socket_connect(void *opaque)
4523 NetSocketState *s = opaque;
4524 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4527 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4528 int is_connected)
4530 NetSocketState *s;
4531 s = qemu_mallocz(sizeof(NetSocketState));
4532 if (!s)
4533 return NULL;
4534 s->fd = fd;
4535 s->vc = qemu_new_vlan_client(vlan,
4536 net_socket_receive, NULL, s);
4537 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4538 "socket: fd=%d", fd);
4539 if (is_connected) {
4540 net_socket_connect(s);
4541 } else {
4542 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4544 return s;
4547 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4548 int is_connected)
4550 int so_type=-1, optlen=sizeof(so_type);
4552 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4553 (socklen_t *)&optlen)< 0) {
4554 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4555 return NULL;
4557 switch(so_type) {
4558 case SOCK_DGRAM:
4559 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4560 case SOCK_STREAM:
4561 return net_socket_fd_init_stream(vlan, fd, is_connected);
4562 default:
4563 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4564 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4565 return net_socket_fd_init_stream(vlan, fd, is_connected);
4567 return NULL;
4570 static void net_socket_accept(void *opaque)
4572 NetSocketListenState *s = opaque;
4573 NetSocketState *s1;
4574 struct sockaddr_in saddr;
4575 socklen_t len;
4576 int fd;
4578 for(;;) {
4579 len = sizeof(saddr);
4580 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4581 if (fd < 0 && errno != EINTR) {
4582 return;
4583 } else if (fd >= 0) {
4584 break;
4587 s1 = net_socket_fd_init(s->vlan, fd, 1);
4588 if (!s1) {
4589 closesocket(fd);
4590 } else {
4591 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4592 "socket: connection from %s:%d",
4593 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4597 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4599 NetSocketListenState *s;
4600 int fd, val, ret;
4601 struct sockaddr_in saddr;
4603 if (parse_host_port(&saddr, host_str) < 0)
4604 return -1;
4606 s = qemu_mallocz(sizeof(NetSocketListenState));
4607 if (!s)
4608 return -1;
4610 fd = socket(PF_INET, SOCK_STREAM, 0);
4611 if (fd < 0) {
4612 perror("socket");
4613 return -1;
4615 socket_set_nonblock(fd);
4617 /* allow fast reuse */
4618 val = 1;
4619 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4621 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4622 if (ret < 0) {
4623 perror("bind");
4624 return -1;
4626 ret = listen(fd, 0);
4627 if (ret < 0) {
4628 perror("listen");
4629 return -1;
4631 s->vlan = vlan;
4632 s->fd = fd;
4633 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4634 return 0;
4637 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4639 NetSocketState *s;
4640 int fd, connected, ret, err;
4641 struct sockaddr_in saddr;
4643 if (parse_host_port(&saddr, host_str) < 0)
4644 return -1;
4646 fd = socket(PF_INET, SOCK_STREAM, 0);
4647 if (fd < 0) {
4648 perror("socket");
4649 return -1;
4651 socket_set_nonblock(fd);
4653 connected = 0;
4654 for(;;) {
4655 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4656 if (ret < 0) {
4657 err = socket_error();
4658 if (err == EINTR || err == EWOULDBLOCK) {
4659 } else if (err == EINPROGRESS) {
4660 break;
4661 #ifdef _WIN32
4662 } else if (err == WSAEALREADY) {
4663 break;
4664 #endif
4665 } else {
4666 perror("connect");
4667 closesocket(fd);
4668 return -1;
4670 } else {
4671 connected = 1;
4672 break;
4675 s = net_socket_fd_init(vlan, fd, connected);
4676 if (!s)
4677 return -1;
4678 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4679 "socket: connect to %s:%d",
4680 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4681 return 0;
4684 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4686 NetSocketState *s;
4687 int fd;
4688 struct sockaddr_in saddr;
4690 if (parse_host_port(&saddr, host_str) < 0)
4691 return -1;
4694 fd = net_socket_mcast_create(&saddr);
4695 if (fd < 0)
4696 return -1;
4698 s = net_socket_fd_init(vlan, fd, 0);
4699 if (!s)
4700 return -1;
4702 s->dgram_dst = saddr;
4704 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4705 "socket: mcast=%s:%d",
4706 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4707 return 0;
4711 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4713 char *q;
4715 q = buf;
4716 while (*p != '\0' && *p != '=') {
4717 if (q && (q - buf) < buf_size - 1)
4718 *q++ = *p;
4719 p++;
4721 if (q)
4722 *q = '\0';
4724 return p;
4727 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4729 char *q;
4731 q = buf;
4732 while (*p != '\0') {
4733 if (*p == ',') {
4734 if (*(p + 1) != ',')
4735 break;
4736 p++;
4738 if (q && (q - buf) < buf_size - 1)
4739 *q++ = *p;
4740 p++;
4742 if (q)
4743 *q = '\0';
4745 return p;
4748 int get_param_value(char *buf, int buf_size,
4749 const char *tag, const char *str)
4751 const char *p;
4752 char option[128];
4754 p = str;
4755 for(;;) {
4756 p = get_opt_name(option, sizeof(option), p);
4757 if (*p != '=')
4758 break;
4759 p++;
4760 if (!strcmp(tag, option)) {
4761 (void)get_opt_value(buf, buf_size, p);
4762 return strlen(buf);
4763 } else {
4764 p = get_opt_value(NULL, 0, p);
4766 if (*p != ',')
4767 break;
4768 p++;
4770 return 0;
4773 int check_params(char *buf, int buf_size,
4774 char **params, const char *str)
4776 const char *p;
4777 int i;
4779 p = str;
4780 for(;;) {
4781 p = get_opt_name(buf, buf_size, p);
4782 if (*p != '=')
4783 return -1;
4784 p++;
4785 for(i = 0; params[i] != NULL; i++)
4786 if (!strcmp(params[i], buf))
4787 break;
4788 if (params[i] == NULL)
4789 return -1;
4790 p = get_opt_value(NULL, 0, p);
4791 if (*p != ',')
4792 break;
4793 p++;
4795 return 0;
4798 static int nic_get_free_idx(void)
4800 int index;
4802 for (index = 0; index < MAX_NICS; index++)
4803 if (!nd_table[index].used)
4804 return index;
4805 return -1;
4808 int net_client_init(const char *str)
4810 const char *p;
4811 char *q;
4812 char device[64];
4813 char buf[1024];
4814 int vlan_id, ret;
4815 VLANState *vlan;
4817 p = str;
4818 q = device;
4819 while (*p != '\0' && *p != ',') {
4820 if ((q - device) < sizeof(device) - 1)
4821 *q++ = *p;
4822 p++;
4824 *q = '\0';
4825 if (*p == ',')
4826 p++;
4827 vlan_id = 0;
4828 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4829 vlan_id = strtol(buf, NULL, 0);
4831 vlan = qemu_find_vlan(vlan_id);
4832 if (!vlan) {
4833 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4834 return -1;
4836 if (!strcmp(device, "nic")) {
4837 NICInfo *nd;
4838 uint8_t *macaddr;
4839 int idx = nic_get_free_idx();
4841 if (idx == -1 || nb_nics >= MAX_NICS) {
4842 fprintf(stderr, "Too Many NICs\n");
4843 return -1;
4845 nd = &nd_table[idx];
4846 macaddr = nd->macaddr;
4847 macaddr[0] = 0x52;
4848 macaddr[1] = 0x54;
4849 macaddr[2] = 0x00;
4850 macaddr[3] = 0x12;
4851 macaddr[4] = 0x34;
4852 macaddr[5] = 0x56 + idx;
4854 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4855 if (parse_macaddr(macaddr, buf) < 0) {
4856 fprintf(stderr, "invalid syntax for ethernet address\n");
4857 return -1;
4860 if (get_param_value(buf, sizeof(buf), "model", p)) {
4861 nd->model = strdup(buf);
4863 nd->vlan = vlan;
4864 nd->used = 1;
4865 nb_nics++;
4866 vlan->nb_guest_devs++;
4867 ret = idx;
4868 } else
4869 if (!strcmp(device, "none")) {
4870 /* does nothing. It is needed to signal that no network cards
4871 are wanted */
4872 ret = 0;
4873 } else
4874 #ifdef CONFIG_SLIRP
4875 if (!strcmp(device, "user")) {
4876 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4877 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4879 vlan->nb_host_devs++;
4880 ret = net_slirp_init(vlan);
4881 } else
4882 #endif
4883 #ifdef _WIN32
4884 if (!strcmp(device, "tap")) {
4885 char ifname[64];
4886 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4887 fprintf(stderr, "tap: no interface name\n");
4888 return -1;
4890 vlan->nb_host_devs++;
4891 ret = tap_win32_init(vlan, ifname);
4892 } else
4893 #else
4894 if (!strcmp(device, "tap")) {
4895 char ifname[64];
4896 char setup_script[1024], down_script[1024];
4897 int fd;
4898 vlan->nb_host_devs++;
4899 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4900 fd = strtol(buf, NULL, 0);
4901 fcntl(fd, F_SETFL, O_NONBLOCK);
4902 ret = -1;
4903 if (net_tap_fd_init(vlan, fd))
4904 ret = 0;
4905 } else {
4906 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4907 ifname[0] = '\0';
4909 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4910 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4912 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4913 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4915 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4917 } else
4918 #endif
4919 if (!strcmp(device, "socket")) {
4920 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4921 int fd;
4922 fd = strtol(buf, NULL, 0);
4923 ret = -1;
4924 if (net_socket_fd_init(vlan, fd, 1))
4925 ret = 0;
4926 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4927 ret = net_socket_listen_init(vlan, buf);
4928 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4929 ret = net_socket_connect_init(vlan, buf);
4930 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4931 ret = net_socket_mcast_init(vlan, buf);
4932 } else {
4933 fprintf(stderr, "Unknown socket options: %s\n", p);
4934 return -1;
4936 vlan->nb_host_devs++;
4937 } else
4939 fprintf(stderr, "Unknown network device: %s\n", device);
4940 return -1;
4942 if (ret < 0) {
4943 fprintf(stderr, "Could not initialize device '%s'\n", device);
4946 return ret;
4949 void net_client_uninit(NICInfo *nd)
4951 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
4952 nb_nics--;
4953 nd->used = 0;
4954 free((void *)nd->model);
4957 void do_info_network(void)
4959 VLANState *vlan;
4960 VLANClientState *vc;
4962 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4963 term_printf("VLAN %d devices:\n", vlan->id);
4964 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4965 term_printf(" %s\n", vc->info_str);
4969 #define HD_ALIAS "index=%d,media=disk"
4970 #ifdef TARGET_PPC
4971 #define CDROM_ALIAS "index=1,media=cdrom"
4972 #else
4973 #define CDROM_ALIAS "index=2,media=cdrom"
4974 #endif
4975 #define FD_ALIAS "index=%d,if=floppy"
4976 #define PFLASH_ALIAS "if=pflash"
4977 #define MTD_ALIAS "if=mtd"
4978 #define SD_ALIAS "index=0,if=sd"
4980 static int drive_opt_get_free_idx(void)
4982 int index;
4984 for (index = 0; index < MAX_DRIVES; index++)
4985 if (!drives_opt[index].used) {
4986 drives_opt[index].used = 1;
4987 return index;
4990 return -1;
4993 static int drive_get_free_idx(void)
4995 int index;
4997 for (index = 0; index < MAX_DRIVES; index++)
4998 if (!drives_table[index].used) {
4999 drives_table[index].used = 1;
5000 return index;
5003 return -1;
5006 int drive_add(const char *file, const char *fmt, ...)
5008 va_list ap;
5009 int index = drive_opt_get_free_idx();
5011 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5012 fprintf(stderr, "qemu: too many drives\n");
5013 return -1;
5016 drives_opt[index].file = file;
5017 va_start(ap, fmt);
5018 vsnprintf(drives_opt[index].opt,
5019 sizeof(drives_opt[0].opt), fmt, ap);
5020 va_end(ap);
5022 nb_drives_opt++;
5023 return index;
5026 void drive_remove(int index)
5028 drives_opt[index].used = 0;
5029 nb_drives_opt--;
5032 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5034 int index;
5036 /* seek interface, bus and unit */
5038 for (index = 0; index < MAX_DRIVES; index++)
5039 if (drives_table[index].type == type &&
5040 drives_table[index].bus == bus &&
5041 drives_table[index].unit == unit &&
5042 drives_table[index].used)
5043 return index;
5045 return -1;
5048 int drive_get_max_bus(BlockInterfaceType type)
5050 int max_bus;
5051 int index;
5053 max_bus = -1;
5054 for (index = 0; index < nb_drives; index++) {
5055 if(drives_table[index].type == type &&
5056 drives_table[index].bus > max_bus)
5057 max_bus = drives_table[index].bus;
5059 return max_bus;
5062 void drive_uninit(BlockDriverState *bdrv)
5064 int i;
5066 for (i = 0; i < MAX_DRIVES; i++)
5067 if (drives_table[i].bdrv == bdrv) {
5068 drives_table[i].bdrv = NULL;
5069 drives_table[i].used = 0;
5070 drive_remove(drives_table[i].drive_opt_idx);
5071 nb_drives--;
5072 break;
5076 int drive_init(struct drive_opt *arg, int snapshot,
5077 void *opaque)
5079 QEMUMachine *machine = opaque;
5080 char buf[128];
5081 char file[1024];
5082 char devname[128];
5083 const char *mediastr = "";
5084 BlockInterfaceType type;
5085 enum { MEDIA_DISK, MEDIA_CDROM } media;
5086 int bus_id, unit_id;
5087 int cyls, heads, secs, translation;
5088 BlockDriverState *bdrv;
5089 int max_devs;
5090 int index;
5091 int cache;
5092 int bdrv_flags;
5093 int drives_table_idx;
5094 char *str = arg->opt;
5095 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5096 "secs", "trans", "media", "snapshot", "file",
5097 "cache", "boot", NULL };
5099 if (check_params(buf, sizeof(buf), params, str) < 0) {
5100 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5101 buf, str);
5102 return -1;
5105 file[0] = 0;
5106 cyls = heads = secs = 0;
5107 bus_id = 0;
5108 unit_id = -1;
5109 translation = BIOS_ATA_TRANSLATION_AUTO;
5110 index = -1;
5111 cache = 1;
5113 if (!strcmp(machine->name, "realview") ||
5114 !strcmp(machine->name, "SS-5") ||
5115 !strcmp(machine->name, "SS-10") ||
5116 !strcmp(machine->name, "SS-600MP") ||
5117 !strcmp(machine->name, "versatilepb") ||
5118 !strcmp(machine->name, "versatileab")) {
5119 type = IF_SCSI;
5120 max_devs = MAX_SCSI_DEVS;
5121 strcpy(devname, "scsi");
5122 } else {
5123 type = IF_IDE;
5124 max_devs = MAX_IDE_DEVS;
5125 strcpy(devname, "ide");
5127 media = MEDIA_DISK;
5129 /* extract parameters */
5131 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5132 bus_id = strtol(buf, NULL, 0);
5133 if (bus_id < 0) {
5134 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5135 return -1;
5139 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5140 unit_id = strtol(buf, NULL, 0);
5141 if (unit_id < 0) {
5142 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5143 return -1;
5147 if (get_param_value(buf, sizeof(buf), "if", str)) {
5148 strncpy(devname, buf, sizeof(devname));
5149 if (!strcmp(buf, "ide")) {
5150 type = IF_IDE;
5151 max_devs = MAX_IDE_DEVS;
5152 } else if (!strcmp(buf, "scsi")) {
5153 type = IF_SCSI;
5154 max_devs = MAX_SCSI_DEVS;
5155 } else if (!strcmp(buf, "floppy")) {
5156 type = IF_FLOPPY;
5157 max_devs = 0;
5158 } else if (!strcmp(buf, "pflash")) {
5159 type = IF_PFLASH;
5160 max_devs = 0;
5161 } else if (!strcmp(buf, "mtd")) {
5162 type = IF_MTD;
5163 max_devs = 0;
5164 } else if (!strcmp(buf, "sd")) {
5165 type = IF_SD;
5166 max_devs = 0;
5167 } else if (!strcmp(buf, "virtio")) {
5168 type = IF_VIRTIO;
5169 max_devs = 0;
5170 } else {
5171 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5172 return -1;
5176 if (get_param_value(buf, sizeof(buf), "index", str)) {
5177 index = strtol(buf, NULL, 0);
5178 if (index < 0) {
5179 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5180 return -1;
5184 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5185 cyls = strtol(buf, NULL, 0);
5188 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5189 heads = strtol(buf, NULL, 0);
5192 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5193 secs = strtol(buf, NULL, 0);
5196 if (cyls || heads || secs) {
5197 if (cyls < 1 || cyls > 16383) {
5198 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5199 return -1;
5201 if (heads < 1 || heads > 16) {
5202 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5203 return -1;
5205 if (secs < 1 || secs > 63) {
5206 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5207 return -1;
5211 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5212 if (!cyls) {
5213 fprintf(stderr,
5214 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5215 str);
5216 return -1;
5218 if (!strcmp(buf, "none"))
5219 translation = BIOS_ATA_TRANSLATION_NONE;
5220 else if (!strcmp(buf, "lba"))
5221 translation = BIOS_ATA_TRANSLATION_LBA;
5222 else if (!strcmp(buf, "auto"))
5223 translation = BIOS_ATA_TRANSLATION_AUTO;
5224 else {
5225 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5226 return -1;
5230 if (get_param_value(buf, sizeof(buf), "media", str)) {
5231 if (!strcmp(buf, "disk")) {
5232 media = MEDIA_DISK;
5233 } else if (!strcmp(buf, "cdrom")) {
5234 if (cyls || secs || heads) {
5235 fprintf(stderr,
5236 "qemu: '%s' invalid physical CHS format\n", str);
5237 return -1;
5239 media = MEDIA_CDROM;
5240 } else {
5241 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5242 return -1;
5246 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5247 if (!strcmp(buf, "on"))
5248 snapshot = 1;
5249 else if (!strcmp(buf, "off"))
5250 snapshot = 0;
5251 else {
5252 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5253 return -1;
5257 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5258 if (!strcmp(buf, "off"))
5259 cache = 0;
5260 else if (!strcmp(buf, "on"))
5261 cache = 1;
5262 else {
5263 fprintf(stderr, "qemu: invalid cache option\n");
5264 return -1;
5268 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5269 if (!strcmp(buf, "on")) {
5270 if (extboot_drive != -1) {
5271 fprintf(stderr, "qemu: two bootable drives specified\n");
5272 return -1;
5274 extboot_drive = nb_drives;
5275 } else if (strcmp(buf, "off")) {
5276 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5277 return -1;
5281 if (arg->file == NULL)
5282 get_param_value(file, sizeof(file), "file", str);
5283 else
5284 pstrcpy(file, sizeof(file), arg->file);
5286 /* compute bus and unit according index */
5288 if (index != -1) {
5289 if (bus_id != 0 || unit_id != -1) {
5290 fprintf(stderr,
5291 "qemu: '%s' index cannot be used with bus and unit\n", str);
5292 return -1;
5294 if (max_devs == 0)
5296 unit_id = index;
5297 bus_id = 0;
5298 } else {
5299 unit_id = index % max_devs;
5300 bus_id = index / max_devs;
5304 /* if user doesn't specify a unit_id,
5305 * try to find the first free
5308 if (unit_id == -1) {
5309 unit_id = 0;
5310 while (drive_get_index(type, bus_id, unit_id) != -1) {
5311 unit_id++;
5312 if (max_devs && unit_id >= max_devs) {
5313 unit_id -= max_devs;
5314 bus_id++;
5319 /* check unit id */
5321 if (max_devs && unit_id >= max_devs) {
5322 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5323 str, unit_id, max_devs - 1);
5324 return -1;
5328 * ignore multiple definitions
5331 if (drive_get_index(type, bus_id, unit_id) != -1)
5332 return -2;
5334 /* init */
5336 if (type == IF_IDE || type == IF_SCSI)
5337 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5338 if (max_devs)
5339 snprintf(buf, sizeof(buf), "%s%i%s%i",
5340 devname, bus_id, mediastr, unit_id);
5341 else
5342 snprintf(buf, sizeof(buf), "%s%s%i",
5343 devname, mediastr, unit_id);
5344 bdrv = bdrv_new(buf);
5345 drives_table_idx = drive_get_free_idx();
5346 drives_table[drives_table_idx].bdrv = bdrv;
5347 drives_table[drives_table_idx].type = type;
5348 drives_table[drives_table_idx].bus = bus_id;
5349 drives_table[drives_table_idx].unit = unit_id;
5350 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
5351 nb_drives++;
5353 switch(type) {
5354 case IF_IDE:
5355 case IF_SCSI:
5356 switch(media) {
5357 case MEDIA_DISK:
5358 if (cyls != 0) {
5359 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5360 bdrv_set_translation_hint(bdrv, translation);
5362 break;
5363 case MEDIA_CDROM:
5364 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5365 break;
5367 break;
5368 case IF_SD:
5369 /* FIXME: This isn't really a floppy, but it's a reasonable
5370 approximation. */
5371 case IF_FLOPPY:
5372 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5373 break;
5374 case IF_PFLASH:
5375 case IF_MTD:
5376 case IF_VIRTIO:
5377 break;
5379 if (!file[0])
5380 return -2;
5381 bdrv_flags = 0;
5382 if (snapshot)
5383 bdrv_flags |= BDRV_O_SNAPSHOT;
5384 if (!cache)
5385 bdrv_flags |= BDRV_O_DIRECT;
5386 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5387 fprintf(stderr, "qemu: could not open disk image %s\n",
5388 file);
5389 return -1;
5391 return drives_table_idx;
5394 /***********************************************************/
5395 /* USB devices */
5397 static USBPort *used_usb_ports;
5398 static USBPort *free_usb_ports;
5400 /* ??? Maybe change this to register a hub to keep track of the topology. */
5401 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5402 usb_attachfn attach)
5404 port->opaque = opaque;
5405 port->index = index;
5406 port->attach = attach;
5407 port->next = free_usb_ports;
5408 free_usb_ports = port;
5411 static int usb_device_add(const char *devname)
5413 const char *p;
5414 USBDevice *dev;
5415 USBPort *port;
5417 if (!free_usb_ports)
5418 return -1;
5420 if (strstart(devname, "host:", &p)) {
5421 dev = usb_host_device_open(p);
5422 } else if (!strcmp(devname, "mouse")) {
5423 dev = usb_mouse_init();
5424 } else if (!strcmp(devname, "tablet")) {
5425 dev = usb_tablet_init();
5426 } else if (!strcmp(devname, "keyboard")) {
5427 dev = usb_keyboard_init();
5428 } else if (strstart(devname, "disk:", &p)) {
5429 dev = usb_msd_init(p);
5430 } else if (!strcmp(devname, "wacom-tablet")) {
5431 dev = usb_wacom_init();
5432 } else if (strstart(devname, "serial:", &p)) {
5433 dev = usb_serial_init(p);
5434 #ifdef CONFIG_BRLAPI
5435 } else if (!strcmp(devname, "braille")) {
5436 dev = usb_baum_init();
5437 #endif
5438 } else {
5439 return -1;
5441 if (!dev)
5442 return -1;
5444 /* Find a USB port to add the device to. */
5445 port = free_usb_ports;
5446 if (!port->next) {
5447 USBDevice *hub;
5449 /* Create a new hub and chain it on. */
5450 free_usb_ports = NULL;
5451 port->next = used_usb_ports;
5452 used_usb_ports = port;
5454 hub = usb_hub_init(VM_USB_HUB_SIZE);
5455 usb_attach(port, hub);
5456 port = free_usb_ports;
5459 free_usb_ports = port->next;
5460 port->next = used_usb_ports;
5461 used_usb_ports = port;
5462 usb_attach(port, dev);
5463 return 0;
5466 static int usb_device_del(const char *devname)
5468 USBPort *port;
5469 USBPort **lastp;
5470 USBDevice *dev;
5471 int bus_num, addr;
5472 const char *p;
5474 if (!used_usb_ports)
5475 return -1;
5477 p = strchr(devname, '.');
5478 if (!p)
5479 return -1;
5480 bus_num = strtoul(devname, NULL, 0);
5481 addr = strtoul(p + 1, NULL, 0);
5482 if (bus_num != 0)
5483 return -1;
5485 lastp = &used_usb_ports;
5486 port = used_usb_ports;
5487 while (port && port->dev->addr != addr) {
5488 lastp = &port->next;
5489 port = port->next;
5492 if (!port)
5493 return -1;
5495 dev = port->dev;
5496 *lastp = port->next;
5497 usb_attach(port, NULL);
5498 dev->handle_destroy(dev);
5499 port->next = free_usb_ports;
5500 free_usb_ports = port;
5501 return 0;
5504 void do_usb_add(const char *devname)
5506 int ret;
5507 ret = usb_device_add(devname);
5508 if (ret < 0)
5509 term_printf("Could not add USB device '%s'\n", devname);
5512 void do_usb_del(const char *devname)
5514 int ret;
5515 ret = usb_device_del(devname);
5516 if (ret < 0)
5517 term_printf("Could not remove USB device '%s'\n", devname);
5520 void usb_info(void)
5522 USBDevice *dev;
5523 USBPort *port;
5524 const char *speed_str;
5526 if (!usb_enabled) {
5527 term_printf("USB support not enabled\n");
5528 return;
5531 for (port = used_usb_ports; port; port = port->next) {
5532 dev = port->dev;
5533 if (!dev)
5534 continue;
5535 switch(dev->speed) {
5536 case USB_SPEED_LOW:
5537 speed_str = "1.5";
5538 break;
5539 case USB_SPEED_FULL:
5540 speed_str = "12";
5541 break;
5542 case USB_SPEED_HIGH:
5543 speed_str = "480";
5544 break;
5545 default:
5546 speed_str = "?";
5547 break;
5549 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5550 0, dev->addr, speed_str, dev->devname);
5554 /***********************************************************/
5555 /* PCMCIA/Cardbus */
5557 static struct pcmcia_socket_entry_s {
5558 struct pcmcia_socket_s *socket;
5559 struct pcmcia_socket_entry_s *next;
5560 } *pcmcia_sockets = 0;
5562 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5564 struct pcmcia_socket_entry_s *entry;
5566 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5567 entry->socket = socket;
5568 entry->next = pcmcia_sockets;
5569 pcmcia_sockets = entry;
5572 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5574 struct pcmcia_socket_entry_s *entry, **ptr;
5576 ptr = &pcmcia_sockets;
5577 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5578 if (entry->socket == socket) {
5579 *ptr = entry->next;
5580 qemu_free(entry);
5584 void pcmcia_info(void)
5586 struct pcmcia_socket_entry_s *iter;
5587 if (!pcmcia_sockets)
5588 term_printf("No PCMCIA sockets\n");
5590 for (iter = pcmcia_sockets; iter; iter = iter->next)
5591 term_printf("%s: %s\n", iter->socket->slot_string,
5592 iter->socket->attached ? iter->socket->card_string :
5593 "Empty");
5596 /***********************************************************/
5597 /* dumb display */
5599 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5603 static void dumb_resize(DisplayState *ds, int w, int h)
5607 static void dumb_refresh(DisplayState *ds)
5609 #if defined(CONFIG_SDL)
5610 vga_hw_update();
5611 #endif
5614 static void dumb_display_init(DisplayState *ds)
5616 ds->data = NULL;
5617 ds->linesize = 0;
5618 ds->depth = 0;
5619 ds->dpy_update = dumb_update;
5620 ds->dpy_resize = dumb_resize;
5621 ds->dpy_refresh = dumb_refresh;
5624 /***********************************************************/
5625 /* I/O handling */
5627 #define MAX_IO_HANDLERS 64
5629 typedef struct IOHandlerRecord {
5630 int fd;
5631 IOCanRWHandler *fd_read_poll;
5632 IOHandler *fd_read;
5633 IOHandler *fd_write;
5634 int deleted;
5635 void *opaque;
5636 /* temporary data */
5637 struct pollfd *ufd;
5638 struct IOHandlerRecord *next;
5639 } IOHandlerRecord;
5641 static IOHandlerRecord *first_io_handler;
5643 /* XXX: fd_read_poll should be suppressed, but an API change is
5644 necessary in the character devices to suppress fd_can_read(). */
5645 int qemu_set_fd_handler2(int fd,
5646 IOCanRWHandler *fd_read_poll,
5647 IOHandler *fd_read,
5648 IOHandler *fd_write,
5649 void *opaque)
5651 IOHandlerRecord **pioh, *ioh;
5653 if (!fd_read && !fd_write) {
5654 pioh = &first_io_handler;
5655 for(;;) {
5656 ioh = *pioh;
5657 if (ioh == NULL)
5658 break;
5659 if (ioh->fd == fd) {
5660 ioh->deleted = 1;
5661 break;
5663 pioh = &ioh->next;
5665 } else {
5666 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5667 if (ioh->fd == fd)
5668 goto found;
5670 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5671 if (!ioh)
5672 return -1;
5673 ioh->next = first_io_handler;
5674 first_io_handler = ioh;
5675 found:
5676 ioh->fd = fd;
5677 ioh->fd_read_poll = fd_read_poll;
5678 ioh->fd_read = fd_read;
5679 ioh->fd_write = fd_write;
5680 ioh->opaque = opaque;
5681 ioh->deleted = 0;
5683 return 0;
5686 int qemu_set_fd_handler(int fd,
5687 IOHandler *fd_read,
5688 IOHandler *fd_write,
5689 void *opaque)
5691 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5694 /***********************************************************/
5695 /* Polling handling */
5697 typedef struct PollingEntry {
5698 PollingFunc *func;
5699 void *opaque;
5700 struct PollingEntry *next;
5701 } PollingEntry;
5703 static PollingEntry *first_polling_entry;
5705 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5707 PollingEntry **ppe, *pe;
5708 pe = qemu_mallocz(sizeof(PollingEntry));
5709 if (!pe)
5710 return -1;
5711 pe->func = func;
5712 pe->opaque = opaque;
5713 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5714 *ppe = pe;
5715 return 0;
5718 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5720 PollingEntry **ppe, *pe;
5721 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5722 pe = *ppe;
5723 if (pe->func == func && pe->opaque == opaque) {
5724 *ppe = pe->next;
5725 qemu_free(pe);
5726 break;
5731 #ifdef _WIN32
5732 /***********************************************************/
5733 /* Wait objects support */
5734 typedef struct WaitObjects {
5735 int num;
5736 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5737 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5738 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5739 } WaitObjects;
5741 static WaitObjects wait_objects = {0};
5743 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5745 WaitObjects *w = &wait_objects;
5747 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5748 return -1;
5749 w->events[w->num] = handle;
5750 w->func[w->num] = func;
5751 w->opaque[w->num] = opaque;
5752 w->num++;
5753 return 0;
5756 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5758 int i, found;
5759 WaitObjects *w = &wait_objects;
5761 found = 0;
5762 for (i = 0; i < w->num; i++) {
5763 if (w->events[i] == handle)
5764 found = 1;
5765 if (found) {
5766 w->events[i] = w->events[i + 1];
5767 w->func[i] = w->func[i + 1];
5768 w->opaque[i] = w->opaque[i + 1];
5771 if (found)
5772 w->num--;
5774 #endif
5776 #define SELF_ANNOUNCE_ROUNDS 5
5777 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5778 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5779 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5781 static int announce_self_create(uint8_t *buf,
5782 uint8_t *mac_addr)
5784 uint32_t magic = EXPERIMENTAL_MAGIC;
5785 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5787 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5789 memset(buf, 0xff, 6); /* h_dst */
5790 memcpy(buf + 6, mac_addr, 6); /* h_src */
5791 memcpy(buf + 12, &proto, 2); /* h_proto */
5792 memcpy(buf + 14, &magic, 4); /* magic */
5794 return 18; /* len */
5797 static void qemu_announce_self(void)
5799 int i, j, len;
5800 VLANState *vlan;
5801 VLANClientState *vc;
5802 uint8_t buf[256];
5804 for (i = 0; i < nb_nics; i++) {
5805 len = announce_self_create(buf, nd_table[i].macaddr);
5806 vlan = nd_table[i].vlan;
5807 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5808 if (vc->fd_read == tap_receive) /* send only if tap */
5809 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5810 vc->fd_read(vc->opaque, buf, len);
5815 /***********************************************************/
5816 /* savevm/loadvm support */
5818 #define IO_BUF_SIZE 32768
5820 struct QEMUFile {
5821 QEMUFilePutBufferFunc *put_buffer;
5822 QEMUFileGetBufferFunc *get_buffer;
5823 QEMUFileCloseFunc *close;
5824 void *opaque;
5826 int64_t buf_offset; /* start of buffer when writing, end of buffer
5827 when reading */
5828 int buf_index;
5829 int buf_size; /* 0 when writing */
5830 uint8_t buf[IO_BUF_SIZE];
5833 typedef struct QEMUFileFD
5835 int fd;
5836 } QEMUFileFD;
5838 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5840 QEMUFileFD *s = opaque;
5841 int offset = 0;
5842 ssize_t len;
5844 again:
5845 len = read(s->fd, buf + offset, size - offset);
5846 if (len == -1) {
5847 if (errno == EINTR || errno == EAGAIN)
5848 goto again;
5851 return len;
5854 QEMUFile *qemu_fopen_fd(int fd)
5856 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5857 s->fd = fd;
5858 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5861 typedef struct QEMUFileUnix
5863 FILE *outfile;
5864 } QEMUFileUnix;
5866 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5868 QEMUFileUnix *s = opaque;
5869 fseek(s->outfile, pos, SEEK_SET);
5870 fwrite(buf, 1, size, s->outfile);
5873 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5875 QEMUFileUnix *s = opaque;
5876 fseek(s->outfile, pos, SEEK_SET);
5877 return fread(buf, 1, size, s->outfile);
5880 static void file_close(void *opaque)
5882 QEMUFileUnix *s = opaque;
5883 fclose(s->outfile);
5884 qemu_free(s);
5887 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5889 QEMUFileUnix *s;
5891 s = qemu_mallocz(sizeof(QEMUFileUnix));
5892 if (!s)
5893 return NULL;
5895 s->outfile = fopen(filename, mode);
5896 if (!s->outfile)
5897 goto fail;
5899 if (!strcmp(mode, "wb"))
5900 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5901 else if (!strcmp(mode, "rb"))
5902 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5904 fail:
5905 if (s->outfile)
5906 fclose(s->outfile);
5907 qemu_free(s);
5908 return NULL;
5911 typedef struct QEMUFileBdrv
5913 BlockDriverState *bs;
5914 int64_t base_offset;
5915 } QEMUFileBdrv;
5917 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5919 QEMUFileBdrv *s = opaque;
5920 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5923 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5925 QEMUFileBdrv *s = opaque;
5926 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5929 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5931 QEMUFileBdrv *s;
5933 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5934 if (!s)
5935 return NULL;
5937 s->bs = bs;
5938 s->base_offset = offset;
5940 if (is_writable)
5941 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5943 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5946 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5947 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5949 QEMUFile *f;
5951 f = qemu_mallocz(sizeof(QEMUFile));
5952 if (!f)
5953 return NULL;
5955 f->opaque = opaque;
5956 f->put_buffer = put_buffer;
5957 f->get_buffer = get_buffer;
5958 f->close = close;
5960 return f;
5963 void qemu_fflush(QEMUFile *f)
5965 if (!f->put_buffer)
5966 return;
5968 if (f->buf_index > 0) {
5969 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5970 f->buf_offset += f->buf_index;
5971 f->buf_index = 0;
5975 static void qemu_fill_buffer(QEMUFile *f)
5977 int len;
5979 if (!f->get_buffer)
5980 return;
5982 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5983 if (len < 0)
5984 len = 0;
5986 f->buf_index = 0;
5987 f->buf_size = len;
5988 f->buf_offset += len;
5991 void qemu_fclose(QEMUFile *f)
5993 qemu_fflush(f);
5994 if (f->close)
5995 f->close(f->opaque);
5996 qemu_free(f);
5999 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6001 int l;
6002 while (size > 0) {
6003 l = IO_BUF_SIZE - f->buf_index;
6004 if (l > size)
6005 l = size;
6006 memcpy(f->buf + f->buf_index, buf, l);
6007 f->buf_index += l;
6008 buf += l;
6009 size -= l;
6010 if (f->buf_index >= IO_BUF_SIZE)
6011 qemu_fflush(f);
6015 void qemu_put_byte(QEMUFile *f, int v)
6017 f->buf[f->buf_index++] = v;
6018 if (f->buf_index >= IO_BUF_SIZE)
6019 qemu_fflush(f);
6022 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6024 int size, l;
6026 size = size1;
6027 while (size > 0) {
6028 l = f->buf_size - f->buf_index;
6029 if (l == 0) {
6030 qemu_fill_buffer(f);
6031 l = f->buf_size - f->buf_index;
6032 if (l == 0)
6033 break;
6035 if (l > size)
6036 l = size;
6037 memcpy(buf, f->buf + f->buf_index, l);
6038 f->buf_index += l;
6039 buf += l;
6040 size -= l;
6042 return size1 - size;
6045 int qemu_get_byte(QEMUFile *f)
6047 if (f->buf_index >= f->buf_size) {
6048 qemu_fill_buffer(f);
6049 if (f->buf_index >= f->buf_size)
6050 return 0;
6052 return f->buf[f->buf_index++];
6055 int64_t qemu_ftell(QEMUFile *f)
6057 return f->buf_offset - f->buf_size + f->buf_index;
6060 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6062 if (whence == SEEK_SET) {
6063 /* nothing to do */
6064 } else if (whence == SEEK_CUR) {
6065 pos += qemu_ftell(f);
6066 } else {
6067 /* SEEK_END not supported */
6068 return -1;
6070 if (f->put_buffer) {
6071 qemu_fflush(f);
6072 f->buf_offset = pos;
6073 } else {
6074 f->buf_offset = pos;
6075 f->buf_index = 0;
6076 f->buf_size = 0;
6078 return pos;
6081 void qemu_put_be16(QEMUFile *f, unsigned int v)
6083 qemu_put_byte(f, v >> 8);
6084 qemu_put_byte(f, v);
6087 void qemu_put_be32(QEMUFile *f, unsigned int v)
6089 qemu_put_byte(f, v >> 24);
6090 qemu_put_byte(f, v >> 16);
6091 qemu_put_byte(f, v >> 8);
6092 qemu_put_byte(f, v);
6095 void qemu_put_be64(QEMUFile *f, uint64_t v)
6097 qemu_put_be32(f, v >> 32);
6098 qemu_put_be32(f, v);
6101 unsigned int qemu_get_be16(QEMUFile *f)
6103 unsigned int v;
6104 v = qemu_get_byte(f) << 8;
6105 v |= qemu_get_byte(f);
6106 return v;
6109 unsigned int qemu_get_be32(QEMUFile *f)
6111 unsigned int v;
6112 v = qemu_get_byte(f) << 24;
6113 v |= qemu_get_byte(f) << 16;
6114 v |= qemu_get_byte(f) << 8;
6115 v |= qemu_get_byte(f);
6116 return v;
6119 uint64_t qemu_get_be64(QEMUFile *f)
6121 uint64_t v;
6122 v = (uint64_t)qemu_get_be32(f) << 32;
6123 v |= qemu_get_be32(f);
6124 return v;
6127 typedef struct SaveStateEntry {
6128 char idstr[256];
6129 int instance_id;
6130 int version_id;
6131 SaveStateHandler *save_state;
6132 LoadStateHandler *load_state;
6133 void *opaque;
6134 struct SaveStateEntry *next;
6135 } SaveStateEntry;
6137 static SaveStateEntry *first_se;
6139 int register_savevm(const char *idstr,
6140 int instance_id,
6141 int version_id,
6142 SaveStateHandler *save_state,
6143 LoadStateHandler *load_state,
6144 void *opaque)
6146 SaveStateEntry *se, **pse;
6148 se = qemu_malloc(sizeof(SaveStateEntry));
6149 if (!se)
6150 return -1;
6151 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6152 se->instance_id = instance_id;
6153 se->version_id = version_id;
6154 se->save_state = save_state;
6155 se->load_state = load_state;
6156 se->opaque = opaque;
6157 se->next = NULL;
6159 /* add at the end of list */
6160 pse = &first_se;
6161 while (*pse != NULL)
6162 pse = &(*pse)->next;
6163 *pse = se;
6164 return 0;
6167 #define QEMU_VM_FILE_MAGIC 0x5145564d
6168 #define QEMU_VM_FILE_VERSION 0x00000002
6170 static int qemu_savevm_state(QEMUFile *f)
6172 SaveStateEntry *se;
6173 int len, ret;
6174 int64_t cur_pos, len_pos, total_len_pos;
6176 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6177 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6178 total_len_pos = qemu_ftell(f);
6179 qemu_put_be64(f, 0); /* total size */
6181 for(se = first_se; se != NULL; se = se->next) {
6182 /* ID string */
6183 len = strlen(se->idstr);
6184 qemu_put_byte(f, len);
6185 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6187 qemu_put_be32(f, se->instance_id);
6188 qemu_put_be32(f, se->version_id);
6190 /* record size: filled later */
6191 len_pos = qemu_ftell(f);
6192 qemu_put_be32(f, 0);
6193 se->save_state(f, se->opaque);
6195 /* fill record size */
6196 cur_pos = qemu_ftell(f);
6197 len = cur_pos - len_pos - 4;
6198 qemu_fseek(f, len_pos, SEEK_SET);
6199 qemu_put_be32(f, len);
6200 qemu_fseek(f, cur_pos, SEEK_SET);
6202 cur_pos = qemu_ftell(f);
6203 qemu_fseek(f, total_len_pos, SEEK_SET);
6204 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6205 qemu_fseek(f, cur_pos, SEEK_SET);
6207 ret = 0;
6208 return ret;
6211 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6213 SaveStateEntry *se;
6215 for(se = first_se; se != NULL; se = se->next) {
6216 if (!strcmp(se->idstr, idstr) &&
6217 instance_id == se->instance_id)
6218 return se;
6220 return NULL;
6223 static int qemu_loadvm_state(QEMUFile *f)
6225 SaveStateEntry *se;
6226 int len, ret, instance_id, record_len, version_id;
6227 int64_t total_len, end_pos, cur_pos;
6228 unsigned int v;
6229 char idstr[256];
6231 v = qemu_get_be32(f);
6232 if (v != QEMU_VM_FILE_MAGIC)
6233 goto fail;
6234 v = qemu_get_be32(f);
6235 if (v != QEMU_VM_FILE_VERSION) {
6236 fail:
6237 ret = -1;
6238 goto the_end;
6240 total_len = qemu_get_be64(f);
6241 end_pos = total_len + qemu_ftell(f);
6242 for(;;) {
6243 if (qemu_ftell(f) >= end_pos)
6244 break;
6245 len = qemu_get_byte(f);
6246 qemu_get_buffer(f, (uint8_t *)idstr, len);
6247 idstr[len] = '\0';
6248 instance_id = qemu_get_be32(f);
6249 version_id = qemu_get_be32(f);
6250 record_len = qemu_get_be32(f);
6251 #if 0
6252 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6253 idstr, instance_id, version_id, record_len);
6254 #endif
6255 cur_pos = qemu_ftell(f);
6256 se = find_se(idstr, instance_id);
6257 if (!se) {
6258 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6259 instance_id, idstr);
6260 } else {
6261 ret = se->load_state(f, se->opaque, version_id);
6262 if (ret < 0) {
6263 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6264 instance_id, idstr);
6265 goto the_end;
6268 /* always seek to exact end of record */
6269 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6271 ret = 0;
6272 the_end:
6273 return ret;
6276 int qemu_live_savevm_state(QEMUFile *f)
6278 SaveStateEntry *se;
6279 int len, ret;
6281 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6282 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6284 for(se = first_se; se != NULL; se = se->next) {
6285 len = strlen(se->idstr);
6287 qemu_put_byte(f, len);
6288 qemu_put_buffer(f, se->idstr, len);
6289 qemu_put_be32(f, se->instance_id);
6290 qemu_put_be32(f, se->version_id);
6292 se->save_state(f, se->opaque);
6295 qemu_put_byte(f, 0);
6297 ret = 0;
6298 return ret;
6301 int qemu_live_loadvm_state(QEMUFile *f)
6303 SaveStateEntry *se;
6304 int len, ret, instance_id, version_id;
6305 unsigned int v;
6306 char idstr[256];
6308 v = qemu_get_be32(f);
6309 if (v != QEMU_VM_FILE_MAGIC)
6310 goto fail;
6311 v = qemu_get_be32(f);
6312 if (v != QEMU_VM_FILE_VERSION) {
6313 fail:
6314 ret = -1;
6315 goto the_end;
6318 for(;;) {
6319 len = qemu_get_byte(f);
6320 if (len == 0)
6321 break;
6322 qemu_get_buffer(f, idstr, len);
6323 idstr[len] = '\0';
6324 instance_id = qemu_get_be32(f);
6325 version_id = qemu_get_be32(f);
6326 se = find_se(idstr, instance_id);
6327 if (!se) {
6328 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6329 instance_id, idstr);
6330 } else {
6331 if (version_id > se->version_id) { /* src version > dst version */
6332 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6333 idstr, version_id, se->version_id);
6334 ret = -1;
6335 goto the_end;
6337 ret = se->load_state(f, se->opaque, version_id);
6338 if (ret < 0) {
6339 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6340 instance_id, idstr);
6341 goto the_end;
6345 ret = 0;
6347 qemu_announce_self();
6349 the_end:
6350 return ret;
6353 /* device can contain snapshots */
6354 static int bdrv_can_snapshot(BlockDriverState *bs)
6356 return (bs &&
6357 !bdrv_is_removable(bs) &&
6358 !bdrv_is_read_only(bs));
6361 /* device must be snapshots in order to have a reliable snapshot */
6362 static int bdrv_has_snapshot(BlockDriverState *bs)
6364 return (bs &&
6365 !bdrv_is_removable(bs) &&
6366 !bdrv_is_read_only(bs));
6369 static BlockDriverState *get_bs_snapshots(void)
6371 BlockDriverState *bs;
6372 int i;
6374 if (bs_snapshots)
6375 return bs_snapshots;
6376 for(i = 0; i <= nb_drives; i++) {
6377 bs = drives_table[i].bdrv;
6378 if (bdrv_can_snapshot(bs))
6379 goto ok;
6381 return NULL;
6383 bs_snapshots = bs;
6384 return bs;
6387 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6388 const char *name)
6390 QEMUSnapshotInfo *sn_tab, *sn;
6391 int nb_sns, i, ret;
6393 ret = -ENOENT;
6394 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6395 if (nb_sns < 0)
6396 return ret;
6397 for(i = 0; i < nb_sns; i++) {
6398 sn = &sn_tab[i];
6399 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6400 *sn_info = *sn;
6401 ret = 0;
6402 break;
6405 qemu_free(sn_tab);
6406 return ret;
6409 void do_savevm(const char *name)
6411 BlockDriverState *bs, *bs1;
6412 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6413 int must_delete, ret, i;
6414 BlockDriverInfo bdi1, *bdi = &bdi1;
6415 QEMUFile *f;
6416 int saved_vm_running;
6417 #ifdef _WIN32
6418 struct _timeb tb;
6419 #else
6420 struct timeval tv;
6421 #endif
6423 bs = get_bs_snapshots();
6424 if (!bs) {
6425 term_printf("No block device can accept snapshots\n");
6426 return;
6429 /* ??? Should this occur after vm_stop? */
6430 qemu_aio_flush();
6432 saved_vm_running = vm_running;
6433 vm_stop(0);
6435 must_delete = 0;
6436 if (name) {
6437 ret = bdrv_snapshot_find(bs, old_sn, name);
6438 if (ret >= 0) {
6439 must_delete = 1;
6442 memset(sn, 0, sizeof(*sn));
6443 if (must_delete) {
6444 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6445 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6446 } else {
6447 if (name)
6448 pstrcpy(sn->name, sizeof(sn->name), name);
6451 /* fill auxiliary fields */
6452 #ifdef _WIN32
6453 _ftime(&tb);
6454 sn->date_sec = tb.time;
6455 sn->date_nsec = tb.millitm * 1000000;
6456 #else
6457 gettimeofday(&tv, NULL);
6458 sn->date_sec = tv.tv_sec;
6459 sn->date_nsec = tv.tv_usec * 1000;
6460 #endif
6461 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6463 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6464 term_printf("Device %s does not support VM state snapshots\n",
6465 bdrv_get_device_name(bs));
6466 goto the_end;
6469 /* save the VM state */
6470 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6471 if (!f) {
6472 term_printf("Could not open VM state file\n");
6473 goto the_end;
6475 ret = qemu_savevm_state(f);
6476 sn->vm_state_size = qemu_ftell(f);
6477 qemu_fclose(f);
6478 if (ret < 0) {
6479 term_printf("Error %d while writing VM\n", ret);
6480 goto the_end;
6483 /* create the snapshots */
6485 for(i = 0; i < nb_drives; i++) {
6486 bs1 = drives_table[i].bdrv;
6487 if (bdrv_has_snapshot(bs1)) {
6488 if (must_delete) {
6489 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6490 if (ret < 0) {
6491 term_printf("Error while deleting snapshot on '%s'\n",
6492 bdrv_get_device_name(bs1));
6495 ret = bdrv_snapshot_create(bs1, sn);
6496 if (ret < 0) {
6497 term_printf("Error while creating snapshot on '%s'\n",
6498 bdrv_get_device_name(bs1));
6503 the_end:
6504 if (saved_vm_running)
6505 vm_start();
6508 void do_loadvm(const char *name)
6510 BlockDriverState *bs, *bs1;
6511 BlockDriverInfo bdi1, *bdi = &bdi1;
6512 QEMUFile *f;
6513 int i, ret;
6514 int saved_vm_running;
6516 bs = get_bs_snapshots();
6517 if (!bs) {
6518 term_printf("No block device supports snapshots\n");
6519 return;
6522 /* Flush all IO requests so they don't interfere with the new state. */
6523 qemu_aio_flush();
6525 saved_vm_running = vm_running;
6526 vm_stop(0);
6528 for(i = 0; i <= nb_drives; i++) {
6529 bs1 = drives_table[i].bdrv;
6530 if (bdrv_has_snapshot(bs1)) {
6531 ret = bdrv_snapshot_goto(bs1, name);
6532 if (ret < 0) {
6533 if (bs != bs1)
6534 term_printf("Warning: ");
6535 switch(ret) {
6536 case -ENOTSUP:
6537 term_printf("Snapshots not supported on device '%s'\n",
6538 bdrv_get_device_name(bs1));
6539 break;
6540 case -ENOENT:
6541 term_printf("Could not find snapshot '%s' on device '%s'\n",
6542 name, bdrv_get_device_name(bs1));
6543 break;
6544 default:
6545 term_printf("Error %d while activating snapshot on '%s'\n",
6546 ret, bdrv_get_device_name(bs1));
6547 break;
6549 /* fatal on snapshot block device */
6550 if (bs == bs1)
6551 goto the_end;
6556 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6557 term_printf("Device %s does not support VM state snapshots\n",
6558 bdrv_get_device_name(bs));
6559 return;
6562 /* restore the VM state */
6563 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6564 if (!f) {
6565 term_printf("Could not open VM state file\n");
6566 goto the_end;
6568 ret = qemu_loadvm_state(f);
6569 qemu_fclose(f);
6570 if (ret < 0) {
6571 term_printf("Error %d while loading VM state\n", ret);
6573 the_end:
6574 if (saved_vm_running)
6575 vm_start();
6578 void do_delvm(const char *name)
6580 BlockDriverState *bs, *bs1;
6581 int i, ret;
6583 bs = get_bs_snapshots();
6584 if (!bs) {
6585 term_printf("No block device supports snapshots\n");
6586 return;
6589 for(i = 0; i <= nb_drives; i++) {
6590 bs1 = drives_table[i].bdrv;
6591 if (bdrv_has_snapshot(bs1)) {
6592 ret = bdrv_snapshot_delete(bs1, name);
6593 if (ret < 0) {
6594 if (ret == -ENOTSUP)
6595 term_printf("Snapshots not supported on device '%s'\n",
6596 bdrv_get_device_name(bs1));
6597 else
6598 term_printf("Error %d while deleting snapshot on '%s'\n",
6599 ret, bdrv_get_device_name(bs1));
6605 void do_info_snapshots(void)
6607 BlockDriverState *bs, *bs1;
6608 QEMUSnapshotInfo *sn_tab, *sn;
6609 int nb_sns, i;
6610 char buf[256];
6612 bs = get_bs_snapshots();
6613 if (!bs) {
6614 term_printf("No available block device supports snapshots\n");
6615 return;
6617 term_printf("Snapshot devices:");
6618 for(i = 0; i <= nb_drives; i++) {
6619 bs1 = drives_table[i].bdrv;
6620 if (bdrv_has_snapshot(bs1)) {
6621 if (bs == bs1)
6622 term_printf(" %s", bdrv_get_device_name(bs1));
6625 term_printf("\n");
6627 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6628 if (nb_sns < 0) {
6629 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6630 return;
6632 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6633 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6634 for(i = 0; i < nb_sns; i++) {
6635 sn = &sn_tab[i];
6636 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6638 qemu_free(sn_tab);
6641 /***********************************************************/
6642 /* cpu save/restore */
6644 #if defined(TARGET_I386)
6646 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6648 qemu_put_be32(f, dt->selector);
6649 qemu_put_betl(f, dt->base);
6650 qemu_put_be32(f, dt->limit);
6651 qemu_put_be32(f, dt->flags);
6654 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6656 dt->selector = qemu_get_be32(f);
6657 dt->base = qemu_get_betl(f);
6658 dt->limit = qemu_get_be32(f);
6659 dt->flags = qemu_get_be32(f);
6662 void cpu_save(QEMUFile *f, void *opaque)
6664 CPUState *env = opaque;
6665 uint16_t fptag, fpus, fpuc, fpregs_format;
6666 uint32_t hflags;
6667 int i;
6669 if (kvm_enabled()) {
6670 kvm_save_registers(env);
6671 kvm_save_mpstate(env);
6674 for(i = 0; i < CPU_NB_REGS; i++)
6675 qemu_put_betls(f, &env->regs[i]);
6676 qemu_put_betls(f, &env->eip);
6677 qemu_put_betls(f, &env->eflags);
6678 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6679 qemu_put_be32s(f, &hflags);
6681 /* FPU */
6682 fpuc = env->fpuc;
6683 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6684 fptag = 0;
6685 for(i = 0; i < 8; i++) {
6686 fptag |= ((!env->fptags[i]) << i);
6689 qemu_put_be16s(f, &fpuc);
6690 qemu_put_be16s(f, &fpus);
6691 qemu_put_be16s(f, &fptag);
6693 #ifdef USE_X86LDOUBLE
6694 fpregs_format = 0;
6695 #else
6696 fpregs_format = 1;
6697 #endif
6698 qemu_put_be16s(f, &fpregs_format);
6700 for(i = 0; i < 8; i++) {
6701 #ifdef USE_X86LDOUBLE
6703 uint64_t mant;
6704 uint16_t exp;
6705 /* we save the real CPU data (in case of MMX usage only 'mant'
6706 contains the MMX register */
6707 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6708 qemu_put_be64(f, mant);
6709 qemu_put_be16(f, exp);
6711 #else
6712 /* if we use doubles for float emulation, we save the doubles to
6713 avoid losing information in case of MMX usage. It can give
6714 problems if the image is restored on a CPU where long
6715 doubles are used instead. */
6716 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6717 #endif
6720 for(i = 0; i < 6; i++)
6721 cpu_put_seg(f, &env->segs[i]);
6722 cpu_put_seg(f, &env->ldt);
6723 cpu_put_seg(f, &env->tr);
6724 cpu_put_seg(f, &env->gdt);
6725 cpu_put_seg(f, &env->idt);
6727 qemu_put_be32s(f, &env->sysenter_cs);
6728 qemu_put_be32s(f, &env->sysenter_esp);
6729 qemu_put_be32s(f, &env->sysenter_eip);
6731 qemu_put_betls(f, &env->cr[0]);
6732 qemu_put_betls(f, &env->cr[2]);
6733 qemu_put_betls(f, &env->cr[3]);
6734 qemu_put_betls(f, &env->cr[4]);
6736 for(i = 0; i < 8; i++)
6737 qemu_put_betls(f, &env->dr[i]);
6739 /* MMU */
6740 qemu_put_be32s(f, &env->a20_mask);
6742 /* XMM */
6743 qemu_put_be32s(f, &env->mxcsr);
6744 for(i = 0; i < CPU_NB_REGS; i++) {
6745 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6746 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6749 #ifdef TARGET_X86_64
6750 qemu_put_be64s(f, &env->efer);
6751 qemu_put_be64s(f, &env->star);
6752 qemu_put_be64s(f, &env->lstar);
6753 qemu_put_be64s(f, &env->cstar);
6754 qemu_put_be64s(f, &env->fmask);
6755 qemu_put_be64s(f, &env->kernelgsbase);
6756 #endif
6757 qemu_put_be32s(f, &env->smbase);
6759 if (kvm_enabled()) {
6760 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6761 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6763 qemu_put_be64s(f, &env->tsc);
6764 qemu_put_be32s(f, &env->mp_state);
6768 #ifdef USE_X86LDOUBLE
6769 /* XXX: add that in a FPU generic layer */
6770 union x86_longdouble {
6771 uint64_t mant;
6772 uint16_t exp;
6775 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6776 #define EXPBIAS1 1023
6777 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6778 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6780 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6782 int e;
6783 /* mantissa */
6784 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6785 /* exponent + sign */
6786 e = EXPD1(temp) - EXPBIAS1 + 16383;
6787 e |= SIGND1(temp) >> 16;
6788 p->exp = e;
6790 #endif
6792 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6794 CPUState *env = opaque;
6795 int i, guess_mmx;
6796 uint32_t hflags;
6797 uint16_t fpus, fpuc, fptag, fpregs_format;
6799 if (version_id < 3 || version_id > 5)
6800 return -EINVAL;
6801 for(i = 0; i < CPU_NB_REGS; i++)
6802 qemu_get_betls(f, &env->regs[i]);
6803 qemu_get_betls(f, &env->eip);
6804 qemu_get_betls(f, &env->eflags);
6805 qemu_get_be32s(f, &hflags);
6807 qemu_get_be16s(f, &fpuc);
6808 qemu_get_be16s(f, &fpus);
6809 qemu_get_be16s(f, &fptag);
6810 qemu_get_be16s(f, &fpregs_format);
6812 /* NOTE: we cannot always restore the FPU state if the image come
6813 from a host with a different 'USE_X86LDOUBLE' define. We guess
6814 if we are in an MMX state to restore correctly in that case. */
6815 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6816 for(i = 0; i < 8; i++) {
6817 uint64_t mant;
6818 uint16_t exp;
6820 switch(fpregs_format) {
6821 case 0:
6822 mant = qemu_get_be64(f);
6823 exp = qemu_get_be16(f);
6824 #ifdef USE_X86LDOUBLE
6825 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6826 #else
6827 /* difficult case */
6828 if (guess_mmx)
6829 env->fpregs[i].mmx.MMX_Q(0) = mant;
6830 else
6831 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6832 #endif
6833 break;
6834 case 1:
6835 mant = qemu_get_be64(f);
6836 #ifdef USE_X86LDOUBLE
6838 union x86_longdouble *p;
6839 /* difficult case */
6840 p = (void *)&env->fpregs[i];
6841 if (guess_mmx) {
6842 p->mant = mant;
6843 p->exp = 0xffff;
6844 } else {
6845 fp64_to_fp80(p, mant);
6848 #else
6849 env->fpregs[i].mmx.MMX_Q(0) = mant;
6850 #endif
6851 break;
6852 default:
6853 return -EINVAL;
6857 env->fpuc = fpuc;
6858 /* XXX: restore FPU round state */
6859 env->fpstt = (fpus >> 11) & 7;
6860 env->fpus = fpus & ~0x3800;
6861 fptag ^= 0xff;
6862 for(i = 0; i < 8; i++) {
6863 env->fptags[i] = (fptag >> i) & 1;
6866 for(i = 0; i < 6; i++)
6867 cpu_get_seg(f, &env->segs[i]);
6868 cpu_get_seg(f, &env->ldt);
6869 cpu_get_seg(f, &env->tr);
6870 cpu_get_seg(f, &env->gdt);
6871 cpu_get_seg(f, &env->idt);
6873 qemu_get_be32s(f, &env->sysenter_cs);
6874 qemu_get_be32s(f, &env->sysenter_esp);
6875 qemu_get_be32s(f, &env->sysenter_eip);
6877 qemu_get_betls(f, &env->cr[0]);
6878 qemu_get_betls(f, &env->cr[2]);
6879 qemu_get_betls(f, &env->cr[3]);
6880 qemu_get_betls(f, &env->cr[4]);
6882 for(i = 0; i < 8; i++)
6883 qemu_get_betls(f, &env->dr[i]);
6885 /* MMU */
6886 qemu_get_be32s(f, &env->a20_mask);
6888 qemu_get_be32s(f, &env->mxcsr);
6889 for(i = 0; i < CPU_NB_REGS; i++) {
6890 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6891 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6894 #ifdef TARGET_X86_64
6895 qemu_get_be64s(f, &env->efer);
6896 qemu_get_be64s(f, &env->star);
6897 qemu_get_be64s(f, &env->lstar);
6898 qemu_get_be64s(f, &env->cstar);
6899 qemu_get_be64s(f, &env->fmask);
6900 qemu_get_be64s(f, &env->kernelgsbase);
6901 #endif
6902 if (version_id >= 4)
6903 qemu_get_be32s(f, &env->smbase);
6905 /* XXX: compute hflags from scratch, except for CPL and IIF */
6906 env->hflags = hflags;
6907 tlb_flush(env, 1);
6908 if (kvm_enabled()) {
6909 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6910 because no userspace IRQs will ever clear this flag */
6911 env->hflags &= ~HF_HALTED_MASK;
6912 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6913 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6915 qemu_get_be64s(f, &env->tsc);
6916 kvm_load_registers(env);
6917 if (version_id >= 5) {
6918 qemu_get_be32s(f, &env->mp_state);
6919 kvm_load_mpstate(env);
6922 return 0;
6925 #elif defined(TARGET_PPC)
6926 void cpu_save(QEMUFile *f, void *opaque)
6930 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6932 return 0;
6935 #elif defined(TARGET_MIPS)
6936 void cpu_save(QEMUFile *f, void *opaque)
6940 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6942 return 0;
6945 #elif defined(TARGET_SPARC)
6946 void cpu_save(QEMUFile *f, void *opaque)
6948 CPUState *env = opaque;
6949 int i;
6950 uint32_t tmp;
6952 for(i = 0; i < 8; i++)
6953 qemu_put_betls(f, &env->gregs[i]);
6954 for(i = 0; i < NWINDOWS * 16; i++)
6955 qemu_put_betls(f, &env->regbase[i]);
6957 /* FPU */
6958 for(i = 0; i < TARGET_FPREGS; i++) {
6959 union {
6960 float32 f;
6961 uint32_t i;
6962 } u;
6963 u.f = env->fpr[i];
6964 qemu_put_be32(f, u.i);
6967 qemu_put_betls(f, &env->pc);
6968 qemu_put_betls(f, &env->npc);
6969 qemu_put_betls(f, &env->y);
6970 tmp = GET_PSR(env);
6971 qemu_put_be32(f, tmp);
6972 qemu_put_betls(f, &env->fsr);
6973 qemu_put_betls(f, &env->tbr);
6974 #ifndef TARGET_SPARC64
6975 qemu_put_be32s(f, &env->wim);
6976 /* MMU */
6977 for(i = 0; i < 16; i++)
6978 qemu_put_be32s(f, &env->mmuregs[i]);
6979 #endif
6982 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6984 CPUState *env = opaque;
6985 int i;
6986 uint32_t tmp;
6988 for(i = 0; i < 8; i++)
6989 qemu_get_betls(f, &env->gregs[i]);
6990 for(i = 0; i < NWINDOWS * 16; i++)
6991 qemu_get_betls(f, &env->regbase[i]);
6993 /* FPU */
6994 for(i = 0; i < TARGET_FPREGS; i++) {
6995 union {
6996 float32 f;
6997 uint32_t i;
6998 } u;
6999 u.i = qemu_get_be32(f);
7000 env->fpr[i] = u.f;
7003 qemu_get_betls(f, &env->pc);
7004 qemu_get_betls(f, &env->npc);
7005 qemu_get_betls(f, &env->y);
7006 tmp = qemu_get_be32(f);
7007 env->cwp = 0; /* needed to ensure that the wrapping registers are
7008 correctly updated */
7009 PUT_PSR(env, tmp);
7010 qemu_get_betls(f, &env->fsr);
7011 qemu_get_betls(f, &env->tbr);
7012 #ifndef TARGET_SPARC64
7013 qemu_get_be32s(f, &env->wim);
7014 /* MMU */
7015 for(i = 0; i < 16; i++)
7016 qemu_get_be32s(f, &env->mmuregs[i]);
7017 #endif
7018 tlb_flush(env, 1);
7019 return 0;
7022 #elif defined(TARGET_ARM)
7024 void cpu_save(QEMUFile *f, void *opaque)
7026 int i;
7027 CPUARMState *env = (CPUARMState *)opaque;
7029 for (i = 0; i < 16; i++) {
7030 qemu_put_be32(f, env->regs[i]);
7032 qemu_put_be32(f, cpsr_read(env));
7033 qemu_put_be32(f, env->spsr);
7034 for (i = 0; i < 6; i++) {
7035 qemu_put_be32(f, env->banked_spsr[i]);
7036 qemu_put_be32(f, env->banked_r13[i]);
7037 qemu_put_be32(f, env->banked_r14[i]);
7039 for (i = 0; i < 5; i++) {
7040 qemu_put_be32(f, env->usr_regs[i]);
7041 qemu_put_be32(f, env->fiq_regs[i]);
7043 qemu_put_be32(f, env->cp15.c0_cpuid);
7044 qemu_put_be32(f, env->cp15.c0_cachetype);
7045 qemu_put_be32(f, env->cp15.c1_sys);
7046 qemu_put_be32(f, env->cp15.c1_coproc);
7047 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
7048 qemu_put_be32(f, env->cp15.c2_base0);
7049 qemu_put_be32(f, env->cp15.c2_base1);
7050 qemu_put_be32(f, env->cp15.c2_mask);
7051 qemu_put_be32(f, env->cp15.c2_data);
7052 qemu_put_be32(f, env->cp15.c2_insn);
7053 qemu_put_be32(f, env->cp15.c3);
7054 qemu_put_be32(f, env->cp15.c5_insn);
7055 qemu_put_be32(f, env->cp15.c5_data);
7056 for (i = 0; i < 8; i++) {
7057 qemu_put_be32(f, env->cp15.c6_region[i]);
7059 qemu_put_be32(f, env->cp15.c6_insn);
7060 qemu_put_be32(f, env->cp15.c6_data);
7061 qemu_put_be32(f, env->cp15.c9_insn);
7062 qemu_put_be32(f, env->cp15.c9_data);
7063 qemu_put_be32(f, env->cp15.c13_fcse);
7064 qemu_put_be32(f, env->cp15.c13_context);
7065 qemu_put_be32(f, env->cp15.c13_tls1);
7066 qemu_put_be32(f, env->cp15.c13_tls2);
7067 qemu_put_be32(f, env->cp15.c13_tls3);
7068 qemu_put_be32(f, env->cp15.c15_cpar);
7070 qemu_put_be32(f, env->features);
7072 if (arm_feature(env, ARM_FEATURE_VFP)) {
7073 for (i = 0; i < 16; i++) {
7074 CPU_DoubleU u;
7075 u.d = env->vfp.regs[i];
7076 qemu_put_be32(f, u.l.upper);
7077 qemu_put_be32(f, u.l.lower);
7079 for (i = 0; i < 16; i++) {
7080 qemu_put_be32(f, env->vfp.xregs[i]);
7083 /* TODO: Should use proper FPSCR access functions. */
7084 qemu_put_be32(f, env->vfp.vec_len);
7085 qemu_put_be32(f, env->vfp.vec_stride);
7087 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7088 for (i = 16; i < 32; i++) {
7089 CPU_DoubleU u;
7090 u.d = env->vfp.regs[i];
7091 qemu_put_be32(f, u.l.upper);
7092 qemu_put_be32(f, u.l.lower);
7097 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7098 for (i = 0; i < 16; i++) {
7099 qemu_put_be64(f, env->iwmmxt.regs[i]);
7101 for (i = 0; i < 16; i++) {
7102 qemu_put_be32(f, env->iwmmxt.cregs[i]);
7106 if (arm_feature(env, ARM_FEATURE_M)) {
7107 qemu_put_be32(f, env->v7m.other_sp);
7108 qemu_put_be32(f, env->v7m.vecbase);
7109 qemu_put_be32(f, env->v7m.basepri);
7110 qemu_put_be32(f, env->v7m.control);
7111 qemu_put_be32(f, env->v7m.current_sp);
7112 qemu_put_be32(f, env->v7m.exception);
7116 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7118 CPUARMState *env = (CPUARMState *)opaque;
7119 int i;
7121 if (version_id != ARM_CPU_SAVE_VERSION)
7122 return -EINVAL;
7124 for (i = 0; i < 16; i++) {
7125 env->regs[i] = qemu_get_be32(f);
7127 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
7128 env->spsr = qemu_get_be32(f);
7129 for (i = 0; i < 6; i++) {
7130 env->banked_spsr[i] = qemu_get_be32(f);
7131 env->banked_r13[i] = qemu_get_be32(f);
7132 env->banked_r14[i] = qemu_get_be32(f);
7134 for (i = 0; i < 5; i++) {
7135 env->usr_regs[i] = qemu_get_be32(f);
7136 env->fiq_regs[i] = qemu_get_be32(f);
7138 env->cp15.c0_cpuid = qemu_get_be32(f);
7139 env->cp15.c0_cachetype = qemu_get_be32(f);
7140 env->cp15.c1_sys = qemu_get_be32(f);
7141 env->cp15.c1_coproc = qemu_get_be32(f);
7142 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
7143 env->cp15.c2_base0 = qemu_get_be32(f);
7144 env->cp15.c2_base1 = qemu_get_be32(f);
7145 env->cp15.c2_mask = qemu_get_be32(f);
7146 env->cp15.c2_data = qemu_get_be32(f);
7147 env->cp15.c2_insn = qemu_get_be32(f);
7148 env->cp15.c3 = qemu_get_be32(f);
7149 env->cp15.c5_insn = qemu_get_be32(f);
7150 env->cp15.c5_data = qemu_get_be32(f);
7151 for (i = 0; i < 8; i++) {
7152 env->cp15.c6_region[i] = qemu_get_be32(f);
7154 env->cp15.c6_insn = qemu_get_be32(f);
7155 env->cp15.c6_data = qemu_get_be32(f);
7156 env->cp15.c9_insn = qemu_get_be32(f);
7157 env->cp15.c9_data = qemu_get_be32(f);
7158 env->cp15.c13_fcse = qemu_get_be32(f);
7159 env->cp15.c13_context = qemu_get_be32(f);
7160 env->cp15.c13_tls1 = qemu_get_be32(f);
7161 env->cp15.c13_tls2 = qemu_get_be32(f);
7162 env->cp15.c13_tls3 = qemu_get_be32(f);
7163 env->cp15.c15_cpar = qemu_get_be32(f);
7165 env->features = qemu_get_be32(f);
7167 if (arm_feature(env, ARM_FEATURE_VFP)) {
7168 for (i = 0; i < 16; i++) {
7169 CPU_DoubleU u;
7170 u.l.upper = qemu_get_be32(f);
7171 u.l.lower = qemu_get_be32(f);
7172 env->vfp.regs[i] = u.d;
7174 for (i = 0; i < 16; i++) {
7175 env->vfp.xregs[i] = qemu_get_be32(f);
7178 /* TODO: Should use proper FPSCR access functions. */
7179 env->vfp.vec_len = qemu_get_be32(f);
7180 env->vfp.vec_stride = qemu_get_be32(f);
7182 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7183 for (i = 0; i < 16; i++) {
7184 CPU_DoubleU u;
7185 u.l.upper = qemu_get_be32(f);
7186 u.l.lower = qemu_get_be32(f);
7187 env->vfp.regs[i] = u.d;
7192 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7193 for (i = 0; i < 16; i++) {
7194 env->iwmmxt.regs[i] = qemu_get_be64(f);
7196 for (i = 0; i < 16; i++) {
7197 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7201 if (arm_feature(env, ARM_FEATURE_M)) {
7202 env->v7m.other_sp = qemu_get_be32(f);
7203 env->v7m.vecbase = qemu_get_be32(f);
7204 env->v7m.basepri = qemu_get_be32(f);
7205 env->v7m.control = qemu_get_be32(f);
7206 env->v7m.current_sp = qemu_get_be32(f);
7207 env->v7m.exception = qemu_get_be32(f);
7210 return 0;
7213 #elif defined(TARGET_IA64)
7214 void cpu_save(QEMUFile *f, void *opaque)
7218 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7220 return 0;
7222 #else
7224 //#warning No CPU save/restore functions
7226 #endif
7228 /***********************************************************/
7229 /* ram save/restore */
7231 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7233 int v;
7235 v = qemu_get_byte(f);
7236 switch(v) {
7237 case 0:
7238 if (qemu_get_buffer(f, buf, len) != len)
7239 return -EIO;
7240 break;
7241 case 1:
7242 v = qemu_get_byte(f);
7243 memset(buf, v, len);
7244 break;
7245 default:
7246 return -EINVAL;
7248 return 0;
7251 static int ram_load_v1(QEMUFile *f, void *opaque)
7253 int i, ret;
7255 if (qemu_get_be32(f) != phys_ram_size)
7256 return -EINVAL;
7257 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7258 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7259 continue;
7260 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7261 if (ret)
7262 return ret;
7264 return 0;
7267 #define BDRV_HASH_BLOCK_SIZE 1024
7268 #define IOBUF_SIZE 4096
7269 #define RAM_CBLOCK_MAGIC 0xfabe
7271 typedef struct RamCompressState {
7272 z_stream zstream;
7273 QEMUFile *f;
7274 uint8_t buf[IOBUF_SIZE];
7275 } RamCompressState;
7277 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7279 int ret;
7280 memset(s, 0, sizeof(*s));
7281 s->f = f;
7282 ret = deflateInit2(&s->zstream, 1,
7283 Z_DEFLATED, 15,
7284 9, Z_DEFAULT_STRATEGY);
7285 if (ret != Z_OK)
7286 return -1;
7287 s->zstream.avail_out = IOBUF_SIZE;
7288 s->zstream.next_out = s->buf;
7289 return 0;
7292 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7294 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7295 qemu_put_be16(s->f, len);
7296 qemu_put_buffer(s->f, buf, len);
7299 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7301 int ret;
7303 s->zstream.avail_in = len;
7304 s->zstream.next_in = (uint8_t *)buf;
7305 while (s->zstream.avail_in > 0) {
7306 ret = deflate(&s->zstream, Z_NO_FLUSH);
7307 if (ret != Z_OK)
7308 return -1;
7309 if (s->zstream.avail_out == 0) {
7310 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7311 s->zstream.avail_out = IOBUF_SIZE;
7312 s->zstream.next_out = s->buf;
7315 return 0;
7318 static void ram_compress_close(RamCompressState *s)
7320 int len, ret;
7322 /* compress last bytes */
7323 for(;;) {
7324 ret = deflate(&s->zstream, Z_FINISH);
7325 if (ret == Z_OK || ret == Z_STREAM_END) {
7326 len = IOBUF_SIZE - s->zstream.avail_out;
7327 if (len > 0) {
7328 ram_put_cblock(s, s->buf, len);
7330 s->zstream.avail_out = IOBUF_SIZE;
7331 s->zstream.next_out = s->buf;
7332 if (ret == Z_STREAM_END)
7333 break;
7334 } else {
7335 goto fail;
7338 fail:
7339 deflateEnd(&s->zstream);
7342 typedef struct RamDecompressState {
7343 z_stream zstream;
7344 QEMUFile *f;
7345 uint8_t buf[IOBUF_SIZE];
7346 } RamDecompressState;
7348 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7350 int ret;
7351 memset(s, 0, sizeof(*s));
7352 s->f = f;
7353 ret = inflateInit(&s->zstream);
7354 if (ret != Z_OK)
7355 return -1;
7356 return 0;
7359 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7361 int ret, clen;
7363 s->zstream.avail_out = len;
7364 s->zstream.next_out = buf;
7365 while (s->zstream.avail_out > 0) {
7366 if (s->zstream.avail_in == 0) {
7367 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7368 return -1;
7369 clen = qemu_get_be16(s->f);
7370 if (clen > IOBUF_SIZE)
7371 return -1;
7372 qemu_get_buffer(s->f, s->buf, clen);
7373 s->zstream.avail_in = clen;
7374 s->zstream.next_in = s->buf;
7376 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7377 if (ret != Z_OK && ret != Z_STREAM_END) {
7378 return -1;
7381 return 0;
7384 static void ram_decompress_close(RamDecompressState *s)
7386 inflateEnd(&s->zstream);
7389 static void ram_save_live(QEMUFile *f, void *opaque)
7391 target_ulong addr;
7393 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7394 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7395 continue;
7396 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7397 qemu_put_be32(f, addr);
7398 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7401 qemu_put_be32(f, 1);
7404 static void ram_save_static(QEMUFile *f, void *opaque)
7406 int i;
7407 RamCompressState s1, *s = &s1;
7408 uint8_t buf[10];
7410 qemu_put_be32(f, phys_ram_size);
7411 if (ram_compress_open(s, f) < 0)
7412 return;
7413 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7414 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7415 continue;
7416 #if 0
7417 if (tight_savevm_enabled) {
7418 int64_t sector_num;
7419 int j;
7421 /* find if the memory block is available on a virtual
7422 block device */
7423 sector_num = -1;
7424 for(j = 0; j < nb_drives; j++) {
7425 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7426 phys_ram_base + i,
7427 BDRV_HASH_BLOCK_SIZE);
7428 if (sector_num >= 0)
7429 break;
7431 if (j == nb_drives)
7432 goto normal_compress;
7433 buf[0] = 1;
7434 buf[1] = j;
7435 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7436 ram_compress_buf(s, buf, 10);
7437 } else
7438 #endif
7440 // normal_compress:
7441 buf[0] = 0;
7442 ram_compress_buf(s, buf, 1);
7443 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7446 ram_compress_close(s);
7449 static void ram_save(QEMUFile *f, void *opaque)
7451 int in_migration = cpu_physical_memory_get_dirty_tracking();
7453 qemu_put_byte(f, in_migration);
7455 if (in_migration)
7456 ram_save_live(f, opaque);
7457 else
7458 ram_save_static(f, opaque);
7461 static int ram_load_live(QEMUFile *f, void *opaque)
7463 target_ulong addr;
7465 do {
7466 addr = qemu_get_be32(f);
7467 if (addr == 1)
7468 break;
7470 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7471 } while (1);
7473 return 0;
7476 static int ram_load_static(QEMUFile *f, void *opaque)
7478 RamDecompressState s1, *s = &s1;
7479 uint8_t buf[10];
7480 int i;
7482 if (qemu_get_be32(f) != phys_ram_size)
7483 return -EINVAL;
7484 if (ram_decompress_open(s, f) < 0)
7485 return -EINVAL;
7486 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7487 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7488 continue;
7489 if (ram_decompress_buf(s, buf, 1) < 0) {
7490 fprintf(stderr, "Error while reading ram block header\n");
7491 goto error;
7493 if (buf[0] == 0) {
7494 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7495 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7496 goto error;
7498 } else
7499 #if 0
7500 if (buf[0] == 1) {
7501 int bs_index;
7502 int64_t sector_num;
7504 ram_decompress_buf(s, buf + 1, 9);
7505 bs_index = buf[1];
7506 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7507 if (bs_index >= nb_drives) {
7508 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7509 goto error;
7511 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7512 phys_ram_base + i,
7513 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7514 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7515 bs_index, sector_num);
7516 goto error;
7518 } else
7519 #endif
7521 error:
7522 printf("Error block header\n");
7523 return -EINVAL;
7526 ram_decompress_close(s);
7527 return 0;
7530 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7532 int ret;
7534 switch (version_id) {
7535 case 1:
7536 ret = ram_load_v1(f, opaque);
7537 break;
7538 case 3:
7539 if (qemu_get_byte(f)) {
7540 ret = ram_load_live(f, opaque);
7541 break;
7543 case 2:
7544 ret = ram_load_static(f, opaque);
7545 break;
7546 default:
7547 ret = -EINVAL;
7548 break;
7551 return ret;
7554 /***********************************************************/
7555 /* bottom halves (can be seen as timers which expire ASAP) */
7557 struct QEMUBH {
7558 QEMUBHFunc *cb;
7559 void *opaque;
7560 int scheduled;
7561 QEMUBH *next;
7564 static QEMUBH *first_bh = NULL;
7566 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7568 QEMUBH *bh;
7569 bh = qemu_mallocz(sizeof(QEMUBH));
7570 if (!bh)
7571 return NULL;
7572 bh->cb = cb;
7573 bh->opaque = opaque;
7574 return bh;
7577 int qemu_bh_poll(void)
7579 QEMUBH *bh, **pbh;
7580 int ret;
7582 ret = 0;
7583 for(;;) {
7584 pbh = &first_bh;
7585 bh = *pbh;
7586 if (!bh)
7587 break;
7588 ret = 1;
7589 *pbh = bh->next;
7590 bh->scheduled = 0;
7591 bh->cb(bh->opaque);
7593 return ret;
7596 void qemu_bh_schedule(QEMUBH *bh)
7598 CPUState *env = cpu_single_env;
7599 if (bh->scheduled)
7600 return;
7601 bh->scheduled = 1;
7602 bh->next = first_bh;
7603 first_bh = bh;
7605 /* stop the currently executing CPU to execute the BH ASAP */
7606 if (env) {
7607 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7609 if (kvm_enabled())
7610 qemu_kvm_notify_work();
7613 void qemu_bh_cancel(QEMUBH *bh)
7615 QEMUBH **pbh;
7616 if (bh->scheduled) {
7617 pbh = &first_bh;
7618 while (*pbh != bh)
7619 pbh = &(*pbh)->next;
7620 *pbh = bh->next;
7621 bh->scheduled = 0;
7625 void qemu_bh_delete(QEMUBH *bh)
7627 qemu_bh_cancel(bh);
7628 qemu_free(bh);
7631 /***********************************************************/
7632 /* machine registration */
7634 QEMUMachine *first_machine = NULL;
7635 QEMUMachine *current_machine = NULL;
7637 int qemu_register_machine(QEMUMachine *m)
7639 QEMUMachine **pm;
7640 pm = &first_machine;
7641 while (*pm != NULL)
7642 pm = &(*pm)->next;
7643 m->next = NULL;
7644 *pm = m;
7645 return 0;
7648 static QEMUMachine *find_machine(const char *name)
7650 QEMUMachine *m;
7652 for(m = first_machine; m != NULL; m = m->next) {
7653 if (!strcmp(m->name, name))
7654 return m;
7656 return NULL;
7659 /***********************************************************/
7660 /* main execution loop */
7662 static void gui_update(void *opaque)
7664 DisplayState *ds = opaque;
7665 ds->dpy_refresh(ds);
7666 qemu_mod_timer(ds->gui_timer,
7667 (ds->gui_timer_interval ?
7668 ds->gui_timer_interval :
7669 GUI_REFRESH_INTERVAL)
7670 + qemu_get_clock(rt_clock));
7673 struct vm_change_state_entry {
7674 VMChangeStateHandler *cb;
7675 void *opaque;
7676 LIST_ENTRY (vm_change_state_entry) entries;
7679 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7681 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7682 void *opaque)
7684 VMChangeStateEntry *e;
7686 e = qemu_mallocz(sizeof (*e));
7687 if (!e)
7688 return NULL;
7690 e->cb = cb;
7691 e->opaque = opaque;
7692 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7693 return e;
7696 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7698 LIST_REMOVE (e, entries);
7699 qemu_free (e);
7702 static void vm_state_notify(int running)
7704 VMChangeStateEntry *e;
7706 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7707 e->cb(e->opaque, running);
7711 /* XXX: support several handlers */
7712 static VMStopHandler *vm_stop_cb;
7713 static void *vm_stop_opaque;
7715 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7717 vm_stop_cb = cb;
7718 vm_stop_opaque = opaque;
7719 return 0;
7722 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7724 vm_stop_cb = NULL;
7727 void vm_start(void)
7729 if (!vm_running) {
7730 cpu_enable_ticks();
7731 vm_running = 1;
7732 vm_state_notify(1);
7733 qemu_rearm_alarm_timer(alarm_timer);
7737 void vm_stop(int reason)
7739 if (vm_running) {
7740 cpu_disable_ticks();
7741 vm_running = 0;
7742 if (reason != 0) {
7743 if (vm_stop_cb) {
7744 vm_stop_cb(vm_stop_opaque, reason);
7747 vm_state_notify(0);
7751 /* reset/shutdown handler */
7753 typedef struct QEMUResetEntry {
7754 QEMUResetHandler *func;
7755 void *opaque;
7756 struct QEMUResetEntry *next;
7757 } QEMUResetEntry;
7759 static QEMUResetEntry *first_reset_entry;
7760 static int reset_requested;
7761 static int shutdown_requested;
7762 static int powerdown_requested;
7764 int qemu_shutdown_requested(void)
7766 int r = shutdown_requested;
7767 shutdown_requested = 0;
7768 return r;
7771 int qemu_reset_requested(void)
7773 int r = reset_requested;
7774 reset_requested = 0;
7775 return r;
7778 int qemu_powerdown_requested(void)
7780 int r = powerdown_requested;
7781 powerdown_requested = 0;
7782 return r;
7785 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7787 QEMUResetEntry **pre, *re;
7789 pre = &first_reset_entry;
7790 while (*pre != NULL)
7791 pre = &(*pre)->next;
7792 re = qemu_mallocz(sizeof(QEMUResetEntry));
7793 re->func = func;
7794 re->opaque = opaque;
7795 re->next = NULL;
7796 *pre = re;
7799 void qemu_system_reset(void)
7801 QEMUResetEntry *re;
7803 /* reset all devices */
7804 for(re = first_reset_entry; re != NULL; re = re->next) {
7805 re->func(re->opaque);
7809 void qemu_system_reset_request(void)
7811 if (no_reboot) {
7812 shutdown_requested = 1;
7813 } else {
7814 reset_requested = 1;
7816 if (cpu_single_env)
7817 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7818 #ifdef USE_KVM
7819 if (kvm_allowed)
7820 if (!no_reboot)
7821 qemu_kvm_system_reset_request();
7822 #endif
7825 void qemu_system_shutdown_request(void)
7827 shutdown_requested = 1;
7828 if (cpu_single_env)
7829 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7832 void qemu_system_powerdown_request(void)
7834 powerdown_requested = 1;
7835 if (cpu_single_env)
7836 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7839 void main_loop_wait(int timeout)
7841 IOHandlerRecord *ioh;
7842 fd_set rfds, wfds, xfds;
7843 int ret, nfds;
7844 #ifdef _WIN32
7845 int ret2, i;
7846 #endif
7847 struct timeval tv;
7848 PollingEntry *pe;
7851 /* XXX: need to suppress polling by better using win32 events */
7852 ret = 0;
7853 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7854 ret |= pe->func(pe->opaque);
7856 #ifdef _WIN32
7857 if (ret == 0) {
7858 int err;
7859 WaitObjects *w = &wait_objects;
7861 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7862 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7863 if (w->func[ret - WAIT_OBJECT_0])
7864 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7866 /* Check for additional signaled events */
7867 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7869 /* Check if event is signaled */
7870 ret2 = WaitForSingleObject(w->events[i], 0);
7871 if(ret2 == WAIT_OBJECT_0) {
7872 if (w->func[i])
7873 w->func[i](w->opaque[i]);
7874 } else if (ret2 == WAIT_TIMEOUT) {
7875 } else {
7876 err = GetLastError();
7877 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7880 } else if (ret == WAIT_TIMEOUT) {
7881 } else {
7882 err = GetLastError();
7883 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7886 #endif
7887 /* poll any events */
7888 /* XXX: separate device handlers from system ones */
7889 nfds = -1;
7890 FD_ZERO(&rfds);
7891 FD_ZERO(&wfds);
7892 FD_ZERO(&xfds);
7893 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7894 if (ioh->deleted)
7895 continue;
7896 if (ioh->fd_read &&
7897 (!ioh->fd_read_poll ||
7898 ioh->fd_read_poll(ioh->opaque) != 0)) {
7899 FD_SET(ioh->fd, &rfds);
7900 if (ioh->fd > nfds)
7901 nfds = ioh->fd;
7903 if (ioh->fd_write) {
7904 FD_SET(ioh->fd, &wfds);
7905 if (ioh->fd > nfds)
7906 nfds = ioh->fd;
7910 tv.tv_sec = 0;
7911 #ifdef _WIN32
7912 tv.tv_usec = 0;
7913 #else
7914 tv.tv_usec = timeout * 1000;
7915 #endif
7916 #if defined(CONFIG_SLIRP)
7917 if (slirp_inited) {
7918 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7920 #endif
7921 moreio:
7922 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7923 if (ret > 0) {
7924 IOHandlerRecord **pioh;
7925 int more = 0;
7927 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7928 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7929 ioh->fd_read(ioh->opaque);
7930 if (!ioh->fd_read_poll || ioh->fd_read_poll(ioh->opaque))
7931 more = 1;
7932 else
7933 FD_CLR(ioh->fd, &rfds);
7935 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7936 ioh->fd_write(ioh->opaque);
7937 more = 1;
7941 /* remove deleted IO handlers */
7942 pioh = &first_io_handler;
7943 while (*pioh) {
7944 ioh = *pioh;
7945 if (ioh->deleted) {
7946 *pioh = ioh->next;
7947 qemu_free(ioh);
7948 } else
7949 pioh = &ioh->next;
7951 if (more)
7952 goto moreio;
7954 #if defined(CONFIG_SLIRP)
7955 if (slirp_inited) {
7956 if (ret < 0) {
7957 FD_ZERO(&rfds);
7958 FD_ZERO(&wfds);
7959 FD_ZERO(&xfds);
7961 slirp_select_poll(&rfds, &wfds, &xfds);
7963 #endif
7964 virtio_net_poll();
7966 qemu_aio_poll();
7968 if (vm_running) {
7969 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7970 qemu_get_clock(vm_clock));
7971 /* run dma transfers, if any */
7972 DMA_run();
7975 /* real time timers */
7976 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7977 qemu_get_clock(rt_clock));
7979 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7980 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7981 qemu_rearm_alarm_timer(alarm_timer);
7984 /* Check bottom-halves last in case any of the earlier events triggered
7985 them. */
7986 qemu_bh_poll();
7990 static int main_loop(void)
7992 int ret, timeout;
7993 #ifdef CONFIG_PROFILER
7994 int64_t ti;
7995 #endif
7996 CPUState *env;
7999 if (kvm_enabled()) {
8000 kvm_main_loop();
8001 cpu_disable_ticks();
8002 return 0;
8005 cur_cpu = first_cpu;
8006 next_cpu = cur_cpu->next_cpu ?: first_cpu;
8007 for(;;) {
8008 if (vm_running) {
8010 for(;;) {
8011 /* get next cpu */
8012 env = next_cpu;
8013 #ifdef CONFIG_PROFILER
8014 ti = profile_getclock();
8015 #endif
8016 ret = cpu_exec(env);
8017 #ifdef CONFIG_PROFILER
8018 qemu_time += profile_getclock() - ti;
8019 #endif
8020 next_cpu = env->next_cpu ?: first_cpu;
8021 if (event_pending && likely(ret != EXCP_DEBUG)) {
8022 ret = EXCP_INTERRUPT;
8023 event_pending = 0;
8024 break;
8026 if (ret == EXCP_HLT) {
8027 /* Give the next CPU a chance to run. */
8028 cur_cpu = env;
8029 continue;
8031 if (ret != EXCP_HALTED)
8032 break;
8033 /* all CPUs are halted ? */
8034 if (env == cur_cpu)
8035 break;
8037 cur_cpu = env;
8039 if (shutdown_requested) {
8040 ret = EXCP_INTERRUPT;
8041 if (no_shutdown) {
8042 vm_stop(0);
8043 no_shutdown = 0;
8045 else
8046 break;
8048 if (reset_requested) {
8049 reset_requested = 0;
8050 qemu_system_reset();
8051 if (kvm_enabled())
8052 kvm_load_registers(env);
8053 ret = EXCP_INTERRUPT;
8055 if (powerdown_requested) {
8056 powerdown_requested = 0;
8057 qemu_system_powerdown();
8058 ret = EXCP_INTERRUPT;
8060 if (unlikely(ret == EXCP_DEBUG)) {
8061 vm_stop(EXCP_DEBUG);
8063 /* If all cpus are halted then wait until the next IRQ */
8064 /* XXX: use timeout computed from timers */
8065 if (ret == EXCP_HALTED)
8066 timeout = 10;
8067 else
8068 timeout = 0;
8069 } else {
8070 timeout = 10;
8072 #ifdef CONFIG_PROFILER
8073 ti = profile_getclock();
8074 #endif
8075 main_loop_wait(timeout);
8076 #ifdef CONFIG_PROFILER
8077 dev_time += profile_getclock() - ti;
8078 #endif
8080 cpu_disable_ticks();
8081 return ret;
8084 static void help(int exitcode)
8086 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
8087 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8088 "usage: %s [options] [disk_image]\n"
8089 "\n"
8090 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8091 "\n"
8092 "Standard options:\n"
8093 "-M machine select emulated machine (-M ? for list)\n"
8094 "-cpu cpu select CPU (-cpu ? for list)\n"
8095 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8096 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8097 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8098 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8099 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
8100 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
8101 " [,cache=on|off][,boot=on|off]\n"
8102 " use 'file' as a drive image\n"
8103 "-mtdblock file use 'file' as on-board Flash memory image\n"
8104 "-sd file use 'file' as SecureDigital card image\n"
8105 "-pflash file use 'file' as a parallel flash image\n"
8106 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8107 "-snapshot write to temporary files instead of disk image files\n"
8108 #ifdef CONFIG_SDL
8109 "-no-frame open SDL window without a frame and window decorations\n"
8110 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8111 "-no-quit disable SDL window close capability\n"
8112 #endif
8113 #ifdef TARGET_I386
8114 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8115 #endif
8116 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8117 "-smp n set the number of CPUs to 'n' [default=1]\n"
8118 "-nographic disable graphical output and redirect serial I/Os to console\n"
8119 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8120 #ifndef _WIN32
8121 "-k language use keyboard layout (for example \"fr\" for French)\n"
8122 #endif
8123 #ifdef HAS_AUDIO
8124 "-audio-help print list of audio drivers and their options\n"
8125 "-soundhw c1,... enable audio support\n"
8126 " and only specified sound cards (comma separated list)\n"
8127 " use -soundhw ? to get the list of supported cards\n"
8128 " use -soundhw all to enable all of them\n"
8129 #endif
8130 "-localtime set the real time clock to local time [default=utc]\n"
8131 "-full-screen start in full screen\n"
8132 #ifdef TARGET_I386
8133 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8134 #endif
8135 "-usb enable the USB driver (will be the default soon)\n"
8136 "-usbdevice name add the host or guest USB device 'name'\n"
8137 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8138 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8139 #endif
8140 "-name string set the name of the guest\n"
8141 "\n"
8142 "Network options:\n"
8143 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8144 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8145 #ifdef CONFIG_SLIRP
8146 "-net user[,vlan=n][,hostname=host]\n"
8147 " connect the user mode network stack to VLAN 'n' and send\n"
8148 " hostname 'host' to DHCP clients\n"
8149 #endif
8150 #ifdef _WIN32
8151 "-net tap[,vlan=n],ifname=name\n"
8152 " connect the host TAP network interface to VLAN 'n'\n"
8153 #else
8154 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8155 " connect the host TAP network interface to VLAN 'n' and use the\n"
8156 " network scripts 'file' (default=%s)\n"
8157 " and 'dfile' (default=%s);\n"
8158 " use '[down]script=no' to disable script execution;\n"
8159 " use 'fd=h' to connect to an already opened TAP interface\n"
8160 #endif
8161 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8162 " connect the vlan 'n' to another VLAN using a socket connection\n"
8163 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8164 " connect the vlan 'n' to multicast maddr and port\n"
8165 "-net none use it alone to have zero network devices; if no -net option\n"
8166 " is provided, the default is '-net nic -net user'\n"
8167 "\n"
8168 #ifdef CONFIG_SLIRP
8169 "-tftp dir allow tftp access to files in dir [-net user]\n"
8170 "-bootp file advertise file in BOOTP replies\n"
8171 #ifndef _WIN32
8172 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8173 #endif
8174 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8175 " redirect TCP or UDP connections from host to guest [-net user]\n"
8176 #endif
8177 "\n"
8178 "Linux boot specific:\n"
8179 "-kernel bzImage use 'bzImage' as kernel image\n"
8180 "-append cmdline use 'cmdline' as kernel command line\n"
8181 "-initrd file use 'file' as initial ram disk\n"
8182 "\n"
8183 "Debug/Expert options:\n"
8184 "-monitor dev redirect the monitor to char device 'dev'\n"
8185 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8186 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8187 "-serial dev redirect the serial port to char device 'dev'\n"
8188 "-parallel dev redirect the parallel port to char device 'dev'\n"
8189 "-pidfile file Write PID to 'file'\n"
8190 "-S freeze CPU at startup (use 'c' to start execution)\n"
8191 "-s wait gdb connection to port\n"
8192 "-p port set gdb connection port [default=%s]\n"
8193 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8194 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8195 " translation (t=none or lba) (usually qemu can guess them)\n"
8196 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8197 #ifdef USE_KQEMU
8198 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8199 "-no-kqemu disable KQEMU kernel module usage\n"
8200 #endif
8201 #ifdef USE_KVM
8202 #ifndef NO_CPU_EMULATION
8203 "-no-kvm disable KVM hardware virtualization\n"
8204 #endif
8205 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8206 "-no-kvm-pit disable KVM kernel mode PIT\n"
8207 #endif
8208 #ifdef TARGET_I386
8209 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8210 " (default is CL-GD5446 PCI VGA)\n"
8211 "-no-acpi disable ACPI\n"
8212 #endif
8213 #ifdef CONFIG_CURSES
8214 "-curses use a curses/ncurses interface instead of SDL\n"
8215 #endif
8216 "-no-reboot exit instead of rebooting\n"
8217 "-no-shutdown stop before shutdown\n"
8218 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8219 "-vnc display start a VNC server on display\n"
8220 #ifndef _WIN32
8221 "-daemonize daemonize QEMU after initializing\n"
8222 #endif
8223 "-tdf inject timer interrupts that got lost\n"
8224 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8225 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8226 "-option-rom rom load a file, rom, into the option ROM space\n"
8227 #ifdef TARGET_SPARC
8228 "-prom-env variable=value set OpenBIOS nvram variables\n"
8229 #endif
8230 "-clock force the use of the given methods for timer alarm.\n"
8231 " To see what timers are available use -clock ?\n"
8232 "-startdate select initial date of the clock\n"
8233 "\n"
8234 "During emulation, the following keys are useful:\n"
8235 "ctrl-alt-f toggle full screen\n"
8236 "ctrl-alt-n switch to virtual console 'n'\n"
8237 "ctrl-alt toggle mouse and keyboard grab\n"
8238 "\n"
8239 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8241 "qemu",
8242 DEFAULT_RAM_SIZE,
8243 #ifndef _WIN32
8244 DEFAULT_NETWORK_SCRIPT,
8245 DEFAULT_NETWORK_DOWN_SCRIPT,
8246 #endif
8247 DEFAULT_GDBSTUB_PORT,
8248 "/tmp/qemu.log");
8249 exit(exitcode);
8252 #define HAS_ARG 0x0001
8254 enum {
8255 QEMU_OPTION_h,
8257 QEMU_OPTION_M,
8258 QEMU_OPTION_cpu,
8259 QEMU_OPTION_fda,
8260 QEMU_OPTION_fdb,
8261 QEMU_OPTION_hda,
8262 QEMU_OPTION_hdb,
8263 QEMU_OPTION_hdc,
8264 QEMU_OPTION_hdd,
8265 QEMU_OPTION_drive,
8266 QEMU_OPTION_cdrom,
8267 QEMU_OPTION_mtdblock,
8268 QEMU_OPTION_sd,
8269 QEMU_OPTION_pflash,
8270 QEMU_OPTION_boot,
8271 QEMU_OPTION_snapshot,
8272 #ifdef TARGET_I386
8273 QEMU_OPTION_no_fd_bootchk,
8274 #endif
8275 QEMU_OPTION_m,
8276 QEMU_OPTION_nographic,
8277 QEMU_OPTION_portrait,
8278 #ifdef HAS_AUDIO
8279 QEMU_OPTION_audio_help,
8280 QEMU_OPTION_soundhw,
8281 #endif
8283 QEMU_OPTION_net,
8284 QEMU_OPTION_tftp,
8285 QEMU_OPTION_bootp,
8286 QEMU_OPTION_smb,
8287 QEMU_OPTION_redir,
8289 QEMU_OPTION_kernel,
8290 QEMU_OPTION_append,
8291 QEMU_OPTION_initrd,
8293 QEMU_OPTION_S,
8294 QEMU_OPTION_s,
8295 QEMU_OPTION_p,
8296 QEMU_OPTION_d,
8297 QEMU_OPTION_hdachs,
8298 QEMU_OPTION_L,
8299 QEMU_OPTION_bios,
8300 QEMU_OPTION_no_code_copy,
8301 QEMU_OPTION_k,
8302 QEMU_OPTION_localtime,
8303 QEMU_OPTION_cirrusvga,
8304 QEMU_OPTION_vmsvga,
8305 QEMU_OPTION_g,
8306 QEMU_OPTION_std_vga,
8307 QEMU_OPTION_echr,
8308 QEMU_OPTION_monitor,
8309 QEMU_OPTION_balloon,
8310 QEMU_OPTION_vmchannel,
8311 QEMU_OPTION_serial,
8312 QEMU_OPTION_parallel,
8313 QEMU_OPTION_loadvm,
8314 QEMU_OPTION_full_screen,
8315 QEMU_OPTION_no_frame,
8316 QEMU_OPTION_alt_grab,
8317 QEMU_OPTION_no_quit,
8318 QEMU_OPTION_pidfile,
8319 QEMU_OPTION_no_kqemu,
8320 QEMU_OPTION_kernel_kqemu,
8321 QEMU_OPTION_win2k_hack,
8322 QEMU_OPTION_usb,
8323 QEMU_OPTION_usbdevice,
8324 QEMU_OPTION_smp,
8325 QEMU_OPTION_vnc,
8326 QEMU_OPTION_no_acpi,
8327 QEMU_OPTION_curses,
8328 QEMU_OPTION_no_kvm,
8329 QEMU_OPTION_no_kvm_irqchip,
8330 QEMU_OPTION_no_kvm_pit,
8331 QEMU_OPTION_no_reboot,
8332 QEMU_OPTION_no_shutdown,
8333 QEMU_OPTION_show_cursor,
8334 QEMU_OPTION_daemonize,
8335 QEMU_OPTION_option_rom,
8336 QEMU_OPTION_semihosting,
8337 QEMU_OPTION_cpu_vendor,
8338 QEMU_OPTION_name,
8339 QEMU_OPTION_prom_env,
8340 QEMU_OPTION_old_param,
8341 QEMU_OPTION_clock,
8342 QEMU_OPTION_startdate,
8343 QEMU_OPTION_translation,
8344 QEMU_OPTION_incoming,
8345 QEMU_OPTION_tdf,
8346 QEMU_OPTION_kvm_shadow_memory,
8347 QEMU_OPTION_mempath,
8350 typedef struct QEMUOption {
8351 const char *name;
8352 int flags;
8353 int index;
8354 } QEMUOption;
8356 const QEMUOption qemu_options[] = {
8357 { "h", 0, QEMU_OPTION_h },
8358 { "help", 0, QEMU_OPTION_h },
8360 { "M", HAS_ARG, QEMU_OPTION_M },
8361 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8362 { "fda", HAS_ARG, QEMU_OPTION_fda },
8363 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8364 { "hda", HAS_ARG, QEMU_OPTION_hda },
8365 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8366 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8367 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8368 { "drive", HAS_ARG, QEMU_OPTION_drive },
8369 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8370 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8371 { "sd", HAS_ARG, QEMU_OPTION_sd },
8372 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8373 { "boot", HAS_ARG, QEMU_OPTION_boot },
8374 { "snapshot", 0, QEMU_OPTION_snapshot },
8375 #ifdef TARGET_I386
8376 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8377 #endif
8378 { "m", HAS_ARG, QEMU_OPTION_m },
8379 { "nographic", 0, QEMU_OPTION_nographic },
8380 { "portrait", 0, QEMU_OPTION_portrait },
8381 { "k", HAS_ARG, QEMU_OPTION_k },
8382 #ifdef HAS_AUDIO
8383 { "audio-help", 0, QEMU_OPTION_audio_help },
8384 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8385 #endif
8387 { "net", HAS_ARG, QEMU_OPTION_net},
8388 #ifdef CONFIG_SLIRP
8389 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8390 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8391 #ifndef _WIN32
8392 { "smb", HAS_ARG, QEMU_OPTION_smb },
8393 #endif
8394 { "redir", HAS_ARG, QEMU_OPTION_redir },
8395 #endif
8397 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8398 { "append", HAS_ARG, QEMU_OPTION_append },
8399 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8401 { "S", 0, QEMU_OPTION_S },
8402 { "s", 0, QEMU_OPTION_s },
8403 { "p", HAS_ARG, QEMU_OPTION_p },
8404 { "d", HAS_ARG, QEMU_OPTION_d },
8405 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8406 { "L", HAS_ARG, QEMU_OPTION_L },
8407 { "bios", HAS_ARG, QEMU_OPTION_bios },
8408 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8409 #ifdef USE_KQEMU
8410 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8411 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8412 #endif
8413 #ifdef USE_KVM
8414 #ifndef NO_CPU_EMULATION
8415 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8416 #endif
8417 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8418 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8419 #endif
8420 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8421 { "g", 1, QEMU_OPTION_g },
8422 #endif
8423 { "localtime", 0, QEMU_OPTION_localtime },
8424 { "std-vga", 0, QEMU_OPTION_std_vga },
8425 { "monitor", 1, QEMU_OPTION_monitor },
8426 { "balloon", 1, QEMU_OPTION_balloon },
8427 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8428 { "echr", HAS_ARG, QEMU_OPTION_echr },
8429 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8430 { "serial", HAS_ARG, QEMU_OPTION_serial },
8431 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8432 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8433 { "incoming", 1, QEMU_OPTION_incoming },
8434 { "full-screen", 0, QEMU_OPTION_full_screen },
8435 #ifdef CONFIG_SDL
8436 { "no-frame", 0, QEMU_OPTION_no_frame },
8437 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8438 { "no-quit", 0, QEMU_OPTION_no_quit },
8439 #endif
8440 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8441 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8442 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8443 { "smp", HAS_ARG, QEMU_OPTION_smp },
8444 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8445 #ifdef CONFIG_CURSES
8446 { "curses", 0, QEMU_OPTION_curses },
8447 #endif
8449 /* temporary options */
8450 { "usb", 0, QEMU_OPTION_usb },
8451 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8452 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8453 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8454 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8455 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8456 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8457 { "daemonize", 0, QEMU_OPTION_daemonize },
8458 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8459 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8460 { "semihosting", 0, QEMU_OPTION_semihosting },
8461 #endif
8462 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8463 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8464 { "name", HAS_ARG, QEMU_OPTION_name },
8465 #if defined(TARGET_SPARC)
8466 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8467 #endif
8468 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8469 #if defined(TARGET_ARM)
8470 { "old-param", 0, QEMU_OPTION_old_param },
8471 #endif
8472 { "clock", HAS_ARG, QEMU_OPTION_clock },
8473 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8474 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8475 { NULL },
8478 /* password input */
8480 int qemu_key_check(BlockDriverState *bs, const char *name)
8482 char password[256];
8483 int i;
8485 if (!bdrv_is_encrypted(bs))
8486 return 0;
8488 term_printf("%s is encrypted.\n", name);
8489 for(i = 0; i < 3; i++) {
8490 monitor_readline("Password: ", 1, password, sizeof(password));
8491 if (bdrv_set_key(bs, password) == 0)
8492 return 0;
8493 term_printf("invalid password\n");
8495 return -EPERM;
8498 static BlockDriverState *get_bdrv(int index)
8500 if (index > nb_drives)
8501 return NULL;
8502 return drives_table[index].bdrv;
8505 static void read_passwords(void)
8507 BlockDriverState *bs;
8508 int i;
8510 for(i = 0; i < 6; i++) {
8511 bs = get_bdrv(i);
8512 if (bs)
8513 qemu_key_check(bs, bdrv_get_device_name(bs));
8517 /* XXX: currently we cannot use simultaneously different CPUs */
8518 static void register_machines(void)
8520 #if defined(TARGET_I386)
8521 qemu_register_machine(&pc_machine);
8522 qemu_register_machine(&isapc_machine);
8523 #elif defined(TARGET_PPC)
8524 qemu_register_machine(&heathrow_machine);
8525 qemu_register_machine(&core99_machine);
8526 qemu_register_machine(&prep_machine);
8527 qemu_register_machine(&ref405ep_machine);
8528 qemu_register_machine(&taihu_machine);
8529 qemu_register_machine(&bamboo_machine);
8530 #elif defined(TARGET_MIPS)
8531 qemu_register_machine(&mips_machine);
8532 qemu_register_machine(&mips_magnum_machine);
8533 qemu_register_machine(&mips_malta_machine);
8534 qemu_register_machine(&mips_pica61_machine);
8535 qemu_register_machine(&mips_mipssim_machine);
8536 #elif defined(TARGET_SPARC)
8537 #ifdef TARGET_SPARC64
8538 qemu_register_machine(&sun4u_machine);
8539 #else
8540 qemu_register_machine(&ss5_machine);
8541 qemu_register_machine(&ss10_machine);
8542 qemu_register_machine(&ss600mp_machine);
8543 qemu_register_machine(&ss20_machine);
8544 qemu_register_machine(&ss2_machine);
8545 qemu_register_machine(&voyager_machine);
8546 qemu_register_machine(&ss_lx_machine);
8547 qemu_register_machine(&ss4_machine);
8548 qemu_register_machine(&scls_machine);
8549 qemu_register_machine(&sbook_machine);
8550 qemu_register_machine(&ss1000_machine);
8551 qemu_register_machine(&ss2000_machine);
8552 #endif
8553 #elif defined(TARGET_ARM)
8554 qemu_register_machine(&integratorcp_machine);
8555 qemu_register_machine(&versatilepb_machine);
8556 qemu_register_machine(&versatileab_machine);
8557 qemu_register_machine(&realview_machine);
8558 qemu_register_machine(&akitapda_machine);
8559 qemu_register_machine(&spitzpda_machine);
8560 qemu_register_machine(&borzoipda_machine);
8561 qemu_register_machine(&terrierpda_machine);
8562 qemu_register_machine(&palmte_machine);
8563 qemu_register_machine(&n800_machine);
8564 qemu_register_machine(&lm3s811evb_machine);
8565 qemu_register_machine(&lm3s6965evb_machine);
8566 qemu_register_machine(&connex_machine);
8567 qemu_register_machine(&verdex_machine);
8568 qemu_register_machine(&mainstone2_machine);
8569 #elif defined(TARGET_SH4)
8570 qemu_register_machine(&shix_machine);
8571 qemu_register_machine(&r2d_machine);
8572 #elif defined(TARGET_ALPHA)
8573 /* XXX: TODO */
8574 #elif defined(TARGET_M68K)
8575 qemu_register_machine(&mcf5208evb_machine);
8576 qemu_register_machine(&an5206_machine);
8577 qemu_register_machine(&dummy_m68k_machine);
8578 #elif defined(TARGET_CRIS)
8579 qemu_register_machine(&bareetraxfs_machine);
8580 #elif defined(TARGET_IA64)
8581 qemu_register_machine(&ipf_machine);
8582 #else
8583 #error unsupported CPU
8584 #endif
8587 #ifdef HAS_AUDIO
8588 struct soundhw soundhw[] = {
8589 #ifdef HAS_AUDIO_CHOICE
8590 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8592 "pcspk",
8593 "PC speaker",
8596 { .init_isa = pcspk_audio_init }
8598 #endif
8600 "sb16",
8601 "Creative Sound Blaster 16",
8604 { .init_isa = SB16_init }
8607 #ifdef CONFIG_ADLIB
8609 "adlib",
8610 #ifdef HAS_YMF262
8611 "Yamaha YMF262 (OPL3)",
8612 #else
8613 "Yamaha YM3812 (OPL2)",
8614 #endif
8617 { .init_isa = Adlib_init }
8619 #endif
8621 #ifdef CONFIG_GUS
8623 "gus",
8624 "Gravis Ultrasound GF1",
8627 { .init_isa = GUS_init }
8629 #endif
8631 #ifdef CONFIG_AC97
8633 "ac97",
8634 "Intel 82801AA AC97 Audio",
8637 { .init_pci = ac97_init }
8639 #endif
8642 "es1370",
8643 "ENSONIQ AudioPCI ES1370",
8646 { .init_pci = es1370_init }
8648 #endif
8650 { NULL, NULL, 0, 0, { NULL } }
8653 static void select_soundhw (const char *optarg)
8655 struct soundhw *c;
8657 if (*optarg == '?') {
8658 show_valid_cards:
8660 printf ("Valid sound card names (comma separated):\n");
8661 for (c = soundhw; c->name; ++c) {
8662 printf ("%-11s %s\n", c->name, c->descr);
8664 printf ("\n-soundhw all will enable all of the above\n");
8665 exit (*optarg != '?');
8667 else {
8668 size_t l;
8669 const char *p;
8670 char *e;
8671 int bad_card = 0;
8673 if (!strcmp (optarg, "all")) {
8674 for (c = soundhw; c->name; ++c) {
8675 c->enabled = 1;
8677 return;
8680 p = optarg;
8681 while (*p) {
8682 e = strchr (p, ',');
8683 l = !e ? strlen (p) : (size_t) (e - p);
8685 for (c = soundhw; c->name; ++c) {
8686 if (!strncmp (c->name, p, l)) {
8687 c->enabled = 1;
8688 break;
8692 if (!c->name) {
8693 if (l > 80) {
8694 fprintf (stderr,
8695 "Unknown sound card name (too big to show)\n");
8697 else {
8698 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8699 (int) l, p);
8701 bad_card = 1;
8703 p += l + (e != NULL);
8706 if (bad_card)
8707 goto show_valid_cards;
8710 #endif
8712 #ifdef _WIN32
8713 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8715 exit(STATUS_CONTROL_C_EXIT);
8716 return TRUE;
8718 #endif
8720 #define MAX_NET_CLIENTS 32
8722 static int saved_argc;
8723 static char **saved_argv;
8725 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8727 *argc = saved_argc;
8728 *argv = saved_argv;
8729 *opt_daemonize = daemonize;
8730 *opt_incoming = incoming;
8734 static int gethugepagesize(void)
8736 int ret, fd;
8737 char buf[4096];
8738 char *needle = "Hugepagesize:";
8739 char *size;
8740 unsigned long hugepagesize;
8742 fd = open("/proc/meminfo", O_RDONLY);
8743 if (fd < 0) {
8744 perror("open");
8745 exit(0);
8748 ret = read(fd, buf, sizeof(buf));
8749 if (ret < 0) {
8750 perror("read");
8751 exit(0);
8754 size = strstr(buf, needle);
8755 if (!size)
8756 return 0;
8757 size += strlen(needle);
8758 hugepagesize = strtol(size, NULL, 0);
8759 return hugepagesize;
8762 void *alloc_mem_area(unsigned long memory, const char *path)
8764 char *filename;
8765 void *area;
8766 int fd;
8768 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8769 return NULL;
8771 hpagesize = gethugepagesize() * 1024;
8772 if (!hpagesize)
8773 return NULL;
8775 fd = mkstemp(filename);
8776 if (fd < 0) {
8777 perror("mkstemp");
8778 free(filename);
8779 return NULL;
8781 unlink(filename);
8782 free(filename);
8784 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8787 * ftruncate is not supported by hugetlbfs in older
8788 * hosts, so don't bother checking for errors.
8789 * If anything goes wrong with it under other filesystems,
8790 * mmap will fail.
8792 ftruncate(fd, memory);
8794 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8795 if (area == MAP_FAILED) {
8796 perror("mmap");
8797 close(fd);
8798 return NULL;
8801 return area;
8804 void *qemu_alloc_physram(unsigned long memory)
8806 void *area = NULL;
8808 if (mem_path)
8809 area = alloc_mem_area(memory, mem_path);
8810 if (!area)
8811 area = qemu_vmalloc(memory);
8813 return area;
8816 int main(int argc, char **argv)
8818 #ifdef CONFIG_GDBSTUB
8819 int use_gdbstub;
8820 const char *gdbstub_port;
8821 #endif
8822 uint32_t boot_devices_bitmap = 0;
8823 int i;
8824 int snapshot, linux_boot, net_boot;
8825 const char *initrd_filename;
8826 const char *kernel_filename, *kernel_cmdline;
8827 const char *boot_devices = "";
8828 DisplayState *ds = &display_state;
8829 int cyls, heads, secs, translation;
8830 const char *net_clients[MAX_NET_CLIENTS];
8831 int nb_net_clients;
8832 int hda_index;
8833 int optind;
8834 const char *r, *optarg;
8835 CharDriverState *monitor_hd;
8836 const char *monitor_device;
8837 const char *serial_devices[MAX_SERIAL_PORTS];
8838 int serial_device_index;
8839 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8840 int vmchannel_device_index;
8841 const char *parallel_devices[MAX_PARALLEL_PORTS];
8842 int parallel_device_index;
8843 const char *loadvm = NULL;
8844 QEMUMachine *machine;
8845 const char *cpu_model;
8846 const char *usb_devices[MAX_USB_CMDLINE];
8847 int usb_devices_index;
8848 int fds[2];
8849 const char *pid_file = NULL;
8850 VLANState *vlan;
8852 saved_argc = argc;
8853 saved_argv = argv;
8855 LIST_INIT (&vm_change_state_head);
8856 #ifndef _WIN32
8858 struct sigaction act;
8859 sigfillset(&act.sa_mask);
8860 act.sa_flags = 0;
8861 act.sa_handler = SIG_IGN;
8862 sigaction(SIGPIPE, &act, NULL);
8864 #else
8865 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8866 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8867 QEMU to run on a single CPU */
8869 HANDLE h;
8870 DWORD mask, smask;
8871 int i;
8872 h = GetCurrentProcess();
8873 if (GetProcessAffinityMask(h, &mask, &smask)) {
8874 for(i = 0; i < 32; i++) {
8875 if (mask & (1 << i))
8876 break;
8878 if (i != 32) {
8879 mask = 1 << i;
8880 SetProcessAffinityMask(h, mask);
8884 #endif
8886 register_machines();
8887 machine = first_machine;
8888 cpu_model = NULL;
8889 initrd_filename = NULL;
8890 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8891 vga_ram_size = VGA_RAM_SIZE;
8892 #ifdef CONFIG_GDBSTUB
8893 use_gdbstub = 0;
8894 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8895 #endif
8896 snapshot = 0;
8897 nographic = 0;
8898 curses = 0;
8899 kernel_filename = NULL;
8900 kernel_cmdline = "";
8901 cyls = heads = secs = 0;
8902 translation = BIOS_ATA_TRANSLATION_AUTO;
8903 monitor_device = "vc";
8905 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8906 vmchannel_devices[i][0] = '\0';
8907 vmchannel_device_index = 0;
8909 serial_devices[0] = "vc";
8910 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8911 serial_devices[i] = NULL;
8912 serial_device_index = 0;
8914 parallel_devices[0] = "vc";
8915 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8916 parallel_devices[i] = NULL;
8917 parallel_device_index = 0;
8919 usb_devices_index = 0;
8921 nb_net_clients = 0;
8922 nb_drives = 0;
8923 nb_drives_opt = 0;
8924 hda_index = -1;
8926 nb_nics = 0;
8927 /* default mac address of the first network interface */
8929 optind = 1;
8930 for(;;) {
8931 if (optind >= argc)
8932 break;
8933 r = argv[optind];
8934 if (r[0] != '-') {
8935 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8936 } else {
8937 const QEMUOption *popt;
8939 optind++;
8940 /* Treat --foo the same as -foo. */
8941 if (r[1] == '-')
8942 r++;
8943 popt = qemu_options;
8944 for(;;) {
8945 if (!popt->name) {
8946 fprintf(stderr, "%s: invalid option -- '%s'\n",
8947 argv[0], r);
8948 exit(1);
8950 if (!strcmp(popt->name, r + 1))
8951 break;
8952 popt++;
8954 if (popt->flags & HAS_ARG) {
8955 if (optind >= argc) {
8956 fprintf(stderr, "%s: option '%s' requires an argument\n",
8957 argv[0], r);
8958 exit(1);
8960 optarg = argv[optind++];
8961 } else {
8962 optarg = NULL;
8965 switch(popt->index) {
8966 case QEMU_OPTION_M:
8967 machine = find_machine(optarg);
8968 if (!machine) {
8969 QEMUMachine *m;
8970 printf("Supported machines are:\n");
8971 for(m = first_machine; m != NULL; m = m->next) {
8972 printf("%-10s %s%s\n",
8973 m->name, m->desc,
8974 m == first_machine ? " (default)" : "");
8976 exit(*optarg != '?');
8978 break;
8979 case QEMU_OPTION_cpu:
8980 /* hw initialization will check this */
8981 if (*optarg == '?') {
8982 /* XXX: implement xxx_cpu_list for targets that still miss it */
8983 #if defined(cpu_list)
8984 cpu_list(stdout, &fprintf);
8985 #endif
8986 exit(0);
8987 } else {
8988 cpu_model = optarg;
8990 break;
8991 case QEMU_OPTION_initrd:
8992 initrd_filename = optarg;
8993 break;
8994 case QEMU_OPTION_hda:
8995 if (cyls == 0)
8996 hda_index = drive_add(optarg, HD_ALIAS, 0);
8997 else
8998 hda_index = drive_add(optarg, HD_ALIAS
8999 ",cyls=%d,heads=%d,secs=%d%s",
9000 0, cyls, heads, secs,
9001 translation == BIOS_ATA_TRANSLATION_LBA ?
9002 ",trans=lba" :
9003 translation == BIOS_ATA_TRANSLATION_NONE ?
9004 ",trans=none" : "");
9005 break;
9006 case QEMU_OPTION_hdb:
9007 case QEMU_OPTION_hdc:
9008 case QEMU_OPTION_hdd:
9009 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
9010 break;
9011 case QEMU_OPTION_drive:
9012 drive_add(NULL, "%s", optarg);
9013 break;
9014 case QEMU_OPTION_mtdblock:
9015 drive_add(optarg, MTD_ALIAS);
9016 break;
9017 case QEMU_OPTION_sd:
9018 drive_add(optarg, SD_ALIAS);
9019 break;
9020 case QEMU_OPTION_pflash:
9021 drive_add(optarg, PFLASH_ALIAS);
9022 break;
9023 case QEMU_OPTION_snapshot:
9024 snapshot = 1;
9025 break;
9026 case QEMU_OPTION_hdachs:
9028 const char *p;
9029 p = optarg;
9030 cyls = strtol(p, (char **)&p, 0);
9031 if (cyls < 1 || cyls > 16383)
9032 goto chs_fail;
9033 if (*p != ',')
9034 goto chs_fail;
9035 p++;
9036 heads = strtol(p, (char **)&p, 0);
9037 if (heads < 1 || heads > 16)
9038 goto chs_fail;
9039 if (*p != ',')
9040 goto chs_fail;
9041 p++;
9042 secs = strtol(p, (char **)&p, 0);
9043 if (secs < 1 || secs > 63)
9044 goto chs_fail;
9045 if (*p == ',') {
9046 p++;
9047 if (!strcmp(p, "none"))
9048 translation = BIOS_ATA_TRANSLATION_NONE;
9049 else if (!strcmp(p, "lba"))
9050 translation = BIOS_ATA_TRANSLATION_LBA;
9051 else if (!strcmp(p, "auto"))
9052 translation = BIOS_ATA_TRANSLATION_AUTO;
9053 else
9054 goto chs_fail;
9055 } else if (*p != '\0') {
9056 chs_fail:
9057 fprintf(stderr, "qemu: invalid physical CHS format\n");
9058 exit(1);
9060 if (hda_index != -1)
9061 snprintf(drives_opt[hda_index].opt,
9062 sizeof(drives_opt[hda_index].opt),
9063 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
9064 0, cyls, heads, secs,
9065 translation == BIOS_ATA_TRANSLATION_LBA ?
9066 ",trans=lba" :
9067 translation == BIOS_ATA_TRANSLATION_NONE ?
9068 ",trans=none" : "");
9070 break;
9071 case QEMU_OPTION_nographic:
9072 serial_devices[0] = "stdio";
9073 parallel_devices[0] = "null";
9074 monitor_device = "stdio";
9075 nographic = 1;
9076 break;
9077 #ifdef CONFIG_CURSES
9078 case QEMU_OPTION_curses:
9079 curses = 1;
9080 break;
9081 #endif
9082 case QEMU_OPTION_portrait:
9083 graphic_rotate = 1;
9084 break;
9085 case QEMU_OPTION_kernel:
9086 kernel_filename = optarg;
9087 break;
9088 case QEMU_OPTION_append:
9089 kernel_cmdline = optarg;
9090 break;
9091 case QEMU_OPTION_cdrom:
9092 drive_add(optarg, CDROM_ALIAS);
9093 break;
9094 case QEMU_OPTION_boot:
9095 boot_devices = optarg;
9096 /* We just do some generic consistency checks */
9098 /* Could easily be extended to 64 devices if needed */
9099 const char *p;
9101 boot_devices_bitmap = 0;
9102 for (p = boot_devices; *p != '\0'; p++) {
9103 /* Allowed boot devices are:
9104 * a b : floppy disk drives
9105 * c ... f : IDE disk drives
9106 * g ... m : machine implementation dependant drives
9107 * n ... p : network devices
9108 * It's up to each machine implementation to check
9109 * if the given boot devices match the actual hardware
9110 * implementation and firmware features.
9112 if (*p < 'a' || *p > 'q') {
9113 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9114 exit(1);
9116 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9117 fprintf(stderr,
9118 "Boot device '%c' was given twice\n",*p);
9119 exit(1);
9121 boot_devices_bitmap |= 1 << (*p - 'a');
9124 break;
9125 case QEMU_OPTION_fda:
9126 case QEMU_OPTION_fdb:
9127 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9128 break;
9129 #ifdef TARGET_I386
9130 case QEMU_OPTION_no_fd_bootchk:
9131 fd_bootchk = 0;
9132 break;
9133 #endif
9134 case QEMU_OPTION_no_code_copy:
9135 code_copy_enabled = 0;
9136 break;
9137 case QEMU_OPTION_net:
9138 if (nb_net_clients >= MAX_NET_CLIENTS) {
9139 fprintf(stderr, "qemu: too many network clients\n");
9140 exit(1);
9142 net_clients[nb_net_clients] = optarg;
9143 nb_net_clients++;
9144 break;
9145 #ifdef CONFIG_SLIRP
9146 case QEMU_OPTION_tftp:
9147 tftp_prefix = optarg;
9148 break;
9149 case QEMU_OPTION_bootp:
9150 bootp_filename = optarg;
9151 break;
9152 #ifndef _WIN32
9153 case QEMU_OPTION_smb:
9154 net_slirp_smb(optarg);
9155 break;
9156 #endif
9157 case QEMU_OPTION_redir:
9158 net_slirp_redir(optarg);
9159 break;
9160 #endif
9161 #ifdef HAS_AUDIO
9162 case QEMU_OPTION_audio_help:
9163 AUD_help ();
9164 exit (0);
9165 break;
9166 case QEMU_OPTION_soundhw:
9167 select_soundhw (optarg);
9168 break;
9169 #endif
9170 case QEMU_OPTION_h:
9171 help(0);
9172 break;
9173 case QEMU_OPTION_m:
9174 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
9175 if (ram_size <= 0)
9176 help(1);
9177 if (ram_size > PHYS_RAM_MAX_SIZE) {
9178 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
9179 PHYS_RAM_MAX_SIZE / (1024 * 1024));
9180 exit(1);
9182 break;
9183 case QEMU_OPTION_d:
9185 int mask;
9186 CPULogItem *item;
9188 mask = cpu_str_to_log_mask(optarg);
9189 if (!mask) {
9190 printf("Log items (comma separated):\n");
9191 for(item = cpu_log_items; item->mask != 0; item++) {
9192 printf("%-10s %s\n", item->name, item->help);
9194 exit(1);
9196 cpu_set_log(mask);
9198 break;
9199 #ifdef CONFIG_GDBSTUB
9200 case QEMU_OPTION_s:
9201 use_gdbstub = 1;
9202 break;
9203 case QEMU_OPTION_p:
9204 gdbstub_port = optarg;
9205 break;
9206 #endif
9207 case QEMU_OPTION_L:
9208 bios_dir = optarg;
9209 break;
9210 case QEMU_OPTION_bios:
9211 bios_name = optarg;
9212 break;
9213 case QEMU_OPTION_S:
9214 autostart = 0;
9215 break;
9216 case QEMU_OPTION_k:
9217 keyboard_layout = optarg;
9218 break;
9219 case QEMU_OPTION_localtime:
9220 rtc_utc = 0;
9221 break;
9222 case QEMU_OPTION_cirrusvga:
9223 cirrus_vga_enabled = 1;
9224 vmsvga_enabled = 0;
9225 break;
9226 case QEMU_OPTION_vmsvga:
9227 cirrus_vga_enabled = 0;
9228 vmsvga_enabled = 1;
9229 break;
9230 case QEMU_OPTION_std_vga:
9231 cirrus_vga_enabled = 0;
9232 vmsvga_enabled = 0;
9233 break;
9234 case QEMU_OPTION_g:
9236 const char *p;
9237 int w, h, depth;
9238 p = optarg;
9239 w = strtol(p, (char **)&p, 10);
9240 if (w <= 0) {
9241 graphic_error:
9242 fprintf(stderr, "qemu: invalid resolution or depth\n");
9243 exit(1);
9245 if (*p != 'x')
9246 goto graphic_error;
9247 p++;
9248 h = strtol(p, (char **)&p, 10);
9249 if (h <= 0)
9250 goto graphic_error;
9251 if (*p == 'x') {
9252 p++;
9253 depth = strtol(p, (char **)&p, 10);
9254 if (depth != 8 && depth != 15 && depth != 16 &&
9255 depth != 24 && depth != 32)
9256 goto graphic_error;
9257 } else if (*p == '\0') {
9258 depth = graphic_depth;
9259 } else {
9260 goto graphic_error;
9263 graphic_width = w;
9264 graphic_height = h;
9265 graphic_depth = depth;
9267 break;
9268 case QEMU_OPTION_echr:
9270 char *r;
9271 term_escape_char = strtol(optarg, &r, 0);
9272 if (r == optarg)
9273 printf("Bad argument to echr\n");
9274 break;
9276 case QEMU_OPTION_monitor:
9277 monitor_device = optarg;
9278 break;
9279 case QEMU_OPTION_balloon:
9280 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9281 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9282 exit(1);
9284 if (balloon_used) {
9285 fprintf(stderr, "qemu: only one balloon device can be used\n");
9286 exit(1);
9288 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
9289 vmchannel_device_index++;
9290 balloon_used = 1;
9291 break;
9292 case QEMU_OPTION_vmchannel:
9293 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9294 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9295 exit(1);
9297 pstrcpy(vmchannel_devices[vmchannel_device_index],
9298 sizeof(vmchannel_devices[0]), optarg);
9299 vmchannel_device_index++;
9300 break;
9301 case QEMU_OPTION_serial:
9302 if (serial_device_index >= MAX_SERIAL_PORTS) {
9303 fprintf(stderr, "qemu: too many serial ports\n");
9304 exit(1);
9306 serial_devices[serial_device_index] = optarg;
9307 serial_device_index++;
9308 break;
9309 case QEMU_OPTION_parallel:
9310 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9311 fprintf(stderr, "qemu: too many parallel ports\n");
9312 exit(1);
9314 parallel_devices[parallel_device_index] = optarg;
9315 parallel_device_index++;
9316 break;
9317 case QEMU_OPTION_loadvm:
9318 loadvm = optarg;
9319 break;
9320 case QEMU_OPTION_incoming:
9321 incoming = optarg;
9322 break;
9323 case QEMU_OPTION_full_screen:
9324 full_screen = 1;
9325 break;
9326 #ifdef CONFIG_SDL
9327 case QEMU_OPTION_no_frame:
9328 no_frame = 1;
9329 break;
9330 case QEMU_OPTION_alt_grab:
9331 alt_grab = 1;
9332 break;
9333 case QEMU_OPTION_no_quit:
9334 no_quit = 1;
9335 break;
9336 #endif
9337 case QEMU_OPTION_pidfile:
9338 pid_file = optarg;
9339 break;
9340 #ifdef TARGET_I386
9341 case QEMU_OPTION_win2k_hack:
9342 win2k_install_hack = 1;
9343 break;
9344 #endif
9345 #ifdef USE_KQEMU
9346 case QEMU_OPTION_no_kqemu:
9347 kqemu_allowed = 0;
9348 break;
9349 case QEMU_OPTION_kernel_kqemu:
9350 kqemu_allowed = 2;
9351 break;
9352 #endif
9353 #ifdef USE_KVM
9354 case QEMU_OPTION_no_kvm:
9355 kvm_allowed = 0;
9356 break;
9357 case QEMU_OPTION_no_kvm_irqchip: {
9358 extern int kvm_irqchip, kvm_pit;
9359 kvm_irqchip = 0;
9360 kvm_pit = 0;
9361 break;
9363 case QEMU_OPTION_no_kvm_pit: {
9364 extern int kvm_pit;
9365 kvm_pit = 0;
9366 break;
9368 #endif
9369 case QEMU_OPTION_usb:
9370 usb_enabled = 1;
9371 break;
9372 case QEMU_OPTION_usbdevice:
9373 usb_enabled = 1;
9374 if (usb_devices_index >= MAX_USB_CMDLINE) {
9375 fprintf(stderr, "Too many USB devices\n");
9376 exit(1);
9378 usb_devices[usb_devices_index] = optarg;
9379 usb_devices_index++;
9380 break;
9381 case QEMU_OPTION_smp:
9382 smp_cpus = atoi(optarg);
9383 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9384 fprintf(stderr, "Invalid number of CPUs\n");
9385 exit(1);
9387 break;
9388 case QEMU_OPTION_vnc:
9389 vnc_display = optarg;
9390 break;
9391 case QEMU_OPTION_no_acpi:
9392 acpi_enabled = 0;
9393 break;
9394 case QEMU_OPTION_no_reboot:
9395 no_reboot = 1;
9396 break;
9397 case QEMU_OPTION_no_shutdown:
9398 no_shutdown = 1;
9399 break;
9400 case QEMU_OPTION_show_cursor:
9401 cursor_hide = 0;
9402 break;
9403 case QEMU_OPTION_daemonize:
9404 daemonize = 1;
9405 break;
9406 case QEMU_OPTION_option_rom:
9407 if (nb_option_roms >= MAX_OPTION_ROMS) {
9408 fprintf(stderr, "Too many option ROMs\n");
9409 exit(1);
9411 option_rom[nb_option_roms] = optarg;
9412 nb_option_roms++;
9413 break;
9414 case QEMU_OPTION_semihosting:
9415 semihosting_enabled = 1;
9416 break;
9417 case QEMU_OPTION_tdf:
9418 time_drift_fix = 1;
9419 break;
9420 case QEMU_OPTION_kvm_shadow_memory:
9421 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9422 break;
9423 case QEMU_OPTION_mempath:
9424 mem_path = optarg;
9425 break;
9426 case QEMU_OPTION_name:
9427 qemu_name = optarg;
9428 break;
9429 #ifdef TARGET_SPARC
9430 case QEMU_OPTION_prom_env:
9431 if (nb_prom_envs >= MAX_PROM_ENVS) {
9432 fprintf(stderr, "Too many prom variables\n");
9433 exit(1);
9435 prom_envs[nb_prom_envs] = optarg;
9436 nb_prom_envs++;
9437 break;
9438 #endif
9439 case QEMU_OPTION_cpu_vendor:
9440 cpu_vendor_string = optarg;
9441 break;
9442 #ifdef TARGET_ARM
9443 case QEMU_OPTION_old_param:
9444 old_param = 1;
9445 break;
9446 #endif
9447 case QEMU_OPTION_clock:
9448 configure_alarms(optarg);
9449 break;
9450 case QEMU_OPTION_startdate:
9452 struct tm tm;
9453 time_t rtc_start_date;
9454 if (!strcmp(optarg, "now")) {
9455 rtc_date_offset = -1;
9456 } else {
9457 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9458 &tm.tm_year,
9459 &tm.tm_mon,
9460 &tm.tm_mday,
9461 &tm.tm_hour,
9462 &tm.tm_min,
9463 &tm.tm_sec) == 6) {
9464 /* OK */
9465 } else if (sscanf(optarg, "%d-%d-%d",
9466 &tm.tm_year,
9467 &tm.tm_mon,
9468 &tm.tm_mday) == 3) {
9469 tm.tm_hour = 0;
9470 tm.tm_min = 0;
9471 tm.tm_sec = 0;
9472 } else {
9473 goto date_fail;
9475 tm.tm_year -= 1900;
9476 tm.tm_mon--;
9477 rtc_start_date = mktimegm(&tm);
9478 if (rtc_start_date == -1) {
9479 date_fail:
9480 fprintf(stderr, "Invalid date format. Valid format are:\n"
9481 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9482 exit(1);
9484 rtc_date_offset = time(NULL) - rtc_start_date;
9487 break;
9492 #ifndef _WIN32
9493 if (daemonize) {
9494 pid_t pid;
9496 if (pipe(fds) == -1)
9497 exit(1);
9499 pid = fork();
9500 if (pid > 0) {
9501 uint8_t status;
9502 ssize_t len;
9504 close(fds[1]);
9506 again:
9507 len = read(fds[0], &status, 1);
9508 if (len == -1 && (errno == EINTR))
9509 goto again;
9511 if (len != 1)
9512 exit(1);
9513 else if (status == 1) {
9514 fprintf(stderr, "Could not acquire pidfile\n");
9515 exit(1);
9516 } else
9517 exit(0);
9518 } else if (pid < 0)
9519 exit(1);
9521 setsid();
9523 pid = fork();
9524 if (pid > 0)
9525 exit(0);
9526 else if (pid < 0)
9527 exit(1);
9529 umask(027);
9531 signal(SIGTSTP, SIG_IGN);
9532 signal(SIGTTOU, SIG_IGN);
9533 signal(SIGTTIN, SIG_IGN);
9535 #endif
9537 #if USE_KVM
9538 if (kvm_enabled()) {
9539 if (kvm_qemu_init() < 0) {
9540 extern int kvm_allowed;
9541 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9542 #ifdef NO_CPU_EMULATION
9543 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9544 exit(1);
9545 #endif
9546 kvm_allowed = 0;
9549 #endif
9551 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9552 if (daemonize) {
9553 uint8_t status = 1;
9554 write(fds[1], &status, 1);
9555 } else
9556 fprintf(stderr, "Could not acquire pid file\n");
9557 exit(1);
9560 #ifdef USE_KQEMU
9561 if (smp_cpus > 1)
9562 kqemu_allowed = 0;
9563 #endif
9564 linux_boot = (kernel_filename != NULL);
9565 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9567 /* XXX: this should not be: some embedded targets just have flash */
9568 if (!linux_boot && net_boot == 0 &&
9569 nb_drives_opt == 0)
9570 help(1);
9572 /* boot to floppy or the default cd if no hard disk defined yet */
9573 if (!boot_devices[0]) {
9574 boot_devices = "cad";
9576 setvbuf(stdout, NULL, _IOLBF, 0);
9578 init_timers();
9579 init_timer_alarm();
9580 qemu_aio_init();
9582 #ifdef _WIN32
9583 socket_init();
9584 #endif
9586 /* init network clients */
9587 if (nb_net_clients == 0) {
9588 /* if no clients, we use a default config */
9589 net_clients[0] = "nic";
9590 net_clients[1] = "user";
9591 nb_net_clients = 2;
9594 for(i = 0;i < nb_net_clients; i++) {
9595 if (net_client_init(net_clients[i]) < 0)
9596 exit(1);
9598 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9599 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9600 continue;
9601 if (vlan->nb_guest_devs == 0) {
9602 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9603 exit(1);
9605 if (vlan->nb_host_devs == 0)
9606 fprintf(stderr,
9607 "Warning: vlan %d is not connected to host network\n",
9608 vlan->id);
9611 #ifdef TARGET_I386
9612 /* XXX: this should be moved in the PC machine instantiation code */
9613 if (net_boot != 0) {
9614 int netroms = 0;
9615 for (i = 0; i < nb_nics && i < 4; i++) {
9616 const char *model = nd_table[i].model;
9617 char buf[1024];
9618 if (net_boot & (1 << i)) {
9619 if (model == NULL)
9620 model = "rtl8139";
9621 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9622 if (get_image_size(buf) > 0) {
9623 if (nb_option_roms >= MAX_OPTION_ROMS) {
9624 fprintf(stderr, "Too many option ROMs\n");
9625 exit(1);
9627 option_rom[nb_option_roms] = strdup(buf);
9628 nb_option_roms++;
9629 netroms++;
9633 if (netroms == 0) {
9634 fprintf(stderr, "No valid PXE rom found for network device\n");
9635 exit(1);
9638 #endif
9640 /* init the memory */
9641 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9643 /* Initialize kvm */
9644 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9645 #define KVM_EXTRA_PAGES 3
9646 #else
9647 #define KVM_EXTRA_PAGES 0
9648 #endif
9649 if (kvm_enabled()) {
9650 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9651 if (kvm_qemu_create_context() < 0) {
9652 fprintf(stderr, "Could not create KVM context\n");
9653 exit(1);
9655 #ifdef KVM_CAP_USER_MEMORY
9657 int ret;
9659 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9660 if (ret) {
9661 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9662 if (!phys_ram_base) {
9663 fprintf(stderr, "Could not allocate physical memory\n");
9664 exit(1);
9668 #endif
9669 } else {
9670 phys_ram_base = qemu_vmalloc(phys_ram_size);
9671 if (!phys_ram_base) {
9672 fprintf(stderr, "Could not allocate physical memory\n");
9673 exit(1);
9677 bdrv_init();
9679 /* we always create the cdrom drive, even if no disk is there */
9681 if (nb_drives_opt < MAX_DRIVES)
9682 drive_add(NULL, CDROM_ALIAS);
9684 /* we always create at least one floppy */
9686 if (nb_drives_opt < MAX_DRIVES)
9687 drive_add(NULL, FD_ALIAS, 0);
9689 /* we always create one sd slot, even if no card is in it */
9691 if (nb_drives_opt < MAX_DRIVES)
9692 drive_add(NULL, SD_ALIAS);
9694 /* open the virtual block devices
9695 * note that migration with device
9696 * hot add/remove is broken.
9698 for(i = 0; i < nb_drives_opt; i++)
9699 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9700 exit(1);
9702 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9703 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9705 init_ioports();
9707 /* terminal init */
9708 memset(&display_state, 0, sizeof(display_state));
9709 if (nographic) {
9710 if (curses) {
9711 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9712 exit(1);
9714 /* nearly nothing to do */
9715 dumb_display_init(ds);
9716 } else if (vnc_display != NULL) {
9717 vnc_display_init(ds);
9718 if (vnc_display_open(ds, vnc_display) < 0)
9719 exit(1);
9720 } else
9721 #if defined(CONFIG_CURSES)
9722 if (curses) {
9723 curses_display_init(ds, full_screen);
9724 } else
9725 #endif
9727 #if defined(CONFIG_SDL)
9728 sdl_display_init(ds, full_screen, no_frame);
9729 #elif defined(CONFIG_COCOA)
9730 cocoa_display_init(ds, full_screen);
9731 #else
9732 dumb_display_init(ds);
9733 #endif
9736 /* Maintain compatibility with multiple stdio monitors */
9737 if (!strcmp(monitor_device,"stdio")) {
9738 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9739 const char *devname = serial_devices[i];
9740 if (devname && !strcmp(devname,"mon:stdio")) {
9741 monitor_device = NULL;
9742 break;
9743 } else if (devname && !strcmp(devname,"stdio")) {
9744 monitor_device = NULL;
9745 serial_devices[i] = "mon:stdio";
9746 break;
9750 if (monitor_device) {
9751 monitor_hd = qemu_chr_open(monitor_device);
9752 if (!monitor_hd) {
9753 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9754 exit(1);
9756 monitor_init(monitor_hd, !nographic);
9759 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9760 const char *devname = vmchannel_devices[i];
9761 if (devname[0] != '\0' && strcmp(devname, "none")) {
9762 int devid;
9763 char *termn;
9765 if (strstart(devname, "di:", &devname)) {
9766 devid = strtol(devname, &termn, 16);
9767 devname = termn + 1;
9769 else {
9770 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9771 devname);
9772 exit(1);
9774 vmchannel_hds[i] = qemu_chr_open(devname);
9775 if (!vmchannel_hds[i]) {
9776 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9777 devname);
9778 exit(1);
9780 vmchannel_init(vmchannel_hds[i], devid, i);
9784 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9785 const char *devname = serial_devices[i];
9786 if (devname && strcmp(devname, "none")) {
9787 serial_hds[i] = qemu_chr_open(devname);
9788 if (!serial_hds[i]) {
9789 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9790 devname);
9791 exit(1);
9793 if (strstart(devname, "vc", 0))
9794 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9798 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9799 const char *devname = parallel_devices[i];
9800 if (devname && strcmp(devname, "none")) {
9801 parallel_hds[i] = qemu_chr_open(devname);
9802 if (!parallel_hds[i]) {
9803 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9804 devname);
9805 exit(1);
9807 if (strstart(devname, "vc", 0))
9808 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9812 if (kvm_enabled())
9813 kvm_init_ap();
9815 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9816 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9818 current_machine = machine;
9820 /* init USB devices */
9821 if (usb_enabled) {
9822 for(i = 0; i < usb_devices_index; i++) {
9823 if (usb_device_add(usb_devices[i]) < 0) {
9824 fprintf(stderr, "Warning: could not add USB device %s\n",
9825 usb_devices[i]);
9830 if (display_state.dpy_refresh) {
9831 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9832 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9835 #ifdef CONFIG_GDBSTUB
9836 if (use_gdbstub) {
9837 /* XXX: use standard host:port notation and modify options
9838 accordingly. */
9839 if (gdbserver_start(gdbstub_port) < 0) {
9840 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9841 gdbstub_port);
9842 exit(1);
9845 #endif
9846 if (loadvm)
9847 do_loadvm(loadvm);
9849 if (incoming) {
9850 int rc;
9852 rc = migrate_incoming(incoming);
9853 if (rc != 0) {
9854 fprintf(stderr, "Migration failed rc=%d\n", rc);
9855 exit(rc);
9860 /* XXX: simplify init */
9861 read_passwords();
9862 if (autostart) {
9863 vm_start();
9867 if (daemonize) {
9868 uint8_t status = 0;
9869 ssize_t len;
9870 int fd;
9872 again1:
9873 len = write(fds[1], &status, 1);
9874 if (len == -1 && (errno == EINTR))
9875 goto again1;
9877 if (len != 1)
9878 exit(1);
9880 chdir("/");
9881 TFR(fd = open("/dev/null", O_RDWR));
9882 if (fd == -1)
9883 exit(1);
9885 dup2(fd, 0);
9886 dup2(fd, 1);
9887 dup2(fd, 2);
9889 close(fd);
9892 main_loop();
9893 quit_timers();
9895 #if !defined(_WIN32)
9896 /* close network clients */
9897 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9898 VLANClientState *vc;
9900 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9901 if (vc->fd_read == tap_receive) {
9902 char ifname[64];
9903 TAPState *s = vc->opaque;
9905 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9906 s->down_script[0])
9907 launch_script(s->down_script, ifname, s->fd);
9911 #endif
9912 return 0;