kvm: libkvm: automatic memory slot management
[qemu-kvm/fedora.git] / vl.c
blob634fb349729f779f62de83619bbdc5a429416389
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2007 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 "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #include <sys/select.h>
46 #include <arpa/inet.h>
47 #ifdef _BSD
48 #include <sys/stat.h>
49 #ifndef __APPLE__
50 #include <libutil.h>
51 #endif
52 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
53 #include <freebsd/stdlib.h>
54 #else
55 #ifndef __sun__
56 #include <linux/if.h>
57 #include <linux/if_tun.h>
58 #include <pty.h>
59 #include <malloc.h>
60 #include <linux/rtc.h>
62 /* For the benefit of older linux systems which don't supply it,
63 we use a local copy of hpet.h. */
64 /* #include <linux/hpet.h> */
65 #include "hpet.h"
67 #include <linux/ppdev.h>
68 #include <linux/parport.h>
69 #else
70 #include <sys/stat.h>
71 #include <sys/ethernet.h>
72 #include <sys/sockio.h>
73 #include <netinet/arp.h>
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_icmp.h> // must come after ip.h
78 #include <netinet/udp.h>
79 #include <netinet/tcp.h>
80 #include <net/if.h>
81 #include <syslog.h>
82 #include <stropts.h>
83 #endif
84 #endif
85 #else
86 #include <winsock2.h>
87 int inet_aton(const char *cp, struct in_addr *ia);
88 #endif
90 #if defined(CONFIG_SLIRP)
91 #include "libslirp.h"
92 #endif
94 #ifdef _WIN32
95 #include <malloc.h>
96 #include <sys/timeb.h>
97 #include <windows.h>
98 #define getopt_long_only getopt_long
99 #define memalign(align, size) malloc(size)
100 #endif
102 #include "qemu_socket.h"
104 #ifdef CONFIG_SDL
105 #ifdef __APPLE__
106 #include <SDL/SDL.h>
107 #endif
108 #endif /* CONFIG_SDL */
110 #ifdef CONFIG_COCOA
111 #undef main
112 #define main qemu_main
113 #endif /* CONFIG_COCOA */
115 #include "disas.h"
117 #include "exec-all.h"
119 #if USE_KVM
120 #include "qemu-kvm.h"
121 #endif
123 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
124 #ifdef __sun__
125 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
126 #else
127 #define SMBD_COMMAND "/usr/sbin/smbd"
128 #endif
130 //#define DEBUG_UNUSED_IOPORT
131 //#define DEBUG_IOPORT
133 #if HOST_LONG_BITS < 64
134 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
135 #else
136 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024 * 1024ULL)
137 #endif
139 #ifdef TARGET_PPC
140 #define DEFAULT_RAM_SIZE 144
141 #else
142 #define DEFAULT_RAM_SIZE 128
143 #endif
144 /* in ms */
145 #define GUI_REFRESH_INTERVAL 30
147 /* Max number of USB devices that can be specified on the commandline. */
148 #define MAX_USB_CMDLINE 8
150 /* XXX: use a two level table to limit memory usage */
151 #define MAX_IOPORTS 65536
153 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
154 char phys_ram_file[1024];
155 void *ioport_opaque[MAX_IOPORTS];
156 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
157 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
158 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
159 to store the VM snapshots */
160 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
161 BlockDriverState *pflash_table[MAX_PFLASH];
162 BlockDriverState *sd_bdrv;
163 BlockDriverState *mtd_bdrv;
164 /* point to the block driver where the snapshots are managed */
165 BlockDriverState *bs_snapshots;
166 int vga_ram_size;
167 static DisplayState display_state;
168 int nographic;
169 const char* keyboard_layout = NULL;
170 int64_t ticks_per_sec;
171 int boot_device = 'c';
172 int64_t ram_size;
173 int pit_min_timer_count = 0;
174 int nb_nics;
175 NICInfo nd_table[MAX_NICS];
176 int vm_running;
177 int rtc_utc = 1;
178 int cirrus_vga_enabled = 1;
179 int vmsvga_enabled = 0;
180 #ifdef TARGET_SPARC
181 int graphic_width = 1024;
182 int graphic_height = 768;
183 int graphic_depth = 8;
184 #else
185 int graphic_width = 800;
186 int graphic_height = 600;
187 int graphic_depth = 15;
188 #endif
189 int full_screen = 0;
190 int no_frame = 0;
191 int no_quit = 0;
192 int balloon_used = 0;
193 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
194 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
195 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
196 #ifdef TARGET_I386
197 int win2k_install_hack = 0;
198 #endif
199 int usb_enabled = 0;
200 static VLANState *first_vlan;
201 int smp_cpus = 1;
202 const char *vnc_display;
203 #if defined(TARGET_SPARC)
204 #define MAX_CPUS 16
205 #elif defined(TARGET_I386)
206 #define MAX_CPUS 255
207 #else
208 #define MAX_CPUS 1
209 #endif
210 int acpi_enabled = 1;
211 int fd_bootchk = 1;
212 int no_reboot = 0;
213 int cursor_hide = 1;
214 int graphic_rotate = 0;
215 int daemonize = 0;
216 const char *incoming;
217 const char *option_rom[MAX_OPTION_ROMS];
218 int nb_option_roms;
219 int semihosting_enabled = 0;
220 int autostart = 1;
221 int time_drift_fix = 0;
222 unsigned int kvm_shadow_memory = 0;
223 const char *cpu_vendor_string;
224 #ifdef TARGET_ARM
225 int old_param = 0;
226 #endif
227 const char *qemu_name;
228 int alt_grab = 0;
229 #ifdef TARGET_SPARC
230 unsigned int nb_prom_envs = 0;
231 const char *prom_envs[MAX_PROM_ENVS];
232 #endif
234 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
236 /***********************************************************/
237 /* x86 ISA bus support */
239 target_phys_addr_t isa_mem_base = 0;
240 PicState2 *isa_pic;
242 uint32_t default_ioport_readb(void *opaque, uint32_t address)
244 #ifdef DEBUG_UNUSED_IOPORT
245 fprintf(stderr, "unused inb: port=0x%04x\n", address);
246 #endif
247 return 0xff;
250 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
252 #ifdef DEBUG_UNUSED_IOPORT
253 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
254 #endif
257 /* default is to make two byte accesses */
258 uint32_t default_ioport_readw(void *opaque, uint32_t address)
260 uint32_t data;
261 data = ioport_read_table[0][address](ioport_opaque[address], address);
262 address = (address + 1) & (MAX_IOPORTS - 1);
263 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
264 return data;
267 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
269 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
270 address = (address + 1) & (MAX_IOPORTS - 1);
271 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
274 uint32_t default_ioport_readl(void *opaque, uint32_t address)
276 #ifdef DEBUG_UNUSED_IOPORT
277 fprintf(stderr, "unused inl: port=0x%04x\n", address);
278 #endif
279 return 0xffffffff;
282 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
284 #ifdef DEBUG_UNUSED_IOPORT
285 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
286 #endif
289 void init_ioports(void)
291 int i;
293 for(i = 0; i < MAX_IOPORTS; i++) {
294 ioport_read_table[0][i] = default_ioport_readb;
295 ioport_write_table[0][i] = default_ioport_writeb;
296 ioport_read_table[1][i] = default_ioport_readw;
297 ioport_write_table[1][i] = default_ioport_writew;
298 ioport_read_table[2][i] = default_ioport_readl;
299 ioport_write_table[2][i] = default_ioport_writel;
303 /* size is the word size in byte */
304 int register_ioport_read(int start, int length, int size,
305 IOPortReadFunc *func, void *opaque)
307 int i, bsize;
309 if (size == 1) {
310 bsize = 0;
311 } else if (size == 2) {
312 bsize = 1;
313 } else if (size == 4) {
314 bsize = 2;
315 } else {
316 hw_error("register_ioport_read: invalid size");
317 return -1;
319 for(i = start; i < start + length; i += size) {
320 ioport_read_table[bsize][i] = func;
321 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
322 hw_error("register_ioport_read: invalid opaque");
323 ioport_opaque[i] = opaque;
325 return 0;
328 /* size is the word size in byte */
329 int register_ioport_write(int start, int length, int size,
330 IOPortWriteFunc *func, void *opaque)
332 int i, bsize;
334 if (size == 1) {
335 bsize = 0;
336 } else if (size == 2) {
337 bsize = 1;
338 } else if (size == 4) {
339 bsize = 2;
340 } else {
341 hw_error("register_ioport_write: invalid size");
342 return -1;
344 for(i = start; i < start + length; i += size) {
345 ioport_write_table[bsize][i] = func;
346 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
347 hw_error("register_ioport_write: invalid opaque");
348 ioport_opaque[i] = opaque;
350 return 0;
353 void isa_unassign_ioport(int start, int length)
355 int i;
357 for(i = start; i < start + length; i++) {
358 ioport_read_table[0][i] = default_ioport_readb;
359 ioport_read_table[1][i] = default_ioport_readw;
360 ioport_read_table[2][i] = default_ioport_readl;
362 ioport_write_table[0][i] = default_ioport_writeb;
363 ioport_write_table[1][i] = default_ioport_writew;
364 ioport_write_table[2][i] = default_ioport_writel;
368 /***********************************************************/
370 void cpu_outb(CPUState *env, int addr, int val)
372 #ifdef DEBUG_IOPORT
373 if (loglevel & CPU_LOG_IOPORT)
374 fprintf(logfile, "outb: %04x %02x\n", addr, val);
375 #endif
376 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
377 #ifdef USE_KQEMU
378 if (env)
379 env->last_io_time = cpu_get_time_fast();
380 #endif
383 void cpu_outw(CPUState *env, int addr, int val)
385 #ifdef DEBUG_IOPORT
386 if (loglevel & CPU_LOG_IOPORT)
387 fprintf(logfile, "outw: %04x %04x\n", addr, val);
388 #endif
389 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
390 #ifdef USE_KQEMU
391 if (env)
392 env->last_io_time = cpu_get_time_fast();
393 #endif
396 void cpu_outl(CPUState *env, int addr, int val)
398 #ifdef DEBUG_IOPORT
399 if (loglevel & CPU_LOG_IOPORT)
400 fprintf(logfile, "outl: %04x %08x\n", addr, val);
401 #endif
402 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
403 #ifdef USE_KQEMU
404 if (env)
405 env->last_io_time = cpu_get_time_fast();
406 #endif
409 int cpu_inb(CPUState *env, int addr)
411 int val;
412 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
413 #ifdef DEBUG_IOPORT
414 if (loglevel & CPU_LOG_IOPORT)
415 fprintf(logfile, "inb : %04x %02x\n", addr, val);
416 #endif
417 #ifdef USE_KQEMU
418 if (env)
419 env->last_io_time = cpu_get_time_fast();
420 #endif
421 return val;
424 int cpu_inw(CPUState *env, int addr)
426 int val;
427 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
428 #ifdef DEBUG_IOPORT
429 if (loglevel & CPU_LOG_IOPORT)
430 fprintf(logfile, "inw : %04x %04x\n", addr, val);
431 #endif
432 #ifdef USE_KQEMU
433 if (env)
434 env->last_io_time = cpu_get_time_fast();
435 #endif
436 return val;
439 int cpu_inl(CPUState *env, int addr)
441 int val;
442 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
443 #ifdef DEBUG_IOPORT
444 if (loglevel & CPU_LOG_IOPORT)
445 fprintf(logfile, "inl : %04x %08x\n", addr, val);
446 #endif
447 #ifdef USE_KQEMU
448 if (env)
449 env->last_io_time = cpu_get_time_fast();
450 #endif
451 return val;
454 /***********************************************************/
455 void hw_error(const char *fmt, ...)
457 va_list ap;
458 CPUState *env;
460 va_start(ap, fmt);
461 fprintf(stderr, "qemu: hardware error: ");
462 vfprintf(stderr, fmt, ap);
463 fprintf(stderr, "\n");
464 for(env = first_cpu; env != NULL; env = env->next_cpu) {
465 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
466 #ifdef TARGET_I386
467 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
468 #else
469 cpu_dump_state(env, stderr, fprintf, 0);
470 #endif
472 va_end(ap);
473 abort();
476 /***********************************************************/
477 /* keyboard/mouse */
479 static QEMUPutKBDEvent *qemu_put_kbd_event;
480 static void *qemu_put_kbd_event_opaque;
481 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
482 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
484 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
486 qemu_put_kbd_event_opaque = opaque;
487 qemu_put_kbd_event = func;
490 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
491 void *opaque, int absolute,
492 const char *name)
494 QEMUPutMouseEntry *s, *cursor;
496 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
497 if (!s)
498 return NULL;
500 s->qemu_put_mouse_event = func;
501 s->qemu_put_mouse_event_opaque = opaque;
502 s->qemu_put_mouse_event_absolute = absolute;
503 s->qemu_put_mouse_event_name = qemu_strdup(name);
504 s->next = NULL;
506 if (!qemu_put_mouse_event_head) {
507 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
508 return s;
511 cursor = qemu_put_mouse_event_head;
512 while (cursor->next != NULL)
513 cursor = cursor->next;
515 cursor->next = s;
516 qemu_put_mouse_event_current = s;
518 return s;
521 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
523 QEMUPutMouseEntry *prev = NULL, *cursor;
525 if (!qemu_put_mouse_event_head || entry == NULL)
526 return;
528 cursor = qemu_put_mouse_event_head;
529 while (cursor != NULL && cursor != entry) {
530 prev = cursor;
531 cursor = cursor->next;
534 if (cursor == NULL) // does not exist or list empty
535 return;
536 else if (prev == NULL) { // entry is head
537 qemu_put_mouse_event_head = cursor->next;
538 if (qemu_put_mouse_event_current == entry)
539 qemu_put_mouse_event_current = cursor->next;
540 qemu_free(entry->qemu_put_mouse_event_name);
541 qemu_free(entry);
542 return;
545 prev->next = entry->next;
547 if (qemu_put_mouse_event_current == entry)
548 qemu_put_mouse_event_current = prev;
550 qemu_free(entry->qemu_put_mouse_event_name);
551 qemu_free(entry);
554 void kbd_put_keycode(int keycode)
556 if (qemu_put_kbd_event) {
557 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
561 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
563 QEMUPutMouseEvent *mouse_event;
564 void *mouse_event_opaque;
565 int width;
567 if (!qemu_put_mouse_event_current) {
568 return;
571 mouse_event =
572 qemu_put_mouse_event_current->qemu_put_mouse_event;
573 mouse_event_opaque =
574 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
576 if (mouse_event) {
577 if (graphic_rotate) {
578 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
579 width = 0x7fff;
580 else
581 width = graphic_width;
582 mouse_event(mouse_event_opaque,
583 width - dy, dx, dz, buttons_state);
584 } else
585 mouse_event(mouse_event_opaque,
586 dx, dy, dz, buttons_state);
590 int kbd_mouse_is_absolute(void)
592 if (!qemu_put_mouse_event_current)
593 return 0;
595 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
598 void do_info_mice(void)
600 QEMUPutMouseEntry *cursor;
601 int index = 0;
603 if (!qemu_put_mouse_event_head) {
604 term_printf("No mouse devices connected\n");
605 return;
608 term_printf("Mouse devices available:\n");
609 cursor = qemu_put_mouse_event_head;
610 while (cursor != NULL) {
611 term_printf("%c Mouse #%d: %s\n",
612 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
613 index, cursor->qemu_put_mouse_event_name);
614 index++;
615 cursor = cursor->next;
619 void do_mouse_set(int index)
621 QEMUPutMouseEntry *cursor;
622 int i = 0;
624 if (!qemu_put_mouse_event_head) {
625 term_printf("No mouse devices connected\n");
626 return;
629 cursor = qemu_put_mouse_event_head;
630 while (cursor != NULL && index != i) {
631 i++;
632 cursor = cursor->next;
635 if (cursor != NULL)
636 qemu_put_mouse_event_current = cursor;
637 else
638 term_printf("Mouse at given index not found\n");
641 /* compute with 96 bit intermediate result: (a*b)/c */
642 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
644 union {
645 uint64_t ll;
646 struct {
647 #ifdef WORDS_BIGENDIAN
648 uint32_t high, low;
649 #else
650 uint32_t low, high;
651 #endif
652 } l;
653 } u, res;
654 uint64_t rl, rh;
656 u.ll = a;
657 rl = (uint64_t)u.l.low * (uint64_t)b;
658 rh = (uint64_t)u.l.high * (uint64_t)b;
659 rh += (rl >> 32);
660 res.l.high = rh / c;
661 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
662 return res.ll;
665 /***********************************************************/
666 /* real time host monotonic timer */
668 #define QEMU_TIMER_BASE 1000000000LL
670 #ifdef WIN32
672 static int64_t clock_freq;
674 static void init_get_clock(void)
676 LARGE_INTEGER freq;
677 int ret;
678 ret = QueryPerformanceFrequency(&freq);
679 if (ret == 0) {
680 fprintf(stderr, "Could not calibrate ticks\n");
681 exit(1);
683 clock_freq = freq.QuadPart;
686 static int64_t get_clock(void)
688 LARGE_INTEGER ti;
689 QueryPerformanceCounter(&ti);
690 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
693 #else
695 static int use_rt_clock;
697 static void init_get_clock(void)
699 use_rt_clock = 0;
700 #if defined(__linux__)
702 struct timespec ts;
703 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
704 use_rt_clock = 1;
707 #endif
710 static int64_t get_clock(void)
712 #if defined(__linux__)
713 if (use_rt_clock) {
714 struct timespec ts;
715 clock_gettime(CLOCK_MONOTONIC, &ts);
716 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
717 } else
718 #endif
720 /* XXX: using gettimeofday leads to problems if the date
721 changes, so it should be avoided. */
722 struct timeval tv;
723 gettimeofday(&tv, NULL);
724 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
728 #endif
730 /***********************************************************/
731 /* guest cycle counter */
733 static int64_t cpu_ticks_prev;
734 static int64_t cpu_ticks_offset;
735 static int64_t cpu_clock_offset;
736 static int cpu_ticks_enabled;
738 /* return the host CPU cycle counter and handle stop/restart */
739 int64_t cpu_get_ticks(void)
741 if (!cpu_ticks_enabled) {
742 return cpu_ticks_offset;
743 } else {
744 int64_t ticks;
745 ticks = cpu_get_real_ticks();
746 if (cpu_ticks_prev > ticks) {
747 /* Note: non increasing ticks may happen if the host uses
748 software suspend */
749 cpu_ticks_offset += cpu_ticks_prev - ticks;
751 cpu_ticks_prev = ticks;
752 return ticks + cpu_ticks_offset;
756 /* return the host CPU monotonic timer and handle stop/restart */
757 static int64_t cpu_get_clock(void)
759 int64_t ti;
760 if (!cpu_ticks_enabled) {
761 return cpu_clock_offset;
762 } else {
763 ti = get_clock();
764 return ti + cpu_clock_offset;
768 /* enable cpu_get_ticks() */
769 void cpu_enable_ticks(void)
771 if (!cpu_ticks_enabled) {
772 cpu_ticks_offset -= cpu_get_real_ticks();
773 cpu_clock_offset -= get_clock();
774 cpu_ticks_enabled = 1;
778 /* disable cpu_get_ticks() : the clock is stopped. You must not call
779 cpu_get_ticks() after that. */
780 void cpu_disable_ticks(void)
782 if (cpu_ticks_enabled) {
783 cpu_ticks_offset = cpu_get_ticks();
784 cpu_clock_offset = cpu_get_clock();
785 cpu_ticks_enabled = 0;
789 /***********************************************************/
790 /* timers */
792 #define QEMU_TIMER_REALTIME 0
793 #define QEMU_TIMER_VIRTUAL 1
795 struct QEMUClock {
796 int type;
797 /* XXX: add frequency */
800 struct QEMUTimer {
801 QEMUClock *clock;
802 int64_t expire_time;
803 QEMUTimerCB *cb;
804 void *opaque;
805 struct QEMUTimer *next;
808 struct qemu_alarm_timer {
809 char const *name;
810 unsigned int flags;
812 int (*start)(struct qemu_alarm_timer *t);
813 void (*stop)(struct qemu_alarm_timer *t);
814 void (*rearm)(struct qemu_alarm_timer *t);
815 void *priv;
818 #define ALARM_FLAG_DYNTICKS 0x1
820 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
822 return t->flags & ALARM_FLAG_DYNTICKS;
825 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
827 if (!alarm_has_dynticks(t))
828 return;
830 t->rearm(t);
833 /* TODO: MIN_TIMER_REARM_US should be optimized */
834 #define MIN_TIMER_REARM_US 250
836 static struct qemu_alarm_timer *alarm_timer;
838 #ifdef _WIN32
840 struct qemu_alarm_win32 {
841 MMRESULT timerId;
842 HANDLE host_alarm;
843 unsigned int period;
844 } alarm_win32_data = {0, NULL, -1};
846 static int win32_start_timer(struct qemu_alarm_timer *t);
847 static void win32_stop_timer(struct qemu_alarm_timer *t);
848 static void win32_rearm_timer(struct qemu_alarm_timer *t);
850 #else
852 static int unix_start_timer(struct qemu_alarm_timer *t);
853 static void unix_stop_timer(struct qemu_alarm_timer *t);
855 #ifdef __linux__
857 static int dynticks_start_timer(struct qemu_alarm_timer *t);
858 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
859 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
861 static int hpet_start_timer(struct qemu_alarm_timer *t);
862 static void hpet_stop_timer(struct qemu_alarm_timer *t);
864 static int rtc_start_timer(struct qemu_alarm_timer *t);
865 static void rtc_stop_timer(struct qemu_alarm_timer *t);
867 #endif /* __linux__ */
869 #endif /* _WIN32 */
871 static struct qemu_alarm_timer alarm_timers[] = {
872 #ifndef _WIN32
873 #ifdef __linux__
874 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
875 dynticks_stop_timer, dynticks_rearm_timer, NULL},
876 /* HPET - if available - is preferred */
877 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
878 /* ...otherwise try RTC */
879 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
880 #endif
881 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
882 #else
883 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
884 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
885 {"win32", 0, win32_start_timer,
886 win32_stop_timer, NULL, &alarm_win32_data},
887 #endif
888 {NULL, }
891 static void show_available_alarms()
893 int i;
895 printf("Available alarm timers, in order of precedence:\n");
896 for (i = 0; alarm_timers[i].name; i++)
897 printf("%s\n", alarm_timers[i].name);
900 static void configure_alarms(char const *opt)
902 int i;
903 int cur = 0;
904 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
905 char *arg;
906 char *name;
908 if (!strcmp(opt, "help")) {
909 show_available_alarms();
910 exit(0);
913 arg = strdup(opt);
915 /* Reorder the array */
916 name = strtok(arg, ",");
917 while (name) {
918 struct qemu_alarm_timer tmp;
920 for (i = 0; i < count && alarm_timers[i].name; i++) {
921 if (!strcmp(alarm_timers[i].name, name))
922 break;
925 if (i == count) {
926 fprintf(stderr, "Unknown clock %s\n", name);
927 goto next;
930 if (i < cur)
931 /* Ignore */
932 goto next;
934 /* Swap */
935 tmp = alarm_timers[i];
936 alarm_timers[i] = alarm_timers[cur];
937 alarm_timers[cur] = tmp;
939 cur++;
940 next:
941 name = strtok(NULL, ",");
944 free(arg);
946 if (cur) {
947 /* Disable remaining timers */
948 for (i = cur; i < count; i++)
949 alarm_timers[i].name = NULL;
952 /* debug */
953 show_available_alarms();
956 QEMUClock *rt_clock;
957 QEMUClock *vm_clock;
959 static QEMUTimer *active_timers[2];
961 QEMUClock *qemu_new_clock(int type)
963 QEMUClock *clock;
964 clock = qemu_mallocz(sizeof(QEMUClock));
965 if (!clock)
966 return NULL;
967 clock->type = type;
968 return clock;
971 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
973 QEMUTimer *ts;
975 ts = qemu_mallocz(sizeof(QEMUTimer));
976 ts->clock = clock;
977 ts->cb = cb;
978 ts->opaque = opaque;
979 return ts;
982 void qemu_free_timer(QEMUTimer *ts)
984 qemu_free(ts);
987 /* stop a timer, but do not dealloc it */
988 void qemu_del_timer(QEMUTimer *ts)
990 QEMUTimer **pt, *t;
992 /* NOTE: this code must be signal safe because
993 qemu_timer_expired() can be called from a signal. */
994 pt = &active_timers[ts->clock->type];
995 for(;;) {
996 t = *pt;
997 if (!t)
998 break;
999 if (t == ts) {
1000 *pt = t->next;
1001 break;
1003 pt = &t->next;
1006 qemu_rearm_alarm_timer(alarm_timer);
1009 /* modify the current timer so that it will be fired when current_time
1010 >= expire_time. The corresponding callback will be called. */
1011 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1013 QEMUTimer **pt, *t;
1015 qemu_del_timer(ts);
1017 /* add the timer in the sorted list */
1018 /* NOTE: this code must be signal safe because
1019 qemu_timer_expired() can be called from a signal. */
1020 pt = &active_timers[ts->clock->type];
1021 for(;;) {
1022 t = *pt;
1023 if (!t)
1024 break;
1025 if (t->expire_time > expire_time)
1026 break;
1027 pt = &t->next;
1029 ts->expire_time = expire_time;
1030 ts->next = *pt;
1031 *pt = ts;
1034 int qemu_timer_pending(QEMUTimer *ts)
1036 QEMUTimer *t;
1037 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1038 if (t == ts)
1039 return 1;
1041 return 0;
1044 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1046 if (!timer_head)
1047 return 0;
1048 return (timer_head->expire_time <= current_time);
1051 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1053 QEMUTimer *ts;
1055 for(;;) {
1056 ts = *ptimer_head;
1057 if (!ts || ts->expire_time > current_time)
1058 break;
1059 /* remove timer from the list before calling the callback */
1060 *ptimer_head = ts->next;
1061 ts->next = NULL;
1063 /* run the callback (the timer list can be modified) */
1064 ts->cb(ts->opaque);
1066 qemu_rearm_alarm_timer(alarm_timer);
1069 int64_t qemu_get_clock(QEMUClock *clock)
1071 switch(clock->type) {
1072 case QEMU_TIMER_REALTIME:
1073 return get_clock() / 1000000;
1074 default:
1075 case QEMU_TIMER_VIRTUAL:
1076 return cpu_get_clock();
1080 static void init_timers(void)
1082 init_get_clock();
1083 ticks_per_sec = QEMU_TIMER_BASE;
1084 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1085 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1088 /* save a timer */
1089 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1091 uint64_t expire_time;
1093 if (qemu_timer_pending(ts)) {
1094 expire_time = ts->expire_time;
1095 } else {
1096 expire_time = -1;
1098 qemu_put_be64(f, expire_time);
1101 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1103 uint64_t expire_time;
1105 expire_time = qemu_get_be64(f);
1106 if (expire_time != -1) {
1107 qemu_mod_timer(ts, expire_time);
1108 } else {
1109 qemu_del_timer(ts);
1113 static void timer_save(QEMUFile *f, void *opaque)
1115 if (cpu_ticks_enabled) {
1116 hw_error("cannot save state if virtual timers are running");
1118 qemu_put_be64s(f, &cpu_ticks_offset);
1119 qemu_put_be64s(f, &ticks_per_sec);
1120 qemu_put_be64s(f, &cpu_clock_offset);
1123 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1125 if (version_id != 1 && version_id != 2)
1126 return -EINVAL;
1127 if (cpu_ticks_enabled) {
1128 return -EINVAL;
1130 qemu_get_be64s(f, &cpu_ticks_offset);
1131 qemu_get_be64s(f, &ticks_per_sec);
1132 if (version_id == 2) {
1133 qemu_get_be64s(f, &cpu_clock_offset);
1135 return 0;
1138 #ifdef _WIN32
1139 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1140 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1141 #else
1142 static void host_alarm_handler(int host_signum)
1143 #endif
1145 #if 0
1146 #define DISP_FREQ 1000
1148 static int64_t delta_min = INT64_MAX;
1149 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1150 static int count;
1151 ti = qemu_get_clock(vm_clock);
1152 if (last_clock != 0) {
1153 delta = ti - last_clock;
1154 if (delta < delta_min)
1155 delta_min = delta;
1156 if (delta > delta_max)
1157 delta_max = delta;
1158 delta_cum += delta;
1159 if (++count == DISP_FREQ) {
1160 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1161 muldiv64(delta_min, 1000000, ticks_per_sec),
1162 muldiv64(delta_max, 1000000, ticks_per_sec),
1163 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1164 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1165 count = 0;
1166 delta_min = INT64_MAX;
1167 delta_max = 0;
1168 delta_cum = 0;
1171 last_clock = ti;
1173 #endif
1174 if (1 ||
1175 alarm_has_dynticks(alarm_timer) ||
1176 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1177 qemu_get_clock(vm_clock)) ||
1178 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1179 qemu_get_clock(rt_clock))) {
1180 #ifdef _WIN32
1181 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1182 SetEvent(data->host_alarm);
1183 #endif
1184 CPUState *env = cpu_single_env;
1185 if (env) {
1186 /* stop the currently executing cpu because a timer occured */
1187 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1188 #ifdef USE_KQEMU
1189 if (env->kqemu_enabled) {
1190 kqemu_cpu_interrupt(env);
1192 #endif
1197 static uint64_t qemu_next_deadline(void)
1199 int64_t nearest_delta_us = UINT64_MAX;
1200 int64_t vmdelta_us;
1202 if (active_timers[QEMU_TIMER_REALTIME])
1203 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1204 qemu_get_clock(rt_clock))*1000;
1206 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1207 /* round up */
1208 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1209 qemu_get_clock(vm_clock)+999)/1000;
1210 if (vmdelta_us < nearest_delta_us)
1211 nearest_delta_us = vmdelta_us;
1214 /* Avoid arming the timer to negative, zero, or too low values */
1215 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1216 nearest_delta_us = MIN_TIMER_REARM_US;
1218 return nearest_delta_us;
1221 #ifndef _WIN32
1223 #if defined(__linux__)
1225 #define RTC_FREQ 1024
1227 static void enable_sigio_timer(int fd)
1229 struct sigaction act;
1231 /* timer signal */
1232 sigfillset(&act.sa_mask);
1233 act.sa_flags = 0;
1234 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1235 act.sa_flags |= SA_ONSTACK;
1236 #endif
1237 act.sa_handler = host_alarm_handler;
1239 sigaction(SIGIO, &act, NULL);
1240 fcntl(fd, F_SETFL, O_ASYNC);
1241 fcntl(fd, F_SETOWN, getpid());
1244 static int hpet_start_timer(struct qemu_alarm_timer *t)
1246 struct hpet_info info;
1247 int r, fd;
1249 fd = open("/dev/hpet", O_RDONLY);
1250 if (fd < 0)
1251 return -1;
1253 /* Set frequency */
1254 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1255 if (r < 0) {
1256 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1257 "error, but for better emulation accuracy type:\n"
1258 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1259 goto fail;
1262 /* Check capabilities */
1263 r = ioctl(fd, HPET_INFO, &info);
1264 if (r < 0)
1265 goto fail;
1267 /* Enable periodic mode */
1268 r = ioctl(fd, HPET_EPI, 0);
1269 if (info.hi_flags && (r < 0))
1270 goto fail;
1272 /* Enable interrupt */
1273 r = ioctl(fd, HPET_IE_ON, 0);
1274 if (r < 0)
1275 goto fail;
1277 enable_sigio_timer(fd);
1278 t->priv = (void *)(long)fd;
1280 return 0;
1281 fail:
1282 close(fd);
1283 return -1;
1286 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1288 int fd = (long)t->priv;
1290 close(fd);
1293 static int rtc_start_timer(struct qemu_alarm_timer *t)
1295 int rtc_fd;
1297 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1298 if (rtc_fd < 0)
1299 return -1;
1300 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1301 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1302 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1303 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1304 goto fail;
1306 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1307 fail:
1308 close(rtc_fd);
1309 return -1;
1312 enable_sigio_timer(rtc_fd);
1314 t->priv = (void *)(long)rtc_fd;
1316 return 0;
1319 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1321 int rtc_fd = (long)t->priv;
1323 close(rtc_fd);
1326 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1328 struct sigevent ev;
1329 timer_t host_timer;
1330 struct sigaction act;
1332 sigfillset(&act.sa_mask);
1333 act.sa_flags = 0;
1334 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1335 act.sa_flags |= SA_ONSTACK;
1336 #endif
1337 act.sa_handler = host_alarm_handler;
1339 sigaction(SIGALRM, &act, NULL);
1341 ev.sigev_value.sival_int = 0;
1342 ev.sigev_notify = SIGEV_SIGNAL;
1343 ev.sigev_signo = SIGALRM;
1345 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1346 perror("timer_create");
1348 /* disable dynticks */
1349 fprintf(stderr, "Dynamic Ticks disabled\n");
1351 return -1;
1354 t->priv = (void *)host_timer;
1356 return 0;
1359 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1361 timer_t host_timer = (timer_t)t->priv;
1363 timer_delete(host_timer);
1366 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1368 timer_t host_timer = (timer_t)t->priv;
1369 struct itimerspec timeout;
1370 int64_t nearest_delta_us = INT64_MAX;
1371 int64_t current_us;
1373 if (!active_timers[QEMU_TIMER_REALTIME] &&
1374 !active_timers[QEMU_TIMER_VIRTUAL])
1375 return;
1377 nearest_delta_us = qemu_next_deadline();
1379 /* check whether a timer is already running */
1380 if (timer_gettime(host_timer, &timeout)) {
1381 perror("gettime");
1382 fprintf(stderr, "Internal timer error: aborting\n");
1383 exit(1);
1385 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1386 if (current_us && current_us <= nearest_delta_us)
1387 return;
1389 timeout.it_interval.tv_sec = 0;
1390 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1391 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1392 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1393 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1394 perror("settime");
1395 fprintf(stderr, "Internal timer error: aborting\n");
1396 exit(1);
1400 #endif /* defined(__linux__) */
1402 static int unix_start_timer(struct qemu_alarm_timer *t)
1404 struct sigaction act;
1405 struct itimerval itv;
1406 int err;
1408 /* timer signal */
1409 sigfillset(&act.sa_mask);
1410 act.sa_flags = 0;
1411 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1412 act.sa_flags |= SA_ONSTACK;
1413 #endif
1414 act.sa_handler = host_alarm_handler;
1416 sigaction(SIGALRM, &act, NULL);
1418 itv.it_interval.tv_sec = 0;
1419 /* for i386 kernel 2.6 to get 1 ms */
1420 itv.it_interval.tv_usec = 999;
1421 itv.it_value.tv_sec = 0;
1422 itv.it_value.tv_usec = 10 * 1000;
1424 err = setitimer(ITIMER_REAL, &itv, NULL);
1425 if (err)
1426 return -1;
1428 return 0;
1431 static void unix_stop_timer(struct qemu_alarm_timer *t)
1433 struct itimerval itv;
1435 memset(&itv, 0, sizeof(itv));
1436 setitimer(ITIMER_REAL, &itv, NULL);
1439 #endif /* !defined(_WIN32) */
1441 #ifdef _WIN32
1443 static int win32_start_timer(struct qemu_alarm_timer *t)
1445 TIMECAPS tc;
1446 struct qemu_alarm_win32 *data = t->priv;
1447 UINT flags;
1449 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1450 if (!data->host_alarm) {
1451 perror("Failed CreateEvent");
1452 return -1;
1455 memset(&tc, 0, sizeof(tc));
1456 timeGetDevCaps(&tc, sizeof(tc));
1458 if (data->period < tc.wPeriodMin)
1459 data->period = tc.wPeriodMin;
1461 timeBeginPeriod(data->period);
1463 flags = TIME_CALLBACK_FUNCTION;
1464 if (alarm_has_dynticks(t))
1465 flags |= TIME_ONESHOT;
1466 else
1467 flags |= TIME_PERIODIC;
1469 data->timerId = timeSetEvent(1, // interval (ms)
1470 data->period, // resolution
1471 host_alarm_handler, // function
1472 (DWORD)t, // parameter
1473 flags);
1475 if (!data->timerId) {
1476 perror("Failed to initialize win32 alarm timer");
1478 timeEndPeriod(data->period);
1479 CloseHandle(data->host_alarm);
1480 return -1;
1483 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1485 return 0;
1488 static void win32_stop_timer(struct qemu_alarm_timer *t)
1490 struct qemu_alarm_win32 *data = t->priv;
1492 timeKillEvent(data->timerId);
1493 timeEndPeriod(data->period);
1495 CloseHandle(data->host_alarm);
1498 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1500 struct qemu_alarm_win32 *data = t->priv;
1501 uint64_t nearest_delta_us;
1503 if (!active_timers[QEMU_TIMER_REALTIME] &&
1504 !active_timers[QEMU_TIMER_VIRTUAL])
1505 return;
1507 nearest_delta_us = qemu_next_deadline();
1508 nearest_delta_us /= 1000;
1510 timeKillEvent(data->timerId);
1512 data->timerId = timeSetEvent(1,
1513 data->period,
1514 host_alarm_handler,
1515 (DWORD)t,
1516 TIME_ONESHOT | TIME_PERIODIC);
1518 if (!data->timerId) {
1519 perror("Failed to re-arm win32 alarm timer");
1521 timeEndPeriod(data->period);
1522 CloseHandle(data->host_alarm);
1523 exit(1);
1527 #endif /* _WIN32 */
1529 static void init_timer_alarm(void)
1531 struct qemu_alarm_timer *t;
1532 int i, err = -1;
1534 for (i = 0; alarm_timers[i].name; i++) {
1535 t = &alarm_timers[i];
1537 err = t->start(t);
1538 if (!err)
1539 break;
1542 if (err) {
1543 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1544 fprintf(stderr, "Terminating\n");
1545 exit(1);
1548 alarm_timer = t;
1551 void quit_timers(void)
1553 alarm_timer->stop(alarm_timer);
1554 alarm_timer = NULL;
1557 /***********************************************************/
1558 /* character device */
1560 static void qemu_chr_event(CharDriverState *s, int event)
1562 if (!s->chr_event)
1563 return;
1564 s->chr_event(s->handler_opaque, event);
1567 static void qemu_chr_reset_bh(void *opaque)
1569 CharDriverState *s = opaque;
1570 qemu_chr_event(s, CHR_EVENT_RESET);
1571 qemu_bh_delete(s->bh);
1572 s->bh = NULL;
1575 void qemu_chr_reset(CharDriverState *s)
1577 if (s->bh == NULL) {
1578 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1579 qemu_bh_schedule(s->bh);
1583 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1585 return s->chr_write(s, buf, len);
1588 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1590 if (!s->chr_ioctl)
1591 return -ENOTSUP;
1592 return s->chr_ioctl(s, cmd, arg);
1595 int qemu_chr_can_read(CharDriverState *s)
1597 if (!s->chr_can_read)
1598 return 0;
1599 return s->chr_can_read(s->handler_opaque);
1602 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1604 s->chr_read(s->handler_opaque, buf, len);
1608 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1610 char buf[4096];
1611 va_list ap;
1612 va_start(ap, fmt);
1613 vsnprintf(buf, sizeof(buf), fmt, ap);
1614 qemu_chr_write(s, buf, strlen(buf));
1615 va_end(ap);
1618 void qemu_chr_send_event(CharDriverState *s, int event)
1620 if (s->chr_send_event)
1621 s->chr_send_event(s, event);
1624 void qemu_chr_add_handlers(CharDriverState *s,
1625 IOCanRWHandler *fd_can_read,
1626 IOReadHandler *fd_read,
1627 IOEventHandler *fd_event,
1628 void *opaque)
1630 s->chr_can_read = fd_can_read;
1631 s->chr_read = fd_read;
1632 s->chr_event = fd_event;
1633 s->handler_opaque = opaque;
1634 if (s->chr_update_read_handler)
1635 s->chr_update_read_handler(s);
1638 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1640 return len;
1643 static CharDriverState *qemu_chr_open_null(void)
1645 CharDriverState *chr;
1647 chr = qemu_mallocz(sizeof(CharDriverState));
1648 if (!chr)
1649 return NULL;
1650 chr->chr_write = null_chr_write;
1651 return chr;
1654 /* MUX driver for serial I/O splitting */
1655 static int term_timestamps;
1656 static int64_t term_timestamps_start;
1657 #define MAX_MUX 4
1658 typedef struct {
1659 IOCanRWHandler *chr_can_read[MAX_MUX];
1660 IOReadHandler *chr_read[MAX_MUX];
1661 IOEventHandler *chr_event[MAX_MUX];
1662 void *ext_opaque[MAX_MUX];
1663 CharDriverState *drv;
1664 int mux_cnt;
1665 int term_got_escape;
1666 int max_size;
1667 } MuxDriver;
1670 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1672 MuxDriver *d = chr->opaque;
1673 int ret;
1674 if (!term_timestamps) {
1675 ret = d->drv->chr_write(d->drv, buf, len);
1676 } else {
1677 int i;
1679 ret = 0;
1680 for(i = 0; i < len; i++) {
1681 ret += d->drv->chr_write(d->drv, buf+i, 1);
1682 if (buf[i] == '\n') {
1683 char buf1[64];
1684 int64_t ti;
1685 int secs;
1687 ti = get_clock();
1688 if (term_timestamps_start == -1)
1689 term_timestamps_start = ti;
1690 ti -= term_timestamps_start;
1691 secs = ti / 1000000000;
1692 snprintf(buf1, sizeof(buf1),
1693 "[%02d:%02d:%02d.%03d] ",
1694 secs / 3600,
1695 (secs / 60) % 60,
1696 secs % 60,
1697 (int)((ti / 1000000) % 1000));
1698 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1702 return ret;
1705 static char *mux_help[] = {
1706 "% h print this help\n\r",
1707 "% x exit emulator\n\r",
1708 "% s save disk data back to file (if -snapshot)\n\r",
1709 "% t toggle console timestamps\n\r"
1710 "% b send break (magic sysrq)\n\r",
1711 "% c switch between console and monitor\n\r",
1712 "% % sends %\n\r",
1713 NULL
1716 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1717 static void mux_print_help(CharDriverState *chr)
1719 int i, j;
1720 char ebuf[15] = "Escape-Char";
1721 char cbuf[50] = "\n\r";
1723 if (term_escape_char > 0 && term_escape_char < 26) {
1724 sprintf(cbuf,"\n\r");
1725 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1726 } else {
1727 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1729 chr->chr_write(chr, cbuf, strlen(cbuf));
1730 for (i = 0; mux_help[i] != NULL; i++) {
1731 for (j=0; mux_help[i][j] != '\0'; j++) {
1732 if (mux_help[i][j] == '%')
1733 chr->chr_write(chr, ebuf, strlen(ebuf));
1734 else
1735 chr->chr_write(chr, &mux_help[i][j], 1);
1740 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1742 if (d->term_got_escape) {
1743 d->term_got_escape = 0;
1744 if (ch == term_escape_char)
1745 goto send_char;
1746 switch(ch) {
1747 case '?':
1748 case 'h':
1749 mux_print_help(chr);
1750 break;
1751 case 'x':
1753 char *term = "QEMU: Terminated\n\r";
1754 chr->chr_write(chr,term,strlen(term));
1755 exit(0);
1756 break;
1758 case 's':
1760 int i;
1761 for (i = 0; i < MAX_DISKS; i++) {
1762 if (bs_table[i])
1763 bdrv_commit(bs_table[i]);
1765 if (mtd_bdrv)
1766 bdrv_commit(mtd_bdrv);
1768 break;
1769 case 'b':
1770 qemu_chr_event(chr, CHR_EVENT_BREAK);
1771 break;
1772 case 'c':
1773 /* Switch to the next registered device */
1774 chr->focus++;
1775 if (chr->focus >= d->mux_cnt)
1776 chr->focus = 0;
1777 break;
1778 case 't':
1779 term_timestamps = !term_timestamps;
1780 term_timestamps_start = -1;
1781 break;
1783 } else if (ch == term_escape_char) {
1784 d->term_got_escape = 1;
1785 } else {
1786 send_char:
1787 return 1;
1789 return 0;
1792 static int mux_chr_can_read(void *opaque)
1794 CharDriverState *chr = opaque;
1795 MuxDriver *d = chr->opaque;
1796 if (d->chr_can_read[chr->focus])
1797 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1798 return 0;
1801 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1803 CharDriverState *chr = opaque;
1804 MuxDriver *d = chr->opaque;
1805 int i;
1806 for(i = 0; i < size; i++)
1807 if (mux_proc_byte(chr, d, buf[i]))
1808 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1811 static void mux_chr_event(void *opaque, int event)
1813 CharDriverState *chr = opaque;
1814 MuxDriver *d = chr->opaque;
1815 int i;
1817 /* Send the event to all registered listeners */
1818 for (i = 0; i < d->mux_cnt; i++)
1819 if (d->chr_event[i])
1820 d->chr_event[i](d->ext_opaque[i], event);
1823 static void mux_chr_update_read_handler(CharDriverState *chr)
1825 MuxDriver *d = chr->opaque;
1827 if (d->mux_cnt >= MAX_MUX) {
1828 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1829 return;
1831 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1832 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1833 d->chr_read[d->mux_cnt] = chr->chr_read;
1834 d->chr_event[d->mux_cnt] = chr->chr_event;
1835 /* Fix up the real driver with mux routines */
1836 if (d->mux_cnt == 0) {
1837 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1838 mux_chr_event, chr);
1840 chr->focus = d->mux_cnt;
1841 d->mux_cnt++;
1844 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1846 CharDriverState *chr;
1847 MuxDriver *d;
1849 chr = qemu_mallocz(sizeof(CharDriverState));
1850 if (!chr)
1851 return NULL;
1852 d = qemu_mallocz(sizeof(MuxDriver));
1853 if (!d) {
1854 free(chr);
1855 return NULL;
1858 chr->opaque = d;
1859 d->drv = drv;
1860 chr->focus = -1;
1861 chr->chr_write = mux_chr_write;
1862 chr->chr_update_read_handler = mux_chr_update_read_handler;
1863 return chr;
1867 #ifdef _WIN32
1869 static void socket_cleanup(void)
1871 WSACleanup();
1874 static int socket_init(void)
1876 WSADATA Data;
1877 int ret, err;
1879 ret = WSAStartup(MAKEWORD(2,2), &Data);
1880 if (ret != 0) {
1881 err = WSAGetLastError();
1882 fprintf(stderr, "WSAStartup: %d\n", err);
1883 return -1;
1885 atexit(socket_cleanup);
1886 return 0;
1889 static int send_all(int fd, const uint8_t *buf, int len1)
1891 int ret, len;
1893 len = len1;
1894 while (len > 0) {
1895 ret = send(fd, buf, len, 0);
1896 if (ret < 0) {
1897 int errno;
1898 errno = WSAGetLastError();
1899 if (errno != WSAEWOULDBLOCK) {
1900 return -1;
1902 } else if (ret == 0) {
1903 break;
1904 } else {
1905 buf += ret;
1906 len -= ret;
1909 return len1 - len;
1912 void socket_set_nonblock(int fd)
1914 unsigned long opt = 1;
1915 ioctlsocket(fd, FIONBIO, &opt);
1918 #else
1920 static int unix_write(int fd, const uint8_t *buf, int len1)
1922 int ret, len;
1924 len = len1;
1925 while (len > 0) {
1926 ret = write(fd, buf, len);
1927 if (ret < 0) {
1928 if (errno != EINTR && errno != EAGAIN)
1929 return -1;
1930 } else if (ret == 0) {
1931 break;
1932 } else {
1933 buf += ret;
1934 len -= ret;
1937 return len1 - len;
1940 static inline int send_all(int fd, const uint8_t *buf, int len1)
1942 return unix_write(fd, buf, len1);
1945 void socket_set_nonblock(int fd)
1947 fcntl(fd, F_SETFL, O_NONBLOCK);
1949 #endif /* !_WIN32 */
1951 #ifndef _WIN32
1953 typedef struct {
1954 int fd_in, fd_out;
1955 int max_size;
1956 } FDCharDriver;
1958 #define STDIO_MAX_CLIENTS 1
1959 static int stdio_nb_clients = 0;
1961 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1963 FDCharDriver *s = chr->opaque;
1964 return unix_write(s->fd_out, buf, len);
1967 static int fd_chr_read_poll(void *opaque)
1969 CharDriverState *chr = opaque;
1970 FDCharDriver *s = chr->opaque;
1972 s->max_size = qemu_chr_can_read(chr);
1973 return s->max_size;
1976 static void fd_chr_read(void *opaque)
1978 CharDriverState *chr = opaque;
1979 FDCharDriver *s = chr->opaque;
1980 int size, len;
1981 uint8_t buf[1024];
1983 len = sizeof(buf);
1984 if (len > s->max_size)
1985 len = s->max_size;
1986 if (len == 0)
1987 return;
1988 size = read(s->fd_in, buf, len);
1989 if (size == 0) {
1990 /* FD has been closed. Remove it from the active list. */
1991 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1992 return;
1994 if (size > 0) {
1995 qemu_chr_read(chr, buf, size);
1999 static void fd_chr_update_read_handler(CharDriverState *chr)
2001 FDCharDriver *s = chr->opaque;
2003 if (s->fd_in >= 0) {
2004 if (nographic && s->fd_in == 0) {
2005 } else {
2006 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2007 fd_chr_read, NULL, chr);
2012 /* open a character device to a unix fd */
2013 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2015 CharDriverState *chr;
2016 FDCharDriver *s;
2018 chr = qemu_mallocz(sizeof(CharDriverState));
2019 if (!chr)
2020 return NULL;
2021 s = qemu_mallocz(sizeof(FDCharDriver));
2022 if (!s) {
2023 free(chr);
2024 return NULL;
2026 s->fd_in = fd_in;
2027 s->fd_out = fd_out;
2028 chr->opaque = s;
2029 chr->chr_write = fd_chr_write;
2030 chr->chr_update_read_handler = fd_chr_update_read_handler;
2032 qemu_chr_reset(chr);
2034 return chr;
2037 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2039 int fd_out;
2041 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2042 if (fd_out < 0)
2043 return NULL;
2044 return qemu_chr_open_fd(-1, fd_out);
2047 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2049 int fd_in, fd_out;
2050 char filename_in[256], filename_out[256];
2052 snprintf(filename_in, 256, "%s.in", filename);
2053 snprintf(filename_out, 256, "%s.out", filename);
2054 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2055 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2056 if (fd_in < 0 || fd_out < 0) {
2057 if (fd_in >= 0)
2058 close(fd_in);
2059 if (fd_out >= 0)
2060 close(fd_out);
2061 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2062 if (fd_in < 0)
2063 return NULL;
2065 return qemu_chr_open_fd(fd_in, fd_out);
2069 /* for STDIO, we handle the case where several clients use it
2070 (nographic mode) */
2072 #define TERM_FIFO_MAX_SIZE 1
2074 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2075 static int term_fifo_size;
2077 static int stdio_read_poll(void *opaque)
2079 CharDriverState *chr = opaque;
2081 /* try to flush the queue if needed */
2082 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2083 qemu_chr_read(chr, term_fifo, 1);
2084 term_fifo_size = 0;
2086 /* see if we can absorb more chars */
2087 if (term_fifo_size == 0)
2088 return 1;
2089 else
2090 return 0;
2093 static void stdio_read(void *opaque)
2095 int size;
2096 uint8_t buf[1];
2097 CharDriverState *chr = opaque;
2099 size = read(0, buf, 1);
2100 if (size == 0) {
2101 /* stdin has been closed. Remove it from the active list. */
2102 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2103 return;
2105 if (size > 0) {
2106 if (qemu_chr_can_read(chr) > 0) {
2107 qemu_chr_read(chr, buf, 1);
2108 } else if (term_fifo_size == 0) {
2109 term_fifo[term_fifo_size++] = buf[0];
2114 /* init terminal so that we can grab keys */
2115 static struct termios oldtty;
2116 static int old_fd0_flags;
2118 static void term_exit(void)
2120 tcsetattr (0, TCSANOW, &oldtty);
2121 fcntl(0, F_SETFL, old_fd0_flags);
2124 static void term_init(void)
2126 struct termios tty;
2128 tcgetattr (0, &tty);
2129 oldtty = tty;
2130 old_fd0_flags = fcntl(0, F_GETFL);
2132 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2133 |INLCR|IGNCR|ICRNL|IXON);
2134 tty.c_oflag |= OPOST;
2135 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2136 /* if graphical mode, we allow Ctrl-C handling */
2137 if (nographic)
2138 tty.c_lflag &= ~ISIG;
2139 tty.c_cflag &= ~(CSIZE|PARENB);
2140 tty.c_cflag |= CS8;
2141 tty.c_cc[VMIN] = 1;
2142 tty.c_cc[VTIME] = 0;
2144 tcsetattr (0, TCSANOW, &tty);
2146 atexit(term_exit);
2148 fcntl(0, F_SETFL, O_NONBLOCK);
2151 static CharDriverState *qemu_chr_open_stdio(void)
2153 CharDriverState *chr;
2155 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2156 return NULL;
2157 chr = qemu_chr_open_fd(0, 1);
2158 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2159 stdio_nb_clients++;
2160 term_init();
2162 return chr;
2165 #if defined(__linux__) || defined(__sun__)
2166 static CharDriverState *qemu_chr_open_pty(void)
2168 struct termios tty;
2169 char slave_name[1024];
2170 int master_fd, slave_fd;
2172 #if defined(__linux__)
2173 /* Not satisfying */
2174 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2175 return NULL;
2177 #endif
2179 /* Disabling local echo and line-buffered output */
2180 tcgetattr (master_fd, &tty);
2181 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2182 tty.c_cc[VMIN] = 1;
2183 tty.c_cc[VTIME] = 0;
2184 tcsetattr (master_fd, TCSAFLUSH, &tty);
2186 fprintf(stderr, "char device redirected to %s\n", slave_name);
2187 return qemu_chr_open_fd(master_fd, master_fd);
2190 static void tty_serial_init(int fd, int speed,
2191 int parity, int data_bits, int stop_bits)
2193 struct termios tty;
2194 speed_t spd;
2196 #if 0
2197 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2198 speed, parity, data_bits, stop_bits);
2199 #endif
2200 tcgetattr (fd, &tty);
2202 switch(speed) {
2203 case 50:
2204 spd = B50;
2205 break;
2206 case 75:
2207 spd = B75;
2208 break;
2209 case 300:
2210 spd = B300;
2211 break;
2212 case 600:
2213 spd = B600;
2214 break;
2215 case 1200:
2216 spd = B1200;
2217 break;
2218 case 2400:
2219 spd = B2400;
2220 break;
2221 case 4800:
2222 spd = B4800;
2223 break;
2224 case 9600:
2225 spd = B9600;
2226 break;
2227 case 19200:
2228 spd = B19200;
2229 break;
2230 case 38400:
2231 spd = B38400;
2232 break;
2233 case 57600:
2234 spd = B57600;
2235 break;
2236 default:
2237 case 115200:
2238 spd = B115200;
2239 break;
2242 cfsetispeed(&tty, spd);
2243 cfsetospeed(&tty, spd);
2245 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2246 |INLCR|IGNCR|ICRNL|IXON);
2247 tty.c_oflag |= OPOST;
2248 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2249 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2250 switch(data_bits) {
2251 default:
2252 case 8:
2253 tty.c_cflag |= CS8;
2254 break;
2255 case 7:
2256 tty.c_cflag |= CS7;
2257 break;
2258 case 6:
2259 tty.c_cflag |= CS6;
2260 break;
2261 case 5:
2262 tty.c_cflag |= CS5;
2263 break;
2265 switch(parity) {
2266 default:
2267 case 'N':
2268 break;
2269 case 'E':
2270 tty.c_cflag |= PARENB;
2271 break;
2272 case 'O':
2273 tty.c_cflag |= PARENB | PARODD;
2274 break;
2276 if (stop_bits == 2)
2277 tty.c_cflag |= CSTOPB;
2279 tcsetattr (fd, TCSANOW, &tty);
2282 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2284 FDCharDriver *s = chr->opaque;
2286 switch(cmd) {
2287 case CHR_IOCTL_SERIAL_SET_PARAMS:
2289 QEMUSerialSetParams *ssp = arg;
2290 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2291 ssp->data_bits, ssp->stop_bits);
2293 break;
2294 case CHR_IOCTL_SERIAL_SET_BREAK:
2296 int enable = *(int *)arg;
2297 if (enable)
2298 tcsendbreak(s->fd_in, 1);
2300 break;
2301 default:
2302 return -ENOTSUP;
2304 return 0;
2307 static CharDriverState *qemu_chr_open_tty(const char *filename)
2309 CharDriverState *chr;
2310 int fd;
2312 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2313 fcntl(fd, F_SETFL, O_NONBLOCK);
2314 tty_serial_init(fd, 115200, 'N', 8, 1);
2315 chr = qemu_chr_open_fd(fd, fd);
2316 if (!chr) {
2317 close(fd);
2318 return NULL;
2320 chr->chr_ioctl = tty_serial_ioctl;
2321 qemu_chr_reset(chr);
2322 return chr;
2324 #else /* ! __linux__ && ! __sun__ */
2325 static CharDriverState *qemu_chr_open_pty(void)
2327 return NULL;
2329 #endif /* __linux__ || __sun__ */
2331 #if defined(__linux__)
2332 typedef struct {
2333 int fd;
2334 int mode;
2335 } ParallelCharDriver;
2337 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2339 if (s->mode != mode) {
2340 int m = mode;
2341 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2342 return 0;
2343 s->mode = mode;
2345 return 1;
2348 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2350 ParallelCharDriver *drv = chr->opaque;
2351 int fd = drv->fd;
2352 uint8_t b;
2354 switch(cmd) {
2355 case CHR_IOCTL_PP_READ_DATA:
2356 if (ioctl(fd, PPRDATA, &b) < 0)
2357 return -ENOTSUP;
2358 *(uint8_t *)arg = b;
2359 break;
2360 case CHR_IOCTL_PP_WRITE_DATA:
2361 b = *(uint8_t *)arg;
2362 if (ioctl(fd, PPWDATA, &b) < 0)
2363 return -ENOTSUP;
2364 break;
2365 case CHR_IOCTL_PP_READ_CONTROL:
2366 if (ioctl(fd, PPRCONTROL, &b) < 0)
2367 return -ENOTSUP;
2368 /* Linux gives only the lowest bits, and no way to know data
2369 direction! For better compatibility set the fixed upper
2370 bits. */
2371 *(uint8_t *)arg = b | 0xc0;
2372 break;
2373 case CHR_IOCTL_PP_WRITE_CONTROL:
2374 b = *(uint8_t *)arg;
2375 if (ioctl(fd, PPWCONTROL, &b) < 0)
2376 return -ENOTSUP;
2377 break;
2378 case CHR_IOCTL_PP_READ_STATUS:
2379 if (ioctl(fd, PPRSTATUS, &b) < 0)
2380 return -ENOTSUP;
2381 *(uint8_t *)arg = b;
2382 break;
2383 case CHR_IOCTL_PP_EPP_READ_ADDR:
2384 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2385 struct ParallelIOArg *parg = arg;
2386 int n = read(fd, parg->buffer, parg->count);
2387 if (n != parg->count) {
2388 return -EIO;
2391 break;
2392 case CHR_IOCTL_PP_EPP_READ:
2393 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2394 struct ParallelIOArg *parg = arg;
2395 int n = read(fd, parg->buffer, parg->count);
2396 if (n != parg->count) {
2397 return -EIO;
2400 break;
2401 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2402 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2403 struct ParallelIOArg *parg = arg;
2404 int n = write(fd, parg->buffer, parg->count);
2405 if (n != parg->count) {
2406 return -EIO;
2409 break;
2410 case CHR_IOCTL_PP_EPP_WRITE:
2411 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2412 struct ParallelIOArg *parg = arg;
2413 int n = write(fd, parg->buffer, parg->count);
2414 if (n != parg->count) {
2415 return -EIO;
2418 break;
2419 default:
2420 return -ENOTSUP;
2422 return 0;
2425 static void pp_close(CharDriverState *chr)
2427 ParallelCharDriver *drv = chr->opaque;
2428 int fd = drv->fd;
2430 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2431 ioctl(fd, PPRELEASE);
2432 close(fd);
2433 qemu_free(drv);
2436 static CharDriverState *qemu_chr_open_pp(const char *filename)
2438 CharDriverState *chr;
2439 ParallelCharDriver *drv;
2440 int fd;
2442 TFR(fd = open(filename, O_RDWR));
2443 if (fd < 0)
2444 return NULL;
2446 if (ioctl(fd, PPCLAIM) < 0) {
2447 close(fd);
2448 return NULL;
2451 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2452 if (!drv) {
2453 close(fd);
2454 return NULL;
2456 drv->fd = fd;
2457 drv->mode = IEEE1284_MODE_COMPAT;
2459 chr = qemu_mallocz(sizeof(CharDriverState));
2460 if (!chr) {
2461 qemu_free(drv);
2462 close(fd);
2463 return NULL;
2465 chr->chr_write = null_chr_write;
2466 chr->chr_ioctl = pp_ioctl;
2467 chr->chr_close = pp_close;
2468 chr->opaque = drv;
2470 qemu_chr_reset(chr);
2472 return chr;
2474 #endif /* __linux__ */
2476 #else /* _WIN32 */
2478 typedef struct {
2479 int max_size;
2480 HANDLE hcom, hrecv, hsend;
2481 OVERLAPPED orecv, osend;
2482 BOOL fpipe;
2483 DWORD len;
2484 } WinCharState;
2486 #define NSENDBUF 2048
2487 #define NRECVBUF 2048
2488 #define MAXCONNECT 1
2489 #define NTIMEOUT 5000
2491 static int win_chr_poll(void *opaque);
2492 static int win_chr_pipe_poll(void *opaque);
2494 static void win_chr_close(CharDriverState *chr)
2496 WinCharState *s = chr->opaque;
2498 if (s->hsend) {
2499 CloseHandle(s->hsend);
2500 s->hsend = NULL;
2502 if (s->hrecv) {
2503 CloseHandle(s->hrecv);
2504 s->hrecv = NULL;
2506 if (s->hcom) {
2507 CloseHandle(s->hcom);
2508 s->hcom = NULL;
2510 if (s->fpipe)
2511 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2512 else
2513 qemu_del_polling_cb(win_chr_poll, chr);
2516 static int win_chr_init(CharDriverState *chr, const char *filename)
2518 WinCharState *s = chr->opaque;
2519 COMMCONFIG comcfg;
2520 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2521 COMSTAT comstat;
2522 DWORD size;
2523 DWORD err;
2525 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2526 if (!s->hsend) {
2527 fprintf(stderr, "Failed CreateEvent\n");
2528 goto fail;
2530 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2531 if (!s->hrecv) {
2532 fprintf(stderr, "Failed CreateEvent\n");
2533 goto fail;
2536 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2537 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2538 if (s->hcom == INVALID_HANDLE_VALUE) {
2539 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2540 s->hcom = NULL;
2541 goto fail;
2544 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2545 fprintf(stderr, "Failed SetupComm\n");
2546 goto fail;
2549 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2550 size = sizeof(COMMCONFIG);
2551 GetDefaultCommConfig(filename, &comcfg, &size);
2552 comcfg.dcb.DCBlength = sizeof(DCB);
2553 CommConfigDialog(filename, NULL, &comcfg);
2555 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2556 fprintf(stderr, "Failed SetCommState\n");
2557 goto fail;
2560 if (!SetCommMask(s->hcom, EV_ERR)) {
2561 fprintf(stderr, "Failed SetCommMask\n");
2562 goto fail;
2565 cto.ReadIntervalTimeout = MAXDWORD;
2566 if (!SetCommTimeouts(s->hcom, &cto)) {
2567 fprintf(stderr, "Failed SetCommTimeouts\n");
2568 goto fail;
2571 if (!ClearCommError(s->hcom, &err, &comstat)) {
2572 fprintf(stderr, "Failed ClearCommError\n");
2573 goto fail;
2575 qemu_add_polling_cb(win_chr_poll, chr);
2576 return 0;
2578 fail:
2579 win_chr_close(chr);
2580 return -1;
2583 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2585 WinCharState *s = chr->opaque;
2586 DWORD len, ret, size, err;
2588 len = len1;
2589 ZeroMemory(&s->osend, sizeof(s->osend));
2590 s->osend.hEvent = s->hsend;
2591 while (len > 0) {
2592 if (s->hsend)
2593 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2594 else
2595 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2596 if (!ret) {
2597 err = GetLastError();
2598 if (err == ERROR_IO_PENDING) {
2599 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2600 if (ret) {
2601 buf += size;
2602 len -= size;
2603 } else {
2604 break;
2606 } else {
2607 break;
2609 } else {
2610 buf += size;
2611 len -= size;
2614 return len1 - len;
2617 static int win_chr_read_poll(CharDriverState *chr)
2619 WinCharState *s = chr->opaque;
2621 s->max_size = qemu_chr_can_read(chr);
2622 return s->max_size;
2625 static void win_chr_readfile(CharDriverState *chr)
2627 WinCharState *s = chr->opaque;
2628 int ret, err;
2629 uint8_t buf[1024];
2630 DWORD size;
2632 ZeroMemory(&s->orecv, sizeof(s->orecv));
2633 s->orecv.hEvent = s->hrecv;
2634 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2635 if (!ret) {
2636 err = GetLastError();
2637 if (err == ERROR_IO_PENDING) {
2638 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2642 if (size > 0) {
2643 qemu_chr_read(chr, buf, size);
2647 static void win_chr_read(CharDriverState *chr)
2649 WinCharState *s = chr->opaque;
2651 if (s->len > s->max_size)
2652 s->len = s->max_size;
2653 if (s->len == 0)
2654 return;
2656 win_chr_readfile(chr);
2659 static int win_chr_poll(void *opaque)
2661 CharDriverState *chr = opaque;
2662 WinCharState *s = chr->opaque;
2663 COMSTAT status;
2664 DWORD comerr;
2666 ClearCommError(s->hcom, &comerr, &status);
2667 if (status.cbInQue > 0) {
2668 s->len = status.cbInQue;
2669 win_chr_read_poll(chr);
2670 win_chr_read(chr);
2671 return 1;
2673 return 0;
2676 static CharDriverState *qemu_chr_open_win(const char *filename)
2678 CharDriverState *chr;
2679 WinCharState *s;
2681 chr = qemu_mallocz(sizeof(CharDriverState));
2682 if (!chr)
2683 return NULL;
2684 s = qemu_mallocz(sizeof(WinCharState));
2685 if (!s) {
2686 free(chr);
2687 return NULL;
2689 chr->opaque = s;
2690 chr->chr_write = win_chr_write;
2691 chr->chr_close = win_chr_close;
2693 if (win_chr_init(chr, filename) < 0) {
2694 free(s);
2695 free(chr);
2696 return NULL;
2698 qemu_chr_reset(chr);
2699 return chr;
2702 static int win_chr_pipe_poll(void *opaque)
2704 CharDriverState *chr = opaque;
2705 WinCharState *s = chr->opaque;
2706 DWORD size;
2708 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2709 if (size > 0) {
2710 s->len = size;
2711 win_chr_read_poll(chr);
2712 win_chr_read(chr);
2713 return 1;
2715 return 0;
2718 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2720 WinCharState *s = chr->opaque;
2721 OVERLAPPED ov;
2722 int ret;
2723 DWORD size;
2724 char openname[256];
2726 s->fpipe = TRUE;
2728 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2729 if (!s->hsend) {
2730 fprintf(stderr, "Failed CreateEvent\n");
2731 goto fail;
2733 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2734 if (!s->hrecv) {
2735 fprintf(stderr, "Failed CreateEvent\n");
2736 goto fail;
2739 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2740 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2741 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2742 PIPE_WAIT,
2743 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2744 if (s->hcom == INVALID_HANDLE_VALUE) {
2745 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2746 s->hcom = NULL;
2747 goto fail;
2750 ZeroMemory(&ov, sizeof(ov));
2751 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2752 ret = ConnectNamedPipe(s->hcom, &ov);
2753 if (ret) {
2754 fprintf(stderr, "Failed ConnectNamedPipe\n");
2755 goto fail;
2758 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2759 if (!ret) {
2760 fprintf(stderr, "Failed GetOverlappedResult\n");
2761 if (ov.hEvent) {
2762 CloseHandle(ov.hEvent);
2763 ov.hEvent = NULL;
2765 goto fail;
2768 if (ov.hEvent) {
2769 CloseHandle(ov.hEvent);
2770 ov.hEvent = NULL;
2772 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2773 return 0;
2775 fail:
2776 win_chr_close(chr);
2777 return -1;
2781 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2783 CharDriverState *chr;
2784 WinCharState *s;
2786 chr = qemu_mallocz(sizeof(CharDriverState));
2787 if (!chr)
2788 return NULL;
2789 s = qemu_mallocz(sizeof(WinCharState));
2790 if (!s) {
2791 free(chr);
2792 return NULL;
2794 chr->opaque = s;
2795 chr->chr_write = win_chr_write;
2796 chr->chr_close = win_chr_close;
2798 if (win_chr_pipe_init(chr, filename) < 0) {
2799 free(s);
2800 free(chr);
2801 return NULL;
2803 qemu_chr_reset(chr);
2804 return chr;
2807 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2809 CharDriverState *chr;
2810 WinCharState *s;
2812 chr = qemu_mallocz(sizeof(CharDriverState));
2813 if (!chr)
2814 return NULL;
2815 s = qemu_mallocz(sizeof(WinCharState));
2816 if (!s) {
2817 free(chr);
2818 return NULL;
2820 s->hcom = fd_out;
2821 chr->opaque = s;
2822 chr->chr_write = win_chr_write;
2823 qemu_chr_reset(chr);
2824 return chr;
2827 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2829 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2832 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2834 HANDLE fd_out;
2836 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2837 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2838 if (fd_out == INVALID_HANDLE_VALUE)
2839 return NULL;
2841 return qemu_chr_open_win_file(fd_out);
2843 #endif /* !_WIN32 */
2845 /***********************************************************/
2846 /* UDP Net console */
2848 typedef struct {
2849 int fd;
2850 struct sockaddr_in daddr;
2851 char buf[1024];
2852 int bufcnt;
2853 int bufptr;
2854 int max_size;
2855 } NetCharDriver;
2857 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2859 NetCharDriver *s = chr->opaque;
2861 return sendto(s->fd, buf, len, 0,
2862 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2865 static int udp_chr_read_poll(void *opaque)
2867 CharDriverState *chr = opaque;
2868 NetCharDriver *s = chr->opaque;
2870 s->max_size = qemu_chr_can_read(chr);
2872 /* If there were any stray characters in the queue process them
2873 * first
2875 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2876 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2877 s->bufptr++;
2878 s->max_size = qemu_chr_can_read(chr);
2880 return s->max_size;
2883 static void udp_chr_read(void *opaque)
2885 CharDriverState *chr = opaque;
2886 NetCharDriver *s = chr->opaque;
2888 if (s->max_size == 0)
2889 return;
2890 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2891 s->bufptr = s->bufcnt;
2892 if (s->bufcnt <= 0)
2893 return;
2895 s->bufptr = 0;
2896 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2897 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2898 s->bufptr++;
2899 s->max_size = qemu_chr_can_read(chr);
2903 static void udp_chr_update_read_handler(CharDriverState *chr)
2905 NetCharDriver *s = chr->opaque;
2907 if (s->fd >= 0) {
2908 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2909 udp_chr_read, NULL, chr);
2913 #ifndef _WIN32
2914 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2915 #endif
2916 int parse_host_src_port(struct sockaddr_in *haddr,
2917 struct sockaddr_in *saddr,
2918 const char *str);
2920 static CharDriverState *qemu_chr_open_udp(const char *def)
2922 CharDriverState *chr = NULL;
2923 NetCharDriver *s = NULL;
2924 int fd = -1;
2925 struct sockaddr_in saddr;
2927 chr = qemu_mallocz(sizeof(CharDriverState));
2928 if (!chr)
2929 goto return_err;
2930 s = qemu_mallocz(sizeof(NetCharDriver));
2931 if (!s)
2932 goto return_err;
2934 fd = socket(PF_INET, SOCK_DGRAM, 0);
2935 if (fd < 0) {
2936 perror("socket(PF_INET, SOCK_DGRAM)");
2937 goto return_err;
2940 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2941 printf("Could not parse: %s\n", def);
2942 goto return_err;
2945 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2947 perror("bind");
2948 goto return_err;
2951 s->fd = fd;
2952 s->bufcnt = 0;
2953 s->bufptr = 0;
2954 chr->opaque = s;
2955 chr->chr_write = udp_chr_write;
2956 chr->chr_update_read_handler = udp_chr_update_read_handler;
2957 return chr;
2959 return_err:
2960 if (chr)
2961 free(chr);
2962 if (s)
2963 free(s);
2964 if (fd >= 0)
2965 closesocket(fd);
2966 return NULL;
2969 /***********************************************************/
2970 /* TCP Net console */
2972 typedef struct {
2973 int fd, listen_fd;
2974 int connected;
2975 int max_size;
2976 int do_telnetopt;
2977 int do_nodelay;
2978 int is_unix;
2979 } TCPCharDriver;
2981 static void tcp_chr_accept(void *opaque);
2983 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2985 TCPCharDriver *s = chr->opaque;
2986 if (s->connected) {
2987 return send_all(s->fd, buf, len);
2988 } else {
2989 /* XXX: indicate an error ? */
2990 return len;
2994 static int tcp_chr_read_poll(void *opaque)
2996 CharDriverState *chr = opaque;
2997 TCPCharDriver *s = chr->opaque;
2998 if (!s->connected)
2999 return 0;
3000 s->max_size = qemu_chr_can_read(chr);
3001 return s->max_size;
3004 #define IAC 255
3005 #define IAC_BREAK 243
3006 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3007 TCPCharDriver *s,
3008 char *buf, int *size)
3010 /* Handle any telnet client's basic IAC options to satisfy char by
3011 * char mode with no echo. All IAC options will be removed from
3012 * the buf and the do_telnetopt variable will be used to track the
3013 * state of the width of the IAC information.
3015 * IAC commands come in sets of 3 bytes with the exception of the
3016 * "IAC BREAK" command and the double IAC.
3019 int i;
3020 int j = 0;
3022 for (i = 0; i < *size; i++) {
3023 if (s->do_telnetopt > 1) {
3024 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3025 /* Double IAC means send an IAC */
3026 if (j != i)
3027 buf[j] = buf[i];
3028 j++;
3029 s->do_telnetopt = 1;
3030 } else {
3031 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3032 /* Handle IAC break commands by sending a serial break */
3033 qemu_chr_event(chr, CHR_EVENT_BREAK);
3034 s->do_telnetopt++;
3036 s->do_telnetopt++;
3038 if (s->do_telnetopt >= 4) {
3039 s->do_telnetopt = 1;
3041 } else {
3042 if ((unsigned char)buf[i] == IAC) {
3043 s->do_telnetopt = 2;
3044 } else {
3045 if (j != i)
3046 buf[j] = buf[i];
3047 j++;
3051 *size = j;
3054 static void tcp_chr_read(void *opaque)
3056 CharDriverState *chr = opaque;
3057 TCPCharDriver *s = chr->opaque;
3058 uint8_t buf[1024];
3059 int len, size;
3061 if (!s->connected || s->max_size <= 0)
3062 return;
3063 len = sizeof(buf);
3064 if (len > s->max_size)
3065 len = s->max_size;
3066 size = recv(s->fd, buf, len, 0);
3067 if (size == 0) {
3068 /* connection closed */
3069 s->connected = 0;
3070 if (s->listen_fd >= 0) {
3071 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3073 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3074 closesocket(s->fd);
3075 s->fd = -1;
3076 } else if (size > 0) {
3077 if (s->do_telnetopt)
3078 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3079 if (size > 0)
3080 qemu_chr_read(chr, buf, size);
3084 static void tcp_chr_connect(void *opaque)
3086 CharDriverState *chr = opaque;
3087 TCPCharDriver *s = chr->opaque;
3089 s->connected = 1;
3090 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3091 tcp_chr_read, NULL, chr);
3092 qemu_chr_reset(chr);
3095 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3096 static void tcp_chr_telnet_init(int fd)
3098 char buf[3];
3099 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3100 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3101 send(fd, (char *)buf, 3, 0);
3102 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3103 send(fd, (char *)buf, 3, 0);
3104 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3105 send(fd, (char *)buf, 3, 0);
3106 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3107 send(fd, (char *)buf, 3, 0);
3110 static void socket_set_nodelay(int fd)
3112 int val = 1;
3113 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3116 static void tcp_chr_accept(void *opaque)
3118 CharDriverState *chr = opaque;
3119 TCPCharDriver *s = chr->opaque;
3120 struct sockaddr_in saddr;
3121 #ifndef _WIN32
3122 struct sockaddr_un uaddr;
3123 #endif
3124 struct sockaddr *addr;
3125 socklen_t len;
3126 int fd;
3128 for(;;) {
3129 #ifndef _WIN32
3130 if (s->is_unix) {
3131 len = sizeof(uaddr);
3132 addr = (struct sockaddr *)&uaddr;
3133 } else
3134 #endif
3136 len = sizeof(saddr);
3137 addr = (struct sockaddr *)&saddr;
3139 fd = accept(s->listen_fd, addr, &len);
3140 if (fd < 0 && errno != EINTR) {
3141 return;
3142 } else if (fd >= 0) {
3143 if (s->do_telnetopt)
3144 tcp_chr_telnet_init(fd);
3145 break;
3148 socket_set_nonblock(fd);
3149 if (s->do_nodelay)
3150 socket_set_nodelay(fd);
3151 s->fd = fd;
3152 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3153 tcp_chr_connect(chr);
3156 static void tcp_chr_close(CharDriverState *chr)
3158 TCPCharDriver *s = chr->opaque;
3159 if (s->fd >= 0)
3160 closesocket(s->fd);
3161 if (s->listen_fd >= 0)
3162 closesocket(s->listen_fd);
3163 qemu_free(s);
3166 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3167 int is_telnet,
3168 int is_unix)
3170 CharDriverState *chr = NULL;
3171 TCPCharDriver *s = NULL;
3172 int fd = -1, ret, err, val;
3173 int is_listen = 0;
3174 int is_waitconnect = 1;
3175 int do_nodelay = 0;
3176 const char *ptr;
3177 struct sockaddr_in saddr;
3178 #ifndef _WIN32
3179 struct sockaddr_un uaddr;
3180 #endif
3181 struct sockaddr *addr;
3182 socklen_t addrlen;
3184 #ifndef _WIN32
3185 if (is_unix) {
3186 addr = (struct sockaddr *)&uaddr;
3187 addrlen = sizeof(uaddr);
3188 if (parse_unix_path(&uaddr, host_str) < 0)
3189 goto fail;
3190 } else
3191 #endif
3193 addr = (struct sockaddr *)&saddr;
3194 addrlen = sizeof(saddr);
3195 if (parse_host_port(&saddr, host_str) < 0)
3196 goto fail;
3199 ptr = host_str;
3200 while((ptr = strchr(ptr,','))) {
3201 ptr++;
3202 if (!strncmp(ptr,"server",6)) {
3203 is_listen = 1;
3204 } else if (!strncmp(ptr,"nowait",6)) {
3205 is_waitconnect = 0;
3206 } else if (!strncmp(ptr,"nodelay",6)) {
3207 do_nodelay = 1;
3208 } else {
3209 printf("Unknown option: %s\n", ptr);
3210 goto fail;
3213 if (!is_listen)
3214 is_waitconnect = 0;
3216 chr = qemu_mallocz(sizeof(CharDriverState));
3217 if (!chr)
3218 goto fail;
3219 s = qemu_mallocz(sizeof(TCPCharDriver));
3220 if (!s)
3221 goto fail;
3223 #ifndef _WIN32
3224 if (is_unix)
3225 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3226 else
3227 #endif
3228 fd = socket(PF_INET, SOCK_STREAM, 0);
3230 if (fd < 0)
3231 goto fail;
3233 if (!is_waitconnect)
3234 socket_set_nonblock(fd);
3236 s->connected = 0;
3237 s->fd = -1;
3238 s->listen_fd = -1;
3239 s->is_unix = is_unix;
3240 s->do_nodelay = do_nodelay && !is_unix;
3242 chr->opaque = s;
3243 chr->chr_write = tcp_chr_write;
3244 chr->chr_close = tcp_chr_close;
3246 if (is_listen) {
3247 /* allow fast reuse */
3248 #ifndef _WIN32
3249 if (is_unix) {
3250 char path[109];
3251 strncpy(path, uaddr.sun_path, 108);
3252 path[108] = 0;
3253 unlink(path);
3254 } else
3255 #endif
3257 val = 1;
3258 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3261 ret = bind(fd, addr, addrlen);
3262 if (ret < 0)
3263 goto fail;
3265 ret = listen(fd, 0);
3266 if (ret < 0)
3267 goto fail;
3269 s->listen_fd = fd;
3270 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3271 if (is_telnet)
3272 s->do_telnetopt = 1;
3273 } else {
3274 for(;;) {
3275 ret = connect(fd, addr, addrlen);
3276 if (ret < 0) {
3277 err = socket_error();
3278 if (err == EINTR || err == EWOULDBLOCK) {
3279 } else if (err == EINPROGRESS) {
3280 break;
3281 #ifdef _WIN32
3282 } else if (err == WSAEALREADY) {
3283 break;
3284 #endif
3285 } else {
3286 goto fail;
3288 } else {
3289 s->connected = 1;
3290 break;
3293 s->fd = fd;
3294 socket_set_nodelay(fd);
3295 if (s->connected)
3296 tcp_chr_connect(chr);
3297 else
3298 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3301 if (is_listen && is_waitconnect) {
3302 printf("QEMU waiting for connection on: %s\n", host_str);
3303 tcp_chr_accept(chr);
3304 socket_set_nonblock(s->listen_fd);
3307 return chr;
3308 fail:
3309 if (fd >= 0)
3310 closesocket(fd);
3311 qemu_free(s);
3312 qemu_free(chr);
3313 return NULL;
3316 CharDriverState *qemu_chr_open(const char *filename)
3318 const char *p;
3320 if (!strcmp(filename, "vc")) {
3321 return text_console_init(&display_state, 0);
3322 } else if (strstart(filename, "vc:", &p)) {
3323 return text_console_init(&display_state, p);
3324 } else if (!strcmp(filename, "null")) {
3325 return qemu_chr_open_null();
3326 } else
3327 if (strstart(filename, "tcp:", &p)) {
3328 return qemu_chr_open_tcp(p, 0, 0);
3329 } else
3330 if (strstart(filename, "telnet:", &p)) {
3331 return qemu_chr_open_tcp(p, 1, 0);
3332 } else
3333 if (strstart(filename, "udp:", &p)) {
3334 return qemu_chr_open_udp(p);
3335 } else
3336 if (strstart(filename, "mon:", &p)) {
3337 CharDriverState *drv = qemu_chr_open(p);
3338 if (drv) {
3339 drv = qemu_chr_open_mux(drv);
3340 monitor_init(drv, !nographic);
3341 return drv;
3343 printf("Unable to open driver: %s\n", p);
3344 return 0;
3345 } else
3346 #ifndef _WIN32
3347 if (strstart(filename, "unix:", &p)) {
3348 return qemu_chr_open_tcp(p, 0, 1);
3349 } else if (strstart(filename, "file:", &p)) {
3350 return qemu_chr_open_file_out(p);
3351 } else if (strstart(filename, "pipe:", &p)) {
3352 return qemu_chr_open_pipe(p);
3353 } else if (!strcmp(filename, "pty")) {
3354 return qemu_chr_open_pty();
3355 } else if (!strcmp(filename, "stdio")) {
3356 return qemu_chr_open_stdio();
3357 } else
3358 #if defined(__linux__)
3359 if (strstart(filename, "/dev/parport", NULL)) {
3360 return qemu_chr_open_pp(filename);
3361 } else
3362 #endif
3363 #if defined(__linux__) || defined(__sun__)
3364 if (strstart(filename, "/dev/", NULL)) {
3365 return qemu_chr_open_tty(filename);
3366 } else
3367 #endif
3368 #else /* !_WIN32 */
3369 if (strstart(filename, "COM", NULL)) {
3370 return qemu_chr_open_win(filename);
3371 } else
3372 if (strstart(filename, "pipe:", &p)) {
3373 return qemu_chr_open_win_pipe(p);
3374 } else
3375 if (strstart(filename, "con:", NULL)) {
3376 return qemu_chr_open_win_con(filename);
3377 } else
3378 if (strstart(filename, "file:", &p)) {
3379 return qemu_chr_open_win_file_out(p);
3381 #endif
3383 return NULL;
3387 void qemu_chr_close(CharDriverState *chr)
3389 if (chr->chr_close)
3390 chr->chr_close(chr);
3393 /***********************************************************/
3394 /* network device redirectors */
3396 void hex_dump(FILE *f, const uint8_t *buf, int size)
3398 int len, i, j, c;
3400 for(i=0;i<size;i+=16) {
3401 len = size - i;
3402 if (len > 16)
3403 len = 16;
3404 fprintf(f, "%08x ", i);
3405 for(j=0;j<16;j++) {
3406 if (j < len)
3407 fprintf(f, " %02x", buf[i+j]);
3408 else
3409 fprintf(f, " ");
3411 fprintf(f, " ");
3412 for(j=0;j<len;j++) {
3413 c = buf[i+j];
3414 if (c < ' ' || c > '~')
3415 c = '.';
3416 fprintf(f, "%c", c);
3418 fprintf(f, "\n");
3422 static int parse_macaddr(uint8_t *macaddr, const char *p)
3424 int i;
3425 for(i = 0; i < 6; i++) {
3426 macaddr[i] = strtol(p, (char **)&p, 16);
3427 if (i == 5) {
3428 if (*p != '\0')
3429 return -1;
3430 } else {
3431 if (*p != ':')
3432 return -1;
3433 p++;
3436 return 0;
3439 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3441 const char *p, *p1;
3442 int len;
3443 p = *pp;
3444 p1 = strchr(p, sep);
3445 if (!p1)
3446 return -1;
3447 len = p1 - p;
3448 p1++;
3449 if (buf_size > 0) {
3450 if (len > buf_size - 1)
3451 len = buf_size - 1;
3452 memcpy(buf, p, len);
3453 buf[len] = '\0';
3455 *pp = p1;
3456 return 0;
3459 int parse_host_src_port(struct sockaddr_in *haddr,
3460 struct sockaddr_in *saddr,
3461 const char *input_str)
3463 char *str = strdup(input_str);
3464 char *host_str = str;
3465 char *src_str;
3466 char *ptr;
3469 * Chop off any extra arguments at the end of the string which
3470 * would start with a comma, then fill in the src port information
3471 * if it was provided else use the "any address" and "any port".
3473 if ((ptr = strchr(str,',')))
3474 *ptr = '\0';
3476 if ((src_str = strchr(input_str,'@'))) {
3477 *src_str = '\0';
3478 src_str++;
3481 if (parse_host_port(haddr, host_str) < 0)
3482 goto fail;
3484 if (!src_str || *src_str == '\0')
3485 src_str = ":0";
3487 if (parse_host_port(saddr, src_str) < 0)
3488 goto fail;
3490 free(str);
3491 return(0);
3493 fail:
3494 free(str);
3495 return -1;
3498 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3500 char buf[512];
3501 struct hostent *he;
3502 const char *p, *r;
3503 int port;
3505 p = str;
3506 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3507 return -1;
3508 saddr->sin_family = AF_INET;
3509 if (buf[0] == '\0') {
3510 saddr->sin_addr.s_addr = 0;
3511 } else {
3512 if (isdigit(buf[0])) {
3513 if (!inet_aton(buf, &saddr->sin_addr))
3514 return -1;
3515 } else {
3516 if ((he = gethostbyname(buf)) == NULL)
3517 return - 1;
3518 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3521 port = strtol(p, (char **)&r, 0);
3522 if (r == p)
3523 return -1;
3524 saddr->sin_port = htons(port);
3525 return 0;
3528 #ifndef _WIN32
3529 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3531 const char *p;
3532 int len;
3534 len = MIN(108, strlen(str));
3535 p = strchr(str, ',');
3536 if (p)
3537 len = MIN(len, p - str);
3539 memset(uaddr, 0, sizeof(*uaddr));
3541 uaddr->sun_family = AF_UNIX;
3542 memcpy(uaddr->sun_path, str, len);
3544 return 0;
3546 #endif
3548 /* find or alloc a new VLAN */
3549 VLANState *qemu_find_vlan(int id)
3551 VLANState **pvlan, *vlan;
3552 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3553 if (vlan->id == id)
3554 return vlan;
3556 vlan = qemu_mallocz(sizeof(VLANState));
3557 if (!vlan)
3558 return NULL;
3559 vlan->id = id;
3560 vlan->next = NULL;
3561 pvlan = &first_vlan;
3562 while (*pvlan != NULL)
3563 pvlan = &(*pvlan)->next;
3564 *pvlan = vlan;
3565 return vlan;
3568 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3569 IOReadHandler *fd_read,
3570 IOCanRWHandler *fd_can_read,
3571 void *opaque)
3573 VLANClientState *vc, **pvc;
3574 vc = qemu_mallocz(sizeof(VLANClientState));
3575 if (!vc)
3576 return NULL;
3577 vc->fd_read = fd_read;
3578 vc->fd_can_read = fd_can_read;
3579 vc->opaque = opaque;
3580 vc->vlan = vlan;
3582 vc->next = NULL;
3583 pvc = &vlan->first_client;
3584 while (*pvc != NULL)
3585 pvc = &(*pvc)->next;
3586 *pvc = vc;
3587 return vc;
3590 int qemu_can_send_packet(VLANClientState *vc1)
3592 VLANState *vlan = vc1->vlan;
3593 VLANClientState *vc;
3595 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3596 if (vc != vc1) {
3597 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3598 return 1;
3601 return 0;
3604 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3606 VLANState *vlan = vc1->vlan;
3607 VLANClientState *vc;
3609 #if 0
3610 printf("vlan %d send:\n", vlan->id);
3611 hex_dump(stdout, buf, size);
3612 #endif
3613 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3614 if (vc != vc1) {
3615 vc->fd_read(vc->opaque, buf, size);
3620 #if defined(CONFIG_SLIRP)
3622 /* slirp network adapter */
3624 static int slirp_inited;
3625 static VLANClientState *slirp_vc;
3627 int slirp_can_output(void)
3629 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3632 void slirp_output(const uint8_t *pkt, int pkt_len)
3634 #if 0
3635 printf("slirp output:\n");
3636 hex_dump(stdout, pkt, pkt_len);
3637 #endif
3638 if (!slirp_vc)
3639 return;
3640 qemu_send_packet(slirp_vc, pkt, pkt_len);
3643 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3645 #if 0
3646 printf("slirp input:\n");
3647 hex_dump(stdout, buf, size);
3648 #endif
3649 slirp_input(buf, size);
3652 static int net_slirp_init(VLANState *vlan)
3654 if (!slirp_inited) {
3655 slirp_inited = 1;
3656 slirp_init();
3658 slirp_vc = qemu_new_vlan_client(vlan,
3659 slirp_receive, NULL, NULL);
3660 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3661 return 0;
3664 static void net_slirp_redir(const char *redir_str)
3666 int is_udp;
3667 char buf[256], *r;
3668 const char *p;
3669 struct in_addr guest_addr;
3670 int host_port, guest_port;
3672 if (!slirp_inited) {
3673 slirp_inited = 1;
3674 slirp_init();
3677 p = redir_str;
3678 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3679 goto fail;
3680 if (!strcmp(buf, "tcp")) {
3681 is_udp = 0;
3682 } else if (!strcmp(buf, "udp")) {
3683 is_udp = 1;
3684 } else {
3685 goto fail;
3688 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3689 goto fail;
3690 host_port = strtol(buf, &r, 0);
3691 if (r == buf)
3692 goto fail;
3694 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3695 goto fail;
3696 if (buf[0] == '\0') {
3697 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3699 if (!inet_aton(buf, &guest_addr))
3700 goto fail;
3702 guest_port = strtol(p, &r, 0);
3703 if (r == p)
3704 goto fail;
3706 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3707 fprintf(stderr, "qemu: could not set up redirection\n");
3708 exit(1);
3710 return;
3711 fail:
3712 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3713 exit(1);
3716 #ifndef _WIN32
3718 char smb_dir[1024];
3720 static void smb_exit(void)
3722 DIR *d;
3723 struct dirent *de;
3724 char filename[1024];
3726 /* erase all the files in the directory */
3727 d = opendir(smb_dir);
3728 for(;;) {
3729 de = readdir(d);
3730 if (!de)
3731 break;
3732 if (strcmp(de->d_name, ".") != 0 &&
3733 strcmp(de->d_name, "..") != 0) {
3734 snprintf(filename, sizeof(filename), "%s/%s",
3735 smb_dir, de->d_name);
3736 unlink(filename);
3739 closedir(d);
3740 rmdir(smb_dir);
3743 /* automatic user mode samba server configuration */
3744 void net_slirp_smb(const char *exported_dir)
3746 char smb_conf[1024];
3747 char smb_cmdline[1024];
3748 FILE *f;
3750 if (!slirp_inited) {
3751 slirp_inited = 1;
3752 slirp_init();
3755 /* XXX: better tmp dir construction */
3756 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3757 if (mkdir(smb_dir, 0700) < 0) {
3758 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3759 exit(1);
3761 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3763 f = fopen(smb_conf, "w");
3764 if (!f) {
3765 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3766 exit(1);
3768 fprintf(f,
3769 "[global]\n"
3770 "private dir=%s\n"
3771 "smb ports=0\n"
3772 "socket address=127.0.0.1\n"
3773 "pid directory=%s\n"
3774 "lock directory=%s\n"
3775 "log file=%s/log.smbd\n"
3776 "smb passwd file=%s/smbpasswd\n"
3777 "security = share\n"
3778 "[qemu]\n"
3779 "path=%s\n"
3780 "read only=no\n"
3781 "guest ok=yes\n",
3782 smb_dir,
3783 smb_dir,
3784 smb_dir,
3785 smb_dir,
3786 smb_dir,
3787 exported_dir
3789 fclose(f);
3790 atexit(smb_exit);
3792 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3793 SMBD_COMMAND, smb_conf);
3795 slirp_add_exec(0, smb_cmdline, 4, 139);
3798 #endif /* !defined(_WIN32) */
3800 #endif /* CONFIG_SLIRP */
3802 #if !defined(_WIN32)
3804 typedef struct TAPState {
3805 VLANClientState *vc;
3806 int fd;
3807 } TAPState;
3809 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3811 TAPState *s = opaque;
3812 int ret;
3813 for(;;) {
3814 ret = write(s->fd, buf, size);
3815 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3816 } else {
3817 break;
3822 static void tap_send(void *opaque)
3824 TAPState *s = opaque;
3825 uint8_t buf[4096];
3826 int size;
3828 #ifdef __sun__
3829 struct strbuf sbuf;
3830 int f = 0;
3831 sbuf.maxlen = sizeof(buf);
3832 sbuf.buf = buf;
3833 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3834 #else
3835 size = read(s->fd, buf, sizeof(buf));
3836 #endif
3837 if (size > 0) {
3838 qemu_send_packet(s->vc, buf, size);
3842 /* fd support */
3844 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3846 TAPState *s;
3848 s = qemu_mallocz(sizeof(TAPState));
3849 if (!s)
3850 return NULL;
3851 s->fd = fd;
3852 enable_sigio_timer(fd);
3853 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3854 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3855 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3856 return s;
3859 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3860 static int tap_open(char *ifname, int ifname_size)
3862 int fd;
3863 char *dev;
3864 struct stat s;
3866 TFR(fd = open("/dev/tap", O_RDWR));
3867 if (fd < 0) {
3868 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3869 return -1;
3872 fstat(fd, &s);
3873 dev = devname(s.st_rdev, S_IFCHR);
3874 pstrcpy(ifname, ifname_size, dev);
3876 fcntl(fd, F_SETFL, O_NONBLOCK);
3877 return fd;
3879 #elif defined(__sun__)
3880 #define TUNNEWPPA (('T'<<16) | 0x0001)
3882 * Allocate TAP device, returns opened fd.
3883 * Stores dev name in the first arg(must be large enough).
3885 int tap_alloc(char *dev)
3887 int tap_fd, if_fd, ppa = -1;
3888 static int ip_fd = 0;
3889 char *ptr;
3891 static int arp_fd = 0;
3892 int ip_muxid, arp_muxid;
3893 struct strioctl strioc_if, strioc_ppa;
3894 int link_type = I_PLINK;;
3895 struct lifreq ifr;
3896 char actual_name[32] = "";
3898 memset(&ifr, 0x0, sizeof(ifr));
3900 if( *dev ){
3901 ptr = dev;
3902 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3903 ppa = atoi(ptr);
3906 /* Check if IP device was opened */
3907 if( ip_fd )
3908 close(ip_fd);
3910 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3911 if (ip_fd < 0) {
3912 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3913 return -1;
3916 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3917 if (tap_fd < 0) {
3918 syslog(LOG_ERR, "Can't open /dev/tap");
3919 return -1;
3922 /* Assign a new PPA and get its unit number. */
3923 strioc_ppa.ic_cmd = TUNNEWPPA;
3924 strioc_ppa.ic_timout = 0;
3925 strioc_ppa.ic_len = sizeof(ppa);
3926 strioc_ppa.ic_dp = (char *)&ppa;
3927 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3928 syslog (LOG_ERR, "Can't assign new interface");
3930 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3931 if (if_fd < 0) {
3932 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3933 return -1;
3935 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3936 syslog(LOG_ERR, "Can't push IP module");
3937 return -1;
3940 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3941 syslog(LOG_ERR, "Can't get flags\n");
3943 snprintf (actual_name, 32, "tap%d", ppa);
3944 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3946 ifr.lifr_ppa = ppa;
3947 /* Assign ppa according to the unit number returned by tun device */
3949 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3950 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3951 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3952 syslog (LOG_ERR, "Can't get flags\n");
3953 /* Push arp module to if_fd */
3954 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3955 syslog (LOG_ERR, "Can't push ARP module (2)");
3957 /* Push arp module to ip_fd */
3958 if (ioctl (ip_fd, I_POP, NULL) < 0)
3959 syslog (LOG_ERR, "I_POP failed\n");
3960 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3961 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3962 /* Open arp_fd */
3963 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3964 if (arp_fd < 0)
3965 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3967 /* Set ifname to arp */
3968 strioc_if.ic_cmd = SIOCSLIFNAME;
3969 strioc_if.ic_timout = 0;
3970 strioc_if.ic_len = sizeof(ifr);
3971 strioc_if.ic_dp = (char *)&ifr;
3972 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3973 syslog (LOG_ERR, "Can't set ifname to arp\n");
3976 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3977 syslog(LOG_ERR, "Can't link TAP device to IP");
3978 return -1;
3981 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3982 syslog (LOG_ERR, "Can't link TAP device to ARP");
3984 close (if_fd);
3986 memset(&ifr, 0x0, sizeof(ifr));
3987 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3988 ifr.lifr_ip_muxid = ip_muxid;
3989 ifr.lifr_arp_muxid = arp_muxid;
3991 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3993 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3994 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3995 syslog (LOG_ERR, "Can't set multiplexor id");
3998 sprintf(dev, "tap%d", ppa);
3999 return tap_fd;
4002 static int tap_open(char *ifname, int ifname_size)
4004 char dev[10]="";
4005 int fd;
4006 if( (fd = tap_alloc(dev)) < 0 ){
4007 fprintf(stderr, "Cannot allocate TAP device\n");
4008 return -1;
4010 pstrcpy(ifname, ifname_size, dev);
4011 fcntl(fd, F_SETFL, O_NONBLOCK);
4012 return fd;
4014 #else
4015 static int tap_open(char *ifname, int ifname_size)
4017 struct ifreq ifr;
4018 int fd, ret;
4020 TFR(fd = open("/dev/net/tun", O_RDWR));
4021 if (fd < 0) {
4022 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4023 return -1;
4025 memset(&ifr, 0, sizeof(ifr));
4026 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4027 if (ifname[0] != '\0')
4028 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4029 else
4030 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4031 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4032 if (ret != 0) {
4033 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4034 close(fd);
4035 return -1;
4037 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4038 fcntl(fd, F_SETFL, O_NONBLOCK);
4039 return fd;
4041 #endif
4043 static int net_tap_init(VLANState *vlan, const char *ifname1,
4044 const char *setup_script)
4046 TAPState *s;
4047 int pid, status, fd;
4048 char *args[3];
4049 char **parg;
4050 char ifname[128];
4052 if (ifname1 != NULL)
4053 pstrcpy(ifname, sizeof(ifname), ifname1);
4054 else
4055 ifname[0] = '\0';
4056 TFR(fd = tap_open(ifname, sizeof(ifname)));
4057 if (fd < 0)
4058 return -1;
4060 if (!setup_script || !strcmp(setup_script, "no"))
4061 setup_script = "";
4062 if (setup_script[0] != '\0') {
4063 /* try to launch network init script */
4064 pid = fork();
4065 if (pid >= 0) {
4066 if (pid == 0) {
4067 int open_max = sysconf (_SC_OPEN_MAX), i;
4068 for (i = 0; i < open_max; i++)
4069 if (i != STDIN_FILENO &&
4070 i != STDOUT_FILENO &&
4071 i != STDERR_FILENO &&
4072 i != fd)
4073 close(i);
4075 parg = args;
4076 *parg++ = (char *)setup_script;
4077 *parg++ = ifname;
4078 *parg++ = NULL;
4079 execv(setup_script, args);
4080 _exit(1);
4082 while (waitpid(pid, &status, 0) != pid);
4083 if (!WIFEXITED(status) ||
4084 WEXITSTATUS(status) != 0) {
4085 fprintf(stderr, "%s: could not launch network script\n",
4086 setup_script);
4087 return -1;
4091 s = net_tap_fd_init(vlan, fd);
4092 if (!s)
4093 return -1;
4094 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4095 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4096 return 0;
4099 #endif /* !_WIN32 */
4101 /* network connection */
4102 typedef struct NetSocketState {
4103 VLANClientState *vc;
4104 int fd;
4105 int state; /* 0 = getting length, 1 = getting data */
4106 int index;
4107 int packet_len;
4108 uint8_t buf[4096];
4109 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4110 } NetSocketState;
4112 typedef struct NetSocketListenState {
4113 VLANState *vlan;
4114 int fd;
4115 } NetSocketListenState;
4117 /* XXX: we consider we can send the whole packet without blocking */
4118 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4120 NetSocketState *s = opaque;
4121 uint32_t len;
4122 len = htonl(size);
4124 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4125 send_all(s->fd, buf, size);
4128 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4130 NetSocketState *s = opaque;
4131 sendto(s->fd, buf, size, 0,
4132 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4135 static void net_socket_send(void *opaque)
4137 NetSocketState *s = opaque;
4138 int l, size, err;
4139 uint8_t buf1[4096];
4140 const uint8_t *buf;
4142 size = recv(s->fd, buf1, sizeof(buf1), 0);
4143 if (size < 0) {
4144 err = socket_error();
4145 if (err != EWOULDBLOCK)
4146 goto eoc;
4147 } else if (size == 0) {
4148 /* end of connection */
4149 eoc:
4150 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4151 closesocket(s->fd);
4152 return;
4154 buf = buf1;
4155 while (size > 0) {
4156 /* reassemble a packet from the network */
4157 switch(s->state) {
4158 case 0:
4159 l = 4 - s->index;
4160 if (l > size)
4161 l = size;
4162 memcpy(s->buf + s->index, buf, l);
4163 buf += l;
4164 size -= l;
4165 s->index += l;
4166 if (s->index == 4) {
4167 /* got length */
4168 s->packet_len = ntohl(*(uint32_t *)s->buf);
4169 s->index = 0;
4170 s->state = 1;
4172 break;
4173 case 1:
4174 l = s->packet_len - s->index;
4175 if (l > size)
4176 l = size;
4177 memcpy(s->buf + s->index, buf, l);
4178 s->index += l;
4179 buf += l;
4180 size -= l;
4181 if (s->index >= s->packet_len) {
4182 qemu_send_packet(s->vc, s->buf, s->packet_len);
4183 s->index = 0;
4184 s->state = 0;
4186 break;
4191 static void net_socket_send_dgram(void *opaque)
4193 NetSocketState *s = opaque;
4194 int size;
4196 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4197 if (size < 0)
4198 return;
4199 if (size == 0) {
4200 /* end of connection */
4201 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4202 return;
4204 qemu_send_packet(s->vc, s->buf, size);
4207 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4209 struct ip_mreq imr;
4210 int fd;
4211 int val, ret;
4212 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4213 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4214 inet_ntoa(mcastaddr->sin_addr),
4215 (int)ntohl(mcastaddr->sin_addr.s_addr));
4216 return -1;
4219 fd = socket(PF_INET, SOCK_DGRAM, 0);
4220 if (fd < 0) {
4221 perror("socket(PF_INET, SOCK_DGRAM)");
4222 return -1;
4225 val = 1;
4226 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4227 (const char *)&val, sizeof(val));
4228 if (ret < 0) {
4229 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4230 goto fail;
4233 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4234 if (ret < 0) {
4235 perror("bind");
4236 goto fail;
4239 /* Add host to multicast group */
4240 imr.imr_multiaddr = mcastaddr->sin_addr;
4241 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4243 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4244 (const char *)&imr, sizeof(struct ip_mreq));
4245 if (ret < 0) {
4246 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4247 goto fail;
4250 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4251 val = 1;
4252 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4253 (const char *)&val, sizeof(val));
4254 if (ret < 0) {
4255 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4256 goto fail;
4259 socket_set_nonblock(fd);
4260 return fd;
4261 fail:
4262 if (fd >= 0)
4263 closesocket(fd);
4264 return -1;
4267 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4268 int is_connected)
4270 struct sockaddr_in saddr;
4271 int newfd;
4272 socklen_t saddr_len;
4273 NetSocketState *s;
4275 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4276 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4277 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4280 if (is_connected) {
4281 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4282 /* must be bound */
4283 if (saddr.sin_addr.s_addr==0) {
4284 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4285 fd);
4286 return NULL;
4288 /* clone dgram socket */
4289 newfd = net_socket_mcast_create(&saddr);
4290 if (newfd < 0) {
4291 /* error already reported by net_socket_mcast_create() */
4292 close(fd);
4293 return NULL;
4295 /* clone newfd to fd, close newfd */
4296 dup2(newfd, fd);
4297 close(newfd);
4299 } else {
4300 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4301 fd, strerror(errno));
4302 return NULL;
4306 s = qemu_mallocz(sizeof(NetSocketState));
4307 if (!s)
4308 return NULL;
4309 s->fd = fd;
4311 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4312 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4314 /* mcast: save bound address as dst */
4315 if (is_connected) s->dgram_dst=saddr;
4317 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4318 "socket: fd=%d (%s mcast=%s:%d)",
4319 fd, is_connected? "cloned" : "",
4320 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4321 return s;
4324 static void net_socket_connect(void *opaque)
4326 NetSocketState *s = opaque;
4327 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4330 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4331 int is_connected)
4333 NetSocketState *s;
4334 s = qemu_mallocz(sizeof(NetSocketState));
4335 if (!s)
4336 return NULL;
4337 s->fd = fd;
4338 s->vc = qemu_new_vlan_client(vlan,
4339 net_socket_receive, NULL, s);
4340 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4341 "socket: fd=%d", fd);
4342 if (is_connected) {
4343 net_socket_connect(s);
4344 } else {
4345 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4347 return s;
4350 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4351 int is_connected)
4353 int so_type=-1, optlen=sizeof(so_type);
4355 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4356 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4357 return NULL;
4359 switch(so_type) {
4360 case SOCK_DGRAM:
4361 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4362 case SOCK_STREAM:
4363 return net_socket_fd_init_stream(vlan, fd, is_connected);
4364 default:
4365 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4366 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4367 return net_socket_fd_init_stream(vlan, fd, is_connected);
4369 return NULL;
4372 static void net_socket_accept(void *opaque)
4374 NetSocketListenState *s = opaque;
4375 NetSocketState *s1;
4376 struct sockaddr_in saddr;
4377 socklen_t len;
4378 int fd;
4380 for(;;) {
4381 len = sizeof(saddr);
4382 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4383 if (fd < 0 && errno != EINTR) {
4384 return;
4385 } else if (fd >= 0) {
4386 break;
4389 s1 = net_socket_fd_init(s->vlan, fd, 1);
4390 if (!s1) {
4391 closesocket(fd);
4392 } else {
4393 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4394 "socket: connection from %s:%d",
4395 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4399 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4401 NetSocketListenState *s;
4402 int fd, val, ret;
4403 struct sockaddr_in saddr;
4405 if (parse_host_port(&saddr, host_str) < 0)
4406 return -1;
4408 s = qemu_mallocz(sizeof(NetSocketListenState));
4409 if (!s)
4410 return -1;
4412 fd = socket(PF_INET, SOCK_STREAM, 0);
4413 if (fd < 0) {
4414 perror("socket");
4415 return -1;
4417 socket_set_nonblock(fd);
4419 /* allow fast reuse */
4420 val = 1;
4421 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4423 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4424 if (ret < 0) {
4425 perror("bind");
4426 return -1;
4428 ret = listen(fd, 0);
4429 if (ret < 0) {
4430 perror("listen");
4431 return -1;
4433 s->vlan = vlan;
4434 s->fd = fd;
4435 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4436 return 0;
4439 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4441 NetSocketState *s;
4442 int fd, connected, ret, err;
4443 struct sockaddr_in saddr;
4445 if (parse_host_port(&saddr, host_str) < 0)
4446 return -1;
4448 fd = socket(PF_INET, SOCK_STREAM, 0);
4449 if (fd < 0) {
4450 perror("socket");
4451 return -1;
4453 socket_set_nonblock(fd);
4455 connected = 0;
4456 for(;;) {
4457 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4458 if (ret < 0) {
4459 err = socket_error();
4460 if (err == EINTR || err == EWOULDBLOCK) {
4461 } else if (err == EINPROGRESS) {
4462 break;
4463 #ifdef _WIN32
4464 } else if (err == WSAEALREADY) {
4465 break;
4466 #endif
4467 } else {
4468 perror("connect");
4469 closesocket(fd);
4470 return -1;
4472 } else {
4473 connected = 1;
4474 break;
4477 s = net_socket_fd_init(vlan, fd, connected);
4478 if (!s)
4479 return -1;
4480 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4481 "socket: connect to %s:%d",
4482 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4483 return 0;
4486 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4488 NetSocketState *s;
4489 int fd;
4490 struct sockaddr_in saddr;
4492 if (parse_host_port(&saddr, host_str) < 0)
4493 return -1;
4496 fd = net_socket_mcast_create(&saddr);
4497 if (fd < 0)
4498 return -1;
4500 s = net_socket_fd_init(vlan, fd, 0);
4501 if (!s)
4502 return -1;
4504 s->dgram_dst = saddr;
4506 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4507 "socket: mcast=%s:%d",
4508 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4509 return 0;
4513 static int get_param_value(char *buf, int buf_size,
4514 const char *tag, const char *str)
4516 const char *p;
4517 char *q;
4518 char option[128];
4520 p = str;
4521 for(;;) {
4522 q = option;
4523 while (*p != '\0' && *p != '=') {
4524 if ((q - option) < sizeof(option) - 1)
4525 *q++ = *p;
4526 p++;
4528 *q = '\0';
4529 if (*p != '=')
4530 break;
4531 p++;
4532 if (!strcmp(tag, option)) {
4533 q = buf;
4534 while (*p != '\0' && *p != ',') {
4535 if ((q - buf) < buf_size - 1)
4536 *q++ = *p;
4537 p++;
4539 *q = '\0';
4540 return q - buf;
4541 } else {
4542 while (*p != '\0' && *p != ',') {
4543 p++;
4546 if (*p != ',')
4547 break;
4548 p++;
4550 return 0;
4553 static int net_client_init(const char *str)
4555 const char *p;
4556 char *q;
4557 char device[64];
4558 char buf[1024];
4559 int vlan_id, ret;
4560 VLANState *vlan;
4562 p = str;
4563 q = device;
4564 while (*p != '\0' && *p != ',') {
4565 if ((q - device) < sizeof(device) - 1)
4566 *q++ = *p;
4567 p++;
4569 *q = '\0';
4570 if (*p == ',')
4571 p++;
4572 vlan_id = 0;
4573 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4574 vlan_id = strtol(buf, NULL, 0);
4576 vlan = qemu_find_vlan(vlan_id);
4577 if (!vlan) {
4578 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4579 return -1;
4581 if (!strcmp(device, "nic")) {
4582 NICInfo *nd;
4583 uint8_t *macaddr;
4585 if (nb_nics >= MAX_NICS) {
4586 fprintf(stderr, "Too Many NICs\n");
4587 return -1;
4589 nd = &nd_table[nb_nics];
4590 macaddr = nd->macaddr;
4591 macaddr[0] = 0x52;
4592 macaddr[1] = 0x54;
4593 macaddr[2] = 0x00;
4594 macaddr[3] = 0x12;
4595 macaddr[4] = 0x34;
4596 macaddr[5] = 0x56 + nb_nics;
4598 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4599 if (parse_macaddr(macaddr, buf) < 0) {
4600 fprintf(stderr, "invalid syntax for ethernet address\n");
4601 return -1;
4604 if (get_param_value(buf, sizeof(buf), "model", p)) {
4605 nd->model = strdup(buf);
4607 nd->vlan = vlan;
4608 nb_nics++;
4609 vlan->nb_guest_devs++;
4610 ret = 0;
4611 } else
4612 if (!strcmp(device, "none")) {
4613 /* does nothing. It is needed to signal that no network cards
4614 are wanted */
4615 ret = 0;
4616 } else
4617 #ifdef CONFIG_SLIRP
4618 if (!strcmp(device, "user")) {
4619 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4620 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4622 vlan->nb_host_devs++;
4623 ret = net_slirp_init(vlan);
4624 } else
4625 #endif
4626 #ifdef _WIN32
4627 if (!strcmp(device, "tap")) {
4628 char ifname[64];
4629 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4630 fprintf(stderr, "tap: no interface name\n");
4631 return -1;
4633 vlan->nb_host_devs++;
4634 ret = tap_win32_init(vlan, ifname);
4635 } else
4636 #else
4637 if (!strcmp(device, "tap")) {
4638 char ifname[64];
4639 char setup_script[1024];
4640 int fd;
4641 vlan->nb_host_devs++;
4642 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4643 fd = strtol(buf, NULL, 0);
4644 ret = -1;
4645 if (net_tap_fd_init(vlan, fd))
4646 ret = 0;
4647 } else {
4648 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4649 ifname[0] = '\0';
4651 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4652 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4654 ret = net_tap_init(vlan, ifname, setup_script);
4656 } else
4657 #endif
4658 if (!strcmp(device, "socket")) {
4659 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4660 int fd;
4661 fd = strtol(buf, NULL, 0);
4662 ret = -1;
4663 if (net_socket_fd_init(vlan, fd, 1))
4664 ret = 0;
4665 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4666 ret = net_socket_listen_init(vlan, buf);
4667 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4668 ret = net_socket_connect_init(vlan, buf);
4669 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4670 ret = net_socket_mcast_init(vlan, buf);
4671 } else {
4672 fprintf(stderr, "Unknown socket options: %s\n", p);
4673 return -1;
4675 vlan->nb_host_devs++;
4676 } else
4678 fprintf(stderr, "Unknown network device: %s\n", device);
4679 return -1;
4681 if (ret < 0) {
4682 fprintf(stderr, "Could not initialize device '%s'\n", device);
4685 return ret;
4688 void do_info_network(void)
4690 VLANState *vlan;
4691 VLANClientState *vc;
4693 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4694 term_printf("VLAN %d devices:\n", vlan->id);
4695 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4696 term_printf(" %s\n", vc->info_str);
4700 /***********************************************************/
4701 /* USB devices */
4703 static USBPort *used_usb_ports;
4704 static USBPort *free_usb_ports;
4706 /* ??? Maybe change this to register a hub to keep track of the topology. */
4707 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4708 usb_attachfn attach)
4710 port->opaque = opaque;
4711 port->index = index;
4712 port->attach = attach;
4713 port->next = free_usb_ports;
4714 free_usb_ports = port;
4717 static int usb_device_add(const char *devname)
4719 const char *p;
4720 USBDevice *dev;
4721 USBPort *port;
4723 if (!free_usb_ports)
4724 return -1;
4726 if (strstart(devname, "host:", &p)) {
4727 dev = usb_host_device_open(p);
4728 } else if (!strcmp(devname, "mouse")) {
4729 dev = usb_mouse_init();
4730 } else if (!strcmp(devname, "tablet")) {
4731 dev = usb_tablet_init();
4732 } else if (!strcmp(devname, "keyboard")) {
4733 dev = usb_keyboard_init();
4734 } else if (strstart(devname, "disk:", &p)) {
4735 dev = usb_msd_init(p);
4736 } else if (!strcmp(devname, "wacom-tablet")) {
4737 dev = usb_wacom_init();
4738 } else {
4739 return -1;
4741 if (!dev)
4742 return -1;
4744 /* Find a USB port to add the device to. */
4745 port = free_usb_ports;
4746 if (!port->next) {
4747 USBDevice *hub;
4749 /* Create a new hub and chain it on. */
4750 free_usb_ports = NULL;
4751 port->next = used_usb_ports;
4752 used_usb_ports = port;
4754 hub = usb_hub_init(VM_USB_HUB_SIZE);
4755 usb_attach(port, hub);
4756 port = free_usb_ports;
4759 free_usb_ports = port->next;
4760 port->next = used_usb_ports;
4761 used_usb_ports = port;
4762 usb_attach(port, dev);
4763 return 0;
4766 static int usb_device_del(const char *devname)
4768 USBPort *port;
4769 USBPort **lastp;
4770 USBDevice *dev;
4771 int bus_num, addr;
4772 const char *p;
4774 if (!used_usb_ports)
4775 return -1;
4777 p = strchr(devname, '.');
4778 if (!p)
4779 return -1;
4780 bus_num = strtoul(devname, NULL, 0);
4781 addr = strtoul(p + 1, NULL, 0);
4782 if (bus_num != 0)
4783 return -1;
4785 lastp = &used_usb_ports;
4786 port = used_usb_ports;
4787 while (port && port->dev->addr != addr) {
4788 lastp = &port->next;
4789 port = port->next;
4792 if (!port)
4793 return -1;
4795 dev = port->dev;
4796 *lastp = port->next;
4797 usb_attach(port, NULL);
4798 dev->handle_destroy(dev);
4799 port->next = free_usb_ports;
4800 free_usb_ports = port;
4801 return 0;
4804 void do_usb_add(const char *devname)
4806 int ret;
4807 ret = usb_device_add(devname);
4808 if (ret < 0)
4809 term_printf("Could not add USB device '%s'\n", devname);
4812 void do_usb_del(const char *devname)
4814 int ret;
4815 ret = usb_device_del(devname);
4816 if (ret < 0)
4817 term_printf("Could not remove USB device '%s'\n", devname);
4820 void usb_info(void)
4822 USBDevice *dev;
4823 USBPort *port;
4824 const char *speed_str;
4826 if (!usb_enabled) {
4827 term_printf("USB support not enabled\n");
4828 return;
4831 for (port = used_usb_ports; port; port = port->next) {
4832 dev = port->dev;
4833 if (!dev)
4834 continue;
4835 switch(dev->speed) {
4836 case USB_SPEED_LOW:
4837 speed_str = "1.5";
4838 break;
4839 case USB_SPEED_FULL:
4840 speed_str = "12";
4841 break;
4842 case USB_SPEED_HIGH:
4843 speed_str = "480";
4844 break;
4845 default:
4846 speed_str = "?";
4847 break;
4849 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4850 0, dev->addr, speed_str, dev->devname);
4854 /***********************************************************/
4855 /* PCMCIA/Cardbus */
4857 static struct pcmcia_socket_entry_s {
4858 struct pcmcia_socket_s *socket;
4859 struct pcmcia_socket_entry_s *next;
4860 } *pcmcia_sockets = 0;
4862 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4864 struct pcmcia_socket_entry_s *entry;
4866 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4867 entry->socket = socket;
4868 entry->next = pcmcia_sockets;
4869 pcmcia_sockets = entry;
4872 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4874 struct pcmcia_socket_entry_s *entry, **ptr;
4876 ptr = &pcmcia_sockets;
4877 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4878 if (entry->socket == socket) {
4879 *ptr = entry->next;
4880 qemu_free(entry);
4884 void pcmcia_info(void)
4886 struct pcmcia_socket_entry_s *iter;
4887 if (!pcmcia_sockets)
4888 term_printf("No PCMCIA sockets\n");
4890 for (iter = pcmcia_sockets; iter; iter = iter->next)
4891 term_printf("%s: %s\n", iter->socket->slot_string,
4892 iter->socket->attached ? iter->socket->card_string :
4893 "Empty");
4896 /***********************************************************/
4897 /* dumb display */
4899 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4903 static void dumb_resize(DisplayState *ds, int w, int h)
4907 static void dumb_refresh(DisplayState *ds)
4909 #if defined(CONFIG_SDL)
4910 vga_hw_update();
4911 #endif
4914 static void dumb_display_init(DisplayState *ds)
4916 ds->data = NULL;
4917 ds->linesize = 0;
4918 ds->depth = 0;
4919 ds->dpy_update = dumb_update;
4920 ds->dpy_resize = dumb_resize;
4921 ds->dpy_refresh = dumb_refresh;
4924 /***********************************************************/
4925 /* I/O handling */
4927 #define MAX_IO_HANDLERS 64
4929 typedef struct IOHandlerRecord {
4930 int fd;
4931 IOCanRWHandler *fd_read_poll;
4932 IOHandler *fd_read;
4933 IOHandler *fd_write;
4934 int deleted;
4935 void *opaque;
4936 /* temporary data */
4937 struct pollfd *ufd;
4938 struct IOHandlerRecord *next;
4939 } IOHandlerRecord;
4941 static IOHandlerRecord *first_io_handler;
4943 /* XXX: fd_read_poll should be suppressed, but an API change is
4944 necessary in the character devices to suppress fd_can_read(). */
4945 int qemu_set_fd_handler2(int fd,
4946 IOCanRWHandler *fd_read_poll,
4947 IOHandler *fd_read,
4948 IOHandler *fd_write,
4949 void *opaque)
4951 IOHandlerRecord **pioh, *ioh;
4953 if (!fd_read && !fd_write) {
4954 pioh = &first_io_handler;
4955 for(;;) {
4956 ioh = *pioh;
4957 if (ioh == NULL)
4958 break;
4959 if (ioh->fd == fd) {
4960 ioh->deleted = 1;
4961 break;
4963 pioh = &ioh->next;
4965 } else {
4966 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4967 if (ioh->fd == fd)
4968 goto found;
4970 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4971 if (!ioh)
4972 return -1;
4973 ioh->next = first_io_handler;
4974 first_io_handler = ioh;
4975 found:
4976 ioh->fd = fd;
4977 ioh->fd_read_poll = fd_read_poll;
4978 ioh->fd_read = fd_read;
4979 ioh->fd_write = fd_write;
4980 ioh->opaque = opaque;
4981 ioh->deleted = 0;
4983 return 0;
4986 int qemu_set_fd_handler(int fd,
4987 IOHandler *fd_read,
4988 IOHandler *fd_write,
4989 void *opaque)
4991 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4994 /***********************************************************/
4995 /* Polling handling */
4997 typedef struct PollingEntry {
4998 PollingFunc *func;
4999 void *opaque;
5000 struct PollingEntry *next;
5001 } PollingEntry;
5003 static PollingEntry *first_polling_entry;
5005 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5007 PollingEntry **ppe, *pe;
5008 pe = qemu_mallocz(sizeof(PollingEntry));
5009 if (!pe)
5010 return -1;
5011 pe->func = func;
5012 pe->opaque = opaque;
5013 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5014 *ppe = pe;
5015 return 0;
5018 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5020 PollingEntry **ppe, *pe;
5021 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5022 pe = *ppe;
5023 if (pe->func == func && pe->opaque == opaque) {
5024 *ppe = pe->next;
5025 qemu_free(pe);
5026 break;
5031 #ifdef _WIN32
5032 /***********************************************************/
5033 /* Wait objects support */
5034 typedef struct WaitObjects {
5035 int num;
5036 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5037 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5038 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5039 } WaitObjects;
5041 static WaitObjects wait_objects = {0};
5043 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5045 WaitObjects *w = &wait_objects;
5047 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5048 return -1;
5049 w->events[w->num] = handle;
5050 w->func[w->num] = func;
5051 w->opaque[w->num] = opaque;
5052 w->num++;
5053 return 0;
5056 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5058 int i, found;
5059 WaitObjects *w = &wait_objects;
5061 found = 0;
5062 for (i = 0; i < w->num; i++) {
5063 if (w->events[i] == handle)
5064 found = 1;
5065 if (found) {
5066 w->events[i] = w->events[i + 1];
5067 w->func[i] = w->func[i + 1];
5068 w->opaque[i] = w->opaque[i + 1];
5071 if (found)
5072 w->num--;
5074 #endif
5076 #define SELF_ANNOUNCE_ROUNDS 5
5077 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5078 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5079 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5081 static int announce_self_create(uint8_t *buf,
5082 uint8_t *mac_addr)
5084 uint32_t magic = EXPERIMENTAL_MAGIC;
5085 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5087 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5089 memset(buf, 0xff, 6); /* h_dst */
5090 memcpy(buf + 6, mac_addr, 6); /* h_src */
5091 memcpy(buf + 12, &proto, 2); /* h_proto */
5092 memcpy(buf + 14, &magic, 4); /* magic */
5094 return 18; /* len */
5097 static void qemu_announce_self(void)
5099 int i, j, len;
5100 VLANState *vlan;
5101 VLANClientState *vc;
5102 uint8_t buf[256];
5104 for (i = 0; i < nb_nics; i++) {
5105 len = announce_self_create(buf, nd_table[i].macaddr);
5106 vlan = nd_table[i].vlan;
5107 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5108 if (vc->fd_read == tap_receive) /* send only if tap */
5109 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5110 vc->fd_read(vc->opaque, buf, len);
5115 /***********************************************************/
5116 /* savevm/loadvm support */
5118 #define IO_BUF_SIZE 32768
5120 struct QEMUFile {
5121 QEMUFilePutBufferFunc *put_buffer;
5122 QEMUFileGetBufferFunc *get_buffer;
5123 QEMUFileCloseFunc *close;
5124 void *opaque;
5126 int64_t buf_offset; /* start of buffer when writing, end of buffer
5127 when reading */
5128 int buf_index;
5129 int buf_size; /* 0 when writing */
5130 uint8_t buf[IO_BUF_SIZE];
5133 typedef struct QEMUFileFD
5135 int fd;
5136 } QEMUFileFD;
5138 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5140 QEMUFileFD *s = opaque;
5141 int offset = 0;
5142 ssize_t len;
5144 again:
5145 len = read(s->fd, buf + offset, size - offset);
5146 if (len == -1) {
5147 if (errno == EINTR || errno == EAGAIN)
5148 goto again;
5151 return len;
5154 QEMUFile *qemu_fopen_fd(int fd)
5156 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5157 s->fd = fd;
5158 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5161 typedef struct QEMUFileUnix
5163 FILE *outfile;
5164 } QEMUFileUnix;
5166 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5168 QEMUFileUnix *s = opaque;
5169 fseek(s->outfile, pos, SEEK_SET);
5170 fwrite(buf, 1, size, s->outfile);
5173 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5175 QEMUFileUnix *s = opaque;
5176 fseek(s->outfile, pos, SEEK_SET);
5177 return fread(buf, 1, size, s->outfile);
5180 static void file_close(void *opaque)
5182 QEMUFileUnix *s = opaque;
5183 fclose(s->outfile);
5184 qemu_free(s);
5187 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5189 QEMUFileUnix *s;
5191 s = qemu_mallocz(sizeof(QEMUFileUnix));
5192 if (!s)
5193 return NULL;
5195 s->outfile = fopen(filename, mode);
5196 if (!s->outfile)
5197 goto fail;
5199 if (!strcmp(mode, "wb"))
5200 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5201 else if (!strcmp(mode, "rb"))
5202 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5204 fail:
5205 if (s->outfile)
5206 fclose(s->outfile);
5207 qemu_free(s);
5208 return NULL;
5211 typedef struct QEMUFileBdrv
5213 BlockDriverState *bs;
5214 int64_t base_offset;
5215 } QEMUFileBdrv;
5217 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5219 QEMUFileBdrv *s = opaque;
5220 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5223 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5225 QEMUFileBdrv *s = opaque;
5226 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5229 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5231 QEMUFileBdrv *s;
5233 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5234 if (!s)
5235 return NULL;
5237 s->bs = bs;
5238 s->base_offset = offset;
5240 if (is_writable)
5241 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5243 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5246 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5247 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5249 QEMUFile *f;
5251 f = qemu_mallocz(sizeof(QEMUFile));
5252 if (!f)
5253 return NULL;
5255 f->opaque = opaque;
5256 f->put_buffer = put_buffer;
5257 f->get_buffer = get_buffer;
5258 f->close = close;
5260 return f;
5263 void qemu_fflush(QEMUFile *f)
5265 if (!f->put_buffer)
5266 return;
5268 if (f->buf_index > 0) {
5269 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5270 f->buf_offset += f->buf_index;
5271 f->buf_index = 0;
5275 static void qemu_fill_buffer(QEMUFile *f)
5277 int len;
5279 if (!f->get_buffer)
5280 return;
5282 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5283 if (len < 0)
5284 len = 0;
5286 f->buf_index = 0;
5287 f->buf_size = len;
5288 f->buf_offset += len;
5291 void qemu_fclose(QEMUFile *f)
5293 qemu_fflush(f);
5294 if (f->close)
5295 f->close(f->opaque);
5296 qemu_free(f);
5299 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5301 int l;
5302 while (size > 0) {
5303 l = IO_BUF_SIZE - f->buf_index;
5304 if (l > size)
5305 l = size;
5306 memcpy(f->buf + f->buf_index, buf, l);
5307 f->buf_index += l;
5308 buf += l;
5309 size -= l;
5310 if (f->buf_index >= IO_BUF_SIZE)
5311 qemu_fflush(f);
5315 void qemu_put_byte(QEMUFile *f, int v)
5317 f->buf[f->buf_index++] = v;
5318 if (f->buf_index >= IO_BUF_SIZE)
5319 qemu_fflush(f);
5322 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5324 int size, l;
5326 size = size1;
5327 while (size > 0) {
5328 l = f->buf_size - f->buf_index;
5329 if (l == 0) {
5330 qemu_fill_buffer(f);
5331 l = f->buf_size - f->buf_index;
5332 if (l == 0)
5333 break;
5335 if (l > size)
5336 l = size;
5337 memcpy(buf, f->buf + f->buf_index, l);
5338 f->buf_index += l;
5339 buf += l;
5340 size -= l;
5342 return size1 - size;
5345 int qemu_get_byte(QEMUFile *f)
5347 if (f->buf_index >= f->buf_size) {
5348 qemu_fill_buffer(f);
5349 if (f->buf_index >= f->buf_size)
5350 return 0;
5352 return f->buf[f->buf_index++];
5355 int64_t qemu_ftell(QEMUFile *f)
5357 return f->buf_offset - f->buf_size + f->buf_index;
5360 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5362 if (whence == SEEK_SET) {
5363 /* nothing to do */
5364 } else if (whence == SEEK_CUR) {
5365 pos += qemu_ftell(f);
5366 } else {
5367 /* SEEK_END not supported */
5368 return -1;
5370 if (f->put_buffer) {
5371 qemu_fflush(f);
5372 f->buf_offset = pos;
5373 } else {
5374 f->buf_offset = pos;
5375 f->buf_index = 0;
5376 f->buf_size = 0;
5378 return pos;
5381 void qemu_put_be16(QEMUFile *f, unsigned int v)
5383 qemu_put_byte(f, v >> 8);
5384 qemu_put_byte(f, v);
5387 void qemu_put_be32(QEMUFile *f, unsigned int v)
5389 qemu_put_byte(f, v >> 24);
5390 qemu_put_byte(f, v >> 16);
5391 qemu_put_byte(f, v >> 8);
5392 qemu_put_byte(f, v);
5395 void qemu_put_be64(QEMUFile *f, uint64_t v)
5397 qemu_put_be32(f, v >> 32);
5398 qemu_put_be32(f, v);
5401 unsigned int qemu_get_be16(QEMUFile *f)
5403 unsigned int v;
5404 v = qemu_get_byte(f) << 8;
5405 v |= qemu_get_byte(f);
5406 return v;
5409 unsigned int qemu_get_be32(QEMUFile *f)
5411 unsigned int v;
5412 v = qemu_get_byte(f) << 24;
5413 v |= qemu_get_byte(f) << 16;
5414 v |= qemu_get_byte(f) << 8;
5415 v |= qemu_get_byte(f);
5416 return v;
5419 uint64_t qemu_get_be64(QEMUFile *f)
5421 uint64_t v;
5422 v = (uint64_t)qemu_get_be32(f) << 32;
5423 v |= qemu_get_be32(f);
5424 return v;
5427 typedef struct SaveStateEntry {
5428 char idstr[256];
5429 int instance_id;
5430 int version_id;
5431 SaveStateHandler *save_state;
5432 LoadStateHandler *load_state;
5433 void *opaque;
5434 struct SaveStateEntry *next;
5435 } SaveStateEntry;
5437 static SaveStateEntry *first_se;
5439 int register_savevm(const char *idstr,
5440 int instance_id,
5441 int version_id,
5442 SaveStateHandler *save_state,
5443 LoadStateHandler *load_state,
5444 void *opaque)
5446 SaveStateEntry *se, **pse;
5448 se = qemu_malloc(sizeof(SaveStateEntry));
5449 if (!se)
5450 return -1;
5451 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5452 se->instance_id = instance_id;
5453 se->version_id = version_id;
5454 se->save_state = save_state;
5455 se->load_state = load_state;
5456 se->opaque = opaque;
5457 se->next = NULL;
5459 /* add at the end of list */
5460 pse = &first_se;
5461 while (*pse != NULL)
5462 pse = &(*pse)->next;
5463 *pse = se;
5464 return 0;
5467 #define QEMU_VM_FILE_MAGIC 0x5145564d
5468 #define QEMU_VM_FILE_VERSION 0x00000002
5470 int qemu_savevm_state(QEMUFile *f)
5472 SaveStateEntry *se;
5473 int len, ret;
5474 int64_t cur_pos, len_pos, total_len_pos;
5476 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5477 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5478 total_len_pos = qemu_ftell(f);
5479 qemu_put_be64(f, 0); /* total size */
5481 for(se = first_se; se != NULL; se = se->next) {
5482 /* ID string */
5483 len = strlen(se->idstr);
5484 qemu_put_byte(f, len);
5485 qemu_put_buffer(f, se->idstr, len);
5487 qemu_put_be32(f, se->instance_id);
5488 qemu_put_be32(f, se->version_id);
5490 /* record size: filled later */
5491 len_pos = qemu_ftell(f);
5492 qemu_put_be32(f, 0);
5494 se->save_state(f, se->opaque);
5496 /* fill record size */
5497 cur_pos = qemu_ftell(f);
5498 len = cur_pos - len_pos - 4;
5499 qemu_fseek(f, len_pos, SEEK_SET);
5500 qemu_put_be32(f, len);
5501 qemu_fseek(f, cur_pos, SEEK_SET);
5503 cur_pos = qemu_ftell(f);
5504 qemu_fseek(f, total_len_pos, SEEK_SET);
5505 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5506 qemu_fseek(f, cur_pos, SEEK_SET);
5508 ret = 0;
5509 return ret;
5512 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5514 SaveStateEntry *se;
5516 for(se = first_se; se != NULL; se = se->next) {
5517 if (!strcmp(se->idstr, idstr) &&
5518 instance_id == se->instance_id)
5519 return se;
5521 return NULL;
5524 int qemu_loadvm_state(QEMUFile *f)
5526 SaveStateEntry *se;
5527 int len, ret, instance_id, record_len, version_id;
5528 int64_t total_len, end_pos, cur_pos;
5529 unsigned int v;
5530 char idstr[256];
5532 v = qemu_get_be32(f);
5533 if (v != QEMU_VM_FILE_MAGIC)
5534 goto fail;
5535 v = qemu_get_be32(f);
5536 if (v != QEMU_VM_FILE_VERSION) {
5537 fail:
5538 ret = -1;
5539 goto the_end;
5541 total_len = qemu_get_be64(f);
5542 end_pos = total_len + qemu_ftell(f);
5543 for(;;) {
5544 if (qemu_ftell(f) >= end_pos)
5545 break;
5546 len = qemu_get_byte(f);
5547 qemu_get_buffer(f, idstr, len);
5548 idstr[len] = '\0';
5549 instance_id = qemu_get_be32(f);
5550 version_id = qemu_get_be32(f);
5551 record_len = qemu_get_be32(f);
5552 #if 0
5553 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5554 idstr, instance_id, version_id, record_len);
5555 #endif
5556 cur_pos = qemu_ftell(f);
5557 se = find_se(idstr, instance_id);
5558 if (!se) {
5559 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5560 instance_id, idstr);
5561 } else {
5562 ret = se->load_state(f, se->opaque, version_id);
5563 if (ret < 0) {
5564 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5565 instance_id, idstr);
5566 goto the_end;
5569 /* always seek to exact end of record */
5570 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5572 ret = 0;
5573 the_end:
5574 return ret;
5577 int qemu_live_savevm_state(QEMUFile *f)
5579 SaveStateEntry *se;
5580 int len, ret;
5582 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5583 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5585 for(se = first_se; se != NULL; se = se->next) {
5586 len = strlen(se->idstr);
5588 qemu_put_byte(f, len);
5589 qemu_put_buffer(f, se->idstr, len);
5590 qemu_put_be32(f, se->instance_id);
5591 qemu_put_be32(f, se->version_id);
5593 se->save_state(f, se->opaque);
5596 qemu_put_byte(f, 0);
5598 ret = 0;
5599 return ret;
5602 int qemu_live_loadvm_state(QEMUFile *f)
5604 SaveStateEntry *se;
5605 int len, ret, instance_id, version_id;
5606 unsigned int v;
5607 char idstr[256];
5609 v = qemu_get_be32(f);
5610 if (v != QEMU_VM_FILE_MAGIC)
5611 goto fail;
5612 v = qemu_get_be32(f);
5613 if (v != QEMU_VM_FILE_VERSION) {
5614 fail:
5615 ret = -1;
5616 goto the_end;
5619 for(;;) {
5620 len = qemu_get_byte(f);
5621 if (len == 0)
5622 break;
5623 qemu_get_buffer(f, idstr, len);
5624 idstr[len] = '\0';
5625 instance_id = qemu_get_be32(f);
5626 version_id = qemu_get_be32(f);
5627 se = find_se(idstr, instance_id);
5628 if (!se) {
5629 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5630 instance_id, idstr);
5631 } else {
5632 if (version_id > se->version_id) { /* src version > dst version */
5633 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
5634 idstr, version_id, se->version_id);
5635 ret = -1;
5636 goto the_end;
5638 ret = se->load_state(f, se->opaque, version_id);
5639 if (ret < 0) {
5640 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5641 instance_id, idstr);
5642 goto the_end;
5646 ret = 0;
5648 qemu_announce_self();
5650 the_end:
5651 return ret;
5654 /* device can contain snapshots */
5655 static int bdrv_can_snapshot(BlockDriverState *bs)
5657 return (bs &&
5658 !bdrv_is_removable(bs) &&
5659 !bdrv_is_read_only(bs));
5662 /* device must be snapshots in order to have a reliable snapshot */
5663 static int bdrv_has_snapshot(BlockDriverState *bs)
5665 return (bs &&
5666 !bdrv_is_removable(bs) &&
5667 !bdrv_is_read_only(bs));
5670 static BlockDriverState *get_bs_snapshots(void)
5672 BlockDriverState *bs;
5673 int i;
5675 if (bs_snapshots)
5676 return bs_snapshots;
5677 for(i = 0; i <= MAX_DISKS; i++) {
5678 bs = bs_table[i];
5679 if (bdrv_can_snapshot(bs))
5680 goto ok;
5682 return NULL;
5684 bs_snapshots = bs;
5685 return bs;
5688 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5689 const char *name)
5691 QEMUSnapshotInfo *sn_tab, *sn;
5692 int nb_sns, i, ret;
5694 ret = -ENOENT;
5695 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5696 if (nb_sns < 0)
5697 return ret;
5698 for(i = 0; i < nb_sns; i++) {
5699 sn = &sn_tab[i];
5700 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5701 *sn_info = *sn;
5702 ret = 0;
5703 break;
5706 qemu_free(sn_tab);
5707 return ret;
5710 void do_savevm(const char *name)
5712 BlockDriverState *bs, *bs1;
5713 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5714 int must_delete, ret, i;
5715 BlockDriverInfo bdi1, *bdi = &bdi1;
5716 QEMUFile *f;
5717 int saved_vm_running;
5718 #ifdef _WIN32
5719 struct _timeb tb;
5720 #else
5721 struct timeval tv;
5722 #endif
5724 bs = get_bs_snapshots();
5725 if (!bs) {
5726 term_printf("No block device can accept snapshots\n");
5727 return;
5730 /* ??? Should this occur after vm_stop? */
5731 qemu_aio_flush();
5733 saved_vm_running = vm_running;
5734 vm_stop(0);
5736 must_delete = 0;
5737 if (name) {
5738 ret = bdrv_snapshot_find(bs, old_sn, name);
5739 if (ret >= 0) {
5740 must_delete = 1;
5743 memset(sn, 0, sizeof(*sn));
5744 if (must_delete) {
5745 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5746 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5747 } else {
5748 if (name)
5749 pstrcpy(sn->name, sizeof(sn->name), name);
5752 /* fill auxiliary fields */
5753 #ifdef _WIN32
5754 _ftime(&tb);
5755 sn->date_sec = tb.time;
5756 sn->date_nsec = tb.millitm * 1000000;
5757 #else
5758 gettimeofday(&tv, NULL);
5759 sn->date_sec = tv.tv_sec;
5760 sn->date_nsec = tv.tv_usec * 1000;
5761 #endif
5762 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5764 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5765 term_printf("Device %s does not support VM state snapshots\n",
5766 bdrv_get_device_name(bs));
5767 goto the_end;
5770 /* save the VM state */
5771 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5772 if (!f) {
5773 term_printf("Could not open VM state file\n");
5774 goto the_end;
5776 ret = qemu_savevm_state(f);
5777 sn->vm_state_size = qemu_ftell(f);
5778 qemu_fclose(f);
5779 if (ret < 0) {
5780 term_printf("Error %d while writing VM\n", ret);
5781 goto the_end;
5784 /* create the snapshots */
5786 for(i = 0; i < MAX_DISKS; i++) {
5787 bs1 = bs_table[i];
5788 if (bdrv_has_snapshot(bs1)) {
5789 if (must_delete) {
5790 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5791 if (ret < 0) {
5792 term_printf("Error while deleting snapshot on '%s'\n",
5793 bdrv_get_device_name(bs1));
5796 ret = bdrv_snapshot_create(bs1, sn);
5797 if (ret < 0) {
5798 term_printf("Error while creating snapshot on '%s'\n",
5799 bdrv_get_device_name(bs1));
5804 the_end:
5805 if (saved_vm_running)
5806 vm_start();
5809 void do_loadvm(const char *name)
5811 BlockDriverState *bs, *bs1;
5812 BlockDriverInfo bdi1, *bdi = &bdi1;
5813 QEMUFile *f;
5814 int i, ret;
5815 int saved_vm_running;
5817 bs = get_bs_snapshots();
5818 if (!bs) {
5819 term_printf("No block device supports snapshots\n");
5820 return;
5823 /* Flush all IO requests so they don't interfere with the new state. */
5824 qemu_aio_flush();
5826 saved_vm_running = vm_running;
5827 vm_stop(0);
5829 for(i = 0; i <= MAX_DISKS; i++) {
5830 bs1 = bs_table[i];
5831 if (bdrv_has_snapshot(bs1)) {
5832 ret = bdrv_snapshot_goto(bs1, name);
5833 if (ret < 0) {
5834 if (bs != bs1)
5835 term_printf("Warning: ");
5836 switch(ret) {
5837 case -ENOTSUP:
5838 term_printf("Snapshots not supported on device '%s'\n",
5839 bdrv_get_device_name(bs1));
5840 break;
5841 case -ENOENT:
5842 term_printf("Could not find snapshot '%s' on device '%s'\n",
5843 name, bdrv_get_device_name(bs1));
5844 break;
5845 default:
5846 term_printf("Error %d while activating snapshot on '%s'\n",
5847 ret, bdrv_get_device_name(bs1));
5848 break;
5850 /* fatal on snapshot block device */
5851 if (bs == bs1)
5852 goto the_end;
5857 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5858 term_printf("Device %s does not support VM state snapshots\n",
5859 bdrv_get_device_name(bs));
5860 return;
5863 /* restore the VM state */
5864 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5865 if (!f) {
5866 term_printf("Could not open VM state file\n");
5867 goto the_end;
5869 ret = qemu_loadvm_state(f);
5870 qemu_fclose(f);
5871 if (ret < 0) {
5872 term_printf("Error %d while loading VM state\n", ret);
5874 the_end:
5875 if (saved_vm_running)
5876 vm_start();
5879 void do_delvm(const char *name)
5881 BlockDriverState *bs, *bs1;
5882 int i, ret;
5884 bs = get_bs_snapshots();
5885 if (!bs) {
5886 term_printf("No block device supports snapshots\n");
5887 return;
5890 for(i = 0; i <= MAX_DISKS; i++) {
5891 bs1 = bs_table[i];
5892 if (bdrv_has_snapshot(bs1)) {
5893 ret = bdrv_snapshot_delete(bs1, name);
5894 if (ret < 0) {
5895 if (ret == -ENOTSUP)
5896 term_printf("Snapshots not supported on device '%s'\n",
5897 bdrv_get_device_name(bs1));
5898 else
5899 term_printf("Error %d while deleting snapshot on '%s'\n",
5900 ret, bdrv_get_device_name(bs1));
5906 void do_info_snapshots(void)
5908 BlockDriverState *bs, *bs1;
5909 QEMUSnapshotInfo *sn_tab, *sn;
5910 int nb_sns, i;
5911 char buf[256];
5913 bs = get_bs_snapshots();
5914 if (!bs) {
5915 term_printf("No available block device supports snapshots\n");
5916 return;
5918 term_printf("Snapshot devices:");
5919 for(i = 0; i <= MAX_DISKS; i++) {
5920 bs1 = bs_table[i];
5921 if (bdrv_has_snapshot(bs1)) {
5922 if (bs == bs1)
5923 term_printf(" %s", bdrv_get_device_name(bs1));
5926 term_printf("\n");
5928 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5929 if (nb_sns < 0) {
5930 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5931 return;
5933 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5934 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5935 for(i = 0; i < nb_sns; i++) {
5936 sn = &sn_tab[i];
5937 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5939 qemu_free(sn_tab);
5942 /***********************************************************/
5943 /* cpu save/restore */
5945 #if defined(TARGET_I386)
5947 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5949 qemu_put_be32(f, dt->selector);
5950 qemu_put_betl(f, dt->base);
5951 qemu_put_be32(f, dt->limit);
5952 qemu_put_be32(f, dt->flags);
5955 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5957 dt->selector = qemu_get_be32(f);
5958 dt->base = qemu_get_betl(f);
5959 dt->limit = qemu_get_be32(f);
5960 dt->flags = qemu_get_be32(f);
5963 void cpu_save(QEMUFile *f, void *opaque)
5965 CPUState *env = opaque;
5966 uint16_t fptag, fpus, fpuc, fpregs_format;
5967 uint32_t hflags;
5968 int i;
5970 #ifdef USE_KVM
5971 if (kvm_allowed)
5972 kvm_save_registers(env);
5973 #endif
5975 for(i = 0; i < CPU_NB_REGS; i++)
5976 qemu_put_betls(f, &env->regs[i]);
5977 qemu_put_betls(f, &env->eip);
5978 qemu_put_betls(f, &env->eflags);
5979 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5980 qemu_put_be32s(f, &hflags);
5982 /* FPU */
5983 fpuc = env->fpuc;
5984 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5985 fptag = 0;
5986 for(i = 0; i < 8; i++) {
5987 fptag |= ((!env->fptags[i]) << i);
5990 qemu_put_be16s(f, &fpuc);
5991 qemu_put_be16s(f, &fpus);
5992 qemu_put_be16s(f, &fptag);
5994 #ifdef USE_X86LDOUBLE
5995 fpregs_format = 0;
5996 #else
5997 fpregs_format = 1;
5998 #endif
5999 qemu_put_be16s(f, &fpregs_format);
6001 for(i = 0; i < 8; i++) {
6002 #ifdef USE_X86LDOUBLE
6004 uint64_t mant;
6005 uint16_t exp;
6006 /* we save the real CPU data (in case of MMX usage only 'mant'
6007 contains the MMX register */
6008 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6009 qemu_put_be64(f, mant);
6010 qemu_put_be16(f, exp);
6012 #else
6013 /* if we use doubles for float emulation, we save the doubles to
6014 avoid losing information in case of MMX usage. It can give
6015 problems if the image is restored on a CPU where long
6016 doubles are used instead. */
6017 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6018 #endif
6021 for(i = 0; i < 6; i++)
6022 cpu_put_seg(f, &env->segs[i]);
6023 cpu_put_seg(f, &env->ldt);
6024 cpu_put_seg(f, &env->tr);
6025 cpu_put_seg(f, &env->gdt);
6026 cpu_put_seg(f, &env->idt);
6028 qemu_put_be32s(f, &env->sysenter_cs);
6029 qemu_put_be32s(f, &env->sysenter_esp);
6030 qemu_put_be32s(f, &env->sysenter_eip);
6032 qemu_put_betls(f, &env->cr[0]);
6033 qemu_put_betls(f, &env->cr[2]);
6034 qemu_put_betls(f, &env->cr[3]);
6035 qemu_put_betls(f, &env->cr[4]);
6037 for(i = 0; i < 8; i++)
6038 qemu_put_betls(f, &env->dr[i]);
6040 /* MMU */
6041 qemu_put_be32s(f, &env->a20_mask);
6043 /* XMM */
6044 qemu_put_be32s(f, &env->mxcsr);
6045 for(i = 0; i < CPU_NB_REGS; i++) {
6046 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6047 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6050 #ifdef TARGET_X86_64
6051 qemu_put_be64s(f, &env->efer);
6052 qemu_put_be64s(f, &env->star);
6053 qemu_put_be64s(f, &env->lstar);
6054 qemu_put_be64s(f, &env->cstar);
6055 qemu_put_be64s(f, &env->fmask);
6056 qemu_put_be64s(f, &env->kernelgsbase);
6057 #endif
6058 qemu_put_be32s(f, &env->smbase);
6060 #ifdef USE_KVM
6061 if (kvm_allowed) {
6062 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6063 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6065 qemu_put_be64s(f, &env->tsc);
6067 #endif
6071 #ifdef USE_X86LDOUBLE
6072 /* XXX: add that in a FPU generic layer */
6073 union x86_longdouble {
6074 uint64_t mant;
6075 uint16_t exp;
6078 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6079 #define EXPBIAS1 1023
6080 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6081 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6083 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6085 int e;
6086 /* mantissa */
6087 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6088 /* exponent + sign */
6089 e = EXPD1(temp) - EXPBIAS1 + 16383;
6090 e |= SIGND1(temp) >> 16;
6091 p->exp = e;
6093 #endif
6095 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6097 CPUState *env = opaque;
6098 int i, guess_mmx;
6099 uint32_t hflags;
6100 uint16_t fpus, fpuc, fptag, fpregs_format;
6102 if (version_id != 3 && version_id != 4)
6103 return -EINVAL;
6104 for(i = 0; i < CPU_NB_REGS; i++)
6105 qemu_get_betls(f, &env->regs[i]);
6106 qemu_get_betls(f, &env->eip);
6107 qemu_get_betls(f, &env->eflags);
6108 qemu_get_be32s(f, &hflags);
6110 qemu_get_be16s(f, &fpuc);
6111 qemu_get_be16s(f, &fpus);
6112 qemu_get_be16s(f, &fptag);
6113 qemu_get_be16s(f, &fpregs_format);
6115 /* NOTE: we cannot always restore the FPU state if the image come
6116 from a host with a different 'USE_X86LDOUBLE' define. We guess
6117 if we are in an MMX state to restore correctly in that case. */
6118 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6119 for(i = 0; i < 8; i++) {
6120 uint64_t mant;
6121 uint16_t exp;
6123 switch(fpregs_format) {
6124 case 0:
6125 mant = qemu_get_be64(f);
6126 exp = qemu_get_be16(f);
6127 #ifdef USE_X86LDOUBLE
6128 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6129 #else
6130 /* difficult case */
6131 if (guess_mmx)
6132 env->fpregs[i].mmx.MMX_Q(0) = mant;
6133 else
6134 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6135 #endif
6136 break;
6137 case 1:
6138 mant = qemu_get_be64(f);
6139 #ifdef USE_X86LDOUBLE
6141 union x86_longdouble *p;
6142 /* difficult case */
6143 p = (void *)&env->fpregs[i];
6144 if (guess_mmx) {
6145 p->mant = mant;
6146 p->exp = 0xffff;
6147 } else {
6148 fp64_to_fp80(p, mant);
6151 #else
6152 env->fpregs[i].mmx.MMX_Q(0) = mant;
6153 #endif
6154 break;
6155 default:
6156 return -EINVAL;
6160 env->fpuc = fpuc;
6161 /* XXX: restore FPU round state */
6162 env->fpstt = (fpus >> 11) & 7;
6163 env->fpus = fpus & ~0x3800;
6164 fptag ^= 0xff;
6165 for(i = 0; i < 8; i++) {
6166 env->fptags[i] = (fptag >> i) & 1;
6169 for(i = 0; i < 6; i++)
6170 cpu_get_seg(f, &env->segs[i]);
6171 cpu_get_seg(f, &env->ldt);
6172 cpu_get_seg(f, &env->tr);
6173 cpu_get_seg(f, &env->gdt);
6174 cpu_get_seg(f, &env->idt);
6176 qemu_get_be32s(f, &env->sysenter_cs);
6177 qemu_get_be32s(f, &env->sysenter_esp);
6178 qemu_get_be32s(f, &env->sysenter_eip);
6180 qemu_get_betls(f, &env->cr[0]);
6181 qemu_get_betls(f, &env->cr[2]);
6182 qemu_get_betls(f, &env->cr[3]);
6183 qemu_get_betls(f, &env->cr[4]);
6185 for(i = 0; i < 8; i++)
6186 qemu_get_betls(f, &env->dr[i]);
6188 /* MMU */
6189 qemu_get_be32s(f, &env->a20_mask);
6191 qemu_get_be32s(f, &env->mxcsr);
6192 for(i = 0; i < CPU_NB_REGS; i++) {
6193 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6194 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6197 #ifdef TARGET_X86_64
6198 qemu_get_be64s(f, &env->efer);
6199 qemu_get_be64s(f, &env->star);
6200 qemu_get_be64s(f, &env->lstar);
6201 qemu_get_be64s(f, &env->cstar);
6202 qemu_get_be64s(f, &env->fmask);
6203 qemu_get_be64s(f, &env->kernelgsbase);
6204 #endif
6205 if (version_id >= 4)
6206 qemu_get_be32s(f, &env->smbase);
6208 /* XXX: compute hflags from scratch, except for CPL and IIF */
6209 env->hflags = hflags;
6210 tlb_flush(env, 1);
6211 #ifdef USE_KVM
6212 if (kvm_allowed) {
6213 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6214 because no userspace IRQs will ever clear this flag */
6215 env->hflags &= ~HF_HALTED_MASK;
6216 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6217 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6219 qemu_get_be64s(f, &env->tsc);
6220 kvm_load_registers(env);
6222 #endif
6223 return 0;
6226 #elif defined(TARGET_PPC)
6227 void cpu_save(QEMUFile *f, void *opaque)
6231 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6233 return 0;
6236 #elif defined(TARGET_MIPS)
6237 void cpu_save(QEMUFile *f, void *opaque)
6241 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6243 return 0;
6246 #elif defined(TARGET_SPARC)
6247 void cpu_save(QEMUFile *f, void *opaque)
6249 CPUState *env = opaque;
6250 int i;
6251 uint32_t tmp;
6253 for(i = 0; i < 8; i++)
6254 qemu_put_betls(f, &env->gregs[i]);
6255 for(i = 0; i < NWINDOWS * 16; i++)
6256 qemu_put_betls(f, &env->regbase[i]);
6258 /* FPU */
6259 for(i = 0; i < TARGET_FPREGS; i++) {
6260 union {
6261 float32 f;
6262 uint32_t i;
6263 } u;
6264 u.f = env->fpr[i];
6265 qemu_put_be32(f, u.i);
6268 qemu_put_betls(f, &env->pc);
6269 qemu_put_betls(f, &env->npc);
6270 qemu_put_betls(f, &env->y);
6271 tmp = GET_PSR(env);
6272 qemu_put_be32(f, tmp);
6273 qemu_put_betls(f, &env->fsr);
6274 qemu_put_betls(f, &env->tbr);
6275 #ifndef TARGET_SPARC64
6276 qemu_put_be32s(f, &env->wim);
6277 /* MMU */
6278 for(i = 0; i < 16; i++)
6279 qemu_put_be32s(f, &env->mmuregs[i]);
6280 #endif
6283 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6285 CPUState *env = opaque;
6286 int i;
6287 uint32_t tmp;
6289 for(i = 0; i < 8; i++)
6290 qemu_get_betls(f, &env->gregs[i]);
6291 for(i = 0; i < NWINDOWS * 16; i++)
6292 qemu_get_betls(f, &env->regbase[i]);
6294 /* FPU */
6295 for(i = 0; i < TARGET_FPREGS; i++) {
6296 union {
6297 float32 f;
6298 uint32_t i;
6299 } u;
6300 u.i = qemu_get_be32(f);
6301 env->fpr[i] = u.f;
6304 qemu_get_betls(f, &env->pc);
6305 qemu_get_betls(f, &env->npc);
6306 qemu_get_betls(f, &env->y);
6307 tmp = qemu_get_be32(f);
6308 env->cwp = 0; /* needed to ensure that the wrapping registers are
6309 correctly updated */
6310 PUT_PSR(env, tmp);
6311 qemu_get_betls(f, &env->fsr);
6312 qemu_get_betls(f, &env->tbr);
6313 #ifndef TARGET_SPARC64
6314 qemu_get_be32s(f, &env->wim);
6315 /* MMU */
6316 for(i = 0; i < 16; i++)
6317 qemu_get_be32s(f, &env->mmuregs[i]);
6318 #endif
6319 tlb_flush(env, 1);
6320 return 0;
6323 #elif defined(TARGET_ARM)
6325 void cpu_save(QEMUFile *f, void *opaque)
6327 int i;
6328 CPUARMState *env = (CPUARMState *)opaque;
6330 for (i = 0; i < 16; i++) {
6331 qemu_put_be32(f, env->regs[i]);
6333 qemu_put_be32(f, cpsr_read(env));
6334 qemu_put_be32(f, env->spsr);
6335 for (i = 0; i < 6; i++) {
6336 qemu_put_be32(f, env->banked_spsr[i]);
6337 qemu_put_be32(f, env->banked_r13[i]);
6338 qemu_put_be32(f, env->banked_r14[i]);
6340 for (i = 0; i < 5; i++) {
6341 qemu_put_be32(f, env->usr_regs[i]);
6342 qemu_put_be32(f, env->fiq_regs[i]);
6344 qemu_put_be32(f, env->cp15.c0_cpuid);
6345 qemu_put_be32(f, env->cp15.c0_cachetype);
6346 qemu_put_be32(f, env->cp15.c1_sys);
6347 qemu_put_be32(f, env->cp15.c1_coproc);
6348 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6349 qemu_put_be32(f, env->cp15.c2_base);
6350 qemu_put_be32(f, env->cp15.c2_data);
6351 qemu_put_be32(f, env->cp15.c2_insn);
6352 qemu_put_be32(f, env->cp15.c3);
6353 qemu_put_be32(f, env->cp15.c5_insn);
6354 qemu_put_be32(f, env->cp15.c5_data);
6355 for (i = 0; i < 8; i++) {
6356 qemu_put_be32(f, env->cp15.c6_region[i]);
6358 qemu_put_be32(f, env->cp15.c6_insn);
6359 qemu_put_be32(f, env->cp15.c6_data);
6360 qemu_put_be32(f, env->cp15.c9_insn);
6361 qemu_put_be32(f, env->cp15.c9_data);
6362 qemu_put_be32(f, env->cp15.c13_fcse);
6363 qemu_put_be32(f, env->cp15.c13_context);
6364 qemu_put_be32(f, env->cp15.c15_cpar);
6366 qemu_put_be32(f, env->features);
6368 if (arm_feature(env, ARM_FEATURE_VFP)) {
6369 for (i = 0; i < 16; i++) {
6370 CPU_DoubleU u;
6371 u.d = env->vfp.regs[i];
6372 qemu_put_be32(f, u.l.upper);
6373 qemu_put_be32(f, u.l.lower);
6375 for (i = 0; i < 16; i++) {
6376 qemu_put_be32(f, env->vfp.xregs[i]);
6379 /* TODO: Should use proper FPSCR access functions. */
6380 qemu_put_be32(f, env->vfp.vec_len);
6381 qemu_put_be32(f, env->vfp.vec_stride);
6384 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6385 for (i = 0; i < 16; i++) {
6386 qemu_put_be64(f, env->iwmmxt.regs[i]);
6388 for (i = 0; i < 16; i++) {
6389 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6394 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6396 CPUARMState *env = (CPUARMState *)opaque;
6397 int i;
6399 if (version_id != 0)
6400 return -EINVAL;
6402 for (i = 0; i < 16; i++) {
6403 env->regs[i] = qemu_get_be32(f);
6405 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6406 env->spsr = qemu_get_be32(f);
6407 for (i = 0; i < 6; i++) {
6408 env->banked_spsr[i] = qemu_get_be32(f);
6409 env->banked_r13[i] = qemu_get_be32(f);
6410 env->banked_r14[i] = qemu_get_be32(f);
6412 for (i = 0; i < 5; i++) {
6413 env->usr_regs[i] = qemu_get_be32(f);
6414 env->fiq_regs[i] = qemu_get_be32(f);
6416 env->cp15.c0_cpuid = qemu_get_be32(f);
6417 env->cp15.c0_cachetype = qemu_get_be32(f);
6418 env->cp15.c1_sys = qemu_get_be32(f);
6419 env->cp15.c1_coproc = qemu_get_be32(f);
6420 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6421 env->cp15.c2_base = qemu_get_be32(f);
6422 env->cp15.c2_data = qemu_get_be32(f);
6423 env->cp15.c2_insn = qemu_get_be32(f);
6424 env->cp15.c3 = qemu_get_be32(f);
6425 env->cp15.c5_insn = qemu_get_be32(f);
6426 env->cp15.c5_data = qemu_get_be32(f);
6427 for (i = 0; i < 8; i++) {
6428 env->cp15.c6_region[i] = qemu_get_be32(f);
6430 env->cp15.c6_insn = qemu_get_be32(f);
6431 env->cp15.c6_data = qemu_get_be32(f);
6432 env->cp15.c9_insn = qemu_get_be32(f);
6433 env->cp15.c9_data = qemu_get_be32(f);
6434 env->cp15.c13_fcse = qemu_get_be32(f);
6435 env->cp15.c13_context = qemu_get_be32(f);
6436 env->cp15.c15_cpar = qemu_get_be32(f);
6438 env->features = qemu_get_be32(f);
6440 if (arm_feature(env, ARM_FEATURE_VFP)) {
6441 for (i = 0; i < 16; i++) {
6442 CPU_DoubleU u;
6443 u.l.upper = qemu_get_be32(f);
6444 u.l.lower = qemu_get_be32(f);
6445 env->vfp.regs[i] = u.d;
6447 for (i = 0; i < 16; i++) {
6448 env->vfp.xregs[i] = qemu_get_be32(f);
6451 /* TODO: Should use proper FPSCR access functions. */
6452 env->vfp.vec_len = qemu_get_be32(f);
6453 env->vfp.vec_stride = qemu_get_be32(f);
6456 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6457 for (i = 0; i < 16; i++) {
6458 env->iwmmxt.regs[i] = qemu_get_be64(f);
6460 for (i = 0; i < 16; i++) {
6461 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6465 return 0;
6468 #else
6470 #warning No CPU save/restore functions
6472 #endif
6474 /***********************************************************/
6475 /* ram save/restore */
6477 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6479 int v;
6481 v = qemu_get_byte(f);
6482 switch(v) {
6483 case 0:
6484 if (qemu_get_buffer(f, buf, len) != len)
6485 return -EIO;
6486 break;
6487 case 1:
6488 v = qemu_get_byte(f);
6489 memset(buf, v, len);
6490 break;
6491 default:
6492 return -EINVAL;
6494 return 0;
6497 static int ram_load_v1(QEMUFile *f, void *opaque)
6499 int i, ret;
6501 if (qemu_get_be32(f) != phys_ram_size)
6502 return -EINVAL;
6503 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6504 #ifdef USE_KVM
6505 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
6506 continue;
6507 #endif
6508 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6509 if (ret)
6510 return ret;
6512 return 0;
6515 #define BDRV_HASH_BLOCK_SIZE 1024
6516 #define IOBUF_SIZE 4096
6517 #define RAM_CBLOCK_MAGIC 0xfabe
6519 typedef struct RamCompressState {
6520 z_stream zstream;
6521 QEMUFile *f;
6522 uint8_t buf[IOBUF_SIZE];
6523 } RamCompressState;
6525 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6527 int ret;
6528 memset(s, 0, sizeof(*s));
6529 s->f = f;
6530 ret = deflateInit2(&s->zstream, 1,
6531 Z_DEFLATED, 15,
6532 9, Z_DEFAULT_STRATEGY);
6533 if (ret != Z_OK)
6534 return -1;
6535 s->zstream.avail_out = IOBUF_SIZE;
6536 s->zstream.next_out = s->buf;
6537 return 0;
6540 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6542 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6543 qemu_put_be16(s->f, len);
6544 qemu_put_buffer(s->f, buf, len);
6547 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6549 int ret;
6551 s->zstream.avail_in = len;
6552 s->zstream.next_in = (uint8_t *)buf;
6553 while (s->zstream.avail_in > 0) {
6554 ret = deflate(&s->zstream, Z_NO_FLUSH);
6555 if (ret != Z_OK)
6556 return -1;
6557 if (s->zstream.avail_out == 0) {
6558 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6559 s->zstream.avail_out = IOBUF_SIZE;
6560 s->zstream.next_out = s->buf;
6563 return 0;
6566 static void ram_compress_close(RamCompressState *s)
6568 int len, ret;
6570 /* compress last bytes */
6571 for(;;) {
6572 ret = deflate(&s->zstream, Z_FINISH);
6573 if (ret == Z_OK || ret == Z_STREAM_END) {
6574 len = IOBUF_SIZE - s->zstream.avail_out;
6575 if (len > 0) {
6576 ram_put_cblock(s, s->buf, len);
6578 s->zstream.avail_out = IOBUF_SIZE;
6579 s->zstream.next_out = s->buf;
6580 if (ret == Z_STREAM_END)
6581 break;
6582 } else {
6583 goto fail;
6586 fail:
6587 deflateEnd(&s->zstream);
6590 typedef struct RamDecompressState {
6591 z_stream zstream;
6592 QEMUFile *f;
6593 uint8_t buf[IOBUF_SIZE];
6594 } RamDecompressState;
6596 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6598 int ret;
6599 memset(s, 0, sizeof(*s));
6600 s->f = f;
6601 ret = inflateInit(&s->zstream);
6602 if (ret != Z_OK)
6603 return -1;
6604 return 0;
6607 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6609 int ret, clen;
6611 s->zstream.avail_out = len;
6612 s->zstream.next_out = buf;
6613 while (s->zstream.avail_out > 0) {
6614 if (s->zstream.avail_in == 0) {
6615 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6616 return -1;
6617 clen = qemu_get_be16(s->f);
6618 if (clen > IOBUF_SIZE)
6619 return -1;
6620 qemu_get_buffer(s->f, s->buf, clen);
6621 s->zstream.avail_in = clen;
6622 s->zstream.next_in = s->buf;
6624 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6625 if (ret != Z_OK && ret != Z_STREAM_END) {
6626 return -1;
6629 return 0;
6632 static void ram_decompress_close(RamDecompressState *s)
6634 inflateEnd(&s->zstream);
6637 static void ram_save_live(QEMUFile *f, void *opaque)
6639 target_ulong addr;
6641 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
6642 #ifdef USE_KVM
6643 if (kvm_allowed && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
6644 continue;
6645 #endif
6646 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
6647 qemu_put_be32(f, addr);
6648 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
6651 qemu_put_be32(f, 1);
6654 static void ram_save_static(QEMUFile *f, void *opaque)
6656 int i;
6657 RamCompressState s1, *s = &s1;
6658 uint8_t buf[10];
6660 qemu_put_be32(f, phys_ram_size);
6661 if (ram_compress_open(s, f) < 0)
6662 return;
6663 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6664 #ifdef USE_KVM
6665 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
6666 continue;
6667 #endif
6668 #if 0
6669 if (tight_savevm_enabled) {
6670 int64_t sector_num;
6671 int j;
6673 /* find if the memory block is available on a virtual
6674 block device */
6675 sector_num = -1;
6676 for(j = 0; j < MAX_DISKS; j++) {
6677 if (bs_table[j]) {
6678 sector_num = bdrv_hash_find(bs_table[j],
6679 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6680 if (sector_num >= 0)
6681 break;
6684 if (j == MAX_DISKS)
6685 goto normal_compress;
6686 buf[0] = 1;
6687 buf[1] = j;
6688 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6689 ram_compress_buf(s, buf, 10);
6690 } else
6691 #endif
6693 // normal_compress:
6694 buf[0] = 0;
6695 ram_compress_buf(s, buf, 1);
6696 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6699 ram_compress_close(s);
6702 static void ram_save(QEMUFile *f, void *opaque)
6704 int in_migration = cpu_physical_memory_get_dirty_tracking();
6706 qemu_put_byte(f, in_migration);
6708 if (in_migration)
6709 ram_save_live(f, opaque);
6710 else
6711 ram_save_static(f, opaque);
6714 static int ram_load_live(QEMUFile *f, void *opaque)
6716 target_ulong addr;
6718 do {
6719 addr = qemu_get_be32(f);
6720 if (addr == 1)
6721 break;
6723 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
6724 } while (1);
6726 return 0;
6729 static int ram_load_static(QEMUFile *f, void *opaque)
6731 RamDecompressState s1, *s = &s1;
6732 uint8_t buf[10];
6733 int i;
6735 if (qemu_get_be32(f) != phys_ram_size)
6736 return -EINVAL;
6737 if (ram_decompress_open(s, f) < 0)
6738 return -EINVAL;
6739 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6740 #ifdef USE_KVM
6741 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
6742 continue;
6743 #endif
6744 if (ram_decompress_buf(s, buf, 1) < 0) {
6745 fprintf(stderr, "Error while reading ram block header\n");
6746 goto error;
6748 if (buf[0] == 0) {
6749 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6750 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6751 goto error;
6753 } else
6754 #if 0
6755 if (buf[0] == 1) {
6756 int bs_index;
6757 int64_t sector_num;
6759 ram_decompress_buf(s, buf + 1, 9);
6760 bs_index = buf[1];
6761 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6762 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6763 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6764 goto error;
6766 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6767 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6768 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6769 bs_index, sector_num);
6770 goto error;
6772 } else
6773 #endif
6775 error:
6776 printf("Error block header\n");
6777 return -EINVAL;
6780 ram_decompress_close(s);
6781 return 0;
6784 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6786 int ret;
6788 switch (version_id) {
6789 case 1:
6790 ret = ram_load_v1(f, opaque);
6791 break;
6792 case 3:
6793 if (qemu_get_byte(f)) {
6794 ret = ram_load_live(f, opaque);
6795 break;
6797 case 2:
6798 ret = ram_load_static(f, opaque);
6799 break;
6800 default:
6801 ret = -EINVAL;
6802 break;
6805 return ret;
6808 /***********************************************************/
6809 /* bottom halves (can be seen as timers which expire ASAP) */
6811 struct QEMUBH {
6812 QEMUBHFunc *cb;
6813 void *opaque;
6814 int scheduled;
6815 QEMUBH *next;
6818 static QEMUBH *first_bh = NULL;
6820 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6822 QEMUBH *bh;
6823 bh = qemu_mallocz(sizeof(QEMUBH));
6824 if (!bh)
6825 return NULL;
6826 bh->cb = cb;
6827 bh->opaque = opaque;
6828 return bh;
6831 int qemu_bh_poll(void)
6833 QEMUBH *bh, **pbh;
6834 int ret;
6836 ret = 0;
6837 for(;;) {
6838 pbh = &first_bh;
6839 bh = *pbh;
6840 if (!bh)
6841 break;
6842 ret = 1;
6843 *pbh = bh->next;
6844 bh->scheduled = 0;
6845 bh->cb(bh->opaque);
6847 return ret;
6850 void qemu_bh_schedule(QEMUBH *bh)
6852 CPUState *env = cpu_single_env;
6853 if (bh->scheduled)
6854 return;
6855 bh->scheduled = 1;
6856 bh->next = first_bh;
6857 first_bh = bh;
6859 /* stop the currently executing CPU to execute the BH ASAP */
6860 if (env) {
6861 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6865 void qemu_bh_cancel(QEMUBH *bh)
6867 QEMUBH **pbh;
6868 if (bh->scheduled) {
6869 pbh = &first_bh;
6870 while (*pbh != bh)
6871 pbh = &(*pbh)->next;
6872 *pbh = bh->next;
6873 bh->scheduled = 0;
6877 void qemu_bh_delete(QEMUBH *bh)
6879 qemu_bh_cancel(bh);
6880 qemu_free(bh);
6883 /***********************************************************/
6884 /* machine registration */
6886 QEMUMachine *first_machine = NULL;
6888 int qemu_register_machine(QEMUMachine *m)
6890 QEMUMachine **pm;
6891 pm = &first_machine;
6892 while (*pm != NULL)
6893 pm = &(*pm)->next;
6894 m->next = NULL;
6895 *pm = m;
6896 return 0;
6899 QEMUMachine *find_machine(const char *name)
6901 QEMUMachine *m;
6903 for(m = first_machine; m != NULL; m = m->next) {
6904 if (!strcmp(m->name, name))
6905 return m;
6907 return NULL;
6910 /***********************************************************/
6911 /* main execution loop */
6913 void gui_update(void *opaque)
6915 DisplayState *ds = opaque;
6916 ds->dpy_refresh(ds);
6917 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6920 struct vm_change_state_entry {
6921 VMChangeStateHandler *cb;
6922 void *opaque;
6923 LIST_ENTRY (vm_change_state_entry) entries;
6926 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6928 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6929 void *opaque)
6931 VMChangeStateEntry *e;
6933 e = qemu_mallocz(sizeof (*e));
6934 if (!e)
6935 return NULL;
6937 e->cb = cb;
6938 e->opaque = opaque;
6939 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6940 return e;
6943 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6945 LIST_REMOVE (e, entries);
6946 qemu_free (e);
6949 static void vm_state_notify(int running)
6951 VMChangeStateEntry *e;
6953 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6954 e->cb(e->opaque, running);
6958 /* XXX: support several handlers */
6959 static VMStopHandler *vm_stop_cb;
6960 static void *vm_stop_opaque;
6962 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6964 vm_stop_cb = cb;
6965 vm_stop_opaque = opaque;
6966 return 0;
6969 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6971 vm_stop_cb = NULL;
6974 void vm_start(void)
6976 if (!vm_running) {
6977 cpu_enable_ticks();
6978 vm_running = 1;
6979 vm_state_notify(1);
6980 qemu_rearm_alarm_timer(alarm_timer);
6984 void vm_stop(int reason)
6986 if (vm_running) {
6987 cpu_disable_ticks();
6988 vm_running = 0;
6989 if (reason != 0) {
6990 if (vm_stop_cb) {
6991 vm_stop_cb(vm_stop_opaque, reason);
6994 vm_state_notify(0);
6998 /* reset/shutdown handler */
7000 typedef struct QEMUResetEntry {
7001 QEMUResetHandler *func;
7002 void *opaque;
7003 struct QEMUResetEntry *next;
7004 } QEMUResetEntry;
7006 static QEMUResetEntry *first_reset_entry;
7007 static int reset_requested;
7008 static int shutdown_requested;
7009 static int powerdown_requested;
7011 int qemu_shutdown_requested(void)
7013 int r = shutdown_requested;
7014 shutdown_requested = 0;
7015 return r;
7018 int qemu_reset_requested(void)
7020 int r = reset_requested;
7021 reset_requested = 0;
7022 return r;
7025 int qemu_powerdown_requested(void)
7027 int r = powerdown_requested;
7028 powerdown_requested = 0;
7029 return r;
7032 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7034 QEMUResetEntry **pre, *re;
7036 pre = &first_reset_entry;
7037 while (*pre != NULL)
7038 pre = &(*pre)->next;
7039 re = qemu_mallocz(sizeof(QEMUResetEntry));
7040 re->func = func;
7041 re->opaque = opaque;
7042 re->next = NULL;
7043 *pre = re;
7046 void qemu_system_reset(void)
7048 QEMUResetEntry *re;
7050 /* reset all devices */
7051 for(re = first_reset_entry; re != NULL; re = re->next) {
7052 re->func(re->opaque);
7056 void qemu_system_reset_request(void)
7058 if (no_reboot) {
7059 shutdown_requested = 1;
7060 } else {
7061 reset_requested = 1;
7063 if (cpu_single_env)
7064 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7067 void qemu_system_shutdown_request(void)
7069 shutdown_requested = 1;
7070 if (cpu_single_env)
7071 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7074 void qemu_system_powerdown_request(void)
7076 powerdown_requested = 1;
7077 if (cpu_single_env)
7078 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7081 void main_loop_wait(int timeout)
7083 IOHandlerRecord *ioh;
7084 fd_set rfds, wfds, xfds;
7085 int ret, nfds;
7086 #ifdef _WIN32
7087 int ret2, i;
7088 #endif
7089 struct timeval tv;
7090 PollingEntry *pe;
7093 /* XXX: need to suppress polling by better using win32 events */
7094 ret = 0;
7095 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7096 ret |= pe->func(pe->opaque);
7098 #ifdef _WIN32
7099 if (ret == 0) {
7100 int err;
7101 WaitObjects *w = &wait_objects;
7103 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7104 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7105 if (w->func[ret - WAIT_OBJECT_0])
7106 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7108 /* Check for additional signaled events */
7109 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7111 /* Check if event is signaled */
7112 ret2 = WaitForSingleObject(w->events[i], 0);
7113 if(ret2 == WAIT_OBJECT_0) {
7114 if (w->func[i])
7115 w->func[i](w->opaque[i]);
7116 } else if (ret2 == WAIT_TIMEOUT) {
7117 } else {
7118 err = GetLastError();
7119 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7122 } else if (ret == WAIT_TIMEOUT) {
7123 } else {
7124 err = GetLastError();
7125 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7128 #endif
7129 /* poll any events */
7130 /* XXX: separate device handlers from system ones */
7131 nfds = -1;
7132 FD_ZERO(&rfds);
7133 FD_ZERO(&wfds);
7134 FD_ZERO(&xfds);
7135 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7136 if (ioh->deleted)
7137 continue;
7138 if (ioh->fd_read &&
7139 (!ioh->fd_read_poll ||
7140 ioh->fd_read_poll(ioh->opaque) != 0)) {
7141 FD_SET(ioh->fd, &rfds);
7142 if (ioh->fd > nfds)
7143 nfds = ioh->fd;
7145 if (ioh->fd_write) {
7146 FD_SET(ioh->fd, &wfds);
7147 if (ioh->fd > nfds)
7148 nfds = ioh->fd;
7152 tv.tv_sec = 0;
7153 #ifdef _WIN32
7154 tv.tv_usec = 0;
7155 #else
7156 tv.tv_usec = timeout * 1000;
7157 #endif
7158 #if defined(CONFIG_SLIRP)
7159 if (slirp_inited) {
7160 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7162 #endif
7163 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7164 if (ret > 0) {
7165 IOHandlerRecord **pioh;
7167 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7168 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7169 ioh->fd_read(ioh->opaque);
7171 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7172 ioh->fd_write(ioh->opaque);
7176 /* remove deleted IO handlers */
7177 pioh = &first_io_handler;
7178 while (*pioh) {
7179 ioh = *pioh;
7180 if (ioh->deleted) {
7181 *pioh = ioh->next;
7182 qemu_free(ioh);
7183 } else
7184 pioh = &ioh->next;
7187 #if defined(CONFIG_SLIRP)
7188 if (slirp_inited) {
7189 if (ret < 0) {
7190 FD_ZERO(&rfds);
7191 FD_ZERO(&wfds);
7192 FD_ZERO(&xfds);
7194 slirp_select_poll(&rfds, &wfds, &xfds);
7196 #endif
7197 qemu_aio_poll();
7199 if (vm_running) {
7200 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7201 qemu_get_clock(vm_clock));
7202 /* run dma transfers, if any */
7203 DMA_run();
7206 /* real time timers */
7207 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7208 qemu_get_clock(rt_clock));
7210 /* Check bottom-halves last in case any of the earlier events triggered
7211 them. */
7212 qemu_bh_poll();
7216 static CPUState *cur_cpu;
7218 int main_loop(void)
7220 int ret, timeout;
7221 #ifdef CONFIG_PROFILER
7222 int64_t ti;
7223 #endif
7224 CPUState *env;
7227 #ifdef USE_KVM
7228 if (kvm_allowed) {
7229 kvm_main_loop();
7230 cpu_disable_ticks();
7231 return 0;
7233 #endif
7234 cur_cpu = first_cpu;
7235 for(;;) {
7236 if (vm_running) {
7238 env = cur_cpu;
7239 for(;;) {
7240 /* get next cpu */
7241 env = env->next_cpu;
7242 if (!env)
7243 env = first_cpu;
7244 #ifdef CONFIG_PROFILER
7245 ti = profile_getclock();
7246 #endif
7247 ret = cpu_exec(env);
7248 #ifdef CONFIG_PROFILER
7249 qemu_time += profile_getclock() - ti;
7250 #endif
7251 if (ret == EXCP_HLT) {
7252 /* Give the next CPU a chance to run. */
7253 cur_cpu = env;
7254 continue;
7256 if (ret != EXCP_HALTED)
7257 break;
7258 /* all CPUs are halted ? */
7259 if (env == cur_cpu)
7260 break;
7262 cur_cpu = env;
7264 if (shutdown_requested) {
7265 ret = EXCP_INTERRUPT;
7266 break;
7268 if (reset_requested) {
7269 reset_requested = 0;
7270 qemu_system_reset();
7271 #ifdef USE_KVM
7272 if (kvm_allowed)
7273 kvm_load_registers(env);
7274 #endif
7275 ret = EXCP_INTERRUPT;
7277 if (powerdown_requested) {
7278 powerdown_requested = 0;
7279 qemu_system_powerdown();
7280 ret = EXCP_INTERRUPT;
7282 if (ret == EXCP_DEBUG) {
7283 vm_stop(EXCP_DEBUG);
7285 /* If all cpus are halted then wait until the next IRQ */
7286 /* XXX: use timeout computed from timers */
7287 if (ret == EXCP_HALTED)
7288 timeout = 10;
7289 else
7290 timeout = 0;
7291 } else {
7292 timeout = 10;
7294 #ifdef CONFIG_PROFILER
7295 ti = profile_getclock();
7296 #endif
7297 main_loop_wait(timeout);
7298 #ifdef CONFIG_PROFILER
7299 dev_time += profile_getclock() - ti;
7300 #endif
7302 cpu_disable_ticks();
7303 return ret;
7306 static void help(int exitcode)
7308 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7309 "usage: %s [options] [disk_image]\n"
7310 "\n"
7311 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7312 "\n"
7313 "Standard options:\n"
7314 "-M machine select emulated machine (-M ? for list)\n"
7315 "-cpu cpu select CPU (-cpu ? for list)\n"
7316 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7317 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7318 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7319 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7320 "-mtdblock file use 'file' as on-board Flash memory image\n"
7321 "-sd file use 'file' as SecureDigital card image\n"
7322 "-pflash file use 'file' as a parallel flash image\n"
7323 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7324 "-snapshot write to temporary files instead of disk image files\n"
7325 #ifdef CONFIG_SDL
7326 "-no-frame open SDL window without a frame and window decorations\n"
7327 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7328 "-no-quit disable SDL window close capability\n"
7329 #endif
7330 #ifdef TARGET_I386
7331 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7332 #endif
7333 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7334 "-smp n set the number of CPUs to 'n' [default=1]\n"
7335 "-nographic disable graphical output and redirect serial I/Os to console\n"
7336 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7337 #ifndef _WIN32
7338 "-k language use keyboard layout (for example \"fr\" for French)\n"
7339 #endif
7340 #ifdef HAS_AUDIO
7341 "-audio-help print list of audio drivers and their options\n"
7342 "-soundhw c1,... enable audio support\n"
7343 " and only specified sound cards (comma separated list)\n"
7344 " use -soundhw ? to get the list of supported cards\n"
7345 " use -soundhw all to enable all of them\n"
7346 #endif
7347 "-localtime set the real time clock to local time [default=utc]\n"
7348 "-full-screen start in full screen\n"
7349 #ifdef TARGET_I386
7350 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7351 #endif
7352 "-usb enable the USB driver (will be the default soon)\n"
7353 "-usbdevice name add the host or guest USB device 'name'\n"
7354 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7355 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7356 #endif
7357 "-name string set the name of the guest\n"
7358 "\n"
7359 "Network options:\n"
7360 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7361 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7362 #ifdef CONFIG_SLIRP
7363 "-net user[,vlan=n][,hostname=host]\n"
7364 " connect the user mode network stack to VLAN 'n' and send\n"
7365 " hostname 'host' to DHCP clients\n"
7366 #endif
7367 #ifdef _WIN32
7368 "-net tap[,vlan=n],ifname=name\n"
7369 " connect the host TAP network interface to VLAN 'n'\n"
7370 #else
7371 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
7372 " connect the host TAP network interface to VLAN 'n' and use\n"
7373 " the network script 'file' (default=%s);\n"
7374 " use 'script=no' to disable script execution;\n"
7375 " use 'fd=h' to connect to an already opened TAP interface\n"
7376 #endif
7377 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7378 " connect the vlan 'n' to another VLAN using a socket connection\n"
7379 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7380 " connect the vlan 'n' to multicast maddr and port\n"
7381 "-net none use it alone to have zero network devices; if no -net option\n"
7382 " is provided, the default is '-net nic -net user'\n"
7383 "\n"
7384 #ifdef CONFIG_SLIRP
7385 "-tftp dir allow tftp access to files in dir [-net user]\n"
7386 "-bootp file advertise file in BOOTP replies\n"
7387 #ifndef _WIN32
7388 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7389 #endif
7390 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7391 " redirect TCP or UDP connections from host to guest [-net user]\n"
7392 #endif
7393 "\n"
7394 "Linux boot specific:\n"
7395 "-kernel bzImage use 'bzImage' as kernel image\n"
7396 "-append cmdline use 'cmdline' as kernel command line\n"
7397 "-initrd file use 'file' as initial ram disk\n"
7398 "\n"
7399 "Debug/Expert options:\n"
7400 "-monitor dev redirect the monitor to char device 'dev'\n"
7401 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
7402 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
7403 "-serial dev redirect the serial port to char device 'dev'\n"
7404 "-parallel dev redirect the parallel port to char device 'dev'\n"
7405 "-pidfile file Write PID to 'file'\n"
7406 "-S freeze CPU at startup (use 'c' to start execution)\n"
7407 "-s wait gdb connection to port\n"
7408 "-p port set gdb connection port [default=%s]\n"
7409 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7410 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7411 " translation (t=none or lba) (usually qemu can guess them)\n"
7412 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7413 #ifdef USE_KQEMU
7414 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7415 "-no-kqemu disable KQEMU kernel module usage\n"
7416 #endif
7417 #ifdef USE_KVM
7418 "-no-kvm disable KVM hardware virtualization\n"
7419 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
7420 #endif
7421 #ifdef USE_CODE_COPY
7422 "-no-code-copy disable code copy acceleration\n"
7423 #endif
7424 #ifdef TARGET_I386
7425 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7426 " (default is CL-GD5446 PCI VGA)\n"
7427 "-no-acpi disable ACPI\n"
7428 #endif
7429 "-no-reboot exit instead of rebooting\n"
7430 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7431 "-vnc display start a VNC server on display\n"
7432 #ifndef _WIN32
7433 "-daemonize daemonize QEMU after initializing\n"
7434 #endif
7435 "-tdf inject timer interrupts that got lost\n"
7436 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
7437 "-option-rom rom load a file, rom, into the option ROM space\n"
7438 #ifdef TARGET_SPARC
7439 "-prom-env variable=value set OpenBIOS nvram variables\n"
7440 #endif
7441 "-clock force the use of the given methods for timer alarm.\n"
7442 " To see what timers are available use -clock help\n"
7443 "\n"
7444 "During emulation, the following keys are useful:\n"
7445 "ctrl-alt-f toggle full screen\n"
7446 "ctrl-alt-n switch to virtual console 'n'\n"
7447 "ctrl-alt toggle mouse and keyboard grab\n"
7448 "\n"
7449 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7451 "qemu",
7452 DEFAULT_RAM_SIZE,
7453 #ifndef _WIN32
7454 DEFAULT_NETWORK_SCRIPT,
7455 #endif
7456 DEFAULT_GDBSTUB_PORT,
7457 "/tmp/qemu.log");
7458 exit(exitcode);
7461 #define HAS_ARG 0x0001
7463 enum {
7464 QEMU_OPTION_h,
7466 QEMU_OPTION_M,
7467 QEMU_OPTION_cpu,
7468 QEMU_OPTION_fda,
7469 QEMU_OPTION_fdb,
7470 QEMU_OPTION_hda,
7471 QEMU_OPTION_hdb,
7472 QEMU_OPTION_hdc,
7473 QEMU_OPTION_hdd,
7474 QEMU_OPTION_cdrom,
7475 QEMU_OPTION_mtdblock,
7476 QEMU_OPTION_sd,
7477 QEMU_OPTION_pflash,
7478 QEMU_OPTION_boot,
7479 QEMU_OPTION_snapshot,
7480 #ifdef TARGET_I386
7481 QEMU_OPTION_no_fd_bootchk,
7482 #endif
7483 QEMU_OPTION_m,
7484 QEMU_OPTION_nographic,
7485 QEMU_OPTION_portrait,
7486 #ifdef HAS_AUDIO
7487 QEMU_OPTION_audio_help,
7488 QEMU_OPTION_soundhw,
7489 #endif
7491 QEMU_OPTION_net,
7492 QEMU_OPTION_tftp,
7493 QEMU_OPTION_bootp,
7494 QEMU_OPTION_smb,
7495 QEMU_OPTION_redir,
7497 QEMU_OPTION_kernel,
7498 QEMU_OPTION_append,
7499 QEMU_OPTION_initrd,
7501 QEMU_OPTION_S,
7502 QEMU_OPTION_s,
7503 QEMU_OPTION_p,
7504 QEMU_OPTION_d,
7505 QEMU_OPTION_hdachs,
7506 QEMU_OPTION_L,
7507 QEMU_OPTION_no_code_copy,
7508 QEMU_OPTION_k,
7509 QEMU_OPTION_localtime,
7510 QEMU_OPTION_cirrusvga,
7511 QEMU_OPTION_vmsvga,
7512 QEMU_OPTION_g,
7513 QEMU_OPTION_std_vga,
7514 QEMU_OPTION_echr,
7515 QEMU_OPTION_monitor,
7516 QEMU_OPTION_balloon,
7517 QEMU_OPTION_vmchannel,
7518 QEMU_OPTION_serial,
7519 QEMU_OPTION_parallel,
7520 QEMU_OPTION_loadvm,
7521 QEMU_OPTION_full_screen,
7522 QEMU_OPTION_no_frame,
7523 QEMU_OPTION_alt_grab,
7524 QEMU_OPTION_no_quit,
7525 QEMU_OPTION_pidfile,
7526 QEMU_OPTION_no_kqemu,
7527 QEMU_OPTION_kernel_kqemu,
7528 QEMU_OPTION_win2k_hack,
7529 QEMU_OPTION_usb,
7530 QEMU_OPTION_usbdevice,
7531 QEMU_OPTION_smp,
7532 QEMU_OPTION_vnc,
7533 QEMU_OPTION_no_acpi,
7534 QEMU_OPTION_no_kvm,
7535 QEMU_OPTION_no_kvm_irqchip,
7536 QEMU_OPTION_no_reboot,
7537 QEMU_OPTION_show_cursor,
7538 QEMU_OPTION_daemonize,
7539 QEMU_OPTION_option_rom,
7540 QEMU_OPTION_semihosting,
7541 QEMU_OPTION_cpu_vendor,
7542 QEMU_OPTION_name,
7543 QEMU_OPTION_prom_env,
7544 QEMU_OPTION_old_param,
7545 QEMU_OPTION_clock,
7546 QEMU_OPTION_incoming,
7547 QEMU_OPTION_tdf,
7548 QEMU_OPTION_kvm_shadow_memory,
7551 typedef struct QEMUOption {
7552 const char *name;
7553 int flags;
7554 int index;
7555 } QEMUOption;
7557 const QEMUOption qemu_options[] = {
7558 { "h", 0, QEMU_OPTION_h },
7559 { "help", 0, QEMU_OPTION_h },
7561 { "M", HAS_ARG, QEMU_OPTION_M },
7562 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7563 { "fda", HAS_ARG, QEMU_OPTION_fda },
7564 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7565 { "hda", HAS_ARG, QEMU_OPTION_hda },
7566 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7567 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7568 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7569 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7570 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7571 { "sd", HAS_ARG, QEMU_OPTION_sd },
7572 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7573 { "boot", HAS_ARG, QEMU_OPTION_boot },
7574 { "snapshot", 0, QEMU_OPTION_snapshot },
7575 #ifdef TARGET_I386
7576 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7577 #endif
7578 { "m", HAS_ARG, QEMU_OPTION_m },
7579 { "nographic", 0, QEMU_OPTION_nographic },
7580 { "portrait", 0, QEMU_OPTION_portrait },
7581 { "k", HAS_ARG, QEMU_OPTION_k },
7582 #ifdef HAS_AUDIO
7583 { "audio-help", 0, QEMU_OPTION_audio_help },
7584 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7585 #endif
7587 { "net", HAS_ARG, QEMU_OPTION_net},
7588 #ifdef CONFIG_SLIRP
7589 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7590 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7591 #ifndef _WIN32
7592 { "smb", HAS_ARG, QEMU_OPTION_smb },
7593 #endif
7594 { "redir", HAS_ARG, QEMU_OPTION_redir },
7595 #endif
7597 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7598 { "append", HAS_ARG, QEMU_OPTION_append },
7599 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7601 { "S", 0, QEMU_OPTION_S },
7602 { "s", 0, QEMU_OPTION_s },
7603 { "p", HAS_ARG, QEMU_OPTION_p },
7604 { "d", HAS_ARG, QEMU_OPTION_d },
7605 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7606 { "L", HAS_ARG, QEMU_OPTION_L },
7607 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7608 #ifdef USE_KQEMU
7609 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7610 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7611 #endif
7612 #ifdef USE_KVM
7613 { "no-kvm", 0, QEMU_OPTION_no_kvm },
7614 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
7615 #endif
7616 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7617 { "g", 1, QEMU_OPTION_g },
7618 #endif
7619 { "localtime", 0, QEMU_OPTION_localtime },
7620 { "std-vga", 0, QEMU_OPTION_std_vga },
7621 { "monitor", 1, QEMU_OPTION_monitor },
7622 { "balloon", 1, QEMU_OPTION_balloon },
7623 { "vmchannel", 1, QEMU_OPTION_vmchannel },
7624 { "echr", HAS_ARG, QEMU_OPTION_echr },
7625 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7626 { "serial", HAS_ARG, QEMU_OPTION_serial },
7627 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7628 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7629 { "incoming", 1, QEMU_OPTION_incoming },
7630 { "full-screen", 0, QEMU_OPTION_full_screen },
7631 #ifdef CONFIG_SDL
7632 { "no-frame", 0, QEMU_OPTION_no_frame },
7633 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7634 { "no-quit", 0, QEMU_OPTION_no_quit },
7635 #endif
7636 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7637 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7638 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7639 { "smp", HAS_ARG, QEMU_OPTION_smp },
7640 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7642 /* temporary options */
7643 { "usb", 0, QEMU_OPTION_usb },
7644 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7645 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7646 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7647 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7648 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7649 { "daemonize", 0, QEMU_OPTION_daemonize },
7650 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7651 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7652 { "semihosting", 0, QEMU_OPTION_semihosting },
7653 #endif
7654 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
7655 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
7656 { "name", HAS_ARG, QEMU_OPTION_name },
7657 #if defined(TARGET_SPARC)
7658 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7659 #endif
7660 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
7661 #if defined(TARGET_ARM)
7662 { "old-param", 0, QEMU_OPTION_old_param },
7663 #endif
7664 { "clock", HAS_ARG, QEMU_OPTION_clock },
7665 { NULL },
7668 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
7670 /* this stack is only used during signal handling */
7671 #define SIGNAL_STACK_SIZE 32768
7673 static uint8_t *signal_stack;
7675 #endif
7677 /* password input */
7679 int qemu_key_check(BlockDriverState *bs, const char *name)
7681 char password[256];
7682 int i;
7684 if (!bdrv_is_encrypted(bs))
7685 return 0;
7687 term_printf("%s is encrypted.\n", name);
7688 for(i = 0; i < 3; i++) {
7689 monitor_readline("Password: ", 1, password, sizeof(password));
7690 if (bdrv_set_key(bs, password) == 0)
7691 return 0;
7692 term_printf("invalid password\n");
7694 return -EPERM;
7697 static BlockDriverState *get_bdrv(int index)
7699 BlockDriverState *bs;
7701 if (index < 4) {
7702 bs = bs_table[index];
7703 } else if (index < 6) {
7704 bs = fd_table[index - 4];
7705 } else {
7706 bs = NULL;
7708 return bs;
7711 static void read_passwords(void)
7713 BlockDriverState *bs;
7714 int i;
7716 for(i = 0; i < 6; i++) {
7717 bs = get_bdrv(i);
7718 if (bs)
7719 qemu_key_check(bs, bdrv_get_device_name(bs));
7723 /* XXX: currently we cannot use simultaneously different CPUs */
7724 void register_machines(void)
7726 #if defined(TARGET_I386)
7727 qemu_register_machine(&pc_machine);
7728 qemu_register_machine(&isapc_machine);
7729 #elif defined(TARGET_PPC)
7730 qemu_register_machine(&heathrow_machine);
7731 qemu_register_machine(&core99_machine);
7732 qemu_register_machine(&prep_machine);
7733 qemu_register_machine(&ref405ep_machine);
7734 qemu_register_machine(&taihu_machine);
7735 #elif defined(TARGET_MIPS)
7736 qemu_register_machine(&mips_machine);
7737 qemu_register_machine(&mips_malta_machine);
7738 qemu_register_machine(&mips_pica61_machine);
7739 #elif defined(TARGET_SPARC)
7740 #ifdef TARGET_SPARC64
7741 qemu_register_machine(&sun4u_machine);
7742 #else
7743 qemu_register_machine(&ss5_machine);
7744 qemu_register_machine(&ss10_machine);
7745 #endif
7746 #elif defined(TARGET_ARM)
7747 qemu_register_machine(&integratorcp_machine);
7748 qemu_register_machine(&versatilepb_machine);
7749 qemu_register_machine(&versatileab_machine);
7750 qemu_register_machine(&realview_machine);
7751 qemu_register_machine(&akitapda_machine);
7752 qemu_register_machine(&spitzpda_machine);
7753 qemu_register_machine(&borzoipda_machine);
7754 qemu_register_machine(&terrierpda_machine);
7755 qemu_register_machine(&palmte_machine);
7756 #elif defined(TARGET_SH4)
7757 qemu_register_machine(&shix_machine);
7758 qemu_register_machine(&r2d_machine);
7759 #elif defined(TARGET_ALPHA)
7760 /* XXX: TODO */
7761 #elif defined(TARGET_M68K)
7762 qemu_register_machine(&mcf5208evb_machine);
7763 qemu_register_machine(&an5206_machine);
7764 #else
7765 #error unsupported CPU
7766 #endif
7769 #ifdef HAS_AUDIO
7770 struct soundhw soundhw[] = {
7771 #ifdef HAS_AUDIO_CHOICE
7772 #ifdef TARGET_I386
7774 "pcspk",
7775 "PC speaker",
7778 { .init_isa = pcspk_audio_init }
7780 #endif
7782 "sb16",
7783 "Creative Sound Blaster 16",
7786 { .init_isa = SB16_init }
7789 #ifdef CONFIG_ADLIB
7791 "adlib",
7792 #ifdef HAS_YMF262
7793 "Yamaha YMF262 (OPL3)",
7794 #else
7795 "Yamaha YM3812 (OPL2)",
7796 #endif
7799 { .init_isa = Adlib_init }
7801 #endif
7803 #ifdef CONFIG_GUS
7805 "gus",
7806 "Gravis Ultrasound GF1",
7809 { .init_isa = GUS_init }
7811 #endif
7814 "es1370",
7815 "ENSONIQ AudioPCI ES1370",
7818 { .init_pci = es1370_init }
7820 #endif
7822 { NULL, NULL, 0, 0, { NULL } }
7825 static void select_soundhw (const char *optarg)
7827 struct soundhw *c;
7829 if (*optarg == '?') {
7830 show_valid_cards:
7832 printf ("Valid sound card names (comma separated):\n");
7833 for (c = soundhw; c->name; ++c) {
7834 printf ("%-11s %s\n", c->name, c->descr);
7836 printf ("\n-soundhw all will enable all of the above\n");
7837 exit (*optarg != '?');
7839 else {
7840 size_t l;
7841 const char *p;
7842 char *e;
7843 int bad_card = 0;
7845 if (!strcmp (optarg, "all")) {
7846 for (c = soundhw; c->name; ++c) {
7847 c->enabled = 1;
7849 return;
7852 p = optarg;
7853 while (*p) {
7854 e = strchr (p, ',');
7855 l = !e ? strlen (p) : (size_t) (e - p);
7857 for (c = soundhw; c->name; ++c) {
7858 if (!strncmp (c->name, p, l)) {
7859 c->enabled = 1;
7860 break;
7864 if (!c->name) {
7865 if (l > 80) {
7866 fprintf (stderr,
7867 "Unknown sound card name (too big to show)\n");
7869 else {
7870 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7871 (int) l, p);
7873 bad_card = 1;
7875 p += l + (e != NULL);
7878 if (bad_card)
7879 goto show_valid_cards;
7882 #endif
7884 #ifdef _WIN32
7885 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7887 exit(STATUS_CONTROL_C_EXIT);
7888 return TRUE;
7890 #endif
7892 #define MAX_NET_CLIENTS 32
7894 static int saved_argc;
7895 static char **saved_argv;
7897 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
7899 *argc = saved_argc;
7900 *argv = saved_argv;
7901 *opt_daemonize = daemonize;
7902 *opt_incoming = incoming;
7905 int main(int argc, char **argv)
7907 #ifdef CONFIG_GDBSTUB
7908 int use_gdbstub;
7909 const char *gdbstub_port;
7910 #endif
7911 int i, cdrom_index, pflash_index;
7912 int snapshot, linux_boot;
7913 const char *initrd_filename;
7914 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7915 const char *pflash_filename[MAX_PFLASH];
7916 const char *sd_filename;
7917 const char *mtd_filename;
7918 const char *kernel_filename, *kernel_cmdline;
7919 DisplayState *ds = &display_state;
7920 int cyls, heads, secs, translation;
7921 char net_clients[MAX_NET_CLIENTS][256];
7922 int nb_net_clients;
7923 int optind;
7924 const char *r, *optarg;
7925 CharDriverState *monitor_hd;
7926 char monitor_device[128];
7927 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
7928 int vmchannel_device_index;
7929 char serial_devices[MAX_SERIAL_PORTS][128];
7930 int serial_device_index;
7931 char parallel_devices[MAX_PARALLEL_PORTS][128];
7932 int parallel_device_index;
7933 const char *loadvm = NULL;
7934 QEMUMachine *machine;
7935 const char *cpu_model;
7936 char usb_devices[MAX_USB_CMDLINE][128];
7937 int usb_devices_index;
7938 int fds[2];
7939 const char *pid_file = NULL;
7940 VLANState *vlan;
7942 saved_argc = argc;
7943 saved_argv = argv;
7945 LIST_INIT (&vm_change_state_head);
7946 #ifndef _WIN32
7948 struct sigaction act;
7949 sigfillset(&act.sa_mask);
7950 act.sa_flags = 0;
7951 act.sa_handler = SIG_IGN;
7952 sigaction(SIGPIPE, &act, NULL);
7954 #else
7955 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7956 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7957 QEMU to run on a single CPU */
7959 HANDLE h;
7960 DWORD mask, smask;
7961 int i;
7962 h = GetCurrentProcess();
7963 if (GetProcessAffinityMask(h, &mask, &smask)) {
7964 for(i = 0; i < 32; i++) {
7965 if (mask & (1 << i))
7966 break;
7968 if (i != 32) {
7969 mask = 1 << i;
7970 SetProcessAffinityMask(h, mask);
7974 #endif
7976 register_machines();
7977 machine = first_machine;
7978 cpu_model = NULL;
7979 initrd_filename = NULL;
7980 for(i = 0; i < MAX_FD; i++)
7981 fd_filename[i] = NULL;
7982 for(i = 0; i < MAX_DISKS; i++)
7983 hd_filename[i] = NULL;
7984 for(i = 0; i < MAX_PFLASH; i++)
7985 pflash_filename[i] = NULL;
7986 pflash_index = 0;
7987 sd_filename = NULL;
7988 mtd_filename = NULL;
7989 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7990 vga_ram_size = VGA_RAM_SIZE;
7991 #ifdef CONFIG_GDBSTUB
7992 use_gdbstub = 0;
7993 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7994 #endif
7995 snapshot = 0;
7996 nographic = 0;
7997 kernel_filename = NULL;
7998 kernel_cmdline = "";
7999 #ifdef TARGET_PPC
8000 cdrom_index = 1;
8001 #else
8002 cdrom_index = 2;
8003 #endif
8004 cyls = heads = secs = 0;
8005 translation = BIOS_ATA_TRANSLATION_AUTO;
8006 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8008 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8009 vmchannel_devices[i][0] = '\0';
8010 vmchannel_device_index = 0;
8012 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8013 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8014 serial_devices[i][0] = '\0';
8015 serial_device_index = 0;
8017 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8018 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8019 parallel_devices[i][0] = '\0';
8020 parallel_device_index = 0;
8022 usb_devices_index = 0;
8024 nb_net_clients = 0;
8026 nb_nics = 0;
8027 /* default mac address of the first network interface */
8029 optind = 1;
8030 for(;;) {
8031 if (optind >= argc)
8032 break;
8033 r = argv[optind];
8034 if (r[0] != '-') {
8035 hd_filename[0] = argv[optind++];
8036 } else {
8037 const QEMUOption *popt;
8039 optind++;
8040 /* Treat --foo the same as -foo. */
8041 if (r[1] == '-')
8042 r++;
8043 popt = qemu_options;
8044 for(;;) {
8045 if (!popt->name) {
8046 fprintf(stderr, "%s: invalid option -- '%s'\n",
8047 argv[0], r);
8048 exit(1);
8050 if (!strcmp(popt->name, r + 1))
8051 break;
8052 popt++;
8054 if (popt->flags & HAS_ARG) {
8055 if (optind >= argc) {
8056 fprintf(stderr, "%s: option '%s' requires an argument\n",
8057 argv[0], r);
8058 exit(1);
8060 optarg = argv[optind++];
8061 } else {
8062 optarg = NULL;
8065 switch(popt->index) {
8066 case QEMU_OPTION_M:
8067 machine = find_machine(optarg);
8068 if (!machine) {
8069 QEMUMachine *m;
8070 printf("Supported machines are:\n");
8071 for(m = first_machine; m != NULL; m = m->next) {
8072 printf("%-10s %s%s\n",
8073 m->name, m->desc,
8074 m == first_machine ? " (default)" : "");
8076 exit(*optarg != '?');
8078 break;
8079 case QEMU_OPTION_cpu:
8080 /* hw initialization will check this */
8081 if (*optarg == '?') {
8082 #if defined(TARGET_PPC)
8083 ppc_cpu_list(stdout, &fprintf);
8084 #elif defined(TARGET_ARM)
8085 arm_cpu_list();
8086 #elif defined(TARGET_MIPS)
8087 mips_cpu_list(stdout, &fprintf);
8088 #elif defined(TARGET_SPARC)
8089 sparc_cpu_list(stdout, &fprintf);
8090 #endif
8091 exit(0);
8092 } else {
8093 cpu_model = optarg;
8095 break;
8096 case QEMU_OPTION_initrd:
8097 initrd_filename = optarg;
8098 break;
8099 case QEMU_OPTION_hda:
8100 case QEMU_OPTION_hdb:
8101 case QEMU_OPTION_hdc:
8102 case QEMU_OPTION_hdd:
8104 int hd_index;
8105 hd_index = popt->index - QEMU_OPTION_hda;
8106 hd_filename[hd_index] = optarg;
8107 if (hd_index == cdrom_index)
8108 cdrom_index = -1;
8110 break;
8111 case QEMU_OPTION_mtdblock:
8112 mtd_filename = optarg;
8113 break;
8114 case QEMU_OPTION_sd:
8115 sd_filename = optarg;
8116 break;
8117 case QEMU_OPTION_pflash:
8118 if (pflash_index >= MAX_PFLASH) {
8119 fprintf(stderr, "qemu: too many parallel flash images\n");
8120 exit(1);
8122 pflash_filename[pflash_index++] = optarg;
8123 break;
8124 case QEMU_OPTION_snapshot:
8125 snapshot = 1;
8126 break;
8127 case QEMU_OPTION_hdachs:
8129 const char *p;
8130 p = optarg;
8131 cyls = strtol(p, (char **)&p, 0);
8132 if (cyls < 1 || cyls > 16383)
8133 goto chs_fail;
8134 if (*p != ',')
8135 goto chs_fail;
8136 p++;
8137 heads = strtol(p, (char **)&p, 0);
8138 if (heads < 1 || heads > 16)
8139 goto chs_fail;
8140 if (*p != ',')
8141 goto chs_fail;
8142 p++;
8143 secs = strtol(p, (char **)&p, 0);
8144 if (secs < 1 || secs > 63)
8145 goto chs_fail;
8146 if (*p == ',') {
8147 p++;
8148 if (!strcmp(p, "none"))
8149 translation = BIOS_ATA_TRANSLATION_NONE;
8150 else if (!strcmp(p, "lba"))
8151 translation = BIOS_ATA_TRANSLATION_LBA;
8152 else if (!strcmp(p, "auto"))
8153 translation = BIOS_ATA_TRANSLATION_AUTO;
8154 else
8155 goto chs_fail;
8156 } else if (*p != '\0') {
8157 chs_fail:
8158 fprintf(stderr, "qemu: invalid physical CHS format\n");
8159 exit(1);
8162 break;
8163 case QEMU_OPTION_nographic:
8164 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8165 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8166 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8167 nographic = 1;
8168 break;
8169 case QEMU_OPTION_portrait:
8170 graphic_rotate = 1;
8171 break;
8172 case QEMU_OPTION_kernel:
8173 kernel_filename = optarg;
8174 break;
8175 case QEMU_OPTION_append:
8176 kernel_cmdline = optarg;
8177 break;
8178 case QEMU_OPTION_cdrom:
8179 if (cdrom_index >= 0) {
8180 hd_filename[cdrom_index] = optarg;
8182 break;
8183 case QEMU_OPTION_boot:
8184 boot_device = optarg[0];
8185 if (boot_device != 'a' &&
8186 #if defined(TARGET_SPARC) || defined(TARGET_I386)
8187 // Network boot
8188 boot_device != 'n' &&
8189 #endif
8190 boot_device != 'c' && boot_device != 'd') {
8191 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
8192 exit(1);
8194 break;
8195 case QEMU_OPTION_fda:
8196 fd_filename[0] = optarg;
8197 break;
8198 case QEMU_OPTION_fdb:
8199 fd_filename[1] = optarg;
8200 break;
8201 #ifdef TARGET_I386
8202 case QEMU_OPTION_no_fd_bootchk:
8203 fd_bootchk = 0;
8204 break;
8205 #endif
8206 case QEMU_OPTION_no_code_copy:
8207 code_copy_enabled = 0;
8208 break;
8209 case QEMU_OPTION_net:
8210 if (nb_net_clients >= MAX_NET_CLIENTS) {
8211 fprintf(stderr, "qemu: too many network clients\n");
8212 exit(1);
8214 pstrcpy(net_clients[nb_net_clients],
8215 sizeof(net_clients[0]),
8216 optarg);
8217 nb_net_clients++;
8218 break;
8219 #ifdef CONFIG_SLIRP
8220 case QEMU_OPTION_tftp:
8221 tftp_prefix = optarg;
8222 break;
8223 case QEMU_OPTION_bootp:
8224 bootp_filename = optarg;
8225 break;
8226 #ifndef _WIN32
8227 case QEMU_OPTION_smb:
8228 net_slirp_smb(optarg);
8229 break;
8230 #endif
8231 case QEMU_OPTION_redir:
8232 net_slirp_redir(optarg);
8233 break;
8234 #endif
8235 #ifdef HAS_AUDIO
8236 case QEMU_OPTION_audio_help:
8237 AUD_help ();
8238 exit (0);
8239 break;
8240 case QEMU_OPTION_soundhw:
8241 select_soundhw (optarg);
8242 break;
8243 #endif
8244 case QEMU_OPTION_h:
8245 help(0);
8246 break;
8247 case QEMU_OPTION_m:
8248 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
8249 if (ram_size <= 0)
8250 help(1);
8251 if (ram_size > PHYS_RAM_MAX_SIZE) {
8252 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8253 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8254 exit(1);
8256 break;
8257 case QEMU_OPTION_d:
8259 int mask;
8260 CPULogItem *item;
8262 mask = cpu_str_to_log_mask(optarg);
8263 if (!mask) {
8264 printf("Log items (comma separated):\n");
8265 for(item = cpu_log_items; item->mask != 0; item++) {
8266 printf("%-10s %s\n", item->name, item->help);
8268 exit(1);
8270 cpu_set_log(mask);
8272 break;
8273 #ifdef CONFIG_GDBSTUB
8274 case QEMU_OPTION_s:
8275 use_gdbstub = 1;
8276 break;
8277 case QEMU_OPTION_p:
8278 gdbstub_port = optarg;
8279 break;
8280 #endif
8281 case QEMU_OPTION_L:
8282 bios_dir = optarg;
8283 break;
8284 case QEMU_OPTION_S:
8285 autostart = 0;
8286 break;
8287 case QEMU_OPTION_k:
8288 keyboard_layout = optarg;
8289 break;
8290 case QEMU_OPTION_localtime:
8291 rtc_utc = 0;
8292 break;
8293 case QEMU_OPTION_cirrusvga:
8294 cirrus_vga_enabled = 1;
8295 vmsvga_enabled = 0;
8296 break;
8297 case QEMU_OPTION_vmsvga:
8298 cirrus_vga_enabled = 0;
8299 vmsvga_enabled = 1;
8300 break;
8301 case QEMU_OPTION_std_vga:
8302 cirrus_vga_enabled = 0;
8303 vmsvga_enabled = 0;
8304 break;
8305 case QEMU_OPTION_g:
8307 const char *p;
8308 int w, h, depth;
8309 p = optarg;
8310 w = strtol(p, (char **)&p, 10);
8311 if (w <= 0) {
8312 graphic_error:
8313 fprintf(stderr, "qemu: invalid resolution or depth\n");
8314 exit(1);
8316 if (*p != 'x')
8317 goto graphic_error;
8318 p++;
8319 h = strtol(p, (char **)&p, 10);
8320 if (h <= 0)
8321 goto graphic_error;
8322 if (*p == 'x') {
8323 p++;
8324 depth = strtol(p, (char **)&p, 10);
8325 if (depth != 8 && depth != 15 && depth != 16 &&
8326 depth != 24 && depth != 32)
8327 goto graphic_error;
8328 } else if (*p == '\0') {
8329 depth = graphic_depth;
8330 } else {
8331 goto graphic_error;
8334 graphic_width = w;
8335 graphic_height = h;
8336 graphic_depth = depth;
8338 break;
8339 case QEMU_OPTION_echr:
8341 char *r;
8342 term_escape_char = strtol(optarg, &r, 0);
8343 if (r == optarg)
8344 printf("Bad argument to echr\n");
8345 break;
8347 case QEMU_OPTION_monitor:
8348 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8349 break;
8350 case QEMU_OPTION_balloon:
8351 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8352 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8353 exit(1);
8355 if (balloon_used) {
8356 fprintf(stderr, "qemu: only one balloon device can be used\n");
8357 exit(1);
8359 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
8360 vmchannel_device_index++;
8361 balloon_used = 1;
8362 break;
8363 case QEMU_OPTION_vmchannel:
8364 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8365 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8366 exit(1);
8368 pstrcpy(vmchannel_devices[vmchannel_device_index],
8369 sizeof(vmchannel_devices[0]), optarg);
8370 vmchannel_device_index++;
8371 break;
8372 case QEMU_OPTION_serial:
8373 if (serial_device_index >= MAX_SERIAL_PORTS) {
8374 fprintf(stderr, "qemu: too many serial ports\n");
8375 exit(1);
8377 pstrcpy(serial_devices[serial_device_index],
8378 sizeof(serial_devices[0]), optarg);
8379 serial_device_index++;
8380 break;
8381 case QEMU_OPTION_parallel:
8382 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8383 fprintf(stderr, "qemu: too many parallel ports\n");
8384 exit(1);
8386 pstrcpy(parallel_devices[parallel_device_index],
8387 sizeof(parallel_devices[0]), optarg);
8388 parallel_device_index++;
8389 break;
8390 case QEMU_OPTION_loadvm:
8391 loadvm = optarg;
8392 break;
8393 case QEMU_OPTION_incoming:
8394 incoming = optarg;
8395 break;
8396 case QEMU_OPTION_full_screen:
8397 full_screen = 1;
8398 break;
8399 #ifdef CONFIG_SDL
8400 case QEMU_OPTION_no_frame:
8401 no_frame = 1;
8402 break;
8403 case QEMU_OPTION_alt_grab:
8404 alt_grab = 1;
8405 break;
8406 case QEMU_OPTION_no_quit:
8407 no_quit = 1;
8408 break;
8409 #endif
8410 case QEMU_OPTION_pidfile:
8411 pid_file = optarg;
8412 break;
8413 #ifdef TARGET_I386
8414 case QEMU_OPTION_win2k_hack:
8415 win2k_install_hack = 1;
8416 break;
8417 #endif
8418 #ifdef USE_KQEMU
8419 case QEMU_OPTION_no_kqemu:
8420 kqemu_allowed = 0;
8421 break;
8422 case QEMU_OPTION_kernel_kqemu:
8423 kqemu_allowed = 2;
8424 break;
8425 #endif
8426 #ifdef USE_KVM
8427 case QEMU_OPTION_no_kvm:
8428 kvm_allowed = 0;
8429 break;
8430 case QEMU_OPTION_no_kvm_irqchip:
8431 kvm_irqchip = 0;
8432 break;
8433 #endif
8434 case QEMU_OPTION_usb:
8435 usb_enabled = 1;
8436 break;
8437 case QEMU_OPTION_usbdevice:
8438 usb_enabled = 1;
8439 if (usb_devices_index >= MAX_USB_CMDLINE) {
8440 fprintf(stderr, "Too many USB devices\n");
8441 exit(1);
8443 pstrcpy(usb_devices[usb_devices_index],
8444 sizeof(usb_devices[usb_devices_index]),
8445 optarg);
8446 usb_devices_index++;
8447 break;
8448 case QEMU_OPTION_smp:
8449 smp_cpus = atoi(optarg);
8450 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8451 fprintf(stderr, "Invalid number of CPUs\n");
8452 exit(1);
8454 break;
8455 case QEMU_OPTION_vnc:
8456 vnc_display = optarg;
8457 break;
8458 case QEMU_OPTION_no_acpi:
8459 acpi_enabled = 0;
8460 break;
8461 case QEMU_OPTION_no_reboot:
8462 no_reboot = 1;
8463 break;
8464 case QEMU_OPTION_show_cursor:
8465 cursor_hide = 0;
8466 break;
8467 case QEMU_OPTION_daemonize:
8468 daemonize = 1;
8469 break;
8470 case QEMU_OPTION_option_rom:
8471 if (nb_option_roms >= MAX_OPTION_ROMS) {
8472 fprintf(stderr, "Too many option ROMs\n");
8473 exit(1);
8475 option_rom[nb_option_roms] = optarg;
8476 nb_option_roms++;
8477 break;
8478 case QEMU_OPTION_semihosting:
8479 semihosting_enabled = 1;
8480 break;
8481 case QEMU_OPTION_tdf:
8482 time_drift_fix = 1;
8483 break;
8484 case QEMU_OPTION_kvm_shadow_memory:
8485 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
8486 break;
8487 case QEMU_OPTION_name:
8488 qemu_name = optarg;
8489 break;
8490 #ifdef TARGET_SPARC
8491 case QEMU_OPTION_prom_env:
8492 if (nb_prom_envs >= MAX_PROM_ENVS) {
8493 fprintf(stderr, "Too many prom variables\n");
8494 exit(1);
8496 prom_envs[nb_prom_envs] = optarg;
8497 nb_prom_envs++;
8498 break;
8499 #endif
8500 case QEMU_OPTION_cpu_vendor:
8501 cpu_vendor_string = optarg;
8502 break;
8503 #ifdef TARGET_ARM
8504 case QEMU_OPTION_old_param:
8505 old_param = 1;
8506 #endif
8507 case QEMU_OPTION_clock:
8508 configure_alarms(optarg);
8509 break;
8514 #ifndef _WIN32
8515 if (daemonize) {
8516 pid_t pid;
8518 if (pipe(fds) == -1)
8519 exit(1);
8521 pid = fork();
8522 if (pid > 0) {
8523 uint8_t status;
8524 ssize_t len;
8526 close(fds[1]);
8528 again:
8529 len = read(fds[0], &status, 1);
8530 if (len == -1 && (errno == EINTR))
8531 goto again;
8533 if (len != 1)
8534 exit(1);
8535 else if (status == 1) {
8536 fprintf(stderr, "Could not acquire pidfile\n");
8537 exit(1);
8538 } else
8539 exit(0);
8540 } else if (pid < 0)
8541 exit(1);
8543 setsid();
8545 pid = fork();
8546 if (pid > 0)
8547 exit(0);
8548 else if (pid < 0)
8549 exit(1);
8551 umask(027);
8553 signal(SIGTSTP, SIG_IGN);
8554 signal(SIGTTOU, SIG_IGN);
8555 signal(SIGTTIN, SIG_IGN);
8557 #endif
8559 #if USE_KVM
8560 if (kvm_allowed) {
8561 if (kvm_qemu_init() < 0) {
8562 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
8563 kvm_allowed = 0;
8566 #endif
8568 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8569 if (daemonize) {
8570 uint8_t status = 1;
8571 write(fds[1], &status, 1);
8572 } else
8573 fprintf(stderr, "Could not acquire pid file\n");
8574 exit(1);
8577 #ifdef USE_KQEMU
8578 if (smp_cpus > 1)
8579 kqemu_allowed = 0;
8580 #endif
8581 linux_boot = (kernel_filename != NULL);
8583 if (!linux_boot &&
8584 boot_device != 'n' &&
8585 hd_filename[0] == '\0' &&
8586 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
8587 fd_filename[0] == '\0')
8588 help(1);
8590 /* boot to floppy or the default cd if no hard disk defined yet */
8591 if (hd_filename[0] == '\0' && boot_device == 'c') {
8592 if (fd_filename[0] != '\0')
8593 boot_device = 'a';
8594 else
8595 boot_device = 'd';
8598 setvbuf(stdout, NULL, _IOLBF, 0);
8600 init_timers();
8601 init_timer_alarm();
8602 qemu_aio_init();
8604 #ifdef _WIN32
8605 socket_init();
8606 #endif
8608 /* init network clients */
8609 if (nb_net_clients == 0) {
8610 /* if no clients, we use a default config */
8611 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8612 "nic");
8613 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8614 "user");
8615 nb_net_clients = 2;
8618 for(i = 0;i < nb_net_clients; i++) {
8619 if (net_client_init(net_clients[i]) < 0)
8620 exit(1);
8622 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8623 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8624 continue;
8625 if (vlan->nb_guest_devs == 0) {
8626 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8627 exit(1);
8629 if (vlan->nb_host_devs == 0)
8630 fprintf(stderr,
8631 "Warning: vlan %d is not connected to host network\n",
8632 vlan->id);
8635 #ifdef TARGET_I386
8636 if (boot_device == 'n') {
8637 for (i = 0; i < nb_nics; i++) {
8638 const char *model = nd_table[i].model;
8639 char buf[1024];
8640 if (model == NULL)
8641 model = "ne2k_pci";
8642 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8643 if (get_image_size(buf) > 0) {
8644 option_rom[nb_option_roms] = strdup(buf);
8645 nb_option_roms++;
8646 break;
8649 if (i == nb_nics) {
8650 fprintf(stderr, "No valid PXE rom found for network device\n");
8651 exit(1);
8654 #endif
8656 /* init the memory */
8657 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8659 #if USE_KVM
8660 /* Initialize kvm */
8661 if (kvm_allowed) {
8662 phys_ram_size += KVM_EXTRA_PAGES * 4096;
8663 if (kvm_qemu_create_context() < 0) {
8664 fprintf(stderr, "Could not create KVM context\n");
8665 exit(1);
8667 } else {
8668 phys_ram_base = qemu_vmalloc(phys_ram_size);
8669 if (!phys_ram_base) {
8670 fprintf(stderr, "Could not allocate physical memory\n");
8671 exit(1);
8674 #else
8675 phys_ram_base = qemu_vmalloc(phys_ram_size);
8676 if (!phys_ram_base) {
8677 fprintf(stderr, "Could not allocate physical memory\n");
8678 exit(1);
8680 #endif
8682 /* we always create the cdrom drive, even if no disk is there */
8683 bdrv_init();
8684 if (cdrom_index >= 0) {
8685 bs_table[cdrom_index] = bdrv_new("cdrom");
8686 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8689 /* open the virtual block devices */
8690 for(i = 0; i < MAX_DISKS; i++) {
8691 if (hd_filename[i]) {
8692 if (!bs_table[i]) {
8693 char buf[64];
8694 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8695 bs_table[i] = bdrv_new(buf);
8697 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8698 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8699 hd_filename[i]);
8700 exit(1);
8702 if (i == 0 && cyls != 0) {
8703 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8704 bdrv_set_translation_hint(bs_table[i], translation);
8709 /* we always create at least one floppy disk */
8710 fd_table[0] = bdrv_new("fda");
8711 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8713 for(i = 0; i < MAX_FD; i++) {
8714 if (fd_filename[i]) {
8715 if (!fd_table[i]) {
8716 char buf[64];
8717 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8718 fd_table[i] = bdrv_new(buf);
8719 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8721 if (fd_filename[i][0] != '\0') {
8722 if (bdrv_open(fd_table[i], fd_filename[i],
8723 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8724 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8725 fd_filename[i]);
8726 exit(1);
8732 /* Open the virtual parallel flash block devices */
8733 for(i = 0; i < MAX_PFLASH; i++) {
8734 if (pflash_filename[i]) {
8735 if (!pflash_table[i]) {
8736 char buf[64];
8737 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8738 pflash_table[i] = bdrv_new(buf);
8740 if (bdrv_open(pflash_table[i], pflash_filename[i],
8741 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8742 fprintf(stderr, "qemu: could not open flash image '%s'\n",
8743 pflash_filename[i]);
8744 exit(1);
8749 sd_bdrv = bdrv_new ("sd");
8750 /* FIXME: This isn't really a floppy, but it's a reasonable
8751 approximation. */
8752 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8753 if (sd_filename) {
8754 if (bdrv_open(sd_bdrv, sd_filename,
8755 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8756 fprintf(stderr, "qemu: could not open SD card image %s\n",
8757 sd_filename);
8758 } else
8759 qemu_key_check(sd_bdrv, sd_filename);
8762 if (mtd_filename) {
8763 mtd_bdrv = bdrv_new ("mtd");
8764 if (bdrv_open(mtd_bdrv, mtd_filename,
8765 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8766 qemu_key_check(mtd_bdrv, mtd_filename)) {
8767 fprintf(stderr, "qemu: could not open Flash image %s\n",
8768 mtd_filename);
8769 bdrv_delete(mtd_bdrv);
8770 mtd_bdrv = 0;
8774 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8775 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
8777 init_ioports();
8779 /* terminal init */
8780 memset(&display_state, 0, sizeof(display_state));
8781 if (nographic) {
8782 /* nearly nothing to do */
8783 dumb_display_init(ds);
8784 } else if (vnc_display != NULL) {
8785 vnc_display_init(ds);
8786 if (vnc_display_open(ds, vnc_display) < 0)
8787 exit(1);
8788 } else {
8789 #if defined(CONFIG_SDL)
8790 sdl_display_init(ds, full_screen, no_frame);
8791 #elif defined(CONFIG_COCOA)
8792 cocoa_display_init(ds, full_screen);
8793 #endif
8796 /* Maintain compatibility with multiple stdio monitors */
8797 if (!strcmp(monitor_device,"stdio")) {
8798 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8799 if (!strcmp(serial_devices[i],"mon:stdio")) {
8800 monitor_device[0] = '\0';
8801 break;
8802 } else if (!strcmp(serial_devices[i],"stdio")) {
8803 monitor_device[0] = '\0';
8804 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8805 break;
8809 if (monitor_device[0] != '\0') {
8810 monitor_hd = qemu_chr_open(monitor_device);
8811 if (!monitor_hd) {
8812 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8813 exit(1);
8815 monitor_init(monitor_hd, !nographic);
8818 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
8819 const char *devname = vmchannel_devices[i];
8820 if (devname[0] != '\0' && strcmp(devname, "none")) {
8821 int devid;
8822 char *termn;
8824 if (strstart(devname, "di:", &devname)) {
8825 devid = strtol(devname, &termn, 16);
8826 devname = termn + 1;
8828 else {
8829 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
8830 devname);
8831 exit(1);
8833 vmchannel_hds[i] = qemu_chr_open(devname);
8834 if (!vmchannel_hds[i]) {
8835 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
8836 devname);
8837 exit(1);
8839 vmchannel_init(vmchannel_hds[i], devid, i);
8843 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8844 const char *devname = serial_devices[i];
8845 if (devname[0] != '\0' && strcmp(devname, "none")) {
8846 serial_hds[i] = qemu_chr_open(devname);
8847 if (!serial_hds[i]) {
8848 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8849 devname);
8850 exit(1);
8852 if (strstart(devname, "vc", 0))
8853 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8857 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8858 const char *devname = parallel_devices[i];
8859 if (devname[0] != '\0' && strcmp(devname, "none")) {
8860 parallel_hds[i] = qemu_chr_open(devname);
8861 if (!parallel_hds[i]) {
8862 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8863 devname);
8864 exit(1);
8866 if (strstart(devname, "vc", 0))
8867 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8871 machine->init(ram_size, vga_ram_size, boot_device,
8872 ds, fd_filename, snapshot,
8873 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8875 /* init USB devices */
8876 if (usb_enabled) {
8877 for(i = 0; i < usb_devices_index; i++) {
8878 if (usb_device_add(usb_devices[i]) < 0) {
8879 fprintf(stderr, "Warning: could not add USB device %s\n",
8880 usb_devices[i]);
8885 if (display_state.dpy_refresh) {
8886 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8887 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8890 #ifdef USE_KVM
8891 if (kvm_allowed)
8892 kvm_init_ap();
8893 #endif
8895 #ifdef CONFIG_GDBSTUB
8896 if (use_gdbstub) {
8897 /* XXX: use standard host:port notation and modify options
8898 accordingly. */
8899 if (gdbserver_start(gdbstub_port) < 0) {
8900 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8901 gdbstub_port);
8902 exit(1);
8905 #endif
8906 if (loadvm)
8907 do_loadvm(loadvm);
8909 if (incoming) {
8910 int rc;
8912 rc = migrate_incoming(incoming);
8913 if (rc != 0) {
8914 fprintf(stderr, "Migration failed rc=%d\n", rc);
8915 exit(rc);
8920 /* XXX: simplify init */
8921 read_passwords();
8922 if (autostart) {
8923 vm_start();
8927 if (daemonize) {
8928 uint8_t status = 0;
8929 ssize_t len;
8930 int fd;
8932 again1:
8933 len = write(fds[1], &status, 1);
8934 if (len == -1 && (errno == EINTR))
8935 goto again1;
8937 if (len != 1)
8938 exit(1);
8940 chdir("/");
8941 TFR(fd = open("/dev/null", O_RDWR));
8942 if (fd == -1)
8943 exit(1);
8945 dup2(fd, 0);
8946 dup2(fd, 1);
8947 dup2(fd, 2);
8949 close(fd);
8952 main_loop();
8953 quit_timers();
8954 return 0;