Separate thread for IO handling
[qemu-kvm/fedora.git] / vl.c
blob8cb827bdfc93211501af2ec3c2c779cefaa41875
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/fdc.h"
30 #include "hw/audiodev.h"
31 #include "hw/isa.h"
32 #include "net.h"
33 #include "console.h"
34 #include "sysemu.h"
35 #include "gdbstub.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
38 #include "block.h"
39 #include "audio/audio.h"
40 #include "migration.h"
41 #include "qemu-kvm.h"
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <time.h>
47 #include <errno.h>
48 #include <sys/time.h>
49 #include <zlib.h>
51 #ifndef _WIN32
52 #include <sys/times.h>
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <sys/poll.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <dirent.h>
61 #include <netdb.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
64 #ifdef _BSD
65 #include <sys/stat.h>
66 #ifndef __APPLE__
67 #include <libutil.h>
68 #endif
69 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
70 #include <freebsd/stdlib.h>
71 #else
72 #ifndef __sun__
73 #include <linux/if.h>
74 #include <linux/if_tun.h>
75 #include <pty.h>
76 #include <malloc.h>
77 #include <linux/rtc.h>
79 /* For the benefit of older linux systems which don't supply it,
80 we use a local copy of hpet.h. */
81 /* #include <linux/hpet.h> */
82 #include "hpet.h"
84 #include <linux/ppdev.h>
85 #include <linux/parport.h>
86 #else
87 #include <sys/stat.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
97 #include <net/if.h>
98 #include <syslog.h>
99 #include <stropts.h>
100 #endif
101 #endif
102 #else
103 #include <winsock2.h>
104 int inet_aton(const char *cp, struct in_addr *ia);
105 #endif
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
109 #endif
111 #ifdef _WIN32
112 #include <malloc.h>
113 #include <sys/timeb.h>
114 #include <mmsystem.h>
115 #define getopt_long_only getopt_long
116 #define memalign(align, size) malloc(size)
117 #endif
119 #include "qemu_socket.h"
121 #ifdef CONFIG_SDL
122 #ifdef __APPLE__
123 #include <SDL/SDL.h>
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "disas.h"
134 #include "exec-all.h"
136 #include "qemu-kvm.h"
138 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
140 #ifdef __sun__
141 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
142 #else
143 #define SMBD_COMMAND "/usr/sbin/smbd"
144 #endif
146 //#define DEBUG_UNUSED_IOPORT
147 //#define DEBUG_IOPORT
149 #if HOST_LONG_BITS < 64
150 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
151 #else
152 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024 * 1024ULL)
153 #endif
155 #ifdef TARGET_PPC
156 #define DEFAULT_RAM_SIZE 144
157 #else
158 #define DEFAULT_RAM_SIZE 128
159 #endif
160 /* in ms */
161 #define GUI_REFRESH_INTERVAL 30
163 /* Max number of USB devices that can be specified on the commandline. */
164 #define MAX_USB_CMDLINE 8
166 /* XXX: use a two level table to limit memory usage */
167 #define MAX_IOPORTS 65536
169 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
170 const char *bios_name = NULL;
171 void *ioport_opaque[MAX_IOPORTS];
172 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
173 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 DriveInfo drives_table[MAX_DRIVES+1];
177 int nb_drives;
178 int extboot_drive = -1;
179 /* point to the block driver where the snapshots are managed */
180 BlockDriverState *bs_snapshots;
181 int vga_ram_size;
182 static DisplayState display_state;
183 int nographic;
184 int curses;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
187 int64_t ram_size;
188 int pit_min_timer_count = 0;
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int cirrus_vga_enabled = 1;
195 int vmsvga_enabled = 0;
196 #ifdef TARGET_SPARC
197 int graphic_width = 1024;
198 int graphic_height = 768;
199 int graphic_depth = 8;
200 #else
201 int graphic_width = 800;
202 int graphic_height = 600;
203 int graphic_depth = 15;
204 #endif
205 int full_screen = 0;
206 int no_frame = 0;
207 int no_quit = 0;
208 int balloon_used = 0;
209 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
210 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
211 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
212 #ifdef TARGET_I386
213 int win2k_install_hack = 0;
214 #endif
215 int usb_enabled = 0;
216 static VLANState *first_vlan;
217 int smp_cpus = 1;
218 const char *vnc_display;
219 #if defined(TARGET_SPARC)
220 #define MAX_CPUS 16
221 #elif defined(TARGET_I386)
222 #define MAX_CPUS 255
223 #elif defined(TARGET_IA64)
224 #define MAX_CPUS 4
225 #else
226 #define MAX_CPUS 1
227 #endif
228 int acpi_enabled = 1;
229 int fd_bootchk = 1;
230 int no_reboot = 0;
231 int cursor_hide = 1;
232 int graphic_rotate = 0;
233 int daemonize = 0;
234 const char *incoming;
235 const char *option_rom[MAX_OPTION_ROMS];
236 int nb_option_roms;
237 int semihosting_enabled = 0;
238 int autostart = 1;
239 int time_drift_fix = 0;
240 unsigned int kvm_shadow_memory = 0;
241 const char *mem_path = NULL;
242 int hpagesize = 0;
243 const char *cpu_vendor_string;
244 #ifdef TARGET_ARM
245 int old_param = 0;
246 #endif
247 const char *qemu_name;
248 int alt_grab = 0;
249 #ifdef TARGET_SPARC
250 unsigned int nb_prom_envs = 0;
251 const char *prom_envs[MAX_PROM_ENVS];
252 #endif
253 int nb_drives_opt;
254 struct drive_opt drives_opt[MAX_DRIVES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int event_pending = 1;
260 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
262 void decorate_application_name(char *appname, int max_len)
264 if (kvm_enabled())
266 int remain = max_len - strlen(appname) - 1;
268 if (remain > 0)
269 strncat(appname, "/KVM", remain);
273 /***********************************************************/
274 /* x86 ISA bus support */
276 target_phys_addr_t isa_mem_base = 0;
277 PicState2 *isa_pic;
279 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
281 #ifdef DEBUG_UNUSED_IOPORT
282 fprintf(stderr, "unused inb: port=0x%04x\n", address);
283 #endif
284 return 0xff;
287 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
289 #ifdef DEBUG_UNUSED_IOPORT
290 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
291 #endif
294 /* default is to make two byte accesses */
295 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
297 uint32_t data;
298 data = ioport_read_table[0][address](ioport_opaque[address], address);
299 address = (address + 1) & (MAX_IOPORTS - 1);
300 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
301 return data;
304 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
306 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
307 address = (address + 1) & (MAX_IOPORTS - 1);
308 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
311 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
313 #ifdef DEBUG_UNUSED_IOPORT
314 fprintf(stderr, "unused inl: port=0x%04x\n", address);
315 #endif
316 return 0xffffffff;
319 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
321 #ifdef DEBUG_UNUSED_IOPORT
322 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
323 #endif
326 static void init_ioports(void)
328 int i;
330 for(i = 0; i < MAX_IOPORTS; i++) {
331 ioport_read_table[0][i] = default_ioport_readb;
332 ioport_write_table[0][i] = default_ioport_writeb;
333 ioport_read_table[1][i] = default_ioport_readw;
334 ioport_write_table[1][i] = default_ioport_writew;
335 ioport_read_table[2][i] = default_ioport_readl;
336 ioport_write_table[2][i] = default_ioport_writel;
340 /* size is the word size in byte */
341 int register_ioport_read(int start, int length, int size,
342 IOPortReadFunc *func, void *opaque)
344 int i, bsize;
346 if (size == 1) {
347 bsize = 0;
348 } else if (size == 2) {
349 bsize = 1;
350 } else if (size == 4) {
351 bsize = 2;
352 } else {
353 hw_error("register_ioport_read: invalid size");
354 return -1;
356 for(i = start; i < start + length; i += size) {
357 ioport_read_table[bsize][i] = func;
358 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
359 hw_error("register_ioport_read: invalid opaque");
360 ioport_opaque[i] = opaque;
362 return 0;
365 /* size is the word size in byte */
366 int register_ioport_write(int start, int length, int size,
367 IOPortWriteFunc *func, void *opaque)
369 int i, bsize;
371 if (size == 1) {
372 bsize = 0;
373 } else if (size == 2) {
374 bsize = 1;
375 } else if (size == 4) {
376 bsize = 2;
377 } else {
378 hw_error("register_ioport_write: invalid size");
379 return -1;
381 for(i = start; i < start + length; i += size) {
382 ioport_write_table[bsize][i] = func;
383 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
384 hw_error("register_ioport_write: invalid opaque");
385 ioport_opaque[i] = opaque;
387 return 0;
390 void isa_unassign_ioport(int start, int length)
392 int i;
394 for(i = start; i < start + length; i++) {
395 ioport_read_table[0][i] = default_ioport_readb;
396 ioport_read_table[1][i] = default_ioport_readw;
397 ioport_read_table[2][i] = default_ioport_readl;
399 ioport_write_table[0][i] = default_ioport_writeb;
400 ioport_write_table[1][i] = default_ioport_writew;
401 ioport_write_table[2][i] = default_ioport_writel;
403 ioport_opaque[i] = NULL;
407 /***********************************************************/
409 void cpu_outb(CPUState *env, int addr, int val)
411 #ifdef DEBUG_IOPORT
412 if (loglevel & CPU_LOG_IOPORT)
413 fprintf(logfile, "outb: %04x %02x\n", addr, val);
414 #endif
415 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
416 #ifdef USE_KQEMU
417 if (env)
418 env->last_io_time = cpu_get_time_fast();
419 #endif
422 void cpu_outw(CPUState *env, int addr, int val)
424 #ifdef DEBUG_IOPORT
425 if (loglevel & CPU_LOG_IOPORT)
426 fprintf(logfile, "outw: %04x %04x\n", addr, val);
427 #endif
428 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
429 #ifdef USE_KQEMU
430 if (env)
431 env->last_io_time = cpu_get_time_fast();
432 #endif
435 void cpu_outl(CPUState *env, int addr, int val)
437 #ifdef DEBUG_IOPORT
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "outl: %04x %08x\n", addr, val);
440 #endif
441 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
442 #ifdef USE_KQEMU
443 if (env)
444 env->last_io_time = cpu_get_time_fast();
445 #endif
448 int cpu_inb(CPUState *env, int addr)
450 int val;
451 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
452 #ifdef DEBUG_IOPORT
453 if (loglevel & CPU_LOG_IOPORT)
454 fprintf(logfile, "inb : %04x %02x\n", addr, val);
455 #endif
456 #ifdef USE_KQEMU
457 if (env)
458 env->last_io_time = cpu_get_time_fast();
459 #endif
460 return val;
463 int cpu_inw(CPUState *env, int addr)
465 int val;
466 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
467 #ifdef DEBUG_IOPORT
468 if (loglevel & CPU_LOG_IOPORT)
469 fprintf(logfile, "inw : %04x %04x\n", addr, val);
470 #endif
471 #ifdef USE_KQEMU
472 if (env)
473 env->last_io_time = cpu_get_time_fast();
474 #endif
475 return val;
478 int cpu_inl(CPUState *env, int addr)
480 int val;
481 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
482 #ifdef DEBUG_IOPORT
483 if (loglevel & CPU_LOG_IOPORT)
484 fprintf(logfile, "inl : %04x %08x\n", addr, val);
485 #endif
486 #ifdef USE_KQEMU
487 if (env)
488 env->last_io_time = cpu_get_time_fast();
489 #endif
490 return val;
493 /***********************************************************/
494 void hw_error(const char *fmt, ...)
496 va_list ap;
497 CPUState *env;
499 va_start(ap, fmt);
500 fprintf(stderr, "qemu: hardware error: ");
501 vfprintf(stderr, fmt, ap);
502 fprintf(stderr, "\n");
503 for(env = first_cpu; env != NULL; env = env->next_cpu) {
504 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
505 #ifdef TARGET_I386
506 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
507 #else
508 cpu_dump_state(env, stderr, fprintf, 0);
509 #endif
511 va_end(ap);
512 abort();
515 /***********************************************************/
516 /* keyboard/mouse */
518 static QEMUPutKBDEvent *qemu_put_kbd_event;
519 static void *qemu_put_kbd_event_opaque;
520 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
521 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
523 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
525 qemu_put_kbd_event_opaque = opaque;
526 qemu_put_kbd_event = func;
529 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
530 void *opaque, int absolute,
531 const char *name)
533 QEMUPutMouseEntry *s, *cursor;
535 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
536 if (!s)
537 return NULL;
539 s->qemu_put_mouse_event = func;
540 s->qemu_put_mouse_event_opaque = opaque;
541 s->qemu_put_mouse_event_absolute = absolute;
542 s->qemu_put_mouse_event_name = qemu_strdup(name);
543 s->next = NULL;
545 if (!qemu_put_mouse_event_head) {
546 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
547 return s;
550 cursor = qemu_put_mouse_event_head;
551 while (cursor->next != NULL)
552 cursor = cursor->next;
554 cursor->next = s;
555 qemu_put_mouse_event_current = s;
557 return s;
560 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
562 QEMUPutMouseEntry *prev = NULL, *cursor;
564 if (!qemu_put_mouse_event_head || entry == NULL)
565 return;
567 cursor = qemu_put_mouse_event_head;
568 while (cursor != NULL && cursor != entry) {
569 prev = cursor;
570 cursor = cursor->next;
573 if (cursor == NULL) // does not exist or list empty
574 return;
575 else if (prev == NULL) { // entry is head
576 qemu_put_mouse_event_head = cursor->next;
577 if (qemu_put_mouse_event_current == entry)
578 qemu_put_mouse_event_current = cursor->next;
579 qemu_free(entry->qemu_put_mouse_event_name);
580 qemu_free(entry);
581 return;
584 prev->next = entry->next;
586 if (qemu_put_mouse_event_current == entry)
587 qemu_put_mouse_event_current = prev;
589 qemu_free(entry->qemu_put_mouse_event_name);
590 qemu_free(entry);
593 void kbd_put_keycode(int keycode)
595 if (qemu_put_kbd_event) {
596 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
600 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
602 QEMUPutMouseEvent *mouse_event;
603 void *mouse_event_opaque;
604 int width;
606 if (!qemu_put_mouse_event_current) {
607 return;
610 mouse_event =
611 qemu_put_mouse_event_current->qemu_put_mouse_event;
612 mouse_event_opaque =
613 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
615 if (mouse_event) {
616 if (graphic_rotate) {
617 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
618 width = 0x7fff;
619 else
620 width = graphic_width - 1;
621 mouse_event(mouse_event_opaque,
622 width - dy, dx, dz, buttons_state);
623 } else
624 mouse_event(mouse_event_opaque,
625 dx, dy, dz, buttons_state);
629 int kbd_mouse_is_absolute(void)
631 if (!qemu_put_mouse_event_current)
632 return 0;
634 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
637 void do_info_mice(void)
639 QEMUPutMouseEntry *cursor;
640 int index = 0;
642 if (!qemu_put_mouse_event_head) {
643 term_printf("No mouse devices connected\n");
644 return;
647 term_printf("Mouse devices available:\n");
648 cursor = qemu_put_mouse_event_head;
649 while (cursor != NULL) {
650 term_printf("%c Mouse #%d: %s\n",
651 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
652 index, cursor->qemu_put_mouse_event_name);
653 index++;
654 cursor = cursor->next;
658 void do_mouse_set(int index)
660 QEMUPutMouseEntry *cursor;
661 int i = 0;
663 if (!qemu_put_mouse_event_head) {
664 term_printf("No mouse devices connected\n");
665 return;
668 cursor = qemu_put_mouse_event_head;
669 while (cursor != NULL && index != i) {
670 i++;
671 cursor = cursor->next;
674 if (cursor != NULL)
675 qemu_put_mouse_event_current = cursor;
676 else
677 term_printf("Mouse at given index not found\n");
680 /* compute with 96 bit intermediate result: (a*b)/c */
681 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
683 union {
684 uint64_t ll;
685 struct {
686 #ifdef WORDS_BIGENDIAN
687 uint32_t high, low;
688 #else
689 uint32_t low, high;
690 #endif
691 } l;
692 } u, res;
693 uint64_t rl, rh;
695 u.ll = a;
696 rl = (uint64_t)u.l.low * (uint64_t)b;
697 rh = (uint64_t)u.l.high * (uint64_t)b;
698 rh += (rl >> 32);
699 res.l.high = rh / c;
700 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
701 return res.ll;
704 /***********************************************************/
705 /* real time host monotonic timer */
707 #define QEMU_TIMER_BASE 1000000000LL
709 #ifdef WIN32
711 static int64_t clock_freq;
713 static void init_get_clock(void)
715 LARGE_INTEGER freq;
716 int ret;
717 ret = QueryPerformanceFrequency(&freq);
718 if (ret == 0) {
719 fprintf(stderr, "Could not calibrate ticks\n");
720 exit(1);
722 clock_freq = freq.QuadPart;
725 static int64_t get_clock(void)
727 LARGE_INTEGER ti;
728 QueryPerformanceCounter(&ti);
729 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
732 #else
734 static int use_rt_clock;
736 static void init_get_clock(void)
738 use_rt_clock = 0;
739 #if defined(__linux__)
741 struct timespec ts;
742 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
743 use_rt_clock = 1;
746 #endif
749 static int64_t get_clock(void)
751 #if defined(__linux__)
752 if (use_rt_clock) {
753 struct timespec ts;
754 clock_gettime(CLOCK_MONOTONIC, &ts);
755 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
756 } else
757 #endif
759 /* XXX: using gettimeofday leads to problems if the date
760 changes, so it should be avoided. */
761 struct timeval tv;
762 gettimeofday(&tv, NULL);
763 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
767 #endif
769 /***********************************************************/
770 /* guest cycle counter */
772 static int64_t cpu_ticks_prev;
773 static int64_t cpu_ticks_offset;
774 static int64_t cpu_clock_offset;
775 static int cpu_ticks_enabled;
777 /* return the host CPU cycle counter and handle stop/restart */
778 int64_t cpu_get_ticks(void)
780 if (!cpu_ticks_enabled) {
781 return cpu_ticks_offset;
782 } else {
783 int64_t ticks;
784 ticks = cpu_get_real_ticks();
785 if (cpu_ticks_prev > ticks) {
786 /* Note: non increasing ticks may happen if the host uses
787 software suspend */
788 cpu_ticks_offset += cpu_ticks_prev - ticks;
790 cpu_ticks_prev = ticks;
791 return ticks + cpu_ticks_offset;
795 /* return the host CPU monotonic timer and handle stop/restart */
796 static int64_t cpu_get_clock(void)
798 int64_t ti;
799 if (!cpu_ticks_enabled) {
800 return cpu_clock_offset;
801 } else {
802 ti = get_clock();
803 return ti + cpu_clock_offset;
807 /* enable cpu_get_ticks() */
808 void cpu_enable_ticks(void)
810 if (!cpu_ticks_enabled) {
811 cpu_ticks_offset -= cpu_get_real_ticks();
812 cpu_clock_offset -= get_clock();
813 cpu_ticks_enabled = 1;
817 /* disable cpu_get_ticks() : the clock is stopped. You must not call
818 cpu_get_ticks() after that. */
819 void cpu_disable_ticks(void)
821 if (cpu_ticks_enabled) {
822 cpu_ticks_offset = cpu_get_ticks();
823 cpu_clock_offset = cpu_get_clock();
824 cpu_ticks_enabled = 0;
828 /***********************************************************/
829 /* timers */
831 #define QEMU_TIMER_REALTIME 0
832 #define QEMU_TIMER_VIRTUAL 1
834 struct QEMUClock {
835 int type;
836 /* XXX: add frequency */
839 struct QEMUTimer {
840 QEMUClock *clock;
841 int64_t expire_time;
842 QEMUTimerCB *cb;
843 void *opaque;
844 struct QEMUTimer *next;
847 struct qemu_alarm_timer {
848 char const *name;
849 unsigned int flags;
851 int (*start)(struct qemu_alarm_timer *t);
852 void (*stop)(struct qemu_alarm_timer *t);
853 void (*rearm)(struct qemu_alarm_timer *t);
854 void *priv;
857 #define ALARM_FLAG_DYNTICKS 0x1
858 #define ALARM_FLAG_EXPIRED 0x2
860 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
862 return t->flags & ALARM_FLAG_DYNTICKS;
865 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
867 if (!alarm_has_dynticks(t))
868 return;
870 t->rearm(t);
873 /* TODO: MIN_TIMER_REARM_US should be optimized */
874 #define MIN_TIMER_REARM_US 250
876 static struct qemu_alarm_timer *alarm_timer;
878 #ifdef _WIN32
880 struct qemu_alarm_win32 {
881 MMRESULT timerId;
882 HANDLE host_alarm;
883 unsigned int period;
884 } alarm_win32_data = {0, NULL, -1};
886 static int win32_start_timer(struct qemu_alarm_timer *t);
887 static void win32_stop_timer(struct qemu_alarm_timer *t);
888 static void win32_rearm_timer(struct qemu_alarm_timer *t);
890 #else
892 static int unix_start_timer(struct qemu_alarm_timer *t);
893 static void unix_stop_timer(struct qemu_alarm_timer *t);
895 #ifdef __linux__
897 static int dynticks_start_timer(struct qemu_alarm_timer *t);
898 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
899 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
901 static int hpet_start_timer(struct qemu_alarm_timer *t);
902 static void hpet_stop_timer(struct qemu_alarm_timer *t);
904 static int rtc_start_timer(struct qemu_alarm_timer *t);
905 static void rtc_stop_timer(struct qemu_alarm_timer *t);
907 #endif /* __linux__ */
909 #endif /* _WIN32 */
911 static struct qemu_alarm_timer alarm_timers[] = {
912 #ifndef _WIN32
913 #ifdef __linux__
914 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
915 dynticks_stop_timer, dynticks_rearm_timer, NULL},
916 /* HPET - if available - is preferred */
917 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
918 /* ...otherwise try RTC */
919 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
920 #endif
921 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
922 #else
923 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
924 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
925 {"win32", 0, win32_start_timer,
926 win32_stop_timer, NULL, &alarm_win32_data},
927 #endif
928 {NULL, }
931 static void show_available_alarms(void)
933 int i;
935 printf("Available alarm timers, in order of precedence:\n");
936 for (i = 0; alarm_timers[i].name; i++)
937 printf("%s\n", alarm_timers[i].name);
940 static void configure_alarms(char const *opt)
942 int i;
943 int cur = 0;
944 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
945 char *arg;
946 char *name;
948 if (!strcmp(opt, "?")) {
949 show_available_alarms();
950 exit(0);
953 arg = strdup(opt);
955 /* Reorder the array */
956 name = strtok(arg, ",");
957 while (name) {
958 struct qemu_alarm_timer tmp;
960 for (i = 0; i < count && alarm_timers[i].name; i++) {
961 if (!strcmp(alarm_timers[i].name, name))
962 break;
965 if (i == count) {
966 fprintf(stderr, "Unknown clock %s\n", name);
967 goto next;
970 if (i < cur)
971 /* Ignore */
972 goto next;
974 /* Swap */
975 tmp = alarm_timers[i];
976 alarm_timers[i] = alarm_timers[cur];
977 alarm_timers[cur] = tmp;
979 cur++;
980 next:
981 name = strtok(NULL, ",");
984 free(arg);
986 if (cur) {
987 /* Disable remaining timers */
988 for (i = cur; i < count; i++)
989 alarm_timers[i].name = NULL;
990 } else {
991 show_available_alarms();
992 exit(1);
996 QEMUClock *rt_clock;
997 QEMUClock *vm_clock;
999 static QEMUTimer *active_timers[2];
1001 static QEMUClock *qemu_new_clock(int type)
1003 QEMUClock *clock;
1004 clock = qemu_mallocz(sizeof(QEMUClock));
1005 if (!clock)
1006 return NULL;
1007 clock->type = type;
1008 return clock;
1011 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1013 QEMUTimer *ts;
1015 ts = qemu_mallocz(sizeof(QEMUTimer));
1016 ts->clock = clock;
1017 ts->cb = cb;
1018 ts->opaque = opaque;
1019 return ts;
1022 void qemu_free_timer(QEMUTimer *ts)
1024 qemu_free(ts);
1027 /* stop a timer, but do not dealloc it */
1028 void qemu_del_timer(QEMUTimer *ts)
1030 QEMUTimer **pt, *t;
1032 /* NOTE: this code must be signal safe because
1033 qemu_timer_expired() can be called from a signal. */
1034 pt = &active_timers[ts->clock->type];
1035 for(;;) {
1036 t = *pt;
1037 if (!t)
1038 break;
1039 if (t == ts) {
1040 *pt = t->next;
1041 break;
1043 pt = &t->next;
1047 /* modify the current timer so that it will be fired when current_time
1048 >= expire_time. The corresponding callback will be called. */
1049 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1051 QEMUTimer **pt, *t;
1053 qemu_del_timer(ts);
1055 /* add the timer in the sorted list */
1056 /* NOTE: this code must be signal safe because
1057 qemu_timer_expired() can be called from a signal. */
1058 pt = &active_timers[ts->clock->type];
1059 for(;;) {
1060 t = *pt;
1061 if (!t)
1062 break;
1063 if (t->expire_time > expire_time)
1064 break;
1065 pt = &t->next;
1067 ts->expire_time = expire_time;
1068 ts->next = *pt;
1069 *pt = ts;
1071 /* Rearm if necessary */
1072 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1073 pt == &active_timers[ts->clock->type])
1074 qemu_rearm_alarm_timer(alarm_timer);
1077 int qemu_timer_pending(QEMUTimer *ts)
1079 QEMUTimer *t;
1080 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1081 if (t == ts)
1082 return 1;
1084 return 0;
1087 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1089 if (!timer_head)
1090 return 0;
1091 return (timer_head->expire_time <= current_time);
1094 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1096 QEMUTimer *ts;
1098 for(;;) {
1099 ts = *ptimer_head;
1100 if (!ts || ts->expire_time > current_time)
1101 break;
1102 /* remove timer from the list before calling the callback */
1103 *ptimer_head = ts->next;
1104 ts->next = NULL;
1106 /* run the callback (the timer list can be modified) */
1107 ts->cb(ts->opaque);
1111 int64_t qemu_get_clock(QEMUClock *clock)
1113 switch(clock->type) {
1114 case QEMU_TIMER_REALTIME:
1115 return get_clock() / 1000000;
1116 default:
1117 case QEMU_TIMER_VIRTUAL:
1118 return cpu_get_clock();
1122 static void init_timers(void)
1124 init_get_clock();
1125 ticks_per_sec = QEMU_TIMER_BASE;
1126 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1127 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1130 /* save a timer */
1131 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1133 uint64_t expire_time;
1135 if (qemu_timer_pending(ts)) {
1136 expire_time = ts->expire_time;
1137 } else {
1138 expire_time = -1;
1140 qemu_put_be64(f, expire_time);
1143 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1145 uint64_t expire_time;
1147 expire_time = qemu_get_be64(f);
1148 if (expire_time != -1) {
1149 qemu_mod_timer(ts, expire_time);
1150 } else {
1151 qemu_del_timer(ts);
1155 static void timer_save(QEMUFile *f, void *opaque)
1157 if (cpu_ticks_enabled) {
1158 hw_error("cannot save state if virtual timers are running");
1160 qemu_put_be64(f, cpu_ticks_offset);
1161 qemu_put_be64(f, ticks_per_sec);
1162 qemu_put_be64(f, cpu_clock_offset);
1165 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1167 if (version_id != 1 && version_id != 2)
1168 return -EINVAL;
1169 if (cpu_ticks_enabled) {
1170 return -EINVAL;
1172 cpu_ticks_offset=qemu_get_be64(f);
1173 ticks_per_sec=qemu_get_be64(f);
1174 if (version_id == 2) {
1175 cpu_clock_offset=qemu_get_be64(f);
1177 return 0;
1180 #ifdef _WIN32
1181 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1182 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1183 #else
1184 static void host_alarm_handler(int host_signum)
1185 #endif
1187 #if 0
1188 #define DISP_FREQ 1000
1190 static int64_t delta_min = INT64_MAX;
1191 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1192 static int count;
1193 ti = qemu_get_clock(vm_clock);
1194 if (last_clock != 0) {
1195 delta = ti - last_clock;
1196 if (delta < delta_min)
1197 delta_min = delta;
1198 if (delta > delta_max)
1199 delta_max = delta;
1200 delta_cum += delta;
1201 if (++count == DISP_FREQ) {
1202 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1203 muldiv64(delta_min, 1000000, ticks_per_sec),
1204 muldiv64(delta_max, 1000000, ticks_per_sec),
1205 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1206 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1207 count = 0;
1208 delta_min = INT64_MAX;
1209 delta_max = 0;
1210 delta_cum = 0;
1213 last_clock = ti;
1215 #endif
1216 if (1 ||
1217 alarm_has_dynticks(alarm_timer) ||
1218 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1219 qemu_get_clock(vm_clock)) ||
1220 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1221 qemu_get_clock(rt_clock))) {
1222 #ifdef _WIN32
1223 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1224 SetEvent(data->host_alarm);
1225 #endif
1226 CPUState *env = next_cpu;
1228 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1230 if (env) {
1231 /* stop the currently executing cpu because a timer occured */
1232 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1233 #ifdef USE_KQEMU
1234 if (env->kqemu_enabled) {
1235 kqemu_cpu_interrupt(env);
1237 #endif
1239 event_pending = 1;
1243 static uint64_t qemu_next_deadline(void)
1245 int64_t nearest_delta_us = INT64_MAX;
1246 int64_t vmdelta_us;
1248 if (active_timers[QEMU_TIMER_REALTIME])
1249 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1250 qemu_get_clock(rt_clock))*1000;
1252 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1253 /* round up */
1254 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1255 qemu_get_clock(vm_clock)+999)/1000;
1256 if (vmdelta_us < nearest_delta_us)
1257 nearest_delta_us = vmdelta_us;
1260 /* Avoid arming the timer to negative, zero, or too low values */
1261 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1262 nearest_delta_us = MIN_TIMER_REARM_US;
1264 return nearest_delta_us;
1267 #ifndef _WIN32
1269 #if defined(__linux__)
1271 #define RTC_FREQ 1024
1273 static void enable_sigio_timer(int fd)
1275 struct sigaction act;
1277 /* timer signal */
1278 sigfillset(&act.sa_mask);
1279 act.sa_flags = 0;
1280 act.sa_handler = host_alarm_handler;
1282 sigaction(SIGIO, &act, NULL);
1283 fcntl(fd, F_SETFL, O_ASYNC);
1284 fcntl(fd, F_SETOWN, getpid());
1287 static int hpet_start_timer(struct qemu_alarm_timer *t)
1289 struct hpet_info info;
1290 int r, fd;
1292 fd = open("/dev/hpet", O_RDONLY);
1293 if (fd < 0)
1294 return -1;
1296 /* Set frequency */
1297 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1298 if (r < 0) {
1299 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1300 "error, but for better emulation accuracy type:\n"
1301 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1302 goto fail;
1305 /* Check capabilities */
1306 r = ioctl(fd, HPET_INFO, &info);
1307 if (r < 0)
1308 goto fail;
1310 /* Enable periodic mode */
1311 r = ioctl(fd, HPET_EPI, 0);
1312 if (info.hi_flags && (r < 0))
1313 goto fail;
1315 /* Enable interrupt */
1316 r = ioctl(fd, HPET_IE_ON, 0);
1317 if (r < 0)
1318 goto fail;
1320 enable_sigio_timer(fd);
1321 t->priv = (void *)(long)fd;
1323 return 0;
1324 fail:
1325 close(fd);
1326 return -1;
1329 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1331 int fd = (long)t->priv;
1333 close(fd);
1336 static int rtc_start_timer(struct qemu_alarm_timer *t)
1338 int rtc_fd;
1339 unsigned long current_rtc_freq = 0;
1341 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1342 if (rtc_fd < 0)
1343 return -1;
1344 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1345 if (current_rtc_freq != RTC_FREQ &&
1346 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1347 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1348 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1349 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1350 goto fail;
1352 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1353 fail:
1354 close(rtc_fd);
1355 return -1;
1358 enable_sigio_timer(rtc_fd);
1360 t->priv = (void *)(long)rtc_fd;
1362 return 0;
1365 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1367 int rtc_fd = (long)t->priv;
1369 close(rtc_fd);
1372 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1374 struct sigevent ev;
1375 timer_t host_timer;
1376 struct sigaction act;
1378 sigfillset(&act.sa_mask);
1379 act.sa_flags = 0;
1380 act.sa_handler = host_alarm_handler;
1382 sigaction(SIGALRM, &act, NULL);
1384 ev.sigev_value.sival_int = 0;
1385 ev.sigev_notify = SIGEV_SIGNAL;
1386 ev.sigev_signo = SIGALRM;
1388 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1389 perror("timer_create");
1391 /* disable dynticks */
1392 fprintf(stderr, "Dynamic Ticks disabled\n");
1394 return -1;
1397 t->priv = (void *)host_timer;
1399 return 0;
1402 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1404 timer_t host_timer = (timer_t)t->priv;
1406 timer_delete(host_timer);
1409 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1411 timer_t host_timer = (timer_t)t->priv;
1412 struct itimerspec timeout;
1413 int64_t nearest_delta_us = INT64_MAX;
1414 int64_t current_us;
1416 if (!active_timers[QEMU_TIMER_REALTIME] &&
1417 !active_timers[QEMU_TIMER_VIRTUAL])
1418 return;
1420 nearest_delta_us = qemu_next_deadline();
1422 /* check whether a timer is already running */
1423 if (timer_gettime(host_timer, &timeout)) {
1424 perror("gettime");
1425 fprintf(stderr, "Internal timer error: aborting\n");
1426 exit(1);
1428 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1429 if (current_us && current_us <= nearest_delta_us)
1430 return;
1432 timeout.it_interval.tv_sec = 0;
1433 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1434 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1435 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1436 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1437 perror("settime");
1438 fprintf(stderr, "Internal timer error: aborting\n");
1439 exit(1);
1443 #endif /* defined(__linux__) */
1445 static int unix_start_timer(struct qemu_alarm_timer *t)
1447 struct sigaction act;
1448 struct itimerval itv;
1449 int err;
1451 /* timer signal */
1452 sigfillset(&act.sa_mask);
1453 act.sa_flags = 0;
1454 act.sa_handler = host_alarm_handler;
1456 sigaction(SIGALRM, &act, NULL);
1458 itv.it_interval.tv_sec = 0;
1459 /* for i386 kernel 2.6 to get 1 ms */
1460 itv.it_interval.tv_usec = 999;
1461 itv.it_value.tv_sec = 0;
1462 itv.it_value.tv_usec = 10 * 1000;
1464 err = setitimer(ITIMER_REAL, &itv, NULL);
1465 if (err)
1466 return -1;
1468 return 0;
1471 static void unix_stop_timer(struct qemu_alarm_timer *t)
1473 struct itimerval itv;
1475 memset(&itv, 0, sizeof(itv));
1476 setitimer(ITIMER_REAL, &itv, NULL);
1479 #endif /* !defined(_WIN32) */
1481 #ifdef _WIN32
1483 static int win32_start_timer(struct qemu_alarm_timer *t)
1485 TIMECAPS tc;
1486 struct qemu_alarm_win32 *data = t->priv;
1487 UINT flags;
1489 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1490 if (!data->host_alarm) {
1491 perror("Failed CreateEvent");
1492 return -1;
1495 memset(&tc, 0, sizeof(tc));
1496 timeGetDevCaps(&tc, sizeof(tc));
1498 if (data->period < tc.wPeriodMin)
1499 data->period = tc.wPeriodMin;
1501 timeBeginPeriod(data->period);
1503 flags = TIME_CALLBACK_FUNCTION;
1504 if (alarm_has_dynticks(t))
1505 flags |= TIME_ONESHOT;
1506 else
1507 flags |= TIME_PERIODIC;
1509 data->timerId = timeSetEvent(1, // interval (ms)
1510 data->period, // resolution
1511 host_alarm_handler, // function
1512 (DWORD)t, // parameter
1513 flags);
1515 if (!data->timerId) {
1516 perror("Failed to initialize win32 alarm timer");
1518 timeEndPeriod(data->period);
1519 CloseHandle(data->host_alarm);
1520 return -1;
1523 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1525 return 0;
1528 static void win32_stop_timer(struct qemu_alarm_timer *t)
1530 struct qemu_alarm_win32 *data = t->priv;
1532 timeKillEvent(data->timerId);
1533 timeEndPeriod(data->period);
1535 CloseHandle(data->host_alarm);
1538 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1540 struct qemu_alarm_win32 *data = t->priv;
1541 uint64_t nearest_delta_us;
1543 if (!active_timers[QEMU_TIMER_REALTIME] &&
1544 !active_timers[QEMU_TIMER_VIRTUAL])
1545 return;
1547 nearest_delta_us = qemu_next_deadline();
1548 nearest_delta_us /= 1000;
1550 timeKillEvent(data->timerId);
1552 data->timerId = timeSetEvent(1,
1553 data->period,
1554 host_alarm_handler,
1555 (DWORD)t,
1556 TIME_ONESHOT | TIME_PERIODIC);
1558 if (!data->timerId) {
1559 perror("Failed to re-arm win32 alarm timer");
1561 timeEndPeriod(data->period);
1562 CloseHandle(data->host_alarm);
1563 exit(1);
1567 #endif /* _WIN32 */
1569 static void init_timer_alarm(void)
1571 struct qemu_alarm_timer *t;
1572 int i, err = -1;
1574 for (i = 0; alarm_timers[i].name; i++) {
1575 t = &alarm_timers[i];
1577 err = t->start(t);
1578 if (!err)
1579 break;
1582 if (err) {
1583 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1584 fprintf(stderr, "Terminating\n");
1585 exit(1);
1588 alarm_timer = t;
1591 static void quit_timers(void)
1593 alarm_timer->stop(alarm_timer);
1594 alarm_timer = NULL;
1597 /***********************************************************/
1598 /* host time/date access */
1599 void qemu_get_timedate(struct tm *tm, int offset)
1601 time_t ti;
1602 struct tm *ret;
1604 time(&ti);
1605 ti += offset;
1606 if (rtc_date_offset == -1) {
1607 if (rtc_utc)
1608 ret = gmtime(&ti);
1609 else
1610 ret = localtime(&ti);
1611 } else {
1612 ti -= rtc_date_offset;
1613 ret = gmtime(&ti);
1616 memcpy(tm, ret, sizeof(struct tm));
1619 int qemu_timedate_diff(struct tm *tm)
1621 time_t seconds;
1623 if (rtc_date_offset == -1)
1624 if (rtc_utc)
1625 seconds = mktimegm(tm);
1626 else
1627 seconds = mktime(tm);
1628 else
1629 seconds = mktimegm(tm) + rtc_date_offset;
1631 return seconds - time(NULL);
1634 /***********************************************************/
1635 /* character device */
1637 static void qemu_chr_event(CharDriverState *s, int event)
1639 if (!s->chr_event)
1640 return;
1641 s->chr_event(s->handler_opaque, event);
1644 static void qemu_chr_reset_bh(void *opaque)
1646 CharDriverState *s = opaque;
1647 qemu_chr_event(s, CHR_EVENT_RESET);
1648 qemu_bh_delete(s->bh);
1649 s->bh = NULL;
1652 void qemu_chr_reset(CharDriverState *s)
1654 if (s->bh == NULL) {
1655 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1656 qemu_bh_schedule(s->bh);
1660 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1662 return s->chr_write(s, buf, len);
1665 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1667 if (!s->chr_ioctl)
1668 return -ENOTSUP;
1669 return s->chr_ioctl(s, cmd, arg);
1672 int qemu_chr_can_read(CharDriverState *s)
1674 if (!s->chr_can_read)
1675 return 0;
1676 return s->chr_can_read(s->handler_opaque);
1679 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1681 s->chr_read(s->handler_opaque, buf, len);
1684 void qemu_chr_accept_input(CharDriverState *s)
1686 if (s->chr_accept_input)
1687 s->chr_accept_input(s);
1690 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1692 char buf[4096];
1693 va_list ap;
1694 va_start(ap, fmt);
1695 vsnprintf(buf, sizeof(buf), fmt, ap);
1696 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1697 va_end(ap);
1700 void qemu_chr_send_event(CharDriverState *s, int event)
1702 if (s->chr_send_event)
1703 s->chr_send_event(s, event);
1706 void qemu_chr_add_handlers(CharDriverState *s,
1707 IOCanRWHandler *fd_can_read,
1708 IOReadHandler *fd_read,
1709 IOEventHandler *fd_event,
1710 void *opaque)
1712 s->chr_can_read = fd_can_read;
1713 s->chr_read = fd_read;
1714 s->chr_event = fd_event;
1715 s->handler_opaque = opaque;
1716 if (s->chr_update_read_handler)
1717 s->chr_update_read_handler(s);
1720 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1722 return len;
1725 static CharDriverState *qemu_chr_open_null(void)
1727 CharDriverState *chr;
1729 chr = qemu_mallocz(sizeof(CharDriverState));
1730 if (!chr)
1731 return NULL;
1732 chr->chr_write = null_chr_write;
1733 return chr;
1736 /* MUX driver for serial I/O splitting */
1737 static int term_timestamps;
1738 static int64_t term_timestamps_start;
1739 #define MAX_MUX 4
1740 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1741 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1742 typedef struct {
1743 IOCanRWHandler *chr_can_read[MAX_MUX];
1744 IOReadHandler *chr_read[MAX_MUX];
1745 IOEventHandler *chr_event[MAX_MUX];
1746 void *ext_opaque[MAX_MUX];
1747 CharDriverState *drv;
1748 unsigned char buffer[MUX_BUFFER_SIZE];
1749 int prod;
1750 int cons;
1751 int mux_cnt;
1752 int term_got_escape;
1753 int max_size;
1754 } MuxDriver;
1757 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1759 MuxDriver *d = chr->opaque;
1760 int ret;
1761 if (!term_timestamps) {
1762 ret = d->drv->chr_write(d->drv, buf, len);
1763 } else {
1764 int i;
1766 ret = 0;
1767 for(i = 0; i < len; i++) {
1768 ret += d->drv->chr_write(d->drv, buf+i, 1);
1769 if (buf[i] == '\n') {
1770 char buf1[64];
1771 int64_t ti;
1772 int secs;
1774 ti = get_clock();
1775 if (term_timestamps_start == -1)
1776 term_timestamps_start = ti;
1777 ti -= term_timestamps_start;
1778 secs = ti / 1000000000;
1779 snprintf(buf1, sizeof(buf1),
1780 "[%02d:%02d:%02d.%03d] ",
1781 secs / 3600,
1782 (secs / 60) % 60,
1783 secs % 60,
1784 (int)((ti / 1000000) % 1000));
1785 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1789 return ret;
1792 static char *mux_help[] = {
1793 "% h print this help\n\r",
1794 "% x exit emulator\n\r",
1795 "% s save disk data back to file (if -snapshot)\n\r",
1796 "% t toggle console timestamps\n\r"
1797 "% b send break (magic sysrq)\n\r",
1798 "% c switch between console and monitor\n\r",
1799 "% % sends %\n\r",
1800 NULL
1803 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1804 static void mux_print_help(CharDriverState *chr)
1806 int i, j;
1807 char ebuf[15] = "Escape-Char";
1808 char cbuf[50] = "\n\r";
1810 if (term_escape_char > 0 && term_escape_char < 26) {
1811 sprintf(cbuf,"\n\r");
1812 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1813 } else {
1814 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1815 term_escape_char);
1817 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1818 for (i = 0; mux_help[i] != NULL; i++) {
1819 for (j=0; mux_help[i][j] != '\0'; j++) {
1820 if (mux_help[i][j] == '%')
1821 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1822 else
1823 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1828 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1830 if (d->term_got_escape) {
1831 d->term_got_escape = 0;
1832 if (ch == term_escape_char)
1833 goto send_char;
1834 switch(ch) {
1835 case '?':
1836 case 'h':
1837 mux_print_help(chr);
1838 break;
1839 case 'x':
1841 char *term = "QEMU: Terminated\n\r";
1842 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1843 exit(0);
1844 break;
1846 case 's':
1848 int i;
1849 for (i = 0; i < nb_drives; i++) {
1850 bdrv_commit(drives_table[i].bdrv);
1853 break;
1854 case 'b':
1855 qemu_chr_event(chr, CHR_EVENT_BREAK);
1856 break;
1857 case 'c':
1858 /* Switch to the next registered device */
1859 chr->focus++;
1860 if (chr->focus >= d->mux_cnt)
1861 chr->focus = 0;
1862 break;
1863 case 't':
1864 term_timestamps = !term_timestamps;
1865 term_timestamps_start = -1;
1866 break;
1868 } else if (ch == term_escape_char) {
1869 d->term_got_escape = 1;
1870 } else {
1871 send_char:
1872 return 1;
1874 return 0;
1877 static void mux_chr_accept_input(CharDriverState *chr)
1879 int m = chr->focus;
1880 MuxDriver *d = chr->opaque;
1882 while (d->prod != d->cons &&
1883 d->chr_can_read[m] &&
1884 d->chr_can_read[m](d->ext_opaque[m])) {
1885 d->chr_read[m](d->ext_opaque[m],
1886 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1890 static int mux_chr_can_read(void *opaque)
1892 CharDriverState *chr = opaque;
1893 MuxDriver *d = chr->opaque;
1895 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1896 return 1;
1897 if (d->chr_can_read[chr->focus])
1898 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1899 return 0;
1902 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1904 CharDriverState *chr = opaque;
1905 MuxDriver *d = chr->opaque;
1906 int m = chr->focus;
1907 int i;
1909 mux_chr_accept_input (opaque);
1911 for(i = 0; i < size; i++)
1912 if (mux_proc_byte(chr, d, buf[i])) {
1913 if (d->prod == d->cons &&
1914 d->chr_can_read[m] &&
1915 d->chr_can_read[m](d->ext_opaque[m]))
1916 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1917 else
1918 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1922 static void mux_chr_event(void *opaque, int event)
1924 CharDriverState *chr = opaque;
1925 MuxDriver *d = chr->opaque;
1926 int i;
1928 /* Send the event to all registered listeners */
1929 for (i = 0; i < d->mux_cnt; i++)
1930 if (d->chr_event[i])
1931 d->chr_event[i](d->ext_opaque[i], event);
1934 static void mux_chr_update_read_handler(CharDriverState *chr)
1936 MuxDriver *d = chr->opaque;
1938 if (d->mux_cnt >= MAX_MUX) {
1939 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1940 return;
1942 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1943 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1944 d->chr_read[d->mux_cnt] = chr->chr_read;
1945 d->chr_event[d->mux_cnt] = chr->chr_event;
1946 /* Fix up the real driver with mux routines */
1947 if (d->mux_cnt == 0) {
1948 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1949 mux_chr_event, chr);
1951 chr->focus = d->mux_cnt;
1952 d->mux_cnt++;
1955 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1957 CharDriverState *chr;
1958 MuxDriver *d;
1960 chr = qemu_mallocz(sizeof(CharDriverState));
1961 if (!chr)
1962 return NULL;
1963 d = qemu_mallocz(sizeof(MuxDriver));
1964 if (!d) {
1965 free(chr);
1966 return NULL;
1969 chr->opaque = d;
1970 d->drv = drv;
1971 chr->focus = -1;
1972 chr->chr_write = mux_chr_write;
1973 chr->chr_update_read_handler = mux_chr_update_read_handler;
1974 chr->chr_accept_input = mux_chr_accept_input;
1975 return chr;
1979 #ifdef _WIN32
1981 static void socket_cleanup(void)
1983 WSACleanup();
1986 static int socket_init(void)
1988 WSADATA Data;
1989 int ret, err;
1991 ret = WSAStartup(MAKEWORD(2,2), &Data);
1992 if (ret != 0) {
1993 err = WSAGetLastError();
1994 fprintf(stderr, "WSAStartup: %d\n", err);
1995 return -1;
1997 atexit(socket_cleanup);
1998 return 0;
2001 static int send_all(int fd, const uint8_t *buf, int len1)
2003 int ret, len;
2005 len = len1;
2006 while (len > 0) {
2007 ret = send(fd, buf, len, 0);
2008 if (ret < 0) {
2009 int errno;
2010 errno = WSAGetLastError();
2011 if (errno != WSAEWOULDBLOCK) {
2012 return -1;
2014 } else if (ret == 0) {
2015 break;
2016 } else {
2017 buf += ret;
2018 len -= ret;
2021 return len1 - len;
2024 void socket_set_nonblock(int fd)
2026 unsigned long opt = 1;
2027 ioctlsocket(fd, FIONBIO, &opt);
2030 #else
2032 static int unix_write(int fd, const uint8_t *buf, int len1)
2034 int ret, len;
2036 len = len1;
2037 while (len > 0) {
2038 ret = write(fd, buf, len);
2039 if (ret < 0) {
2040 if (errno != EINTR && errno != EAGAIN)
2041 return -1;
2042 } else if (ret == 0) {
2043 break;
2044 } else {
2045 buf += ret;
2046 len -= ret;
2049 return len1 - len;
2052 static inline int send_all(int fd, const uint8_t *buf, int len1)
2054 return unix_write(fd, buf, len1);
2057 void socket_set_nonblock(int fd)
2059 fcntl(fd, F_SETFL, O_NONBLOCK);
2061 #endif /* !_WIN32 */
2063 #ifndef _WIN32
2065 typedef struct {
2066 int fd_in, fd_out;
2067 int max_size;
2068 } FDCharDriver;
2070 #define STDIO_MAX_CLIENTS 1
2071 static int stdio_nb_clients = 0;
2073 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2075 FDCharDriver *s = chr->opaque;
2076 return unix_write(s->fd_out, buf, len);
2079 static int fd_chr_read_poll(void *opaque)
2081 CharDriverState *chr = opaque;
2082 FDCharDriver *s = chr->opaque;
2084 s->max_size = qemu_chr_can_read(chr);
2085 return s->max_size;
2088 static void fd_chr_read(void *opaque)
2090 CharDriverState *chr = opaque;
2091 FDCharDriver *s = chr->opaque;
2092 int size, len;
2093 uint8_t buf[1024];
2095 len = sizeof(buf);
2096 if (len > s->max_size)
2097 len = s->max_size;
2098 if (len == 0)
2099 return;
2100 size = read(s->fd_in, buf, len);
2101 if (size == 0) {
2102 /* FD has been closed. Remove it from the active list. */
2103 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2104 return;
2106 if (size > 0) {
2107 qemu_chr_read(chr, buf, size);
2111 static void fd_chr_update_read_handler(CharDriverState *chr)
2113 FDCharDriver *s = chr->opaque;
2115 if (s->fd_in >= 0) {
2116 if (nographic && s->fd_in == 0) {
2117 } else {
2118 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2119 fd_chr_read, NULL, chr);
2124 static void fd_chr_close(struct CharDriverState *chr)
2126 FDCharDriver *s = chr->opaque;
2128 if (s->fd_in >= 0) {
2129 if (nographic && s->fd_in == 0) {
2130 } else {
2131 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2135 qemu_free(s);
2138 /* open a character device to a unix fd */
2139 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2141 CharDriverState *chr;
2142 FDCharDriver *s;
2144 chr = qemu_mallocz(sizeof(CharDriverState));
2145 if (!chr)
2146 return NULL;
2147 s = qemu_mallocz(sizeof(FDCharDriver));
2148 if (!s) {
2149 free(chr);
2150 return NULL;
2152 s->fd_in = fd_in;
2153 s->fd_out = fd_out;
2154 chr->opaque = s;
2155 chr->chr_write = fd_chr_write;
2156 chr->chr_update_read_handler = fd_chr_update_read_handler;
2157 chr->chr_close = fd_chr_close;
2159 qemu_chr_reset(chr);
2161 return chr;
2164 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2166 int fd_out;
2168 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2169 if (fd_out < 0)
2170 return NULL;
2171 return qemu_chr_open_fd(-1, fd_out);
2174 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2176 int fd_in, fd_out;
2177 char filename_in[256], filename_out[256];
2179 snprintf(filename_in, 256, "%s.in", filename);
2180 snprintf(filename_out, 256, "%s.out", filename);
2181 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2182 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2183 if (fd_in < 0 || fd_out < 0) {
2184 if (fd_in >= 0)
2185 close(fd_in);
2186 if (fd_out >= 0)
2187 close(fd_out);
2188 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2189 if (fd_in < 0)
2190 return NULL;
2192 return qemu_chr_open_fd(fd_in, fd_out);
2196 /* for STDIO, we handle the case where several clients use it
2197 (nographic mode) */
2199 #define TERM_FIFO_MAX_SIZE 1
2201 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2202 static int term_fifo_size;
2204 static int stdio_read_poll(void *opaque)
2206 CharDriverState *chr = opaque;
2208 /* try to flush the queue if needed */
2209 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2210 qemu_chr_read(chr, term_fifo, 1);
2211 term_fifo_size = 0;
2213 /* see if we can absorb more chars */
2214 if (term_fifo_size == 0)
2215 return 1;
2216 else
2217 return 0;
2220 static void stdio_read(void *opaque)
2222 int size;
2223 uint8_t buf[1];
2224 CharDriverState *chr = opaque;
2226 size = read(0, buf, 1);
2227 if (size == 0) {
2228 /* stdin has been closed. Remove it from the active list. */
2229 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2230 return;
2232 if (size > 0) {
2233 if (qemu_chr_can_read(chr) > 0) {
2234 qemu_chr_read(chr, buf, 1);
2235 } else if (term_fifo_size == 0) {
2236 term_fifo[term_fifo_size++] = buf[0];
2241 /* init terminal so that we can grab keys */
2242 static struct termios oldtty;
2243 static int old_fd0_flags;
2244 static int term_atexit_done;
2246 static void term_exit(void)
2248 tcsetattr (0, TCSANOW, &oldtty);
2249 fcntl(0, F_SETFL, old_fd0_flags);
2252 static void term_init(void)
2254 struct termios tty;
2256 tcgetattr (0, &tty);
2257 oldtty = tty;
2258 old_fd0_flags = fcntl(0, F_GETFL);
2260 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2261 |INLCR|IGNCR|ICRNL|IXON);
2262 tty.c_oflag |= OPOST;
2263 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2264 /* if graphical mode, we allow Ctrl-C handling */
2265 if (nographic)
2266 tty.c_lflag &= ~ISIG;
2267 tty.c_cflag &= ~(CSIZE|PARENB);
2268 tty.c_cflag |= CS8;
2269 tty.c_cc[VMIN] = 1;
2270 tty.c_cc[VTIME] = 0;
2272 tcsetattr (0, TCSANOW, &tty);
2274 if (!term_atexit_done++)
2275 atexit(term_exit);
2277 fcntl(0, F_SETFL, O_NONBLOCK);
2280 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2282 term_exit();
2283 stdio_nb_clients--;
2284 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2285 fd_chr_close(chr);
2288 static CharDriverState *qemu_chr_open_stdio(void)
2290 CharDriverState *chr;
2292 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2293 return NULL;
2294 chr = qemu_chr_open_fd(0, 1);
2295 chr->chr_close = qemu_chr_close_stdio;
2296 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2297 stdio_nb_clients++;
2298 term_init();
2300 return chr;
2303 #if defined(__linux__) || defined(__sun__)
2304 static CharDriverState *qemu_chr_open_pty(void)
2306 struct termios tty;
2307 char slave_name[1024];
2308 int master_fd, slave_fd;
2310 #if defined(__linux__)
2311 /* Not satisfying */
2312 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2313 return NULL;
2315 #endif
2317 /* Disabling local echo and line-buffered output */
2318 tcgetattr (master_fd, &tty);
2319 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2320 tty.c_cc[VMIN] = 1;
2321 tty.c_cc[VTIME] = 0;
2322 tcsetattr (master_fd, TCSAFLUSH, &tty);
2324 fprintf(stderr, "char device redirected to %s\n", slave_name);
2325 return qemu_chr_open_fd(master_fd, master_fd);
2328 static void tty_serial_init(int fd, int speed,
2329 int parity, int data_bits, int stop_bits)
2331 struct termios tty;
2332 speed_t spd;
2334 #if 0
2335 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2336 speed, parity, data_bits, stop_bits);
2337 #endif
2338 tcgetattr (fd, &tty);
2340 #define MARGIN 1.1
2341 if (speed <= 50 * MARGIN)
2342 spd = B50;
2343 else if (speed <= 75 * MARGIN)
2344 spd = B75;
2345 else if (speed <= 300 * MARGIN)
2346 spd = B300;
2347 else if (speed <= 600 * MARGIN)
2348 spd = B600;
2349 else if (speed <= 1200 * MARGIN)
2350 spd = B1200;
2351 else if (speed <= 2400 * MARGIN)
2352 spd = B2400;
2353 else if (speed <= 4800 * MARGIN)
2354 spd = B4800;
2355 else if (speed <= 9600 * MARGIN)
2356 spd = B9600;
2357 else if (speed <= 19200 * MARGIN)
2358 spd = B19200;
2359 else if (speed <= 38400 * MARGIN)
2360 spd = B38400;
2361 else if (speed <= 57600 * MARGIN)
2362 spd = B57600;
2363 else if (speed <= 115200 * MARGIN)
2364 spd = B115200;
2365 else
2366 spd = B115200;
2368 cfsetispeed(&tty, spd);
2369 cfsetospeed(&tty, spd);
2371 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2372 |INLCR|IGNCR|ICRNL|IXON);
2373 tty.c_oflag |= OPOST;
2374 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2375 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2376 switch(data_bits) {
2377 default:
2378 case 8:
2379 tty.c_cflag |= CS8;
2380 break;
2381 case 7:
2382 tty.c_cflag |= CS7;
2383 break;
2384 case 6:
2385 tty.c_cflag |= CS6;
2386 break;
2387 case 5:
2388 tty.c_cflag |= CS5;
2389 break;
2391 switch(parity) {
2392 default:
2393 case 'N':
2394 break;
2395 case 'E':
2396 tty.c_cflag |= PARENB;
2397 break;
2398 case 'O':
2399 tty.c_cflag |= PARENB | PARODD;
2400 break;
2402 if (stop_bits == 2)
2403 tty.c_cflag |= CSTOPB;
2405 tcsetattr (fd, TCSANOW, &tty);
2408 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2410 FDCharDriver *s = chr->opaque;
2412 switch(cmd) {
2413 case CHR_IOCTL_SERIAL_SET_PARAMS:
2415 QEMUSerialSetParams *ssp = arg;
2416 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2417 ssp->data_bits, ssp->stop_bits);
2419 break;
2420 case CHR_IOCTL_SERIAL_SET_BREAK:
2422 int enable = *(int *)arg;
2423 if (enable)
2424 tcsendbreak(s->fd_in, 1);
2426 break;
2427 default:
2428 return -ENOTSUP;
2430 return 0;
2433 static CharDriverState *qemu_chr_open_tty(const char *filename)
2435 CharDriverState *chr;
2436 int fd;
2438 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2439 fcntl(fd, F_SETFL, O_NONBLOCK);
2440 tty_serial_init(fd, 115200, 'N', 8, 1);
2441 chr = qemu_chr_open_fd(fd, fd);
2442 if (!chr) {
2443 close(fd);
2444 return NULL;
2446 chr->chr_ioctl = tty_serial_ioctl;
2447 qemu_chr_reset(chr);
2448 return chr;
2450 #else /* ! __linux__ && ! __sun__ */
2451 static CharDriverState *qemu_chr_open_pty(void)
2453 return NULL;
2455 #endif /* __linux__ || __sun__ */
2457 #if defined(__linux__)
2458 typedef struct {
2459 int fd;
2460 int mode;
2461 } ParallelCharDriver;
2463 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2465 if (s->mode != mode) {
2466 int m = mode;
2467 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2468 return 0;
2469 s->mode = mode;
2471 return 1;
2474 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2476 ParallelCharDriver *drv = chr->opaque;
2477 int fd = drv->fd;
2478 uint8_t b;
2480 switch(cmd) {
2481 case CHR_IOCTL_PP_READ_DATA:
2482 if (ioctl(fd, PPRDATA, &b) < 0)
2483 return -ENOTSUP;
2484 *(uint8_t *)arg = b;
2485 break;
2486 case CHR_IOCTL_PP_WRITE_DATA:
2487 b = *(uint8_t *)arg;
2488 if (ioctl(fd, PPWDATA, &b) < 0)
2489 return -ENOTSUP;
2490 break;
2491 case CHR_IOCTL_PP_READ_CONTROL:
2492 if (ioctl(fd, PPRCONTROL, &b) < 0)
2493 return -ENOTSUP;
2494 /* Linux gives only the lowest bits, and no way to know data
2495 direction! For better compatibility set the fixed upper
2496 bits. */
2497 *(uint8_t *)arg = b | 0xc0;
2498 break;
2499 case CHR_IOCTL_PP_WRITE_CONTROL:
2500 b = *(uint8_t *)arg;
2501 if (ioctl(fd, PPWCONTROL, &b) < 0)
2502 return -ENOTSUP;
2503 break;
2504 case CHR_IOCTL_PP_READ_STATUS:
2505 if (ioctl(fd, PPRSTATUS, &b) < 0)
2506 return -ENOTSUP;
2507 *(uint8_t *)arg = b;
2508 break;
2509 case CHR_IOCTL_PP_EPP_READ_ADDR:
2510 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2511 struct ParallelIOArg *parg = arg;
2512 int n = read(fd, parg->buffer, parg->count);
2513 if (n != parg->count) {
2514 return -EIO;
2517 break;
2518 case CHR_IOCTL_PP_EPP_READ:
2519 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2520 struct ParallelIOArg *parg = arg;
2521 int n = read(fd, parg->buffer, parg->count);
2522 if (n != parg->count) {
2523 return -EIO;
2526 break;
2527 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2528 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2529 struct ParallelIOArg *parg = arg;
2530 int n = write(fd, parg->buffer, parg->count);
2531 if (n != parg->count) {
2532 return -EIO;
2535 break;
2536 case CHR_IOCTL_PP_EPP_WRITE:
2537 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2538 struct ParallelIOArg *parg = arg;
2539 int n = write(fd, parg->buffer, parg->count);
2540 if (n != parg->count) {
2541 return -EIO;
2544 break;
2545 default:
2546 return -ENOTSUP;
2548 return 0;
2551 static void pp_close(CharDriverState *chr)
2553 ParallelCharDriver *drv = chr->opaque;
2554 int fd = drv->fd;
2556 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2557 ioctl(fd, PPRELEASE);
2558 close(fd);
2559 qemu_free(drv);
2562 static CharDriverState *qemu_chr_open_pp(const char *filename)
2564 CharDriverState *chr;
2565 ParallelCharDriver *drv;
2566 int fd;
2568 TFR(fd = open(filename, O_RDWR));
2569 if (fd < 0)
2570 return NULL;
2572 if (ioctl(fd, PPCLAIM) < 0) {
2573 close(fd);
2574 return NULL;
2577 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2578 if (!drv) {
2579 close(fd);
2580 return NULL;
2582 drv->fd = fd;
2583 drv->mode = IEEE1284_MODE_COMPAT;
2585 chr = qemu_mallocz(sizeof(CharDriverState));
2586 if (!chr) {
2587 qemu_free(drv);
2588 close(fd);
2589 return NULL;
2591 chr->chr_write = null_chr_write;
2592 chr->chr_ioctl = pp_ioctl;
2593 chr->chr_close = pp_close;
2594 chr->opaque = drv;
2596 qemu_chr_reset(chr);
2598 return chr;
2600 #endif /* __linux__ */
2602 #else /* _WIN32 */
2604 typedef struct {
2605 int max_size;
2606 HANDLE hcom, hrecv, hsend;
2607 OVERLAPPED orecv, osend;
2608 BOOL fpipe;
2609 DWORD len;
2610 } WinCharState;
2612 #define NSENDBUF 2048
2613 #define NRECVBUF 2048
2614 #define MAXCONNECT 1
2615 #define NTIMEOUT 5000
2617 static int win_chr_poll(void *opaque);
2618 static int win_chr_pipe_poll(void *opaque);
2620 static void win_chr_close(CharDriverState *chr)
2622 WinCharState *s = chr->opaque;
2624 if (s->hsend) {
2625 CloseHandle(s->hsend);
2626 s->hsend = NULL;
2628 if (s->hrecv) {
2629 CloseHandle(s->hrecv);
2630 s->hrecv = NULL;
2632 if (s->hcom) {
2633 CloseHandle(s->hcom);
2634 s->hcom = NULL;
2636 if (s->fpipe)
2637 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2638 else
2639 qemu_del_polling_cb(win_chr_poll, chr);
2642 static int win_chr_init(CharDriverState *chr, const char *filename)
2644 WinCharState *s = chr->opaque;
2645 COMMCONFIG comcfg;
2646 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2647 COMSTAT comstat;
2648 DWORD size;
2649 DWORD err;
2651 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2652 if (!s->hsend) {
2653 fprintf(stderr, "Failed CreateEvent\n");
2654 goto fail;
2656 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2657 if (!s->hrecv) {
2658 fprintf(stderr, "Failed CreateEvent\n");
2659 goto fail;
2662 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2663 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2664 if (s->hcom == INVALID_HANDLE_VALUE) {
2665 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2666 s->hcom = NULL;
2667 goto fail;
2670 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2671 fprintf(stderr, "Failed SetupComm\n");
2672 goto fail;
2675 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2676 size = sizeof(COMMCONFIG);
2677 GetDefaultCommConfig(filename, &comcfg, &size);
2678 comcfg.dcb.DCBlength = sizeof(DCB);
2679 CommConfigDialog(filename, NULL, &comcfg);
2681 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2682 fprintf(stderr, "Failed SetCommState\n");
2683 goto fail;
2686 if (!SetCommMask(s->hcom, EV_ERR)) {
2687 fprintf(stderr, "Failed SetCommMask\n");
2688 goto fail;
2691 cto.ReadIntervalTimeout = MAXDWORD;
2692 if (!SetCommTimeouts(s->hcom, &cto)) {
2693 fprintf(stderr, "Failed SetCommTimeouts\n");
2694 goto fail;
2697 if (!ClearCommError(s->hcom, &err, &comstat)) {
2698 fprintf(stderr, "Failed ClearCommError\n");
2699 goto fail;
2701 qemu_add_polling_cb(win_chr_poll, chr);
2702 return 0;
2704 fail:
2705 win_chr_close(chr);
2706 return -1;
2709 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2711 WinCharState *s = chr->opaque;
2712 DWORD len, ret, size, err;
2714 len = len1;
2715 ZeroMemory(&s->osend, sizeof(s->osend));
2716 s->osend.hEvent = s->hsend;
2717 while (len > 0) {
2718 if (s->hsend)
2719 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2720 else
2721 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2722 if (!ret) {
2723 err = GetLastError();
2724 if (err == ERROR_IO_PENDING) {
2725 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2726 if (ret) {
2727 buf += size;
2728 len -= size;
2729 } else {
2730 break;
2732 } else {
2733 break;
2735 } else {
2736 buf += size;
2737 len -= size;
2740 return len1 - len;
2743 static int win_chr_read_poll(CharDriverState *chr)
2745 WinCharState *s = chr->opaque;
2747 s->max_size = qemu_chr_can_read(chr);
2748 return s->max_size;
2751 static void win_chr_readfile(CharDriverState *chr)
2753 WinCharState *s = chr->opaque;
2754 int ret, err;
2755 uint8_t buf[1024];
2756 DWORD size;
2758 ZeroMemory(&s->orecv, sizeof(s->orecv));
2759 s->orecv.hEvent = s->hrecv;
2760 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2761 if (!ret) {
2762 err = GetLastError();
2763 if (err == ERROR_IO_PENDING) {
2764 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2768 if (size > 0) {
2769 qemu_chr_read(chr, buf, size);
2773 static void win_chr_read(CharDriverState *chr)
2775 WinCharState *s = chr->opaque;
2777 if (s->len > s->max_size)
2778 s->len = s->max_size;
2779 if (s->len == 0)
2780 return;
2782 win_chr_readfile(chr);
2785 static int win_chr_poll(void *opaque)
2787 CharDriverState *chr = opaque;
2788 WinCharState *s = chr->opaque;
2789 COMSTAT status;
2790 DWORD comerr;
2792 ClearCommError(s->hcom, &comerr, &status);
2793 if (status.cbInQue > 0) {
2794 s->len = status.cbInQue;
2795 win_chr_read_poll(chr);
2796 win_chr_read(chr);
2797 return 1;
2799 return 0;
2802 static CharDriverState *qemu_chr_open_win(const char *filename)
2804 CharDriverState *chr;
2805 WinCharState *s;
2807 chr = qemu_mallocz(sizeof(CharDriverState));
2808 if (!chr)
2809 return NULL;
2810 s = qemu_mallocz(sizeof(WinCharState));
2811 if (!s) {
2812 free(chr);
2813 return NULL;
2815 chr->opaque = s;
2816 chr->chr_write = win_chr_write;
2817 chr->chr_close = win_chr_close;
2819 if (win_chr_init(chr, filename) < 0) {
2820 free(s);
2821 free(chr);
2822 return NULL;
2824 qemu_chr_reset(chr);
2825 return chr;
2828 static int win_chr_pipe_poll(void *opaque)
2830 CharDriverState *chr = opaque;
2831 WinCharState *s = chr->opaque;
2832 DWORD size;
2834 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2835 if (size > 0) {
2836 s->len = size;
2837 win_chr_read_poll(chr);
2838 win_chr_read(chr);
2839 return 1;
2841 return 0;
2844 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2846 WinCharState *s = chr->opaque;
2847 OVERLAPPED ov;
2848 int ret;
2849 DWORD size;
2850 char openname[256];
2852 s->fpipe = TRUE;
2854 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2855 if (!s->hsend) {
2856 fprintf(stderr, "Failed CreateEvent\n");
2857 goto fail;
2859 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2860 if (!s->hrecv) {
2861 fprintf(stderr, "Failed CreateEvent\n");
2862 goto fail;
2865 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2866 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2867 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2868 PIPE_WAIT,
2869 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2870 if (s->hcom == INVALID_HANDLE_VALUE) {
2871 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2872 s->hcom = NULL;
2873 goto fail;
2876 ZeroMemory(&ov, sizeof(ov));
2877 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2878 ret = ConnectNamedPipe(s->hcom, &ov);
2879 if (ret) {
2880 fprintf(stderr, "Failed ConnectNamedPipe\n");
2881 goto fail;
2884 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2885 if (!ret) {
2886 fprintf(stderr, "Failed GetOverlappedResult\n");
2887 if (ov.hEvent) {
2888 CloseHandle(ov.hEvent);
2889 ov.hEvent = NULL;
2891 goto fail;
2894 if (ov.hEvent) {
2895 CloseHandle(ov.hEvent);
2896 ov.hEvent = NULL;
2898 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2899 return 0;
2901 fail:
2902 win_chr_close(chr);
2903 return -1;
2907 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2909 CharDriverState *chr;
2910 WinCharState *s;
2912 chr = qemu_mallocz(sizeof(CharDriverState));
2913 if (!chr)
2914 return NULL;
2915 s = qemu_mallocz(sizeof(WinCharState));
2916 if (!s) {
2917 free(chr);
2918 return NULL;
2920 chr->opaque = s;
2921 chr->chr_write = win_chr_write;
2922 chr->chr_close = win_chr_close;
2924 if (win_chr_pipe_init(chr, filename) < 0) {
2925 free(s);
2926 free(chr);
2927 return NULL;
2929 qemu_chr_reset(chr);
2930 return chr;
2933 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2935 CharDriverState *chr;
2936 WinCharState *s;
2938 chr = qemu_mallocz(sizeof(CharDriverState));
2939 if (!chr)
2940 return NULL;
2941 s = qemu_mallocz(sizeof(WinCharState));
2942 if (!s) {
2943 free(chr);
2944 return NULL;
2946 s->hcom = fd_out;
2947 chr->opaque = s;
2948 chr->chr_write = win_chr_write;
2949 qemu_chr_reset(chr);
2950 return chr;
2953 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2955 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2958 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2960 HANDLE fd_out;
2962 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2963 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2964 if (fd_out == INVALID_HANDLE_VALUE)
2965 return NULL;
2967 return qemu_chr_open_win_file(fd_out);
2969 #endif /* !_WIN32 */
2971 /***********************************************************/
2972 /* UDP Net console */
2974 typedef struct {
2975 int fd;
2976 struct sockaddr_in daddr;
2977 uint8_t buf[1024];
2978 int bufcnt;
2979 int bufptr;
2980 int max_size;
2981 } NetCharDriver;
2983 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2985 NetCharDriver *s = chr->opaque;
2987 return sendto(s->fd, buf, len, 0,
2988 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2991 static int udp_chr_read_poll(void *opaque)
2993 CharDriverState *chr = opaque;
2994 NetCharDriver *s = chr->opaque;
2996 s->max_size = qemu_chr_can_read(chr);
2998 /* If there were any stray characters in the queue process them
2999 * first
3001 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3002 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3003 s->bufptr++;
3004 s->max_size = qemu_chr_can_read(chr);
3006 return s->max_size;
3009 static void udp_chr_read(void *opaque)
3011 CharDriverState *chr = opaque;
3012 NetCharDriver *s = chr->opaque;
3014 if (s->max_size == 0)
3015 return;
3016 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3017 s->bufptr = s->bufcnt;
3018 if (s->bufcnt <= 0)
3019 return;
3021 s->bufptr = 0;
3022 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3023 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3024 s->bufptr++;
3025 s->max_size = qemu_chr_can_read(chr);
3029 static void udp_chr_update_read_handler(CharDriverState *chr)
3031 NetCharDriver *s = chr->opaque;
3033 if (s->fd >= 0) {
3034 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3035 udp_chr_read, NULL, chr);
3039 #ifndef _WIN32
3040 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3041 #endif
3042 int parse_host_src_port(struct sockaddr_in *haddr,
3043 struct sockaddr_in *saddr,
3044 const char *str);
3046 static CharDriverState *qemu_chr_open_udp(const char *def)
3048 CharDriverState *chr = NULL;
3049 NetCharDriver *s = NULL;
3050 int fd = -1;
3051 struct sockaddr_in saddr;
3053 chr = qemu_mallocz(sizeof(CharDriverState));
3054 if (!chr)
3055 goto return_err;
3056 s = qemu_mallocz(sizeof(NetCharDriver));
3057 if (!s)
3058 goto return_err;
3060 fd = socket(PF_INET, SOCK_DGRAM, 0);
3061 if (fd < 0) {
3062 perror("socket(PF_INET, SOCK_DGRAM)");
3063 goto return_err;
3066 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3067 printf("Could not parse: %s\n", def);
3068 goto return_err;
3071 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3073 perror("bind");
3074 goto return_err;
3077 s->fd = fd;
3078 s->bufcnt = 0;
3079 s->bufptr = 0;
3080 chr->opaque = s;
3081 chr->chr_write = udp_chr_write;
3082 chr->chr_update_read_handler = udp_chr_update_read_handler;
3083 return chr;
3085 return_err:
3086 if (chr)
3087 free(chr);
3088 if (s)
3089 free(s);
3090 if (fd >= 0)
3091 closesocket(fd);
3092 return NULL;
3095 /***********************************************************/
3096 /* TCP Net console */
3098 typedef struct {
3099 int fd, listen_fd;
3100 int connected;
3101 int max_size;
3102 int do_telnetopt;
3103 int do_nodelay;
3104 int is_unix;
3105 } TCPCharDriver;
3107 static void tcp_chr_accept(void *opaque);
3109 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3111 TCPCharDriver *s = chr->opaque;
3112 if (s->connected) {
3113 return send_all(s->fd, buf, len);
3114 } else {
3115 /* XXX: indicate an error ? */
3116 return len;
3120 static int tcp_chr_read_poll(void *opaque)
3122 CharDriverState *chr = opaque;
3123 TCPCharDriver *s = chr->opaque;
3124 if (!s->connected)
3125 return 0;
3126 s->max_size = qemu_chr_can_read(chr);
3127 return s->max_size;
3130 #define IAC 255
3131 #define IAC_BREAK 243
3132 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3133 TCPCharDriver *s,
3134 uint8_t *buf, int *size)
3136 /* Handle any telnet client's basic IAC options to satisfy char by
3137 * char mode with no echo. All IAC options will be removed from
3138 * the buf and the do_telnetopt variable will be used to track the
3139 * state of the width of the IAC information.
3141 * IAC commands come in sets of 3 bytes with the exception of the
3142 * "IAC BREAK" command and the double IAC.
3145 int i;
3146 int j = 0;
3148 for (i = 0; i < *size; i++) {
3149 if (s->do_telnetopt > 1) {
3150 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3151 /* Double IAC means send an IAC */
3152 if (j != i)
3153 buf[j] = buf[i];
3154 j++;
3155 s->do_telnetopt = 1;
3156 } else {
3157 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3158 /* Handle IAC break commands by sending a serial break */
3159 qemu_chr_event(chr, CHR_EVENT_BREAK);
3160 s->do_telnetopt++;
3162 s->do_telnetopt++;
3164 if (s->do_telnetopt >= 4) {
3165 s->do_telnetopt = 1;
3167 } else {
3168 if ((unsigned char)buf[i] == IAC) {
3169 s->do_telnetopt = 2;
3170 } else {
3171 if (j != i)
3172 buf[j] = buf[i];
3173 j++;
3177 *size = j;
3180 static void tcp_chr_read(void *opaque)
3182 CharDriverState *chr = opaque;
3183 TCPCharDriver *s = chr->opaque;
3184 uint8_t buf[1024];
3185 int len, size;
3187 if (!s->connected || s->max_size <= 0)
3188 return;
3189 len = sizeof(buf);
3190 if (len > s->max_size)
3191 len = s->max_size;
3192 size = recv(s->fd, buf, len, 0);
3193 if (size == 0) {
3194 /* connection closed */
3195 s->connected = 0;
3196 if (s->listen_fd >= 0) {
3197 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3199 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3200 closesocket(s->fd);
3201 s->fd = -1;
3202 } else if (size > 0) {
3203 if (s->do_telnetopt)
3204 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3205 if (size > 0)
3206 qemu_chr_read(chr, buf, size);
3210 static void tcp_chr_connect(void *opaque)
3212 CharDriverState *chr = opaque;
3213 TCPCharDriver *s = chr->opaque;
3215 s->connected = 1;
3216 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3217 tcp_chr_read, NULL, chr);
3218 qemu_chr_reset(chr);
3221 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3222 static void tcp_chr_telnet_init(int fd)
3224 char buf[3];
3225 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3226 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3227 send(fd, (char *)buf, 3, 0);
3228 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3229 send(fd, (char *)buf, 3, 0);
3230 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3231 send(fd, (char *)buf, 3, 0);
3232 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3233 send(fd, (char *)buf, 3, 0);
3236 static void socket_set_nodelay(int fd)
3238 int val = 1;
3239 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3242 static void tcp_chr_accept(void *opaque)
3244 CharDriverState *chr = opaque;
3245 TCPCharDriver *s = chr->opaque;
3246 struct sockaddr_in saddr;
3247 #ifndef _WIN32
3248 struct sockaddr_un uaddr;
3249 #endif
3250 struct sockaddr *addr;
3251 socklen_t len;
3252 int fd;
3254 for(;;) {
3255 #ifndef _WIN32
3256 if (s->is_unix) {
3257 len = sizeof(uaddr);
3258 addr = (struct sockaddr *)&uaddr;
3259 } else
3260 #endif
3262 len = sizeof(saddr);
3263 addr = (struct sockaddr *)&saddr;
3265 fd = accept(s->listen_fd, addr, &len);
3266 if (fd < 0 && errno != EINTR) {
3267 return;
3268 } else if (fd >= 0) {
3269 if (s->do_telnetopt)
3270 tcp_chr_telnet_init(fd);
3271 break;
3274 socket_set_nonblock(fd);
3275 if (s->do_nodelay)
3276 socket_set_nodelay(fd);
3277 s->fd = fd;
3278 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3279 tcp_chr_connect(chr);
3282 static void tcp_chr_close(CharDriverState *chr)
3284 TCPCharDriver *s = chr->opaque;
3285 if (s->fd >= 0)
3286 closesocket(s->fd);
3287 if (s->listen_fd >= 0)
3288 closesocket(s->listen_fd);
3289 qemu_free(s);
3292 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3293 int is_telnet,
3294 int is_unix)
3296 CharDriverState *chr = NULL;
3297 TCPCharDriver *s = NULL;
3298 int fd = -1, ret, err, val;
3299 int is_listen = 0;
3300 int is_waitconnect = 1;
3301 int do_nodelay = 0;
3302 const char *ptr;
3303 struct sockaddr_in saddr;
3304 #ifndef _WIN32
3305 struct sockaddr_un uaddr;
3306 #endif
3307 struct sockaddr *addr;
3308 socklen_t addrlen;
3310 #ifndef _WIN32
3311 if (is_unix) {
3312 addr = (struct sockaddr *)&uaddr;
3313 addrlen = sizeof(uaddr);
3314 if (parse_unix_path(&uaddr, host_str) < 0)
3315 goto fail;
3316 } else
3317 #endif
3319 addr = (struct sockaddr *)&saddr;
3320 addrlen = sizeof(saddr);
3321 if (parse_host_port(&saddr, host_str) < 0)
3322 goto fail;
3325 ptr = host_str;
3326 while((ptr = strchr(ptr,','))) {
3327 ptr++;
3328 if (!strncmp(ptr,"server",6)) {
3329 is_listen = 1;
3330 } else if (!strncmp(ptr,"nowait",6)) {
3331 is_waitconnect = 0;
3332 } else if (!strncmp(ptr,"nodelay",6)) {
3333 do_nodelay = 1;
3334 } else {
3335 printf("Unknown option: %s\n", ptr);
3336 goto fail;
3339 if (!is_listen)
3340 is_waitconnect = 0;
3342 chr = qemu_mallocz(sizeof(CharDriverState));
3343 if (!chr)
3344 goto fail;
3345 s = qemu_mallocz(sizeof(TCPCharDriver));
3346 if (!s)
3347 goto fail;
3349 #ifndef _WIN32
3350 if (is_unix)
3351 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3352 else
3353 #endif
3354 fd = socket(PF_INET, SOCK_STREAM, 0);
3356 if (fd < 0)
3357 goto fail;
3359 if (!is_waitconnect)
3360 socket_set_nonblock(fd);
3362 s->connected = 0;
3363 s->fd = -1;
3364 s->listen_fd = -1;
3365 s->is_unix = is_unix;
3366 s->do_nodelay = do_nodelay && !is_unix;
3368 chr->opaque = s;
3369 chr->chr_write = tcp_chr_write;
3370 chr->chr_close = tcp_chr_close;
3372 if (is_listen) {
3373 /* allow fast reuse */
3374 #ifndef _WIN32
3375 if (is_unix) {
3376 char path[109];
3377 strncpy(path, uaddr.sun_path, 108);
3378 path[108] = 0;
3379 unlink(path);
3380 } else
3381 #endif
3383 val = 1;
3384 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3387 ret = bind(fd, addr, addrlen);
3388 if (ret < 0)
3389 goto fail;
3391 ret = listen(fd, 0);
3392 if (ret < 0)
3393 goto fail;
3395 s->listen_fd = fd;
3396 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3397 if (is_telnet)
3398 s->do_telnetopt = 1;
3399 } else {
3400 for(;;) {
3401 ret = connect(fd, addr, addrlen);
3402 if (ret < 0) {
3403 err = socket_error();
3404 if (err == EINTR || err == EWOULDBLOCK) {
3405 } else if (err == EINPROGRESS) {
3406 break;
3407 #ifdef _WIN32
3408 } else if (err == WSAEALREADY) {
3409 break;
3410 #endif
3411 } else {
3412 goto fail;
3414 } else {
3415 s->connected = 1;
3416 break;
3419 s->fd = fd;
3420 socket_set_nodelay(fd);
3421 if (s->connected)
3422 tcp_chr_connect(chr);
3423 else
3424 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3427 if (is_listen && is_waitconnect) {
3428 printf("QEMU waiting for connection on: %s\n", host_str);
3429 tcp_chr_accept(chr);
3430 socket_set_nonblock(s->listen_fd);
3433 return chr;
3434 fail:
3435 if (fd >= 0)
3436 closesocket(fd);
3437 qemu_free(s);
3438 qemu_free(chr);
3439 return NULL;
3442 CharDriverState *qemu_chr_open(const char *filename)
3444 const char *p;
3446 if (!strcmp(filename, "vc")) {
3447 return text_console_init(&display_state, 0);
3448 } else if (strstart(filename, "vc:", &p)) {
3449 return text_console_init(&display_state, p);
3450 } else if (!strcmp(filename, "null")) {
3451 return qemu_chr_open_null();
3452 } else
3453 if (strstart(filename, "tcp:", &p)) {
3454 return qemu_chr_open_tcp(p, 0, 0);
3455 } else
3456 if (strstart(filename, "telnet:", &p)) {
3457 return qemu_chr_open_tcp(p, 1, 0);
3458 } else
3459 if (strstart(filename, "udp:", &p)) {
3460 return qemu_chr_open_udp(p);
3461 } else
3462 if (strstart(filename, "mon:", &p)) {
3463 CharDriverState *drv = qemu_chr_open(p);
3464 if (drv) {
3465 drv = qemu_chr_open_mux(drv);
3466 monitor_init(drv, !nographic);
3467 return drv;
3469 printf("Unable to open driver: %s\n", p);
3470 return 0;
3471 } else
3472 #ifndef _WIN32
3473 if (strstart(filename, "unix:", &p)) {
3474 return qemu_chr_open_tcp(p, 0, 1);
3475 } else if (strstart(filename, "file:", &p)) {
3476 return qemu_chr_open_file_out(p);
3477 } else if (strstart(filename, "pipe:", &p)) {
3478 return qemu_chr_open_pipe(p);
3479 } else if (!strcmp(filename, "pty")) {
3480 return qemu_chr_open_pty();
3481 } else if (!strcmp(filename, "stdio")) {
3482 return qemu_chr_open_stdio();
3483 } else
3484 #if defined(__linux__)
3485 if (strstart(filename, "/dev/parport", NULL)) {
3486 return qemu_chr_open_pp(filename);
3487 } else
3488 #endif
3489 #if defined(__linux__) || defined(__sun__)
3490 if (strstart(filename, "/dev/", NULL)) {
3491 return qemu_chr_open_tty(filename);
3492 } else
3493 #endif
3494 #else /* !_WIN32 */
3495 if (strstart(filename, "COM", NULL)) {
3496 return qemu_chr_open_win(filename);
3497 } else
3498 if (strstart(filename, "pipe:", &p)) {
3499 return qemu_chr_open_win_pipe(p);
3500 } else
3501 if (strstart(filename, "con:", NULL)) {
3502 return qemu_chr_open_win_con(filename);
3503 } else
3504 if (strstart(filename, "file:", &p)) {
3505 return qemu_chr_open_win_file_out(p);
3507 #endif
3509 return NULL;
3513 void qemu_chr_close(CharDriverState *chr)
3515 if (chr->chr_close)
3516 chr->chr_close(chr);
3517 qemu_free(chr);
3520 /***********************************************************/
3521 /* network device redirectors */
3523 __attribute__ (( unused ))
3524 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3526 int len, i, j, c;
3528 for(i=0;i<size;i+=16) {
3529 len = size - i;
3530 if (len > 16)
3531 len = 16;
3532 fprintf(f, "%08x ", i);
3533 for(j=0;j<16;j++) {
3534 if (j < len)
3535 fprintf(f, " %02x", buf[i+j]);
3536 else
3537 fprintf(f, " ");
3539 fprintf(f, " ");
3540 for(j=0;j<len;j++) {
3541 c = buf[i+j];
3542 if (c < ' ' || c > '~')
3543 c = '.';
3544 fprintf(f, "%c", c);
3546 fprintf(f, "\n");
3550 static int parse_macaddr(uint8_t *macaddr, const char *p)
3552 int i;
3553 char *last_char;
3554 long int offset;
3556 errno = 0;
3557 offset = strtol(p, &last_char, 0);
3558 if (0 == errno && '\0' == *last_char &&
3559 offset >= 0 && offset <= 0xFFFFFF) {
3560 macaddr[3] = (offset & 0xFF0000) >> 16;
3561 macaddr[4] = (offset & 0xFF00) >> 8;
3562 macaddr[5] = offset & 0xFF;
3563 return 0;
3564 } else {
3565 for(i = 0; i < 6; i++) {
3566 macaddr[i] = strtol(p, (char **)&p, 16);
3567 if (i == 5) {
3568 if (*p != '\0')
3569 return -1;
3570 } else {
3571 if (*p != ':' && *p != '-')
3572 return -1;
3573 p++;
3576 return 0;
3579 return -1;
3582 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3584 const char *p, *p1;
3585 int len;
3586 p = *pp;
3587 p1 = strchr(p, sep);
3588 if (!p1)
3589 return -1;
3590 len = p1 - p;
3591 p1++;
3592 if (buf_size > 0) {
3593 if (len > buf_size - 1)
3594 len = buf_size - 1;
3595 memcpy(buf, p, len);
3596 buf[len] = '\0';
3598 *pp = p1;
3599 return 0;
3602 int parse_host_src_port(struct sockaddr_in *haddr,
3603 struct sockaddr_in *saddr,
3604 const char *input_str)
3606 char *str = strdup(input_str);
3607 char *host_str = str;
3608 char *src_str;
3609 char *ptr;
3612 * Chop off any extra arguments at the end of the string which
3613 * would start with a comma, then fill in the src port information
3614 * if it was provided else use the "any address" and "any port".
3616 if ((ptr = strchr(str,',')))
3617 *ptr = '\0';
3619 if ((src_str = strchr(input_str,'@'))) {
3620 *src_str = '\0';
3621 src_str++;
3624 if (parse_host_port(haddr, host_str) < 0)
3625 goto fail;
3627 if (!src_str || *src_str == '\0')
3628 src_str = ":0";
3630 if (parse_host_port(saddr, src_str) < 0)
3631 goto fail;
3633 free(str);
3634 return(0);
3636 fail:
3637 free(str);
3638 return -1;
3641 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3643 char buf[512];
3644 struct hostent *he;
3645 const char *p, *r;
3646 int port;
3648 p = str;
3649 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3650 return -1;
3651 saddr->sin_family = AF_INET;
3652 if (buf[0] == '\0') {
3653 saddr->sin_addr.s_addr = 0;
3654 } else {
3655 if (isdigit(buf[0])) {
3656 if (!inet_aton(buf, &saddr->sin_addr))
3657 return -1;
3658 } else {
3659 if ((he = gethostbyname(buf)) == NULL)
3660 return - 1;
3661 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3664 port = strtol(p, (char **)&r, 0);
3665 if (r == p)
3666 return -1;
3667 saddr->sin_port = htons(port);
3668 return 0;
3671 #ifndef _WIN32
3672 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3674 const char *p;
3675 int len;
3677 len = MIN(108, strlen(str));
3678 p = strchr(str, ',');
3679 if (p)
3680 len = MIN(len, p - str);
3682 memset(uaddr, 0, sizeof(*uaddr));
3684 uaddr->sun_family = AF_UNIX;
3685 memcpy(uaddr->sun_path, str, len);
3687 return 0;
3689 #endif
3691 /* find or alloc a new VLAN */
3692 VLANState *qemu_find_vlan(int id)
3694 VLANState **pvlan, *vlan;
3695 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3696 if (vlan->id == id)
3697 return vlan;
3699 vlan = qemu_mallocz(sizeof(VLANState));
3700 if (!vlan)
3701 return NULL;
3702 vlan->id = id;
3703 vlan->next = NULL;
3704 pvlan = &first_vlan;
3705 while (*pvlan != NULL)
3706 pvlan = &(*pvlan)->next;
3707 *pvlan = vlan;
3708 return vlan;
3711 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3712 IOReadHandler *fd_read,
3713 IOCanRWHandler *fd_can_read,
3714 void *opaque)
3716 VLANClientState *vc, **pvc;
3717 vc = qemu_mallocz(sizeof(VLANClientState));
3718 if (!vc)
3719 return NULL;
3720 vc->fd_read = fd_read;
3721 vc->fd_can_read = fd_can_read;
3722 vc->opaque = opaque;
3723 vc->vlan = vlan;
3725 vc->next = NULL;
3726 pvc = &vlan->first_client;
3727 while (*pvc != NULL)
3728 pvc = &(*pvc)->next;
3729 *pvc = vc;
3730 return vc;
3733 int qemu_can_send_packet(VLANClientState *vc1)
3735 VLANState *vlan = vc1->vlan;
3736 VLANClientState *vc;
3738 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3739 if (vc != vc1) {
3740 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3741 return 1;
3744 return 0;
3747 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3749 VLANState *vlan = vc1->vlan;
3750 VLANClientState *vc;
3752 #if 0
3753 printf("vlan %d send:\n", vlan->id);
3754 hex_dump(stdout, buf, size);
3755 #endif
3756 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3757 if (vc != vc1) {
3758 vc->fd_read(vc->opaque, buf, size);
3763 #if defined(CONFIG_SLIRP)
3765 /* slirp network adapter */
3767 static int slirp_inited;
3768 static VLANClientState *slirp_vc;
3770 int slirp_can_output(void)
3772 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3775 void slirp_output(const uint8_t *pkt, int pkt_len)
3777 #if 0
3778 printf("slirp output:\n");
3779 hex_dump(stdout, pkt, pkt_len);
3780 #endif
3781 if (!slirp_vc)
3782 return;
3783 qemu_send_packet(slirp_vc, pkt, pkt_len);
3786 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3788 #if 0
3789 printf("slirp input:\n");
3790 hex_dump(stdout, buf, size);
3791 #endif
3792 slirp_input(buf, size);
3795 static int net_slirp_init(VLANState *vlan)
3797 if (!slirp_inited) {
3798 slirp_inited = 1;
3799 slirp_init();
3801 slirp_vc = qemu_new_vlan_client(vlan,
3802 slirp_receive, NULL, NULL);
3803 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3804 return 0;
3807 static void net_slirp_redir(const char *redir_str)
3809 int is_udp;
3810 char buf[256], *r;
3811 const char *p;
3812 struct in_addr guest_addr;
3813 int host_port, guest_port;
3815 if (!slirp_inited) {
3816 slirp_inited = 1;
3817 slirp_init();
3820 p = redir_str;
3821 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3822 goto fail;
3823 if (!strcmp(buf, "tcp")) {
3824 is_udp = 0;
3825 } else if (!strcmp(buf, "udp")) {
3826 is_udp = 1;
3827 } else {
3828 goto fail;
3831 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3832 goto fail;
3833 host_port = strtol(buf, &r, 0);
3834 if (r == buf)
3835 goto fail;
3837 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3838 goto fail;
3839 if (buf[0] == '\0') {
3840 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3842 if (!inet_aton(buf, &guest_addr))
3843 goto fail;
3845 guest_port = strtol(p, &r, 0);
3846 if (r == p)
3847 goto fail;
3849 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3850 fprintf(stderr, "qemu: could not set up redirection\n");
3851 exit(1);
3853 return;
3854 fail:
3855 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3856 exit(1);
3859 #ifndef _WIN32
3861 char smb_dir[1024];
3863 static void erase_dir(char *dir_name)
3865 DIR *d;
3866 struct dirent *de;
3867 char filename[1024];
3869 /* erase all the files in the directory */
3870 if ((d = opendir(dir_name)) != 0) {
3871 for(;;) {
3872 de = readdir(d);
3873 if (!de)
3874 break;
3875 if (strcmp(de->d_name, ".") != 0 &&
3876 strcmp(de->d_name, "..") != 0) {
3877 snprintf(filename, sizeof(filename), "%s/%s",
3878 smb_dir, de->d_name);
3879 if (unlink(filename) != 0) /* is it a directory? */
3880 erase_dir(filename);
3883 closedir(d);
3884 rmdir(dir_name);
3888 /* automatic user mode samba server configuration */
3889 static void smb_exit(void)
3891 erase_dir(smb_dir);
3894 /* automatic user mode samba server configuration */
3895 static void net_slirp_smb(const char *exported_dir)
3897 char smb_conf[1024];
3898 char smb_cmdline[1024];
3899 FILE *f;
3901 if (!slirp_inited) {
3902 slirp_inited = 1;
3903 slirp_init();
3906 /* XXX: better tmp dir construction */
3907 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3908 if (mkdir(smb_dir, 0700) < 0) {
3909 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3910 exit(1);
3912 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3914 f = fopen(smb_conf, "w");
3915 if (!f) {
3916 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3917 exit(1);
3919 fprintf(f,
3920 "[global]\n"
3921 "private dir=%s\n"
3922 "smb ports=0\n"
3923 "socket address=127.0.0.1\n"
3924 "pid directory=%s\n"
3925 "lock directory=%s\n"
3926 "log file=%s/log.smbd\n"
3927 "smb passwd file=%s/smbpasswd\n"
3928 "security = share\n"
3929 "[qemu]\n"
3930 "path=%s\n"
3931 "read only=no\n"
3932 "guest ok=yes\n",
3933 smb_dir,
3934 smb_dir,
3935 smb_dir,
3936 smb_dir,
3937 smb_dir,
3938 exported_dir
3940 fclose(f);
3941 atexit(smb_exit);
3943 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3944 SMBD_COMMAND, smb_conf);
3946 slirp_add_exec(0, smb_cmdline, 4, 139);
3949 #endif /* !defined(_WIN32) */
3950 void do_info_slirp(void)
3952 slirp_stats();
3955 #endif /* CONFIG_SLIRP */
3957 #if !defined(_WIN32)
3959 typedef struct TAPState {
3960 VLANClientState *vc;
3961 int fd;
3962 char down_script[1024];
3963 int no_poll;
3964 } TAPState;
3966 static int tap_read_poll(void *opaque)
3968 TAPState *s = opaque;
3969 return (!s->no_poll);
3972 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3974 TAPState *s = opaque;
3975 int ret;
3976 for(;;) {
3977 ret = write(s->fd, buf, size);
3978 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3979 } else {
3980 break;
3985 static void tap_send(void *opaque)
3987 TAPState *s = opaque;
3988 uint8_t buf[4096];
3989 int size;
3991 #ifdef __sun__
3992 struct strbuf sbuf;
3993 int f = 0;
3994 sbuf.maxlen = sizeof(buf);
3995 sbuf.buf = buf;
3996 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3997 #else
3998 size = read(s->fd, buf, sizeof(buf));
3999 #endif
4000 if (size > 0) {
4001 qemu_send_packet(s->vc, buf, size);
4005 int hack_around_tap(void *opaque)
4007 VLANClientState *vc = opaque;
4008 TAPState *ts = vc->opaque;
4010 if (vc->fd_read != tap_receive)
4011 return -1;
4013 if (ts) {
4014 ts->no_poll = 1;
4015 return ts->fd;
4018 return -1;
4021 /* fd support */
4023 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4025 TAPState *s;
4027 s = qemu_mallocz(sizeof(TAPState));
4028 if (!s)
4029 return NULL;
4030 s->fd = fd;
4031 s->no_poll = 0;
4032 enable_sigio_timer(fd);
4033 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4034 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
4035 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4036 return s;
4039 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4040 static int tap_open(char *ifname, int ifname_size)
4042 int fd;
4043 char *dev;
4044 struct stat s;
4046 TFR(fd = open("/dev/tap", O_RDWR));
4047 if (fd < 0) {
4048 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4049 return -1;
4052 fstat(fd, &s);
4053 dev = devname(s.st_rdev, S_IFCHR);
4054 pstrcpy(ifname, ifname_size, dev);
4056 fcntl(fd, F_SETFL, O_NONBLOCK);
4057 return fd;
4059 #elif defined(__sun__)
4060 #define TUNNEWPPA (('T'<<16) | 0x0001)
4062 * Allocate TAP device, returns opened fd.
4063 * Stores dev name in the first arg(must be large enough).
4065 int tap_alloc(char *dev)
4067 int tap_fd, if_fd, ppa = -1;
4068 static int ip_fd = 0;
4069 char *ptr;
4071 static int arp_fd = 0;
4072 int ip_muxid, arp_muxid;
4073 struct strioctl strioc_if, strioc_ppa;
4074 int link_type = I_PLINK;;
4075 struct lifreq ifr;
4076 char actual_name[32] = "";
4078 memset(&ifr, 0x0, sizeof(ifr));
4080 if( *dev ){
4081 ptr = dev;
4082 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4083 ppa = atoi(ptr);
4086 /* Check if IP device was opened */
4087 if( ip_fd )
4088 close(ip_fd);
4090 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4091 if (ip_fd < 0) {
4092 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4093 return -1;
4096 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4097 if (tap_fd < 0) {
4098 syslog(LOG_ERR, "Can't open /dev/tap");
4099 return -1;
4102 /* Assign a new PPA and get its unit number. */
4103 strioc_ppa.ic_cmd = TUNNEWPPA;
4104 strioc_ppa.ic_timout = 0;
4105 strioc_ppa.ic_len = sizeof(ppa);
4106 strioc_ppa.ic_dp = (char *)&ppa;
4107 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4108 syslog (LOG_ERR, "Can't assign new interface");
4110 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4111 if (if_fd < 0) {
4112 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4113 return -1;
4115 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4116 syslog(LOG_ERR, "Can't push IP module");
4117 return -1;
4120 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4121 syslog(LOG_ERR, "Can't get flags\n");
4123 snprintf (actual_name, 32, "tap%d", ppa);
4124 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4126 ifr.lifr_ppa = ppa;
4127 /* Assign ppa according to the unit number returned by tun device */
4129 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4130 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4131 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4132 syslog (LOG_ERR, "Can't get flags\n");
4133 /* Push arp module to if_fd */
4134 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4135 syslog (LOG_ERR, "Can't push ARP module (2)");
4137 /* Push arp module to ip_fd */
4138 if (ioctl (ip_fd, I_POP, NULL) < 0)
4139 syslog (LOG_ERR, "I_POP failed\n");
4140 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4141 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4142 /* Open arp_fd */
4143 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4144 if (arp_fd < 0)
4145 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4147 /* Set ifname to arp */
4148 strioc_if.ic_cmd = SIOCSLIFNAME;
4149 strioc_if.ic_timout = 0;
4150 strioc_if.ic_len = sizeof(ifr);
4151 strioc_if.ic_dp = (char *)&ifr;
4152 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4153 syslog (LOG_ERR, "Can't set ifname to arp\n");
4156 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4157 syslog(LOG_ERR, "Can't link TAP device to IP");
4158 return -1;
4161 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4162 syslog (LOG_ERR, "Can't link TAP device to ARP");
4164 close (if_fd);
4166 memset(&ifr, 0x0, sizeof(ifr));
4167 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4168 ifr.lifr_ip_muxid = ip_muxid;
4169 ifr.lifr_arp_muxid = arp_muxid;
4171 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4173 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4174 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4175 syslog (LOG_ERR, "Can't set multiplexor id");
4178 sprintf(dev, "tap%d", ppa);
4179 return tap_fd;
4182 static int tap_open(char *ifname, int ifname_size)
4184 char dev[10]="";
4185 int fd;
4186 if( (fd = tap_alloc(dev)) < 0 ){
4187 fprintf(stderr, "Cannot allocate TAP device\n");
4188 return -1;
4190 pstrcpy(ifname, ifname_size, dev);
4191 fcntl(fd, F_SETFL, O_NONBLOCK);
4192 return fd;
4194 #else
4195 static int tap_open(char *ifname, int ifname_size)
4197 struct ifreq ifr;
4198 int fd, ret;
4200 TFR(fd = open("/dev/net/tun", O_RDWR));
4201 if (fd < 0) {
4202 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4203 return -1;
4205 memset(&ifr, 0, sizeof(ifr));
4206 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4207 if (ifname[0] != '\0')
4208 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4209 else
4210 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4211 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4212 if (ret != 0) {
4213 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4214 close(fd);
4215 return -1;
4217 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4218 fcntl(fd, F_SETFL, O_NONBLOCK);
4219 return fd;
4221 #endif
4223 static int launch_script(const char *setup_script, const char *ifname, int fd)
4225 int pid, status;
4226 char *args[3];
4227 char **parg;
4229 /* try to launch network script */
4230 pid = fork();
4231 if (pid >= 0) {
4232 if (pid == 0) {
4233 int open_max = sysconf (_SC_OPEN_MAX), i;
4234 for (i = 0; i < open_max; i++)
4235 if (i != STDIN_FILENO &&
4236 i != STDOUT_FILENO &&
4237 i != STDERR_FILENO &&
4238 i != fd)
4239 close(i);
4241 parg = args;
4242 *parg++ = (char *)setup_script;
4243 *parg++ = (char *)ifname;
4244 *parg++ = NULL;
4245 execv(setup_script, args);
4246 _exit(1);
4248 while (waitpid(pid, &status, 0) != pid);
4249 if (!WIFEXITED(status) ||
4250 WEXITSTATUS(status) != 0) {
4251 fprintf(stderr, "%s: could not launch network script\n",
4252 setup_script);
4253 return -1;
4256 return 0;
4259 static int net_tap_init(VLANState *vlan, const char *ifname1,
4260 const char *setup_script, const char *down_script)
4262 TAPState *s;
4263 int fd;
4264 char ifname[128];
4266 if (ifname1 != NULL)
4267 pstrcpy(ifname, sizeof(ifname), ifname1);
4268 else
4269 ifname[0] = '\0';
4270 TFR(fd = tap_open(ifname, sizeof(ifname)));
4271 if (fd < 0)
4272 return -1;
4274 if (!setup_script || !strcmp(setup_script, "no"))
4275 setup_script = "";
4276 if (setup_script[0] != '\0') {
4277 if (launch_script(setup_script, ifname, fd))
4278 return -1;
4280 s = net_tap_fd_init(vlan, fd);
4281 if (!s)
4282 return -1;
4283 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4284 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4285 if (down_script && strcmp(down_script, "no"))
4286 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4287 return 0;
4290 #endif /* !_WIN32 */
4292 /* network connection */
4293 typedef struct NetSocketState {
4294 VLANClientState *vc;
4295 int fd;
4296 int state; /* 0 = getting length, 1 = getting data */
4297 int index;
4298 int packet_len;
4299 uint8_t buf[4096];
4300 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4301 } NetSocketState;
4303 typedef struct NetSocketListenState {
4304 VLANState *vlan;
4305 int fd;
4306 } NetSocketListenState;
4308 /* XXX: we consider we can send the whole packet without blocking */
4309 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4311 NetSocketState *s = opaque;
4312 uint32_t len;
4313 len = htonl(size);
4315 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4316 send_all(s->fd, buf, size);
4319 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4321 NetSocketState *s = opaque;
4322 sendto(s->fd, buf, size, 0,
4323 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4326 static void net_socket_send(void *opaque)
4328 NetSocketState *s = opaque;
4329 int l, size, err;
4330 uint8_t buf1[4096];
4331 const uint8_t *buf;
4333 size = recv(s->fd, buf1, sizeof(buf1), 0);
4334 if (size < 0) {
4335 err = socket_error();
4336 if (err != EWOULDBLOCK)
4337 goto eoc;
4338 } else if (size == 0) {
4339 /* end of connection */
4340 eoc:
4341 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4342 closesocket(s->fd);
4343 return;
4345 buf = buf1;
4346 while (size > 0) {
4347 /* reassemble a packet from the network */
4348 switch(s->state) {
4349 case 0:
4350 l = 4 - s->index;
4351 if (l > size)
4352 l = size;
4353 memcpy(s->buf + s->index, buf, l);
4354 buf += l;
4355 size -= l;
4356 s->index += l;
4357 if (s->index == 4) {
4358 /* got length */
4359 s->packet_len = ntohl(*(uint32_t *)s->buf);
4360 s->index = 0;
4361 s->state = 1;
4363 break;
4364 case 1:
4365 l = s->packet_len - s->index;
4366 if (l > size)
4367 l = size;
4368 memcpy(s->buf + s->index, buf, l);
4369 s->index += l;
4370 buf += l;
4371 size -= l;
4372 if (s->index >= s->packet_len) {
4373 qemu_send_packet(s->vc, s->buf, s->packet_len);
4374 s->index = 0;
4375 s->state = 0;
4377 break;
4382 static void net_socket_send_dgram(void *opaque)
4384 NetSocketState *s = opaque;
4385 int size;
4387 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4388 if (size < 0)
4389 return;
4390 if (size == 0) {
4391 /* end of connection */
4392 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4393 return;
4395 qemu_send_packet(s->vc, s->buf, size);
4398 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4400 struct ip_mreq imr;
4401 int fd;
4402 int val, ret;
4403 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4404 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4405 inet_ntoa(mcastaddr->sin_addr),
4406 (int)ntohl(mcastaddr->sin_addr.s_addr));
4407 return -1;
4410 fd = socket(PF_INET, SOCK_DGRAM, 0);
4411 if (fd < 0) {
4412 perror("socket(PF_INET, SOCK_DGRAM)");
4413 return -1;
4416 val = 1;
4417 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4418 (const char *)&val, sizeof(val));
4419 if (ret < 0) {
4420 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4421 goto fail;
4424 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4425 if (ret < 0) {
4426 perror("bind");
4427 goto fail;
4430 /* Add host to multicast group */
4431 imr.imr_multiaddr = mcastaddr->sin_addr;
4432 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4434 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4435 (const char *)&imr, sizeof(struct ip_mreq));
4436 if (ret < 0) {
4437 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4438 goto fail;
4441 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4442 val = 1;
4443 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4444 (const char *)&val, sizeof(val));
4445 if (ret < 0) {
4446 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4447 goto fail;
4450 socket_set_nonblock(fd);
4451 return fd;
4452 fail:
4453 if (fd >= 0)
4454 closesocket(fd);
4455 return -1;
4458 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4459 int is_connected)
4461 struct sockaddr_in saddr;
4462 int newfd;
4463 socklen_t saddr_len;
4464 NetSocketState *s;
4466 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4467 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4468 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4471 if (is_connected) {
4472 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4473 /* must be bound */
4474 if (saddr.sin_addr.s_addr==0) {
4475 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4476 fd);
4477 return NULL;
4479 /* clone dgram socket */
4480 newfd = net_socket_mcast_create(&saddr);
4481 if (newfd < 0) {
4482 /* error already reported by net_socket_mcast_create() */
4483 close(fd);
4484 return NULL;
4486 /* clone newfd to fd, close newfd */
4487 dup2(newfd, fd);
4488 close(newfd);
4490 } else {
4491 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4492 fd, strerror(errno));
4493 return NULL;
4497 s = qemu_mallocz(sizeof(NetSocketState));
4498 if (!s)
4499 return NULL;
4500 s->fd = fd;
4502 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4503 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4505 /* mcast: save bound address as dst */
4506 if (is_connected) s->dgram_dst=saddr;
4508 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4509 "socket: fd=%d (%s mcast=%s:%d)",
4510 fd, is_connected? "cloned" : "",
4511 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4512 return s;
4515 static void net_socket_connect(void *opaque)
4517 NetSocketState *s = opaque;
4518 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4521 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4522 int is_connected)
4524 NetSocketState *s;
4525 s = qemu_mallocz(sizeof(NetSocketState));
4526 if (!s)
4527 return NULL;
4528 s->fd = fd;
4529 s->vc = qemu_new_vlan_client(vlan,
4530 net_socket_receive, NULL, s);
4531 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4532 "socket: fd=%d", fd);
4533 if (is_connected) {
4534 net_socket_connect(s);
4535 } else {
4536 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4538 return s;
4541 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4542 int is_connected)
4544 int so_type=-1, optlen=sizeof(so_type);
4546 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4547 (socklen_t *)&optlen)< 0) {
4548 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4549 return NULL;
4551 switch(so_type) {
4552 case SOCK_DGRAM:
4553 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4554 case SOCK_STREAM:
4555 return net_socket_fd_init_stream(vlan, fd, is_connected);
4556 default:
4557 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4558 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4559 return net_socket_fd_init_stream(vlan, fd, is_connected);
4561 return NULL;
4564 static void net_socket_accept(void *opaque)
4566 NetSocketListenState *s = opaque;
4567 NetSocketState *s1;
4568 struct sockaddr_in saddr;
4569 socklen_t len;
4570 int fd;
4572 for(;;) {
4573 len = sizeof(saddr);
4574 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4575 if (fd < 0 && errno != EINTR) {
4576 return;
4577 } else if (fd >= 0) {
4578 break;
4581 s1 = net_socket_fd_init(s->vlan, fd, 1);
4582 if (!s1) {
4583 closesocket(fd);
4584 } else {
4585 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4586 "socket: connection from %s:%d",
4587 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4591 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4593 NetSocketListenState *s;
4594 int fd, val, ret;
4595 struct sockaddr_in saddr;
4597 if (parse_host_port(&saddr, host_str) < 0)
4598 return -1;
4600 s = qemu_mallocz(sizeof(NetSocketListenState));
4601 if (!s)
4602 return -1;
4604 fd = socket(PF_INET, SOCK_STREAM, 0);
4605 if (fd < 0) {
4606 perror("socket");
4607 return -1;
4609 socket_set_nonblock(fd);
4611 /* allow fast reuse */
4612 val = 1;
4613 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4615 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4616 if (ret < 0) {
4617 perror("bind");
4618 return -1;
4620 ret = listen(fd, 0);
4621 if (ret < 0) {
4622 perror("listen");
4623 return -1;
4625 s->vlan = vlan;
4626 s->fd = fd;
4627 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4628 return 0;
4631 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4633 NetSocketState *s;
4634 int fd, connected, ret, err;
4635 struct sockaddr_in saddr;
4637 if (parse_host_port(&saddr, host_str) < 0)
4638 return -1;
4640 fd = socket(PF_INET, SOCK_STREAM, 0);
4641 if (fd < 0) {
4642 perror("socket");
4643 return -1;
4645 socket_set_nonblock(fd);
4647 connected = 0;
4648 for(;;) {
4649 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4650 if (ret < 0) {
4651 err = socket_error();
4652 if (err == EINTR || err == EWOULDBLOCK) {
4653 } else if (err == EINPROGRESS) {
4654 break;
4655 #ifdef _WIN32
4656 } else if (err == WSAEALREADY) {
4657 break;
4658 #endif
4659 } else {
4660 perror("connect");
4661 closesocket(fd);
4662 return -1;
4664 } else {
4665 connected = 1;
4666 break;
4669 s = net_socket_fd_init(vlan, fd, connected);
4670 if (!s)
4671 return -1;
4672 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4673 "socket: connect to %s:%d",
4674 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4675 return 0;
4678 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4680 NetSocketState *s;
4681 int fd;
4682 struct sockaddr_in saddr;
4684 if (parse_host_port(&saddr, host_str) < 0)
4685 return -1;
4688 fd = net_socket_mcast_create(&saddr);
4689 if (fd < 0)
4690 return -1;
4692 s = net_socket_fd_init(vlan, fd, 0);
4693 if (!s)
4694 return -1;
4696 s->dgram_dst = saddr;
4698 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4699 "socket: mcast=%s:%d",
4700 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4701 return 0;
4705 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4707 char *q;
4709 q = buf;
4710 while (*p != '\0' && *p != '=') {
4711 if (q && (q - buf) < buf_size - 1)
4712 *q++ = *p;
4713 p++;
4715 if (q)
4716 *q = '\0';
4718 return p;
4721 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4723 char *q;
4725 q = buf;
4726 while (*p != '\0') {
4727 if (*p == ',') {
4728 if (*(p + 1) != ',')
4729 break;
4730 p++;
4732 if (q && (q - buf) < buf_size - 1)
4733 *q++ = *p;
4734 p++;
4736 if (q)
4737 *q = '\0';
4739 return p;
4742 int get_param_value(char *buf, int buf_size,
4743 const char *tag, const char *str)
4745 const char *p;
4746 char option[128];
4748 p = str;
4749 for(;;) {
4750 p = get_opt_name(option, sizeof(option), p);
4751 if (*p != '=')
4752 break;
4753 p++;
4754 if (!strcmp(tag, option)) {
4755 (void)get_opt_value(buf, buf_size, p);
4756 return strlen(buf);
4757 } else {
4758 p = get_opt_value(NULL, 0, p);
4760 if (*p != ',')
4761 break;
4762 p++;
4764 return 0;
4767 int check_params(char *buf, int buf_size,
4768 char **params, const char *str)
4770 const char *p;
4771 int i;
4773 p = str;
4774 for(;;) {
4775 p = get_opt_name(buf, buf_size, p);
4776 if (*p != '=')
4777 return -1;
4778 p++;
4779 for(i = 0; params[i] != NULL; i++)
4780 if (!strcmp(params[i], buf))
4781 break;
4782 if (params[i] == NULL)
4783 return -1;
4784 p = get_opt_value(NULL, 0, p);
4785 if (*p != ',')
4786 break;
4787 p++;
4789 return 0;
4792 static int nic_get_free_idx(void)
4794 int index;
4796 for (index = 0; index < MAX_NICS; index++)
4797 if (!nd_table[index].used)
4798 return index;
4799 return -1;
4802 int net_client_init(const char *str)
4804 const char *p;
4805 char *q;
4806 char device[64];
4807 char buf[1024];
4808 int vlan_id, ret;
4809 VLANState *vlan;
4811 p = str;
4812 q = device;
4813 while (*p != '\0' && *p != ',') {
4814 if ((q - device) < sizeof(device) - 1)
4815 *q++ = *p;
4816 p++;
4818 *q = '\0';
4819 if (*p == ',')
4820 p++;
4821 vlan_id = 0;
4822 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4823 vlan_id = strtol(buf, NULL, 0);
4825 vlan = qemu_find_vlan(vlan_id);
4826 if (!vlan) {
4827 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4828 return -1;
4830 if (!strcmp(device, "nic")) {
4831 NICInfo *nd;
4832 uint8_t *macaddr;
4833 int idx = nic_get_free_idx();
4835 if (idx == -1 || nb_nics >= MAX_NICS) {
4836 fprintf(stderr, "Too Many NICs\n");
4837 return -1;
4839 nd = &nd_table[idx];
4840 macaddr = nd->macaddr;
4841 macaddr[0] = 0x52;
4842 macaddr[1] = 0x54;
4843 macaddr[2] = 0x00;
4844 macaddr[3] = 0x12;
4845 macaddr[4] = 0x34;
4846 macaddr[5] = 0x56 + idx;
4848 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4849 if (parse_macaddr(macaddr, buf) < 0) {
4850 fprintf(stderr, "invalid syntax for ethernet address\n");
4851 return -1;
4854 if (get_param_value(buf, sizeof(buf), "model", p)) {
4855 nd->model = strdup(buf);
4857 nd->vlan = vlan;
4858 nd->used = 1;
4859 nb_nics++;
4860 vlan->nb_guest_devs++;
4861 ret = idx;
4862 } else
4863 if (!strcmp(device, "none")) {
4864 /* does nothing. It is needed to signal that no network cards
4865 are wanted */
4866 ret = 0;
4867 } else
4868 #ifdef CONFIG_SLIRP
4869 if (!strcmp(device, "user")) {
4870 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4871 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4873 vlan->nb_host_devs++;
4874 ret = net_slirp_init(vlan);
4875 } else
4876 #endif
4877 #ifdef _WIN32
4878 if (!strcmp(device, "tap")) {
4879 char ifname[64];
4880 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4881 fprintf(stderr, "tap: no interface name\n");
4882 return -1;
4884 vlan->nb_host_devs++;
4885 ret = tap_win32_init(vlan, ifname);
4886 } else
4887 #else
4888 if (!strcmp(device, "tap")) {
4889 char ifname[64];
4890 char setup_script[1024], down_script[1024];
4891 int fd;
4892 vlan->nb_host_devs++;
4893 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4894 fd = strtol(buf, NULL, 0);
4895 ret = -1;
4896 if (net_tap_fd_init(vlan, fd))
4897 ret = 0;
4898 } else {
4899 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4900 ifname[0] = '\0';
4902 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4903 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4905 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4906 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4908 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4910 } else
4911 #endif
4912 if (!strcmp(device, "socket")) {
4913 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4914 int fd;
4915 fd = strtol(buf, NULL, 0);
4916 ret = -1;
4917 if (net_socket_fd_init(vlan, fd, 1))
4918 ret = 0;
4919 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4920 ret = net_socket_listen_init(vlan, buf);
4921 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4922 ret = net_socket_connect_init(vlan, buf);
4923 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4924 ret = net_socket_mcast_init(vlan, buf);
4925 } else {
4926 fprintf(stderr, "Unknown socket options: %s\n", p);
4927 return -1;
4929 vlan->nb_host_devs++;
4930 } else
4932 fprintf(stderr, "Unknown network device: %s\n", device);
4933 return -1;
4935 if (ret < 0) {
4936 fprintf(stderr, "Could not initialize device '%s'\n", device);
4939 return ret;
4942 void net_client_uninit(NICInfo *nd)
4944 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
4945 nb_nics--;
4946 nd->used = 0;
4947 free((void *)nd->model);
4950 void do_info_network(void)
4952 VLANState *vlan;
4953 VLANClientState *vc;
4955 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4956 term_printf("VLAN %d devices:\n", vlan->id);
4957 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4958 term_printf(" %s\n", vc->info_str);
4962 #define HD_ALIAS "index=%d,media=disk"
4963 #ifdef TARGET_PPC
4964 #define CDROM_ALIAS "index=1,media=cdrom"
4965 #else
4966 #define CDROM_ALIAS "index=2,media=cdrom"
4967 #endif
4968 #define FD_ALIAS "index=%d,if=floppy"
4969 #define PFLASH_ALIAS "if=pflash"
4970 #define MTD_ALIAS "if=mtd"
4971 #define SD_ALIAS "index=0,if=sd"
4973 static int drive_opt_get_free_idx(void)
4975 int index;
4977 for (index = 0; index < MAX_DRIVES; index++)
4978 if (!drives_opt[index].used) {
4979 drives_opt[index].used = 1;
4980 return index;
4983 return -1;
4986 static int drive_get_free_idx(void)
4988 int index;
4990 for (index = 0; index < MAX_DRIVES; index++)
4991 if (!drives_table[index].used) {
4992 drives_table[index].used = 1;
4993 return index;
4996 return -1;
4999 int drive_add(const char *file, const char *fmt, ...)
5001 va_list ap;
5002 int index = drive_opt_get_free_idx();
5004 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5005 fprintf(stderr, "qemu: too many drives\n");
5006 return -1;
5009 drives_opt[index].file = file;
5010 va_start(ap, fmt);
5011 vsnprintf(drives_opt[index].opt,
5012 sizeof(drives_opt[0].opt), fmt, ap);
5013 va_end(ap);
5015 nb_drives_opt++;
5016 return index;
5019 void drive_remove(int index)
5021 drives_opt[index].used = 0;
5022 nb_drives_opt--;
5025 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5027 int index;
5029 /* seek interface, bus and unit */
5031 for (index = 0; index < MAX_DRIVES; index++)
5032 if (drives_table[index].type == type &&
5033 drives_table[index].bus == bus &&
5034 drives_table[index].unit == unit &&
5035 drives_table[index].used)
5036 return index;
5038 return -1;
5041 int drive_get_max_bus(BlockInterfaceType type)
5043 int max_bus;
5044 int index;
5046 max_bus = -1;
5047 for (index = 0; index < nb_drives; index++) {
5048 if(drives_table[index].type == type &&
5049 drives_table[index].bus > max_bus)
5050 max_bus = drives_table[index].bus;
5052 return max_bus;
5055 void drive_uninit(BlockDriverState *bdrv)
5057 int i;
5059 for (i = 0; i < MAX_DRIVES; i++)
5060 if (drives_table[i].bdrv == bdrv) {
5061 drives_table[i].bdrv = NULL;
5062 drives_table[i].used = 0;
5063 drive_remove(drives_table[i].drive_opt_idx);
5064 nb_drives--;
5065 break;
5069 int drive_init(struct drive_opt *arg, int snapshot,
5070 void *opaque)
5072 QEMUMachine *machine = opaque;
5073 char buf[128];
5074 char file[1024];
5075 char devname[128];
5076 const char *mediastr = "";
5077 BlockInterfaceType type;
5078 enum { MEDIA_DISK, MEDIA_CDROM } media;
5079 int bus_id, unit_id;
5080 int cyls, heads, secs, translation;
5081 BlockDriverState *bdrv;
5082 int max_devs;
5083 int index;
5084 int cache;
5085 int bdrv_flags;
5086 int drives_table_idx;
5087 char *str = arg->opt;
5088 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5089 "secs", "trans", "media", "snapshot", "file",
5090 "cache", "boot", NULL };
5092 if (check_params(buf, sizeof(buf), params, str) < 0) {
5093 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5094 buf, str);
5095 return -1;
5098 file[0] = 0;
5099 cyls = heads = secs = 0;
5100 bus_id = 0;
5101 unit_id = -1;
5102 translation = BIOS_ATA_TRANSLATION_AUTO;
5103 index = -1;
5104 cache = 1;
5106 if (!strcmp(machine->name, "realview") ||
5107 !strcmp(machine->name, "SS-5") ||
5108 !strcmp(machine->name, "SS-10") ||
5109 !strcmp(machine->name, "SS-600MP") ||
5110 !strcmp(machine->name, "versatilepb") ||
5111 !strcmp(machine->name, "versatileab")) {
5112 type = IF_SCSI;
5113 max_devs = MAX_SCSI_DEVS;
5114 strcpy(devname, "scsi");
5115 } else {
5116 type = IF_IDE;
5117 max_devs = MAX_IDE_DEVS;
5118 strcpy(devname, "ide");
5120 media = MEDIA_DISK;
5122 /* extract parameters */
5124 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5125 bus_id = strtol(buf, NULL, 0);
5126 if (bus_id < 0) {
5127 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5128 return -1;
5132 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5133 unit_id = strtol(buf, NULL, 0);
5134 if (unit_id < 0) {
5135 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5136 return -1;
5140 if (get_param_value(buf, sizeof(buf), "if", str)) {
5141 strncpy(devname, buf, sizeof(devname));
5142 if (!strcmp(buf, "ide")) {
5143 type = IF_IDE;
5144 max_devs = MAX_IDE_DEVS;
5145 } else if (!strcmp(buf, "scsi")) {
5146 type = IF_SCSI;
5147 max_devs = MAX_SCSI_DEVS;
5148 } else if (!strcmp(buf, "floppy")) {
5149 type = IF_FLOPPY;
5150 max_devs = 0;
5151 } else if (!strcmp(buf, "pflash")) {
5152 type = IF_PFLASH;
5153 max_devs = 0;
5154 } else if (!strcmp(buf, "mtd")) {
5155 type = IF_MTD;
5156 max_devs = 0;
5157 } else if (!strcmp(buf, "sd")) {
5158 type = IF_SD;
5159 max_devs = 0;
5160 } else if (!strcmp(buf, "virtio")) {
5161 type = IF_VIRTIO;
5162 max_devs = 0;
5163 } else {
5164 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5165 return -1;
5169 if (get_param_value(buf, sizeof(buf), "index", str)) {
5170 index = strtol(buf, NULL, 0);
5171 if (index < 0) {
5172 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5173 return -1;
5177 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5178 cyls = strtol(buf, NULL, 0);
5181 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5182 heads = strtol(buf, NULL, 0);
5185 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5186 secs = strtol(buf, NULL, 0);
5189 if (cyls || heads || secs) {
5190 if (cyls < 1 || cyls > 16383) {
5191 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5192 return -1;
5194 if (heads < 1 || heads > 16) {
5195 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5196 return -1;
5198 if (secs < 1 || secs > 63) {
5199 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5200 return -1;
5204 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5205 if (!cyls) {
5206 fprintf(stderr,
5207 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5208 str);
5209 return -1;
5211 if (!strcmp(buf, "none"))
5212 translation = BIOS_ATA_TRANSLATION_NONE;
5213 else if (!strcmp(buf, "lba"))
5214 translation = BIOS_ATA_TRANSLATION_LBA;
5215 else if (!strcmp(buf, "auto"))
5216 translation = BIOS_ATA_TRANSLATION_AUTO;
5217 else {
5218 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5219 return -1;
5223 if (get_param_value(buf, sizeof(buf), "media", str)) {
5224 if (!strcmp(buf, "disk")) {
5225 media = MEDIA_DISK;
5226 } else if (!strcmp(buf, "cdrom")) {
5227 if (cyls || secs || heads) {
5228 fprintf(stderr,
5229 "qemu: '%s' invalid physical CHS format\n", str);
5230 return -1;
5232 media = MEDIA_CDROM;
5233 } else {
5234 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5235 return -1;
5239 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5240 if (!strcmp(buf, "on"))
5241 snapshot = 1;
5242 else if (!strcmp(buf, "off"))
5243 snapshot = 0;
5244 else {
5245 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5246 return -1;
5250 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5251 if (!strcmp(buf, "off"))
5252 cache = 0;
5253 else if (!strcmp(buf, "on"))
5254 cache = 1;
5255 else {
5256 fprintf(stderr, "qemu: invalid cache option\n");
5257 return -1;
5261 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5262 if (!strcmp(buf, "on")) {
5263 if (extboot_drive != -1) {
5264 fprintf(stderr, "qemu: two bootable drives specified\n");
5265 return -1;
5267 extboot_drive = nb_drives;
5268 } else if (strcmp(buf, "off")) {
5269 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5270 return -1;
5274 if (arg->file == NULL)
5275 get_param_value(file, sizeof(file), "file", str);
5276 else
5277 pstrcpy(file, sizeof(file), arg->file);
5279 /* compute bus and unit according index */
5281 if (index != -1) {
5282 if (bus_id != 0 || unit_id != -1) {
5283 fprintf(stderr,
5284 "qemu: '%s' index cannot be used with bus and unit\n", str);
5285 return -1;
5287 if (max_devs == 0)
5289 unit_id = index;
5290 bus_id = 0;
5291 } else {
5292 unit_id = index % max_devs;
5293 bus_id = index / max_devs;
5297 /* if user doesn't specify a unit_id,
5298 * try to find the first free
5301 if (unit_id == -1) {
5302 unit_id = 0;
5303 while (drive_get_index(type, bus_id, unit_id) != -1) {
5304 unit_id++;
5305 if (max_devs && unit_id >= max_devs) {
5306 unit_id -= max_devs;
5307 bus_id++;
5312 /* check unit id */
5314 if (max_devs && unit_id >= max_devs) {
5315 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5316 str, unit_id, max_devs - 1);
5317 return -1;
5321 * ignore multiple definitions
5324 if (drive_get_index(type, bus_id, unit_id) != -1)
5325 return -2;
5327 /* init */
5329 if (type == IF_IDE || type == IF_SCSI)
5330 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5331 if (max_devs)
5332 snprintf(buf, sizeof(buf), "%s%i%s%i",
5333 devname, bus_id, mediastr, unit_id);
5334 else
5335 snprintf(buf, sizeof(buf), "%s%s%i",
5336 devname, mediastr, unit_id);
5337 bdrv = bdrv_new(buf);
5338 drives_table_idx = drive_get_free_idx();
5339 drives_table[drives_table_idx].bdrv = bdrv;
5340 drives_table[drives_table_idx].type = type;
5341 drives_table[drives_table_idx].bus = bus_id;
5342 drives_table[drives_table_idx].unit = unit_id;
5343 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
5344 nb_drives++;
5346 switch(type) {
5347 case IF_IDE:
5348 case IF_SCSI:
5349 switch(media) {
5350 case MEDIA_DISK:
5351 if (cyls != 0) {
5352 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5353 bdrv_set_translation_hint(bdrv, translation);
5355 break;
5356 case MEDIA_CDROM:
5357 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5358 break;
5360 break;
5361 case IF_SD:
5362 /* FIXME: This isn't really a floppy, but it's a reasonable
5363 approximation. */
5364 case IF_FLOPPY:
5365 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5366 break;
5367 case IF_PFLASH:
5368 case IF_MTD:
5369 case IF_VIRTIO:
5370 break;
5372 if (!file[0])
5373 return -2;
5374 bdrv_flags = 0;
5375 if (snapshot)
5376 bdrv_flags |= BDRV_O_SNAPSHOT;
5377 if (!cache)
5378 bdrv_flags |= BDRV_O_DIRECT;
5379 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5380 fprintf(stderr, "qemu: could not open disk image %s\n",
5381 file);
5382 return -1;
5384 return drives_table_idx;
5387 /***********************************************************/
5388 /* USB devices */
5390 static USBPort *used_usb_ports;
5391 static USBPort *free_usb_ports;
5393 /* ??? Maybe change this to register a hub to keep track of the topology. */
5394 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5395 usb_attachfn attach)
5397 port->opaque = opaque;
5398 port->index = index;
5399 port->attach = attach;
5400 port->next = free_usb_ports;
5401 free_usb_ports = port;
5404 static int usb_device_add(const char *devname)
5406 const char *p;
5407 USBDevice *dev;
5408 USBPort *port;
5410 if (!free_usb_ports)
5411 return -1;
5413 if (strstart(devname, "host:", &p)) {
5414 dev = usb_host_device_open(p);
5415 } else if (!strcmp(devname, "mouse")) {
5416 dev = usb_mouse_init();
5417 } else if (!strcmp(devname, "tablet")) {
5418 dev = usb_tablet_init();
5419 } else if (!strcmp(devname, "keyboard")) {
5420 dev = usb_keyboard_init();
5421 } else if (strstart(devname, "disk:", &p)) {
5422 dev = usb_msd_init(p);
5423 } else if (!strcmp(devname, "wacom-tablet")) {
5424 dev = usb_wacom_init();
5425 } else if (strstart(devname, "serial:", &p)) {
5426 dev = usb_serial_init(p);
5427 } else {
5428 return -1;
5430 if (!dev)
5431 return -1;
5433 /* Find a USB port to add the device to. */
5434 port = free_usb_ports;
5435 if (!port->next) {
5436 USBDevice *hub;
5438 /* Create a new hub and chain it on. */
5439 free_usb_ports = NULL;
5440 port->next = used_usb_ports;
5441 used_usb_ports = port;
5443 hub = usb_hub_init(VM_USB_HUB_SIZE);
5444 usb_attach(port, hub);
5445 port = free_usb_ports;
5448 free_usb_ports = port->next;
5449 port->next = used_usb_ports;
5450 used_usb_ports = port;
5451 usb_attach(port, dev);
5452 return 0;
5455 static int usb_device_del(const char *devname)
5457 USBPort *port;
5458 USBPort **lastp;
5459 USBDevice *dev;
5460 int bus_num, addr;
5461 const char *p;
5463 if (!used_usb_ports)
5464 return -1;
5466 p = strchr(devname, '.');
5467 if (!p)
5468 return -1;
5469 bus_num = strtoul(devname, NULL, 0);
5470 addr = strtoul(p + 1, NULL, 0);
5471 if (bus_num != 0)
5472 return -1;
5474 lastp = &used_usb_ports;
5475 port = used_usb_ports;
5476 while (port && port->dev->addr != addr) {
5477 lastp = &port->next;
5478 port = port->next;
5481 if (!port)
5482 return -1;
5484 dev = port->dev;
5485 *lastp = port->next;
5486 usb_attach(port, NULL);
5487 dev->handle_destroy(dev);
5488 port->next = free_usb_ports;
5489 free_usb_ports = port;
5490 return 0;
5493 void do_usb_add(const char *devname)
5495 int ret;
5496 ret = usb_device_add(devname);
5497 if (ret < 0)
5498 term_printf("Could not add USB device '%s'\n", devname);
5501 void do_usb_del(const char *devname)
5503 int ret;
5504 ret = usb_device_del(devname);
5505 if (ret < 0)
5506 term_printf("Could not remove USB device '%s'\n", devname);
5509 void usb_info(void)
5511 USBDevice *dev;
5512 USBPort *port;
5513 const char *speed_str;
5515 if (!usb_enabled) {
5516 term_printf("USB support not enabled\n");
5517 return;
5520 for (port = used_usb_ports; port; port = port->next) {
5521 dev = port->dev;
5522 if (!dev)
5523 continue;
5524 switch(dev->speed) {
5525 case USB_SPEED_LOW:
5526 speed_str = "1.5";
5527 break;
5528 case USB_SPEED_FULL:
5529 speed_str = "12";
5530 break;
5531 case USB_SPEED_HIGH:
5532 speed_str = "480";
5533 break;
5534 default:
5535 speed_str = "?";
5536 break;
5538 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5539 0, dev->addr, speed_str, dev->devname);
5543 /***********************************************************/
5544 /* PCMCIA/Cardbus */
5546 static struct pcmcia_socket_entry_s {
5547 struct pcmcia_socket_s *socket;
5548 struct pcmcia_socket_entry_s *next;
5549 } *pcmcia_sockets = 0;
5551 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5553 struct pcmcia_socket_entry_s *entry;
5555 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5556 entry->socket = socket;
5557 entry->next = pcmcia_sockets;
5558 pcmcia_sockets = entry;
5561 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5563 struct pcmcia_socket_entry_s *entry, **ptr;
5565 ptr = &pcmcia_sockets;
5566 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5567 if (entry->socket == socket) {
5568 *ptr = entry->next;
5569 qemu_free(entry);
5573 void pcmcia_info(void)
5575 struct pcmcia_socket_entry_s *iter;
5576 if (!pcmcia_sockets)
5577 term_printf("No PCMCIA sockets\n");
5579 for (iter = pcmcia_sockets; iter; iter = iter->next)
5580 term_printf("%s: %s\n", iter->socket->slot_string,
5581 iter->socket->attached ? iter->socket->card_string :
5582 "Empty");
5585 /***********************************************************/
5586 /* dumb display */
5588 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5592 static void dumb_resize(DisplayState *ds, int w, int h)
5596 static void dumb_refresh(DisplayState *ds)
5598 #if defined(CONFIG_SDL)
5599 vga_hw_update();
5600 #endif
5603 static void dumb_display_init(DisplayState *ds)
5605 ds->data = NULL;
5606 ds->linesize = 0;
5607 ds->depth = 0;
5608 ds->dpy_update = dumb_update;
5609 ds->dpy_resize = dumb_resize;
5610 ds->dpy_refresh = dumb_refresh;
5613 /***********************************************************/
5614 /* I/O handling */
5616 #define MAX_IO_HANDLERS 64
5618 typedef struct IOHandlerRecord {
5619 int fd;
5620 IOCanRWHandler *fd_read_poll;
5621 IOHandler *fd_read;
5622 IOHandler *fd_write;
5623 int deleted;
5624 void *opaque;
5625 /* temporary data */
5626 struct pollfd *ufd;
5627 struct IOHandlerRecord *next;
5628 } IOHandlerRecord;
5630 static IOHandlerRecord *first_io_handler;
5632 /* XXX: fd_read_poll should be suppressed, but an API change is
5633 necessary in the character devices to suppress fd_can_read(). */
5634 int qemu_set_fd_handler2(int fd,
5635 IOCanRWHandler *fd_read_poll,
5636 IOHandler *fd_read,
5637 IOHandler *fd_write,
5638 void *opaque)
5640 IOHandlerRecord **pioh, *ioh;
5642 if (!fd_read && !fd_write) {
5643 pioh = &first_io_handler;
5644 for(;;) {
5645 ioh = *pioh;
5646 if (ioh == NULL)
5647 break;
5648 if (ioh->fd == fd) {
5649 ioh->deleted = 1;
5650 break;
5652 pioh = &ioh->next;
5654 } else {
5655 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5656 if (ioh->fd == fd)
5657 goto found;
5659 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5660 if (!ioh)
5661 return -1;
5662 ioh->next = first_io_handler;
5663 first_io_handler = ioh;
5664 found:
5665 ioh->fd = fd;
5666 ioh->fd_read_poll = fd_read_poll;
5667 ioh->fd_read = fd_read;
5668 ioh->fd_write = fd_write;
5669 ioh->opaque = opaque;
5670 ioh->deleted = 0;
5672 return 0;
5675 int qemu_set_fd_handler(int fd,
5676 IOHandler *fd_read,
5677 IOHandler *fd_write,
5678 void *opaque)
5680 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5683 /***********************************************************/
5684 /* Polling handling */
5686 typedef struct PollingEntry {
5687 PollingFunc *func;
5688 void *opaque;
5689 struct PollingEntry *next;
5690 } PollingEntry;
5692 static PollingEntry *first_polling_entry;
5694 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5696 PollingEntry **ppe, *pe;
5697 pe = qemu_mallocz(sizeof(PollingEntry));
5698 if (!pe)
5699 return -1;
5700 pe->func = func;
5701 pe->opaque = opaque;
5702 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5703 *ppe = pe;
5704 return 0;
5707 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5709 PollingEntry **ppe, *pe;
5710 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5711 pe = *ppe;
5712 if (pe->func == func && pe->opaque == opaque) {
5713 *ppe = pe->next;
5714 qemu_free(pe);
5715 break;
5720 #ifdef _WIN32
5721 /***********************************************************/
5722 /* Wait objects support */
5723 typedef struct WaitObjects {
5724 int num;
5725 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5726 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5727 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5728 } WaitObjects;
5730 static WaitObjects wait_objects = {0};
5732 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5734 WaitObjects *w = &wait_objects;
5736 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5737 return -1;
5738 w->events[w->num] = handle;
5739 w->func[w->num] = func;
5740 w->opaque[w->num] = opaque;
5741 w->num++;
5742 return 0;
5745 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5747 int i, found;
5748 WaitObjects *w = &wait_objects;
5750 found = 0;
5751 for (i = 0; i < w->num; i++) {
5752 if (w->events[i] == handle)
5753 found = 1;
5754 if (found) {
5755 w->events[i] = w->events[i + 1];
5756 w->func[i] = w->func[i + 1];
5757 w->opaque[i] = w->opaque[i + 1];
5760 if (found)
5761 w->num--;
5763 #endif
5765 #define SELF_ANNOUNCE_ROUNDS 5
5766 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5767 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5768 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5770 static int announce_self_create(uint8_t *buf,
5771 uint8_t *mac_addr)
5773 uint32_t magic = EXPERIMENTAL_MAGIC;
5774 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5776 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5778 memset(buf, 0xff, 6); /* h_dst */
5779 memcpy(buf + 6, mac_addr, 6); /* h_src */
5780 memcpy(buf + 12, &proto, 2); /* h_proto */
5781 memcpy(buf + 14, &magic, 4); /* magic */
5783 return 18; /* len */
5786 static void qemu_announce_self(void)
5788 int i, j, len;
5789 VLANState *vlan;
5790 VLANClientState *vc;
5791 uint8_t buf[256];
5793 for (i = 0; i < nb_nics; i++) {
5794 len = announce_self_create(buf, nd_table[i].macaddr);
5795 vlan = nd_table[i].vlan;
5796 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5797 if (vc->fd_read == tap_receive) /* send only if tap */
5798 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5799 vc->fd_read(vc->opaque, buf, len);
5804 /***********************************************************/
5805 /* savevm/loadvm support */
5807 #define IO_BUF_SIZE 32768
5809 struct QEMUFile {
5810 QEMUFilePutBufferFunc *put_buffer;
5811 QEMUFileGetBufferFunc *get_buffer;
5812 QEMUFileCloseFunc *close;
5813 void *opaque;
5815 int64_t buf_offset; /* start of buffer when writing, end of buffer
5816 when reading */
5817 int buf_index;
5818 int buf_size; /* 0 when writing */
5819 uint8_t buf[IO_BUF_SIZE];
5822 typedef struct QEMUFileFD
5824 int fd;
5825 } QEMUFileFD;
5827 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5829 QEMUFileFD *s = opaque;
5830 int offset = 0;
5831 ssize_t len;
5833 again:
5834 len = read(s->fd, buf + offset, size - offset);
5835 if (len == -1) {
5836 if (errno == EINTR || errno == EAGAIN)
5837 goto again;
5840 return len;
5843 QEMUFile *qemu_fopen_fd(int fd)
5845 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5846 s->fd = fd;
5847 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5850 typedef struct QEMUFileUnix
5852 FILE *outfile;
5853 } QEMUFileUnix;
5855 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5857 QEMUFileUnix *s = opaque;
5858 fseek(s->outfile, pos, SEEK_SET);
5859 fwrite(buf, 1, size, s->outfile);
5862 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5864 QEMUFileUnix *s = opaque;
5865 fseek(s->outfile, pos, SEEK_SET);
5866 return fread(buf, 1, size, s->outfile);
5869 static void file_close(void *opaque)
5871 QEMUFileUnix *s = opaque;
5872 fclose(s->outfile);
5873 qemu_free(s);
5876 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5878 QEMUFileUnix *s;
5880 s = qemu_mallocz(sizeof(QEMUFileUnix));
5881 if (!s)
5882 return NULL;
5884 s->outfile = fopen(filename, mode);
5885 if (!s->outfile)
5886 goto fail;
5888 if (!strcmp(mode, "wb"))
5889 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5890 else if (!strcmp(mode, "rb"))
5891 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5893 fail:
5894 if (s->outfile)
5895 fclose(s->outfile);
5896 qemu_free(s);
5897 return NULL;
5900 typedef struct QEMUFileBdrv
5902 BlockDriverState *bs;
5903 int64_t base_offset;
5904 } QEMUFileBdrv;
5906 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5908 QEMUFileBdrv *s = opaque;
5909 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5912 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5914 QEMUFileBdrv *s = opaque;
5915 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5918 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5920 QEMUFileBdrv *s;
5922 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5923 if (!s)
5924 return NULL;
5926 s->bs = bs;
5927 s->base_offset = offset;
5929 if (is_writable)
5930 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5932 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5935 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5936 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5938 QEMUFile *f;
5940 f = qemu_mallocz(sizeof(QEMUFile));
5941 if (!f)
5942 return NULL;
5944 f->opaque = opaque;
5945 f->put_buffer = put_buffer;
5946 f->get_buffer = get_buffer;
5947 f->close = close;
5949 return f;
5952 void qemu_fflush(QEMUFile *f)
5954 if (!f->put_buffer)
5955 return;
5957 if (f->buf_index > 0) {
5958 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5959 f->buf_offset += f->buf_index;
5960 f->buf_index = 0;
5964 static void qemu_fill_buffer(QEMUFile *f)
5966 int len;
5968 if (!f->get_buffer)
5969 return;
5971 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5972 if (len < 0)
5973 len = 0;
5975 f->buf_index = 0;
5976 f->buf_size = len;
5977 f->buf_offset += len;
5980 void qemu_fclose(QEMUFile *f)
5982 qemu_fflush(f);
5983 if (f->close)
5984 f->close(f->opaque);
5985 qemu_free(f);
5988 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5990 int l;
5991 while (size > 0) {
5992 l = IO_BUF_SIZE - f->buf_index;
5993 if (l > size)
5994 l = size;
5995 memcpy(f->buf + f->buf_index, buf, l);
5996 f->buf_index += l;
5997 buf += l;
5998 size -= l;
5999 if (f->buf_index >= IO_BUF_SIZE)
6000 qemu_fflush(f);
6004 void qemu_put_byte(QEMUFile *f, int v)
6006 f->buf[f->buf_index++] = v;
6007 if (f->buf_index >= IO_BUF_SIZE)
6008 qemu_fflush(f);
6011 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6013 int size, l;
6015 size = size1;
6016 while (size > 0) {
6017 l = f->buf_size - f->buf_index;
6018 if (l == 0) {
6019 qemu_fill_buffer(f);
6020 l = f->buf_size - f->buf_index;
6021 if (l == 0)
6022 break;
6024 if (l > size)
6025 l = size;
6026 memcpy(buf, f->buf + f->buf_index, l);
6027 f->buf_index += l;
6028 buf += l;
6029 size -= l;
6031 return size1 - size;
6034 int qemu_get_byte(QEMUFile *f)
6036 if (f->buf_index >= f->buf_size) {
6037 qemu_fill_buffer(f);
6038 if (f->buf_index >= f->buf_size)
6039 return 0;
6041 return f->buf[f->buf_index++];
6044 int64_t qemu_ftell(QEMUFile *f)
6046 return f->buf_offset - f->buf_size + f->buf_index;
6049 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6051 if (whence == SEEK_SET) {
6052 /* nothing to do */
6053 } else if (whence == SEEK_CUR) {
6054 pos += qemu_ftell(f);
6055 } else {
6056 /* SEEK_END not supported */
6057 return -1;
6059 if (f->put_buffer) {
6060 qemu_fflush(f);
6061 f->buf_offset = pos;
6062 } else {
6063 f->buf_offset = pos;
6064 f->buf_index = 0;
6065 f->buf_size = 0;
6067 return pos;
6070 void qemu_put_be16(QEMUFile *f, unsigned int v)
6072 qemu_put_byte(f, v >> 8);
6073 qemu_put_byte(f, v);
6076 void qemu_put_be32(QEMUFile *f, unsigned int v)
6078 qemu_put_byte(f, v >> 24);
6079 qemu_put_byte(f, v >> 16);
6080 qemu_put_byte(f, v >> 8);
6081 qemu_put_byte(f, v);
6084 void qemu_put_be64(QEMUFile *f, uint64_t v)
6086 qemu_put_be32(f, v >> 32);
6087 qemu_put_be32(f, v);
6090 unsigned int qemu_get_be16(QEMUFile *f)
6092 unsigned int v;
6093 v = qemu_get_byte(f) << 8;
6094 v |= qemu_get_byte(f);
6095 return v;
6098 unsigned int qemu_get_be32(QEMUFile *f)
6100 unsigned int v;
6101 v = qemu_get_byte(f) << 24;
6102 v |= qemu_get_byte(f) << 16;
6103 v |= qemu_get_byte(f) << 8;
6104 v |= qemu_get_byte(f);
6105 return v;
6108 uint64_t qemu_get_be64(QEMUFile *f)
6110 uint64_t v;
6111 v = (uint64_t)qemu_get_be32(f) << 32;
6112 v |= qemu_get_be32(f);
6113 return v;
6116 typedef struct SaveStateEntry {
6117 char idstr[256];
6118 int instance_id;
6119 int version_id;
6120 SaveStateHandler *save_state;
6121 LoadStateHandler *load_state;
6122 void *opaque;
6123 struct SaveStateEntry *next;
6124 } SaveStateEntry;
6126 static SaveStateEntry *first_se;
6128 int register_savevm(const char *idstr,
6129 int instance_id,
6130 int version_id,
6131 SaveStateHandler *save_state,
6132 LoadStateHandler *load_state,
6133 void *opaque)
6135 SaveStateEntry *se, **pse;
6137 se = qemu_malloc(sizeof(SaveStateEntry));
6138 if (!se)
6139 return -1;
6140 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6141 se->instance_id = instance_id;
6142 se->version_id = version_id;
6143 se->save_state = save_state;
6144 se->load_state = load_state;
6145 se->opaque = opaque;
6146 se->next = NULL;
6148 /* add at the end of list */
6149 pse = &first_se;
6150 while (*pse != NULL)
6151 pse = &(*pse)->next;
6152 *pse = se;
6153 return 0;
6156 #define QEMU_VM_FILE_MAGIC 0x5145564d
6157 #define QEMU_VM_FILE_VERSION 0x00000002
6159 static int qemu_savevm_state(QEMUFile *f)
6161 SaveStateEntry *se;
6162 int len, ret;
6163 int64_t cur_pos, len_pos, total_len_pos;
6165 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6166 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6167 total_len_pos = qemu_ftell(f);
6168 qemu_put_be64(f, 0); /* total size */
6170 for(se = first_se; se != NULL; se = se->next) {
6171 /* ID string */
6172 len = strlen(se->idstr);
6173 qemu_put_byte(f, len);
6174 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6176 qemu_put_be32(f, se->instance_id);
6177 qemu_put_be32(f, se->version_id);
6179 /* record size: filled later */
6180 len_pos = qemu_ftell(f);
6181 qemu_put_be32(f, 0);
6182 se->save_state(f, se->opaque);
6184 /* fill record size */
6185 cur_pos = qemu_ftell(f);
6186 len = cur_pos - len_pos - 4;
6187 qemu_fseek(f, len_pos, SEEK_SET);
6188 qemu_put_be32(f, len);
6189 qemu_fseek(f, cur_pos, SEEK_SET);
6191 cur_pos = qemu_ftell(f);
6192 qemu_fseek(f, total_len_pos, SEEK_SET);
6193 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6194 qemu_fseek(f, cur_pos, SEEK_SET);
6196 ret = 0;
6197 return ret;
6200 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6202 SaveStateEntry *se;
6204 for(se = first_se; se != NULL; se = se->next) {
6205 if (!strcmp(se->idstr, idstr) &&
6206 instance_id == se->instance_id)
6207 return se;
6209 return NULL;
6212 static int qemu_loadvm_state(QEMUFile *f)
6214 SaveStateEntry *se;
6215 int len, ret, instance_id, record_len, version_id;
6216 int64_t total_len, end_pos, cur_pos;
6217 unsigned int v;
6218 char idstr[256];
6220 v = qemu_get_be32(f);
6221 if (v != QEMU_VM_FILE_MAGIC)
6222 goto fail;
6223 v = qemu_get_be32(f);
6224 if (v != QEMU_VM_FILE_VERSION) {
6225 fail:
6226 ret = -1;
6227 goto the_end;
6229 total_len = qemu_get_be64(f);
6230 end_pos = total_len + qemu_ftell(f);
6231 for(;;) {
6232 if (qemu_ftell(f) >= end_pos)
6233 break;
6234 len = qemu_get_byte(f);
6235 qemu_get_buffer(f, (uint8_t *)idstr, len);
6236 idstr[len] = '\0';
6237 instance_id = qemu_get_be32(f);
6238 version_id = qemu_get_be32(f);
6239 record_len = qemu_get_be32(f);
6240 #if 0
6241 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6242 idstr, instance_id, version_id, record_len);
6243 #endif
6244 cur_pos = qemu_ftell(f);
6245 se = find_se(idstr, instance_id);
6246 if (!se) {
6247 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6248 instance_id, idstr);
6249 } else {
6250 ret = se->load_state(f, se->opaque, version_id);
6251 if (ret < 0) {
6252 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6253 instance_id, idstr);
6254 goto the_end;
6257 /* always seek to exact end of record */
6258 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6260 ret = 0;
6261 the_end:
6262 return ret;
6265 int qemu_live_savevm_state(QEMUFile *f)
6267 SaveStateEntry *se;
6268 int len, ret;
6270 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6271 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6273 for(se = first_se; se != NULL; se = se->next) {
6274 len = strlen(se->idstr);
6276 qemu_put_byte(f, len);
6277 qemu_put_buffer(f, se->idstr, len);
6278 qemu_put_be32(f, se->instance_id);
6279 qemu_put_be32(f, se->version_id);
6281 se->save_state(f, se->opaque);
6284 qemu_put_byte(f, 0);
6286 ret = 0;
6287 return ret;
6290 int qemu_live_loadvm_state(QEMUFile *f)
6292 SaveStateEntry *se;
6293 int len, ret, instance_id, version_id;
6294 unsigned int v;
6295 char idstr[256];
6297 v = qemu_get_be32(f);
6298 if (v != QEMU_VM_FILE_MAGIC)
6299 goto fail;
6300 v = qemu_get_be32(f);
6301 if (v != QEMU_VM_FILE_VERSION) {
6302 fail:
6303 ret = -1;
6304 goto the_end;
6307 for(;;) {
6308 len = qemu_get_byte(f);
6309 if (len == 0)
6310 break;
6311 qemu_get_buffer(f, idstr, len);
6312 idstr[len] = '\0';
6313 instance_id = qemu_get_be32(f);
6314 version_id = qemu_get_be32(f);
6315 se = find_se(idstr, instance_id);
6316 if (!se) {
6317 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6318 instance_id, idstr);
6319 } else {
6320 if (version_id > se->version_id) { /* src version > dst version */
6321 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6322 idstr, version_id, se->version_id);
6323 ret = -1;
6324 goto the_end;
6326 ret = se->load_state(f, se->opaque, version_id);
6327 if (ret < 0) {
6328 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6329 instance_id, idstr);
6330 goto the_end;
6334 ret = 0;
6336 qemu_announce_self();
6338 the_end:
6339 return ret;
6342 /* device can contain snapshots */
6343 static int bdrv_can_snapshot(BlockDriverState *bs)
6345 return (bs &&
6346 !bdrv_is_removable(bs) &&
6347 !bdrv_is_read_only(bs));
6350 /* device must be snapshots in order to have a reliable snapshot */
6351 static int bdrv_has_snapshot(BlockDriverState *bs)
6353 return (bs &&
6354 !bdrv_is_removable(bs) &&
6355 !bdrv_is_read_only(bs));
6358 static BlockDriverState *get_bs_snapshots(void)
6360 BlockDriverState *bs;
6361 int i;
6363 if (bs_snapshots)
6364 return bs_snapshots;
6365 for(i = 0; i <= nb_drives; i++) {
6366 bs = drives_table[i].bdrv;
6367 if (bdrv_can_snapshot(bs))
6368 goto ok;
6370 return NULL;
6372 bs_snapshots = bs;
6373 return bs;
6376 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6377 const char *name)
6379 QEMUSnapshotInfo *sn_tab, *sn;
6380 int nb_sns, i, ret;
6382 ret = -ENOENT;
6383 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6384 if (nb_sns < 0)
6385 return ret;
6386 for(i = 0; i < nb_sns; i++) {
6387 sn = &sn_tab[i];
6388 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6389 *sn_info = *sn;
6390 ret = 0;
6391 break;
6394 qemu_free(sn_tab);
6395 return ret;
6398 void do_savevm(const char *name)
6400 BlockDriverState *bs, *bs1;
6401 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6402 int must_delete, ret, i;
6403 BlockDriverInfo bdi1, *bdi = &bdi1;
6404 QEMUFile *f;
6405 int saved_vm_running;
6406 #ifdef _WIN32
6407 struct _timeb tb;
6408 #else
6409 struct timeval tv;
6410 #endif
6412 bs = get_bs_snapshots();
6413 if (!bs) {
6414 term_printf("No block device can accept snapshots\n");
6415 return;
6418 /* ??? Should this occur after vm_stop? */
6419 qemu_aio_flush();
6421 saved_vm_running = vm_running;
6422 vm_stop(0);
6424 must_delete = 0;
6425 if (name) {
6426 ret = bdrv_snapshot_find(bs, old_sn, name);
6427 if (ret >= 0) {
6428 must_delete = 1;
6431 memset(sn, 0, sizeof(*sn));
6432 if (must_delete) {
6433 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6434 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6435 } else {
6436 if (name)
6437 pstrcpy(sn->name, sizeof(sn->name), name);
6440 /* fill auxiliary fields */
6441 #ifdef _WIN32
6442 _ftime(&tb);
6443 sn->date_sec = tb.time;
6444 sn->date_nsec = tb.millitm * 1000000;
6445 #else
6446 gettimeofday(&tv, NULL);
6447 sn->date_sec = tv.tv_sec;
6448 sn->date_nsec = tv.tv_usec * 1000;
6449 #endif
6450 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6452 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6453 term_printf("Device %s does not support VM state snapshots\n",
6454 bdrv_get_device_name(bs));
6455 goto the_end;
6458 /* save the VM state */
6459 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6460 if (!f) {
6461 term_printf("Could not open VM state file\n");
6462 goto the_end;
6464 ret = qemu_savevm_state(f);
6465 sn->vm_state_size = qemu_ftell(f);
6466 qemu_fclose(f);
6467 if (ret < 0) {
6468 term_printf("Error %d while writing VM\n", ret);
6469 goto the_end;
6472 /* create the snapshots */
6474 for(i = 0; i < nb_drives; i++) {
6475 bs1 = drives_table[i].bdrv;
6476 if (bdrv_has_snapshot(bs1)) {
6477 if (must_delete) {
6478 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6479 if (ret < 0) {
6480 term_printf("Error while deleting snapshot on '%s'\n",
6481 bdrv_get_device_name(bs1));
6484 ret = bdrv_snapshot_create(bs1, sn);
6485 if (ret < 0) {
6486 term_printf("Error while creating snapshot on '%s'\n",
6487 bdrv_get_device_name(bs1));
6492 the_end:
6493 if (saved_vm_running)
6494 vm_start();
6497 void do_loadvm(const char *name)
6499 BlockDriverState *bs, *bs1;
6500 BlockDriverInfo bdi1, *bdi = &bdi1;
6501 QEMUFile *f;
6502 int i, ret;
6503 int saved_vm_running;
6505 bs = get_bs_snapshots();
6506 if (!bs) {
6507 term_printf("No block device supports snapshots\n");
6508 return;
6511 /* Flush all IO requests so they don't interfere with the new state. */
6512 qemu_aio_flush();
6514 saved_vm_running = vm_running;
6515 vm_stop(0);
6517 for(i = 0; i <= nb_drives; i++) {
6518 bs1 = drives_table[i].bdrv;
6519 if (bdrv_has_snapshot(bs1)) {
6520 ret = bdrv_snapshot_goto(bs1, name);
6521 if (ret < 0) {
6522 if (bs != bs1)
6523 term_printf("Warning: ");
6524 switch(ret) {
6525 case -ENOTSUP:
6526 term_printf("Snapshots not supported on device '%s'\n",
6527 bdrv_get_device_name(bs1));
6528 break;
6529 case -ENOENT:
6530 term_printf("Could not find snapshot '%s' on device '%s'\n",
6531 name, bdrv_get_device_name(bs1));
6532 break;
6533 default:
6534 term_printf("Error %d while activating snapshot on '%s'\n",
6535 ret, bdrv_get_device_name(bs1));
6536 break;
6538 /* fatal on snapshot block device */
6539 if (bs == bs1)
6540 goto the_end;
6545 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6546 term_printf("Device %s does not support VM state snapshots\n",
6547 bdrv_get_device_name(bs));
6548 return;
6551 /* restore the VM state */
6552 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6553 if (!f) {
6554 term_printf("Could not open VM state file\n");
6555 goto the_end;
6557 ret = qemu_loadvm_state(f);
6558 qemu_fclose(f);
6559 if (ret < 0) {
6560 term_printf("Error %d while loading VM state\n", ret);
6562 the_end:
6563 if (saved_vm_running)
6564 vm_start();
6567 void do_delvm(const char *name)
6569 BlockDriverState *bs, *bs1;
6570 int i, ret;
6572 bs = get_bs_snapshots();
6573 if (!bs) {
6574 term_printf("No block device supports snapshots\n");
6575 return;
6578 for(i = 0; i <= nb_drives; i++) {
6579 bs1 = drives_table[i].bdrv;
6580 if (bdrv_has_snapshot(bs1)) {
6581 ret = bdrv_snapshot_delete(bs1, name);
6582 if (ret < 0) {
6583 if (ret == -ENOTSUP)
6584 term_printf("Snapshots not supported on device '%s'\n",
6585 bdrv_get_device_name(bs1));
6586 else
6587 term_printf("Error %d while deleting snapshot on '%s'\n",
6588 ret, bdrv_get_device_name(bs1));
6594 void do_info_snapshots(void)
6596 BlockDriverState *bs, *bs1;
6597 QEMUSnapshotInfo *sn_tab, *sn;
6598 int nb_sns, i;
6599 char buf[256];
6601 bs = get_bs_snapshots();
6602 if (!bs) {
6603 term_printf("No available block device supports snapshots\n");
6604 return;
6606 term_printf("Snapshot devices:");
6607 for(i = 0; i <= nb_drives; i++) {
6608 bs1 = drives_table[i].bdrv;
6609 if (bdrv_has_snapshot(bs1)) {
6610 if (bs == bs1)
6611 term_printf(" %s", bdrv_get_device_name(bs1));
6614 term_printf("\n");
6616 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6617 if (nb_sns < 0) {
6618 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6619 return;
6621 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6622 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6623 for(i = 0; i < nb_sns; i++) {
6624 sn = &sn_tab[i];
6625 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6627 qemu_free(sn_tab);
6630 /***********************************************************/
6631 /* cpu save/restore */
6633 #if defined(TARGET_I386)
6635 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6637 qemu_put_be32(f, dt->selector);
6638 qemu_put_betl(f, dt->base);
6639 qemu_put_be32(f, dt->limit);
6640 qemu_put_be32(f, dt->flags);
6643 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6645 dt->selector = qemu_get_be32(f);
6646 dt->base = qemu_get_betl(f);
6647 dt->limit = qemu_get_be32(f);
6648 dt->flags = qemu_get_be32(f);
6651 void cpu_save(QEMUFile *f, void *opaque)
6653 CPUState *env = opaque;
6654 uint16_t fptag, fpus, fpuc, fpregs_format;
6655 uint32_t hflags;
6656 int i;
6658 if (kvm_enabled())
6659 kvm_save_registers(env);
6661 for(i = 0; i < CPU_NB_REGS; i++)
6662 qemu_put_betls(f, &env->regs[i]);
6663 qemu_put_betls(f, &env->eip);
6664 qemu_put_betls(f, &env->eflags);
6665 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6666 qemu_put_be32s(f, &hflags);
6668 /* FPU */
6669 fpuc = env->fpuc;
6670 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6671 fptag = 0;
6672 for(i = 0; i < 8; i++) {
6673 fptag |= ((!env->fptags[i]) << i);
6676 qemu_put_be16s(f, &fpuc);
6677 qemu_put_be16s(f, &fpus);
6678 qemu_put_be16s(f, &fptag);
6680 #ifdef USE_X86LDOUBLE
6681 fpregs_format = 0;
6682 #else
6683 fpregs_format = 1;
6684 #endif
6685 qemu_put_be16s(f, &fpregs_format);
6687 for(i = 0; i < 8; i++) {
6688 #ifdef USE_X86LDOUBLE
6690 uint64_t mant;
6691 uint16_t exp;
6692 /* we save the real CPU data (in case of MMX usage only 'mant'
6693 contains the MMX register */
6694 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6695 qemu_put_be64(f, mant);
6696 qemu_put_be16(f, exp);
6698 #else
6699 /* if we use doubles for float emulation, we save the doubles to
6700 avoid losing information in case of MMX usage. It can give
6701 problems if the image is restored on a CPU where long
6702 doubles are used instead. */
6703 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6704 #endif
6707 for(i = 0; i < 6; i++)
6708 cpu_put_seg(f, &env->segs[i]);
6709 cpu_put_seg(f, &env->ldt);
6710 cpu_put_seg(f, &env->tr);
6711 cpu_put_seg(f, &env->gdt);
6712 cpu_put_seg(f, &env->idt);
6714 qemu_put_be32s(f, &env->sysenter_cs);
6715 qemu_put_be32s(f, &env->sysenter_esp);
6716 qemu_put_be32s(f, &env->sysenter_eip);
6718 qemu_put_betls(f, &env->cr[0]);
6719 qemu_put_betls(f, &env->cr[2]);
6720 qemu_put_betls(f, &env->cr[3]);
6721 qemu_put_betls(f, &env->cr[4]);
6723 for(i = 0; i < 8; i++)
6724 qemu_put_betls(f, &env->dr[i]);
6726 /* MMU */
6727 qemu_put_be32s(f, &env->a20_mask);
6729 /* XMM */
6730 qemu_put_be32s(f, &env->mxcsr);
6731 for(i = 0; i < CPU_NB_REGS; i++) {
6732 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6733 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6736 #ifdef TARGET_X86_64
6737 qemu_put_be64s(f, &env->efer);
6738 qemu_put_be64s(f, &env->star);
6739 qemu_put_be64s(f, &env->lstar);
6740 qemu_put_be64s(f, &env->cstar);
6741 qemu_put_be64s(f, &env->fmask);
6742 qemu_put_be64s(f, &env->kernelgsbase);
6743 #endif
6744 qemu_put_be32s(f, &env->smbase);
6746 if (kvm_enabled()) {
6747 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6748 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6750 qemu_put_be64s(f, &env->tsc);
6754 #ifdef USE_X86LDOUBLE
6755 /* XXX: add that in a FPU generic layer */
6756 union x86_longdouble {
6757 uint64_t mant;
6758 uint16_t exp;
6761 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6762 #define EXPBIAS1 1023
6763 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6764 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6766 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6768 int e;
6769 /* mantissa */
6770 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6771 /* exponent + sign */
6772 e = EXPD1(temp) - EXPBIAS1 + 16383;
6773 e |= SIGND1(temp) >> 16;
6774 p->exp = e;
6776 #endif
6778 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6780 CPUState *env = opaque;
6781 int i, guess_mmx;
6782 uint32_t hflags;
6783 uint16_t fpus, fpuc, fptag, fpregs_format;
6785 if (version_id != 3 && version_id != 4)
6786 return -EINVAL;
6787 for(i = 0; i < CPU_NB_REGS; i++)
6788 qemu_get_betls(f, &env->regs[i]);
6789 qemu_get_betls(f, &env->eip);
6790 qemu_get_betls(f, &env->eflags);
6791 qemu_get_be32s(f, &hflags);
6793 qemu_get_be16s(f, &fpuc);
6794 qemu_get_be16s(f, &fpus);
6795 qemu_get_be16s(f, &fptag);
6796 qemu_get_be16s(f, &fpregs_format);
6798 /* NOTE: we cannot always restore the FPU state if the image come
6799 from a host with a different 'USE_X86LDOUBLE' define. We guess
6800 if we are in an MMX state to restore correctly in that case. */
6801 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6802 for(i = 0; i < 8; i++) {
6803 uint64_t mant;
6804 uint16_t exp;
6806 switch(fpregs_format) {
6807 case 0:
6808 mant = qemu_get_be64(f);
6809 exp = qemu_get_be16(f);
6810 #ifdef USE_X86LDOUBLE
6811 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6812 #else
6813 /* difficult case */
6814 if (guess_mmx)
6815 env->fpregs[i].mmx.MMX_Q(0) = mant;
6816 else
6817 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6818 #endif
6819 break;
6820 case 1:
6821 mant = qemu_get_be64(f);
6822 #ifdef USE_X86LDOUBLE
6824 union x86_longdouble *p;
6825 /* difficult case */
6826 p = (void *)&env->fpregs[i];
6827 if (guess_mmx) {
6828 p->mant = mant;
6829 p->exp = 0xffff;
6830 } else {
6831 fp64_to_fp80(p, mant);
6834 #else
6835 env->fpregs[i].mmx.MMX_Q(0) = mant;
6836 #endif
6837 break;
6838 default:
6839 return -EINVAL;
6843 env->fpuc = fpuc;
6844 /* XXX: restore FPU round state */
6845 env->fpstt = (fpus >> 11) & 7;
6846 env->fpus = fpus & ~0x3800;
6847 fptag ^= 0xff;
6848 for(i = 0; i < 8; i++) {
6849 env->fptags[i] = (fptag >> i) & 1;
6852 for(i = 0; i < 6; i++)
6853 cpu_get_seg(f, &env->segs[i]);
6854 cpu_get_seg(f, &env->ldt);
6855 cpu_get_seg(f, &env->tr);
6856 cpu_get_seg(f, &env->gdt);
6857 cpu_get_seg(f, &env->idt);
6859 qemu_get_be32s(f, &env->sysenter_cs);
6860 qemu_get_be32s(f, &env->sysenter_esp);
6861 qemu_get_be32s(f, &env->sysenter_eip);
6863 qemu_get_betls(f, &env->cr[0]);
6864 qemu_get_betls(f, &env->cr[2]);
6865 qemu_get_betls(f, &env->cr[3]);
6866 qemu_get_betls(f, &env->cr[4]);
6868 for(i = 0; i < 8; i++)
6869 qemu_get_betls(f, &env->dr[i]);
6871 /* MMU */
6872 qemu_get_be32s(f, &env->a20_mask);
6874 qemu_get_be32s(f, &env->mxcsr);
6875 for(i = 0; i < CPU_NB_REGS; i++) {
6876 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6877 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6880 #ifdef TARGET_X86_64
6881 qemu_get_be64s(f, &env->efer);
6882 qemu_get_be64s(f, &env->star);
6883 qemu_get_be64s(f, &env->lstar);
6884 qemu_get_be64s(f, &env->cstar);
6885 qemu_get_be64s(f, &env->fmask);
6886 qemu_get_be64s(f, &env->kernelgsbase);
6887 #endif
6888 if (version_id >= 4)
6889 qemu_get_be32s(f, &env->smbase);
6891 /* XXX: compute hflags from scratch, except for CPL and IIF */
6892 env->hflags = hflags;
6893 tlb_flush(env, 1);
6894 if (kvm_enabled()) {
6895 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6896 because no userspace IRQs will ever clear this flag */
6897 env->hflags &= ~HF_HALTED_MASK;
6898 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6899 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6901 qemu_get_be64s(f, &env->tsc);
6902 kvm_load_registers(env);
6904 return 0;
6907 #elif defined(TARGET_PPC)
6908 void cpu_save(QEMUFile *f, void *opaque)
6912 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6914 return 0;
6917 #elif defined(TARGET_MIPS)
6918 void cpu_save(QEMUFile *f, void *opaque)
6922 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6924 return 0;
6927 #elif defined(TARGET_SPARC)
6928 void cpu_save(QEMUFile *f, void *opaque)
6930 CPUState *env = opaque;
6931 int i;
6932 uint32_t tmp;
6934 for(i = 0; i < 8; i++)
6935 qemu_put_betls(f, &env->gregs[i]);
6936 for(i = 0; i < NWINDOWS * 16; i++)
6937 qemu_put_betls(f, &env->regbase[i]);
6939 /* FPU */
6940 for(i = 0; i < TARGET_FPREGS; i++) {
6941 union {
6942 float32 f;
6943 uint32_t i;
6944 } u;
6945 u.f = env->fpr[i];
6946 qemu_put_be32(f, u.i);
6949 qemu_put_betls(f, &env->pc);
6950 qemu_put_betls(f, &env->npc);
6951 qemu_put_betls(f, &env->y);
6952 tmp = GET_PSR(env);
6953 qemu_put_be32(f, tmp);
6954 qemu_put_betls(f, &env->fsr);
6955 qemu_put_betls(f, &env->tbr);
6956 #ifndef TARGET_SPARC64
6957 qemu_put_be32s(f, &env->wim);
6958 /* MMU */
6959 for(i = 0; i < 16; i++)
6960 qemu_put_be32s(f, &env->mmuregs[i]);
6961 #endif
6964 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6966 CPUState *env = opaque;
6967 int i;
6968 uint32_t tmp;
6970 for(i = 0; i < 8; i++)
6971 qemu_get_betls(f, &env->gregs[i]);
6972 for(i = 0; i < NWINDOWS * 16; i++)
6973 qemu_get_betls(f, &env->regbase[i]);
6975 /* FPU */
6976 for(i = 0; i < TARGET_FPREGS; i++) {
6977 union {
6978 float32 f;
6979 uint32_t i;
6980 } u;
6981 u.i = qemu_get_be32(f);
6982 env->fpr[i] = u.f;
6985 qemu_get_betls(f, &env->pc);
6986 qemu_get_betls(f, &env->npc);
6987 qemu_get_betls(f, &env->y);
6988 tmp = qemu_get_be32(f);
6989 env->cwp = 0; /* needed to ensure that the wrapping registers are
6990 correctly updated */
6991 PUT_PSR(env, tmp);
6992 qemu_get_betls(f, &env->fsr);
6993 qemu_get_betls(f, &env->tbr);
6994 #ifndef TARGET_SPARC64
6995 qemu_get_be32s(f, &env->wim);
6996 /* MMU */
6997 for(i = 0; i < 16; i++)
6998 qemu_get_be32s(f, &env->mmuregs[i]);
6999 #endif
7000 tlb_flush(env, 1);
7001 return 0;
7004 #elif defined(TARGET_ARM)
7006 void cpu_save(QEMUFile *f, void *opaque)
7008 int i;
7009 CPUARMState *env = (CPUARMState *)opaque;
7011 for (i = 0; i < 16; i++) {
7012 qemu_put_be32(f, env->regs[i]);
7014 qemu_put_be32(f, cpsr_read(env));
7015 qemu_put_be32(f, env->spsr);
7016 for (i = 0; i < 6; i++) {
7017 qemu_put_be32(f, env->banked_spsr[i]);
7018 qemu_put_be32(f, env->banked_r13[i]);
7019 qemu_put_be32(f, env->banked_r14[i]);
7021 for (i = 0; i < 5; i++) {
7022 qemu_put_be32(f, env->usr_regs[i]);
7023 qemu_put_be32(f, env->fiq_regs[i]);
7025 qemu_put_be32(f, env->cp15.c0_cpuid);
7026 qemu_put_be32(f, env->cp15.c0_cachetype);
7027 qemu_put_be32(f, env->cp15.c1_sys);
7028 qemu_put_be32(f, env->cp15.c1_coproc);
7029 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
7030 qemu_put_be32(f, env->cp15.c2_base0);
7031 qemu_put_be32(f, env->cp15.c2_base1);
7032 qemu_put_be32(f, env->cp15.c2_mask);
7033 qemu_put_be32(f, env->cp15.c2_data);
7034 qemu_put_be32(f, env->cp15.c2_insn);
7035 qemu_put_be32(f, env->cp15.c3);
7036 qemu_put_be32(f, env->cp15.c5_insn);
7037 qemu_put_be32(f, env->cp15.c5_data);
7038 for (i = 0; i < 8; i++) {
7039 qemu_put_be32(f, env->cp15.c6_region[i]);
7041 qemu_put_be32(f, env->cp15.c6_insn);
7042 qemu_put_be32(f, env->cp15.c6_data);
7043 qemu_put_be32(f, env->cp15.c9_insn);
7044 qemu_put_be32(f, env->cp15.c9_data);
7045 qemu_put_be32(f, env->cp15.c13_fcse);
7046 qemu_put_be32(f, env->cp15.c13_context);
7047 qemu_put_be32(f, env->cp15.c13_tls1);
7048 qemu_put_be32(f, env->cp15.c13_tls2);
7049 qemu_put_be32(f, env->cp15.c13_tls3);
7050 qemu_put_be32(f, env->cp15.c15_cpar);
7052 qemu_put_be32(f, env->features);
7054 if (arm_feature(env, ARM_FEATURE_VFP)) {
7055 for (i = 0; i < 16; i++) {
7056 CPU_DoubleU u;
7057 u.d = env->vfp.regs[i];
7058 qemu_put_be32(f, u.l.upper);
7059 qemu_put_be32(f, u.l.lower);
7061 for (i = 0; i < 16; i++) {
7062 qemu_put_be32(f, env->vfp.xregs[i]);
7065 /* TODO: Should use proper FPSCR access functions. */
7066 qemu_put_be32(f, env->vfp.vec_len);
7067 qemu_put_be32(f, env->vfp.vec_stride);
7069 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7070 for (i = 16; i < 32; i++) {
7071 CPU_DoubleU u;
7072 u.d = env->vfp.regs[i];
7073 qemu_put_be32(f, u.l.upper);
7074 qemu_put_be32(f, u.l.lower);
7079 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7080 for (i = 0; i < 16; i++) {
7081 qemu_put_be64(f, env->iwmmxt.regs[i]);
7083 for (i = 0; i < 16; i++) {
7084 qemu_put_be32(f, env->iwmmxt.cregs[i]);
7088 if (arm_feature(env, ARM_FEATURE_M)) {
7089 qemu_put_be32(f, env->v7m.other_sp);
7090 qemu_put_be32(f, env->v7m.vecbase);
7091 qemu_put_be32(f, env->v7m.basepri);
7092 qemu_put_be32(f, env->v7m.control);
7093 qemu_put_be32(f, env->v7m.current_sp);
7094 qemu_put_be32(f, env->v7m.exception);
7098 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7100 CPUARMState *env = (CPUARMState *)opaque;
7101 int i;
7103 if (version_id != ARM_CPU_SAVE_VERSION)
7104 return -EINVAL;
7106 for (i = 0; i < 16; i++) {
7107 env->regs[i] = qemu_get_be32(f);
7109 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
7110 env->spsr = qemu_get_be32(f);
7111 for (i = 0; i < 6; i++) {
7112 env->banked_spsr[i] = qemu_get_be32(f);
7113 env->banked_r13[i] = qemu_get_be32(f);
7114 env->banked_r14[i] = qemu_get_be32(f);
7116 for (i = 0; i < 5; i++) {
7117 env->usr_regs[i] = qemu_get_be32(f);
7118 env->fiq_regs[i] = qemu_get_be32(f);
7120 env->cp15.c0_cpuid = qemu_get_be32(f);
7121 env->cp15.c0_cachetype = qemu_get_be32(f);
7122 env->cp15.c1_sys = qemu_get_be32(f);
7123 env->cp15.c1_coproc = qemu_get_be32(f);
7124 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
7125 env->cp15.c2_base0 = qemu_get_be32(f);
7126 env->cp15.c2_base1 = qemu_get_be32(f);
7127 env->cp15.c2_mask = qemu_get_be32(f);
7128 env->cp15.c2_data = qemu_get_be32(f);
7129 env->cp15.c2_insn = qemu_get_be32(f);
7130 env->cp15.c3 = qemu_get_be32(f);
7131 env->cp15.c5_insn = qemu_get_be32(f);
7132 env->cp15.c5_data = qemu_get_be32(f);
7133 for (i = 0; i < 8; i++) {
7134 env->cp15.c6_region[i] = qemu_get_be32(f);
7136 env->cp15.c6_insn = qemu_get_be32(f);
7137 env->cp15.c6_data = qemu_get_be32(f);
7138 env->cp15.c9_insn = qemu_get_be32(f);
7139 env->cp15.c9_data = qemu_get_be32(f);
7140 env->cp15.c13_fcse = qemu_get_be32(f);
7141 env->cp15.c13_context = qemu_get_be32(f);
7142 env->cp15.c13_tls1 = qemu_get_be32(f);
7143 env->cp15.c13_tls2 = qemu_get_be32(f);
7144 env->cp15.c13_tls3 = qemu_get_be32(f);
7145 env->cp15.c15_cpar = qemu_get_be32(f);
7147 env->features = qemu_get_be32(f);
7149 if (arm_feature(env, ARM_FEATURE_VFP)) {
7150 for (i = 0; i < 16; i++) {
7151 CPU_DoubleU u;
7152 u.l.upper = qemu_get_be32(f);
7153 u.l.lower = qemu_get_be32(f);
7154 env->vfp.regs[i] = u.d;
7156 for (i = 0; i < 16; i++) {
7157 env->vfp.xregs[i] = qemu_get_be32(f);
7160 /* TODO: Should use proper FPSCR access functions. */
7161 env->vfp.vec_len = qemu_get_be32(f);
7162 env->vfp.vec_stride = qemu_get_be32(f);
7164 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7165 for (i = 0; i < 16; i++) {
7166 CPU_DoubleU u;
7167 u.l.upper = qemu_get_be32(f);
7168 u.l.lower = qemu_get_be32(f);
7169 env->vfp.regs[i] = u.d;
7174 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7175 for (i = 0; i < 16; i++) {
7176 env->iwmmxt.regs[i] = qemu_get_be64(f);
7178 for (i = 0; i < 16; i++) {
7179 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7183 if (arm_feature(env, ARM_FEATURE_M)) {
7184 env->v7m.other_sp = qemu_get_be32(f);
7185 env->v7m.vecbase = qemu_get_be32(f);
7186 env->v7m.basepri = qemu_get_be32(f);
7187 env->v7m.control = qemu_get_be32(f);
7188 env->v7m.current_sp = qemu_get_be32(f);
7189 env->v7m.exception = qemu_get_be32(f);
7192 return 0;
7195 #elif defined(TARGET_IA64)
7196 void cpu_save(QEMUFile *f, void *opaque)
7200 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7202 return 0;
7204 #else
7206 //#warning No CPU save/restore functions
7208 #endif
7210 /***********************************************************/
7211 /* ram save/restore */
7213 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7215 int v;
7217 v = qemu_get_byte(f);
7218 switch(v) {
7219 case 0:
7220 if (qemu_get_buffer(f, buf, len) != len)
7221 return -EIO;
7222 break;
7223 case 1:
7224 v = qemu_get_byte(f);
7225 memset(buf, v, len);
7226 break;
7227 default:
7228 return -EINVAL;
7230 return 0;
7233 static int ram_load_v1(QEMUFile *f, void *opaque)
7235 int i, ret;
7237 if (qemu_get_be32(f) != phys_ram_size)
7238 return -EINVAL;
7239 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7240 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7241 continue;
7242 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7243 if (ret)
7244 return ret;
7246 return 0;
7249 #define BDRV_HASH_BLOCK_SIZE 1024
7250 #define IOBUF_SIZE 4096
7251 #define RAM_CBLOCK_MAGIC 0xfabe
7253 typedef struct RamCompressState {
7254 z_stream zstream;
7255 QEMUFile *f;
7256 uint8_t buf[IOBUF_SIZE];
7257 } RamCompressState;
7259 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7261 int ret;
7262 memset(s, 0, sizeof(*s));
7263 s->f = f;
7264 ret = deflateInit2(&s->zstream, 1,
7265 Z_DEFLATED, 15,
7266 9, Z_DEFAULT_STRATEGY);
7267 if (ret != Z_OK)
7268 return -1;
7269 s->zstream.avail_out = IOBUF_SIZE;
7270 s->zstream.next_out = s->buf;
7271 return 0;
7274 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7276 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7277 qemu_put_be16(s->f, len);
7278 qemu_put_buffer(s->f, buf, len);
7281 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7283 int ret;
7285 s->zstream.avail_in = len;
7286 s->zstream.next_in = (uint8_t *)buf;
7287 while (s->zstream.avail_in > 0) {
7288 ret = deflate(&s->zstream, Z_NO_FLUSH);
7289 if (ret != Z_OK)
7290 return -1;
7291 if (s->zstream.avail_out == 0) {
7292 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7293 s->zstream.avail_out = IOBUF_SIZE;
7294 s->zstream.next_out = s->buf;
7297 return 0;
7300 static void ram_compress_close(RamCompressState *s)
7302 int len, ret;
7304 /* compress last bytes */
7305 for(;;) {
7306 ret = deflate(&s->zstream, Z_FINISH);
7307 if (ret == Z_OK || ret == Z_STREAM_END) {
7308 len = IOBUF_SIZE - s->zstream.avail_out;
7309 if (len > 0) {
7310 ram_put_cblock(s, s->buf, len);
7312 s->zstream.avail_out = IOBUF_SIZE;
7313 s->zstream.next_out = s->buf;
7314 if (ret == Z_STREAM_END)
7315 break;
7316 } else {
7317 goto fail;
7320 fail:
7321 deflateEnd(&s->zstream);
7324 typedef struct RamDecompressState {
7325 z_stream zstream;
7326 QEMUFile *f;
7327 uint8_t buf[IOBUF_SIZE];
7328 } RamDecompressState;
7330 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7332 int ret;
7333 memset(s, 0, sizeof(*s));
7334 s->f = f;
7335 ret = inflateInit(&s->zstream);
7336 if (ret != Z_OK)
7337 return -1;
7338 return 0;
7341 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7343 int ret, clen;
7345 s->zstream.avail_out = len;
7346 s->zstream.next_out = buf;
7347 while (s->zstream.avail_out > 0) {
7348 if (s->zstream.avail_in == 0) {
7349 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7350 return -1;
7351 clen = qemu_get_be16(s->f);
7352 if (clen > IOBUF_SIZE)
7353 return -1;
7354 qemu_get_buffer(s->f, s->buf, clen);
7355 s->zstream.avail_in = clen;
7356 s->zstream.next_in = s->buf;
7358 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7359 if (ret != Z_OK && ret != Z_STREAM_END) {
7360 return -1;
7363 return 0;
7366 static void ram_decompress_close(RamDecompressState *s)
7368 inflateEnd(&s->zstream);
7371 static void ram_save_live(QEMUFile *f, void *opaque)
7373 target_ulong addr;
7375 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7376 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7377 continue;
7378 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7379 qemu_put_be32(f, addr);
7380 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7383 qemu_put_be32(f, 1);
7386 static void ram_save_static(QEMUFile *f, void *opaque)
7388 int i;
7389 RamCompressState s1, *s = &s1;
7390 uint8_t buf[10];
7392 qemu_put_be32(f, phys_ram_size);
7393 if (ram_compress_open(s, f) < 0)
7394 return;
7395 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7396 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7397 continue;
7398 #if 0
7399 if (tight_savevm_enabled) {
7400 int64_t sector_num;
7401 int j;
7403 /* find if the memory block is available on a virtual
7404 block device */
7405 sector_num = -1;
7406 for(j = 0; j < nb_drives; j++) {
7407 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7408 phys_ram_base + i,
7409 BDRV_HASH_BLOCK_SIZE);
7410 if (sector_num >= 0)
7411 break;
7413 if (j == nb_drives)
7414 goto normal_compress;
7415 buf[0] = 1;
7416 buf[1] = j;
7417 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7418 ram_compress_buf(s, buf, 10);
7419 } else
7420 #endif
7422 // normal_compress:
7423 buf[0] = 0;
7424 ram_compress_buf(s, buf, 1);
7425 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7428 ram_compress_close(s);
7431 static void ram_save(QEMUFile *f, void *opaque)
7433 int in_migration = cpu_physical_memory_get_dirty_tracking();
7435 qemu_put_byte(f, in_migration);
7437 if (in_migration)
7438 ram_save_live(f, opaque);
7439 else
7440 ram_save_static(f, opaque);
7443 static int ram_load_live(QEMUFile *f, void *opaque)
7445 target_ulong addr;
7447 do {
7448 addr = qemu_get_be32(f);
7449 if (addr == 1)
7450 break;
7452 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7453 } while (1);
7455 return 0;
7458 static int ram_load_static(QEMUFile *f, void *opaque)
7460 RamDecompressState s1, *s = &s1;
7461 uint8_t buf[10];
7462 int i;
7464 if (qemu_get_be32(f) != phys_ram_size)
7465 return -EINVAL;
7466 if (ram_decompress_open(s, f) < 0)
7467 return -EINVAL;
7468 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7469 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7470 continue;
7471 if (ram_decompress_buf(s, buf, 1) < 0) {
7472 fprintf(stderr, "Error while reading ram block header\n");
7473 goto error;
7475 if (buf[0] == 0) {
7476 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7477 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7478 goto error;
7480 } else
7481 #if 0
7482 if (buf[0] == 1) {
7483 int bs_index;
7484 int64_t sector_num;
7486 ram_decompress_buf(s, buf + 1, 9);
7487 bs_index = buf[1];
7488 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7489 if (bs_index >= nb_drives) {
7490 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7491 goto error;
7493 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7494 phys_ram_base + i,
7495 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7496 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7497 bs_index, sector_num);
7498 goto error;
7500 } else
7501 #endif
7503 error:
7504 printf("Error block header\n");
7505 return -EINVAL;
7508 ram_decompress_close(s);
7509 return 0;
7512 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7514 int ret;
7516 switch (version_id) {
7517 case 1:
7518 ret = ram_load_v1(f, opaque);
7519 break;
7520 case 3:
7521 if (qemu_get_byte(f)) {
7522 ret = ram_load_live(f, opaque);
7523 break;
7525 case 2:
7526 ret = ram_load_static(f, opaque);
7527 break;
7528 default:
7529 ret = -EINVAL;
7530 break;
7533 return ret;
7536 /***********************************************************/
7537 /* bottom halves (can be seen as timers which expire ASAP) */
7539 struct QEMUBH {
7540 QEMUBHFunc *cb;
7541 void *opaque;
7542 int scheduled;
7543 QEMUBH *next;
7546 static QEMUBH *first_bh = NULL;
7548 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7550 QEMUBH *bh;
7551 bh = qemu_mallocz(sizeof(QEMUBH));
7552 if (!bh)
7553 return NULL;
7554 bh->cb = cb;
7555 bh->opaque = opaque;
7556 return bh;
7559 int qemu_bh_poll(void)
7561 QEMUBH *bh, **pbh;
7562 int ret;
7564 ret = 0;
7565 for(;;) {
7566 pbh = &first_bh;
7567 bh = *pbh;
7568 if (!bh)
7569 break;
7570 ret = 1;
7571 *pbh = bh->next;
7572 bh->scheduled = 0;
7573 bh->cb(bh->opaque);
7575 return ret;
7578 void qemu_bh_schedule(QEMUBH *bh)
7580 CPUState *env = cpu_single_env;
7581 if (bh->scheduled)
7582 return;
7583 bh->scheduled = 1;
7584 bh->next = first_bh;
7585 first_bh = bh;
7587 /* stop the currently executing CPU to execute the BH ASAP */
7588 if (env) {
7589 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7593 void qemu_bh_cancel(QEMUBH *bh)
7595 QEMUBH **pbh;
7596 if (bh->scheduled) {
7597 pbh = &first_bh;
7598 while (*pbh != bh)
7599 pbh = &(*pbh)->next;
7600 *pbh = bh->next;
7601 bh->scheduled = 0;
7605 void qemu_bh_delete(QEMUBH *bh)
7607 qemu_bh_cancel(bh);
7608 qemu_free(bh);
7611 /***********************************************************/
7612 /* machine registration */
7614 QEMUMachine *first_machine = NULL;
7615 QEMUMachine *current_machine = NULL;
7617 int qemu_register_machine(QEMUMachine *m)
7619 QEMUMachine **pm;
7620 pm = &first_machine;
7621 while (*pm != NULL)
7622 pm = &(*pm)->next;
7623 m->next = NULL;
7624 *pm = m;
7625 return 0;
7628 static QEMUMachine *find_machine(const char *name)
7630 QEMUMachine *m;
7632 for(m = first_machine; m != NULL; m = m->next) {
7633 if (!strcmp(m->name, name))
7634 return m;
7636 return NULL;
7639 /***********************************************************/
7640 /* main execution loop */
7642 static void gui_update(void *opaque)
7644 DisplayState *ds = opaque;
7645 ds->dpy_refresh(ds);
7646 qemu_mod_timer(ds->gui_timer,
7647 (ds->gui_timer_interval ?
7648 ds->gui_timer_interval :
7649 GUI_REFRESH_INTERVAL)
7650 + qemu_get_clock(rt_clock));
7653 struct vm_change_state_entry {
7654 VMChangeStateHandler *cb;
7655 void *opaque;
7656 LIST_ENTRY (vm_change_state_entry) entries;
7659 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7661 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7662 void *opaque)
7664 VMChangeStateEntry *e;
7666 e = qemu_mallocz(sizeof (*e));
7667 if (!e)
7668 return NULL;
7670 e->cb = cb;
7671 e->opaque = opaque;
7672 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7673 return e;
7676 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7678 LIST_REMOVE (e, entries);
7679 qemu_free (e);
7682 static void vm_state_notify(int running)
7684 VMChangeStateEntry *e;
7686 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7687 e->cb(e->opaque, running);
7691 /* XXX: support several handlers */
7692 static VMStopHandler *vm_stop_cb;
7693 static void *vm_stop_opaque;
7695 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7697 vm_stop_cb = cb;
7698 vm_stop_opaque = opaque;
7699 return 0;
7702 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7704 vm_stop_cb = NULL;
7707 void vm_start(void)
7709 if (!vm_running) {
7710 cpu_enable_ticks();
7711 vm_running = 1;
7712 vm_state_notify(1);
7713 qemu_rearm_alarm_timer(alarm_timer);
7717 void vm_stop(int reason)
7719 if (vm_running) {
7720 cpu_disable_ticks();
7721 vm_running = 0;
7722 if (reason != 0) {
7723 if (vm_stop_cb) {
7724 vm_stop_cb(vm_stop_opaque, reason);
7727 vm_state_notify(0);
7731 /* reset/shutdown handler */
7733 typedef struct QEMUResetEntry {
7734 QEMUResetHandler *func;
7735 void *opaque;
7736 struct QEMUResetEntry *next;
7737 } QEMUResetEntry;
7739 static QEMUResetEntry *first_reset_entry;
7740 static int reset_requested;
7741 static int shutdown_requested;
7742 static int powerdown_requested;
7744 int qemu_shutdown_requested(void)
7746 int r = shutdown_requested;
7747 shutdown_requested = 0;
7748 return r;
7751 int qemu_reset_requested(void)
7753 int r = reset_requested;
7754 reset_requested = 0;
7755 return r;
7758 int qemu_powerdown_requested(void)
7760 int r = powerdown_requested;
7761 powerdown_requested = 0;
7762 return r;
7765 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7767 QEMUResetEntry **pre, *re;
7769 pre = &first_reset_entry;
7770 while (*pre != NULL)
7771 pre = &(*pre)->next;
7772 re = qemu_mallocz(sizeof(QEMUResetEntry));
7773 re->func = func;
7774 re->opaque = opaque;
7775 re->next = NULL;
7776 *pre = re;
7779 void qemu_system_reset(void)
7781 QEMUResetEntry *re;
7783 /* reset all devices */
7784 for(re = first_reset_entry; re != NULL; re = re->next) {
7785 re->func(re->opaque);
7789 void qemu_system_reset_request(void)
7791 if (no_reboot) {
7792 shutdown_requested = 1;
7793 } else {
7794 reset_requested = 1;
7796 if (cpu_single_env)
7797 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7800 void qemu_system_shutdown_request(void)
7802 shutdown_requested = 1;
7803 if (cpu_single_env)
7804 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7807 void qemu_system_powerdown_request(void)
7809 powerdown_requested = 1;
7810 if (cpu_single_env)
7811 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7814 void main_loop_wait(int timeout)
7816 IOHandlerRecord *ioh;
7817 fd_set rfds, wfds, xfds;
7818 int ret, nfds;
7819 #ifdef _WIN32
7820 int ret2, i;
7821 #endif
7822 struct timeval tv;
7823 PollingEntry *pe;
7826 /* XXX: need to suppress polling by better using win32 events */
7827 ret = 0;
7828 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7829 ret |= pe->func(pe->opaque);
7831 #ifdef _WIN32
7832 if (ret == 0) {
7833 int err;
7834 WaitObjects *w = &wait_objects;
7836 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7837 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7838 if (w->func[ret - WAIT_OBJECT_0])
7839 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7841 /* Check for additional signaled events */
7842 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7844 /* Check if event is signaled */
7845 ret2 = WaitForSingleObject(w->events[i], 0);
7846 if(ret2 == WAIT_OBJECT_0) {
7847 if (w->func[i])
7848 w->func[i](w->opaque[i]);
7849 } else if (ret2 == WAIT_TIMEOUT) {
7850 } else {
7851 err = GetLastError();
7852 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7855 } else if (ret == WAIT_TIMEOUT) {
7856 } else {
7857 err = GetLastError();
7858 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7861 #endif
7862 /* poll any events */
7863 /* XXX: separate device handlers from system ones */
7864 nfds = -1;
7865 FD_ZERO(&rfds);
7866 FD_ZERO(&wfds);
7867 FD_ZERO(&xfds);
7868 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7869 if (ioh->deleted)
7870 continue;
7871 if (ioh->fd_read &&
7872 (!ioh->fd_read_poll ||
7873 ioh->fd_read_poll(ioh->opaque) != 0)) {
7874 FD_SET(ioh->fd, &rfds);
7875 if (ioh->fd > nfds)
7876 nfds = ioh->fd;
7878 if (ioh->fd_write) {
7879 FD_SET(ioh->fd, &wfds);
7880 if (ioh->fd > nfds)
7881 nfds = ioh->fd;
7885 tv.tv_sec = 0;
7886 #ifdef _WIN32
7887 tv.tv_usec = 0;
7888 #else
7889 tv.tv_usec = timeout * 1000;
7890 #endif
7891 #if defined(CONFIG_SLIRP)
7892 if (slirp_inited) {
7893 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7895 #endif
7896 moreio:
7897 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7898 if (ret > 0) {
7899 IOHandlerRecord **pioh;
7900 int more = 0;
7902 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7903 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7904 ioh->fd_read(ioh->opaque);
7905 if (!ioh->fd_read_poll || ioh->fd_read_poll(ioh->opaque))
7906 more = 1;
7907 else
7908 FD_CLR(ioh->fd, &rfds);
7910 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7911 ioh->fd_write(ioh->opaque);
7912 more = 1;
7916 /* remove deleted IO handlers */
7917 pioh = &first_io_handler;
7918 while (*pioh) {
7919 ioh = *pioh;
7920 if (ioh->deleted) {
7921 *pioh = ioh->next;
7922 qemu_free(ioh);
7923 } else
7924 pioh = &ioh->next;
7926 if (more)
7927 goto moreio;
7929 #if defined(CONFIG_SLIRP)
7930 if (slirp_inited) {
7931 if (ret < 0) {
7932 FD_ZERO(&rfds);
7933 FD_ZERO(&wfds);
7934 FD_ZERO(&xfds);
7936 slirp_select_poll(&rfds, &wfds, &xfds);
7938 #endif
7939 virtio_net_poll();
7941 qemu_aio_poll();
7943 if (vm_running) {
7944 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7945 qemu_get_clock(vm_clock));
7946 /* run dma transfers, if any */
7947 DMA_run();
7950 /* real time timers */
7951 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7952 qemu_get_clock(rt_clock));
7954 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7955 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7956 qemu_rearm_alarm_timer(alarm_timer);
7959 /* Check bottom-halves last in case any of the earlier events triggered
7960 them. */
7961 qemu_bh_poll();
7965 static int main_loop(void)
7967 int ret, timeout;
7968 #ifdef CONFIG_PROFILER
7969 int64_t ti;
7970 #endif
7971 CPUState *env;
7974 if (kvm_enabled()) {
7975 kvm_main_loop();
7976 cpu_disable_ticks();
7977 return 0;
7980 cur_cpu = first_cpu;
7981 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7982 for(;;) {
7983 if (vm_running) {
7985 for(;;) {
7986 /* get next cpu */
7987 env = next_cpu;
7988 #ifdef CONFIG_PROFILER
7989 ti = profile_getclock();
7990 #endif
7991 ret = cpu_exec(env);
7992 #ifdef CONFIG_PROFILER
7993 qemu_time += profile_getclock() - ti;
7994 #endif
7995 next_cpu = env->next_cpu ?: first_cpu;
7996 if (event_pending) {
7997 ret = EXCP_INTERRUPT;
7998 event_pending = 0;
7999 break;
8001 if (ret == EXCP_HLT) {
8002 /* Give the next CPU a chance to run. */
8003 cur_cpu = env;
8004 continue;
8006 if (ret != EXCP_HALTED)
8007 break;
8008 /* all CPUs are halted ? */
8009 if (env == cur_cpu)
8010 break;
8012 cur_cpu = env;
8014 if (shutdown_requested) {
8015 ret = EXCP_INTERRUPT;
8016 break;
8018 if (reset_requested) {
8019 reset_requested = 0;
8020 qemu_system_reset();
8021 if (kvm_enabled())
8022 kvm_load_registers(env);
8023 ret = EXCP_INTERRUPT;
8025 if (powerdown_requested) {
8026 powerdown_requested = 0;
8027 qemu_system_powerdown();
8028 ret = EXCP_INTERRUPT;
8030 if (ret == EXCP_DEBUG) {
8031 vm_stop(EXCP_DEBUG);
8033 /* If all cpus are halted then wait until the next IRQ */
8034 /* XXX: use timeout computed from timers */
8035 if (ret == EXCP_HALTED)
8036 timeout = 10;
8037 else
8038 timeout = 0;
8039 } else {
8040 timeout = 10;
8042 #ifdef CONFIG_PROFILER
8043 ti = profile_getclock();
8044 #endif
8045 main_loop_wait(timeout);
8046 #ifdef CONFIG_PROFILER
8047 dev_time += profile_getclock() - ti;
8048 #endif
8050 cpu_disable_ticks();
8051 return ret;
8054 static void help(int exitcode)
8056 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
8057 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8058 "usage: %s [options] [disk_image]\n"
8059 "\n"
8060 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8061 "\n"
8062 "Standard options:\n"
8063 "-M machine select emulated machine (-M ? for list)\n"
8064 "-cpu cpu select CPU (-cpu ? for list)\n"
8065 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8066 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8067 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8068 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8069 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
8070 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
8071 " [,cache=on|off][,boot=on|off]\n"
8072 " use 'file' as a drive image\n"
8073 "-mtdblock file use 'file' as on-board Flash memory image\n"
8074 "-sd file use 'file' as SecureDigital card image\n"
8075 "-pflash file use 'file' as a parallel flash image\n"
8076 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8077 "-snapshot write to temporary files instead of disk image files\n"
8078 #ifdef CONFIG_SDL
8079 "-no-frame open SDL window without a frame and window decorations\n"
8080 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8081 "-no-quit disable SDL window close capability\n"
8082 #endif
8083 #ifdef TARGET_I386
8084 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8085 #endif
8086 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8087 "-smp n set the number of CPUs to 'n' [default=1]\n"
8088 "-nographic disable graphical output and redirect serial I/Os to console\n"
8089 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8090 #ifndef _WIN32
8091 "-k language use keyboard layout (for example \"fr\" for French)\n"
8092 #endif
8093 #ifdef HAS_AUDIO
8094 "-audio-help print list of audio drivers and their options\n"
8095 "-soundhw c1,... enable audio support\n"
8096 " and only specified sound cards (comma separated list)\n"
8097 " use -soundhw ? to get the list of supported cards\n"
8098 " use -soundhw all to enable all of them\n"
8099 #endif
8100 "-localtime set the real time clock to local time [default=utc]\n"
8101 "-full-screen start in full screen\n"
8102 #ifdef TARGET_I386
8103 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8104 #endif
8105 "-usb enable the USB driver (will be the default soon)\n"
8106 "-usbdevice name add the host or guest USB device 'name'\n"
8107 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8108 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8109 #endif
8110 "-name string set the name of the guest\n"
8111 "\n"
8112 "Network options:\n"
8113 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8114 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8115 #ifdef CONFIG_SLIRP
8116 "-net user[,vlan=n][,hostname=host]\n"
8117 " connect the user mode network stack to VLAN 'n' and send\n"
8118 " hostname 'host' to DHCP clients\n"
8119 #endif
8120 #ifdef _WIN32
8121 "-net tap[,vlan=n],ifname=name\n"
8122 " connect the host TAP network interface to VLAN 'n'\n"
8123 #else
8124 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8125 " connect the host TAP network interface to VLAN 'n' and use the\n"
8126 " network scripts 'file' (default=%s)\n"
8127 " and 'dfile' (default=%s);\n"
8128 " use '[down]script=no' to disable script execution;\n"
8129 " use 'fd=h' to connect to an already opened TAP interface\n"
8130 #endif
8131 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8132 " connect the vlan 'n' to another VLAN using a socket connection\n"
8133 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8134 " connect the vlan 'n' to multicast maddr and port\n"
8135 "-net none use it alone to have zero network devices; if no -net option\n"
8136 " is provided, the default is '-net nic -net user'\n"
8137 "\n"
8138 #ifdef CONFIG_SLIRP
8139 "-tftp dir allow tftp access to files in dir [-net user]\n"
8140 "-bootp file advertise file in BOOTP replies\n"
8141 #ifndef _WIN32
8142 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8143 #endif
8144 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8145 " redirect TCP or UDP connections from host to guest [-net user]\n"
8146 #endif
8147 "\n"
8148 "Linux boot specific:\n"
8149 "-kernel bzImage use 'bzImage' as kernel image\n"
8150 "-append cmdline use 'cmdline' as kernel command line\n"
8151 "-initrd file use 'file' as initial ram disk\n"
8152 "\n"
8153 "Debug/Expert options:\n"
8154 "-monitor dev redirect the monitor to char device 'dev'\n"
8155 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8156 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8157 "-serial dev redirect the serial port to char device 'dev'\n"
8158 "-parallel dev redirect the parallel port to char device 'dev'\n"
8159 "-pidfile file Write PID to 'file'\n"
8160 "-S freeze CPU at startup (use 'c' to start execution)\n"
8161 "-s wait gdb connection to port\n"
8162 "-p port set gdb connection port [default=%s]\n"
8163 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8164 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8165 " translation (t=none or lba) (usually qemu can guess them)\n"
8166 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8167 #ifdef USE_KQEMU
8168 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8169 "-no-kqemu disable KQEMU kernel module usage\n"
8170 #endif
8171 #ifdef USE_KVM
8172 #ifndef NO_CPU_EMULATION
8173 "-no-kvm disable KVM hardware virtualization\n"
8174 #endif
8175 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8176 "-no-kvm-pit disable KVM kernel mode PIT\n"
8177 #endif
8178 #ifdef TARGET_I386
8179 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8180 " (default is CL-GD5446 PCI VGA)\n"
8181 "-no-acpi disable ACPI\n"
8182 #endif
8183 #ifdef CONFIG_CURSES
8184 "-curses use a curses/ncurses interface instead of SDL\n"
8185 #endif
8186 "-no-reboot exit instead of rebooting\n"
8187 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8188 "-vnc display start a VNC server on display\n"
8189 #ifndef _WIN32
8190 "-daemonize daemonize QEMU after initializing\n"
8191 #endif
8192 "-tdf inject timer interrupts that got lost\n"
8193 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8194 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8195 "-option-rom rom load a file, rom, into the option ROM space\n"
8196 #ifdef TARGET_SPARC
8197 "-prom-env variable=value set OpenBIOS nvram variables\n"
8198 #endif
8199 "-clock force the use of the given methods for timer alarm.\n"
8200 " To see what timers are available use -clock ?\n"
8201 "-startdate select initial date of the clock\n"
8202 "\n"
8203 "During emulation, the following keys are useful:\n"
8204 "ctrl-alt-f toggle full screen\n"
8205 "ctrl-alt-n switch to virtual console 'n'\n"
8206 "ctrl-alt toggle mouse and keyboard grab\n"
8207 "\n"
8208 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8210 "qemu",
8211 DEFAULT_RAM_SIZE,
8212 #ifndef _WIN32
8213 DEFAULT_NETWORK_SCRIPT,
8214 DEFAULT_NETWORK_DOWN_SCRIPT,
8215 #endif
8216 DEFAULT_GDBSTUB_PORT,
8217 "/tmp/qemu.log");
8218 exit(exitcode);
8221 #define HAS_ARG 0x0001
8223 enum {
8224 QEMU_OPTION_h,
8226 QEMU_OPTION_M,
8227 QEMU_OPTION_cpu,
8228 QEMU_OPTION_fda,
8229 QEMU_OPTION_fdb,
8230 QEMU_OPTION_hda,
8231 QEMU_OPTION_hdb,
8232 QEMU_OPTION_hdc,
8233 QEMU_OPTION_hdd,
8234 QEMU_OPTION_drive,
8235 QEMU_OPTION_cdrom,
8236 QEMU_OPTION_mtdblock,
8237 QEMU_OPTION_sd,
8238 QEMU_OPTION_pflash,
8239 QEMU_OPTION_boot,
8240 QEMU_OPTION_snapshot,
8241 #ifdef TARGET_I386
8242 QEMU_OPTION_no_fd_bootchk,
8243 #endif
8244 QEMU_OPTION_m,
8245 QEMU_OPTION_nographic,
8246 QEMU_OPTION_portrait,
8247 #ifdef HAS_AUDIO
8248 QEMU_OPTION_audio_help,
8249 QEMU_OPTION_soundhw,
8250 #endif
8252 QEMU_OPTION_net,
8253 QEMU_OPTION_tftp,
8254 QEMU_OPTION_bootp,
8255 QEMU_OPTION_smb,
8256 QEMU_OPTION_redir,
8258 QEMU_OPTION_kernel,
8259 QEMU_OPTION_append,
8260 QEMU_OPTION_initrd,
8262 QEMU_OPTION_S,
8263 QEMU_OPTION_s,
8264 QEMU_OPTION_p,
8265 QEMU_OPTION_d,
8266 QEMU_OPTION_hdachs,
8267 QEMU_OPTION_L,
8268 QEMU_OPTION_bios,
8269 QEMU_OPTION_no_code_copy,
8270 QEMU_OPTION_k,
8271 QEMU_OPTION_localtime,
8272 QEMU_OPTION_cirrusvga,
8273 QEMU_OPTION_vmsvga,
8274 QEMU_OPTION_g,
8275 QEMU_OPTION_std_vga,
8276 QEMU_OPTION_echr,
8277 QEMU_OPTION_monitor,
8278 QEMU_OPTION_balloon,
8279 QEMU_OPTION_vmchannel,
8280 QEMU_OPTION_serial,
8281 QEMU_OPTION_parallel,
8282 QEMU_OPTION_loadvm,
8283 QEMU_OPTION_full_screen,
8284 QEMU_OPTION_no_frame,
8285 QEMU_OPTION_alt_grab,
8286 QEMU_OPTION_no_quit,
8287 QEMU_OPTION_pidfile,
8288 QEMU_OPTION_no_kqemu,
8289 QEMU_OPTION_kernel_kqemu,
8290 QEMU_OPTION_win2k_hack,
8291 QEMU_OPTION_usb,
8292 QEMU_OPTION_usbdevice,
8293 QEMU_OPTION_smp,
8294 QEMU_OPTION_vnc,
8295 QEMU_OPTION_no_acpi,
8296 QEMU_OPTION_curses,
8297 QEMU_OPTION_no_kvm,
8298 QEMU_OPTION_no_kvm_irqchip,
8299 QEMU_OPTION_no_kvm_pit,
8300 QEMU_OPTION_no_reboot,
8301 QEMU_OPTION_show_cursor,
8302 QEMU_OPTION_daemonize,
8303 QEMU_OPTION_option_rom,
8304 QEMU_OPTION_semihosting,
8305 QEMU_OPTION_cpu_vendor,
8306 QEMU_OPTION_name,
8307 QEMU_OPTION_prom_env,
8308 QEMU_OPTION_old_param,
8309 QEMU_OPTION_clock,
8310 QEMU_OPTION_startdate,
8311 QEMU_OPTION_translation,
8312 QEMU_OPTION_incoming,
8313 QEMU_OPTION_tdf,
8314 QEMU_OPTION_kvm_shadow_memory,
8315 QEMU_OPTION_mempath,
8318 typedef struct QEMUOption {
8319 const char *name;
8320 int flags;
8321 int index;
8322 } QEMUOption;
8324 const QEMUOption qemu_options[] = {
8325 { "h", 0, QEMU_OPTION_h },
8326 { "help", 0, QEMU_OPTION_h },
8328 { "M", HAS_ARG, QEMU_OPTION_M },
8329 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8330 { "fda", HAS_ARG, QEMU_OPTION_fda },
8331 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8332 { "hda", HAS_ARG, QEMU_OPTION_hda },
8333 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8334 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8335 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8336 { "drive", HAS_ARG, QEMU_OPTION_drive },
8337 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8338 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8339 { "sd", HAS_ARG, QEMU_OPTION_sd },
8340 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8341 { "boot", HAS_ARG, QEMU_OPTION_boot },
8342 { "snapshot", 0, QEMU_OPTION_snapshot },
8343 #ifdef TARGET_I386
8344 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8345 #endif
8346 { "m", HAS_ARG, QEMU_OPTION_m },
8347 { "nographic", 0, QEMU_OPTION_nographic },
8348 { "portrait", 0, QEMU_OPTION_portrait },
8349 { "k", HAS_ARG, QEMU_OPTION_k },
8350 #ifdef HAS_AUDIO
8351 { "audio-help", 0, QEMU_OPTION_audio_help },
8352 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8353 #endif
8355 { "net", HAS_ARG, QEMU_OPTION_net},
8356 #ifdef CONFIG_SLIRP
8357 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8358 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8359 #ifndef _WIN32
8360 { "smb", HAS_ARG, QEMU_OPTION_smb },
8361 #endif
8362 { "redir", HAS_ARG, QEMU_OPTION_redir },
8363 #endif
8365 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8366 { "append", HAS_ARG, QEMU_OPTION_append },
8367 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8369 { "S", 0, QEMU_OPTION_S },
8370 { "s", 0, QEMU_OPTION_s },
8371 { "p", HAS_ARG, QEMU_OPTION_p },
8372 { "d", HAS_ARG, QEMU_OPTION_d },
8373 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8374 { "L", HAS_ARG, QEMU_OPTION_L },
8375 { "bios", HAS_ARG, QEMU_OPTION_bios },
8376 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8377 #ifdef USE_KQEMU
8378 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8379 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8380 #endif
8381 #ifdef USE_KVM
8382 #ifndef NO_CPU_EMULATION
8383 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8384 #endif
8385 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8386 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8387 #endif
8388 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8389 { "g", 1, QEMU_OPTION_g },
8390 #endif
8391 { "localtime", 0, QEMU_OPTION_localtime },
8392 { "std-vga", 0, QEMU_OPTION_std_vga },
8393 { "monitor", 1, QEMU_OPTION_monitor },
8394 { "balloon", 1, QEMU_OPTION_balloon },
8395 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8396 { "echr", HAS_ARG, QEMU_OPTION_echr },
8397 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8398 { "serial", HAS_ARG, QEMU_OPTION_serial },
8399 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8400 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8401 { "incoming", 1, QEMU_OPTION_incoming },
8402 { "full-screen", 0, QEMU_OPTION_full_screen },
8403 #ifdef CONFIG_SDL
8404 { "no-frame", 0, QEMU_OPTION_no_frame },
8405 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8406 { "no-quit", 0, QEMU_OPTION_no_quit },
8407 #endif
8408 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8409 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8410 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8411 { "smp", HAS_ARG, QEMU_OPTION_smp },
8412 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8413 #ifdef CONFIG_CURSES
8414 { "curses", 0, QEMU_OPTION_curses },
8415 #endif
8417 /* temporary options */
8418 { "usb", 0, QEMU_OPTION_usb },
8419 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8420 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8421 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8422 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8423 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8424 { "daemonize", 0, QEMU_OPTION_daemonize },
8425 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8426 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8427 { "semihosting", 0, QEMU_OPTION_semihosting },
8428 #endif
8429 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8430 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8431 { "name", HAS_ARG, QEMU_OPTION_name },
8432 #if defined(TARGET_SPARC)
8433 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8434 #endif
8435 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8436 #if defined(TARGET_ARM)
8437 { "old-param", 0, QEMU_OPTION_old_param },
8438 #endif
8439 { "clock", HAS_ARG, QEMU_OPTION_clock },
8440 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8441 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8442 { NULL },
8445 /* password input */
8447 int qemu_key_check(BlockDriverState *bs, const char *name)
8449 char password[256];
8450 int i;
8452 if (!bdrv_is_encrypted(bs))
8453 return 0;
8455 term_printf("%s is encrypted.\n", name);
8456 for(i = 0; i < 3; i++) {
8457 monitor_readline("Password: ", 1, password, sizeof(password));
8458 if (bdrv_set_key(bs, password) == 0)
8459 return 0;
8460 term_printf("invalid password\n");
8462 return -EPERM;
8465 static BlockDriverState *get_bdrv(int index)
8467 if (index > nb_drives)
8468 return NULL;
8469 return drives_table[index].bdrv;
8472 static void read_passwords(void)
8474 BlockDriverState *bs;
8475 int i;
8477 for(i = 0; i < 6; i++) {
8478 bs = get_bdrv(i);
8479 if (bs)
8480 qemu_key_check(bs, bdrv_get_device_name(bs));
8484 /* XXX: currently we cannot use simultaneously different CPUs */
8485 static void register_machines(void)
8487 #if defined(TARGET_I386)
8488 qemu_register_machine(&pc_machine);
8489 qemu_register_machine(&isapc_machine);
8490 #elif defined(TARGET_PPC)
8491 qemu_register_machine(&heathrow_machine);
8492 qemu_register_machine(&core99_machine);
8493 qemu_register_machine(&prep_machine);
8494 qemu_register_machine(&ref405ep_machine);
8495 qemu_register_machine(&taihu_machine);
8496 qemu_register_machine(&bamboo_machine);
8497 #elif defined(TARGET_MIPS)
8498 qemu_register_machine(&mips_machine);
8499 qemu_register_machine(&mips_malta_machine);
8500 qemu_register_machine(&mips_pica61_machine);
8501 qemu_register_machine(&mips_mipssim_machine);
8502 #elif defined(TARGET_SPARC)
8503 #ifdef TARGET_SPARC64
8504 qemu_register_machine(&sun4u_machine);
8505 #else
8506 qemu_register_machine(&ss5_machine);
8507 qemu_register_machine(&ss10_machine);
8508 qemu_register_machine(&ss600mp_machine);
8509 qemu_register_machine(&ss20_machine);
8510 qemu_register_machine(&ss2_machine);
8511 qemu_register_machine(&voyager_machine);
8512 qemu_register_machine(&ss_lx_machine);
8513 qemu_register_machine(&ss4_machine);
8514 qemu_register_machine(&scls_machine);
8515 qemu_register_machine(&sbook_machine);
8516 qemu_register_machine(&ss1000_machine);
8517 qemu_register_machine(&ss2000_machine);
8518 #endif
8519 #elif defined(TARGET_ARM)
8520 qemu_register_machine(&integratorcp_machine);
8521 qemu_register_machine(&versatilepb_machine);
8522 qemu_register_machine(&versatileab_machine);
8523 qemu_register_machine(&realview_machine);
8524 qemu_register_machine(&akitapda_machine);
8525 qemu_register_machine(&spitzpda_machine);
8526 qemu_register_machine(&borzoipda_machine);
8527 qemu_register_machine(&terrierpda_machine);
8528 qemu_register_machine(&palmte_machine);
8529 qemu_register_machine(&lm3s811evb_machine);
8530 qemu_register_machine(&lm3s6965evb_machine);
8531 qemu_register_machine(&connex_machine);
8532 qemu_register_machine(&verdex_machine);
8533 qemu_register_machine(&mainstone2_machine);
8534 #elif defined(TARGET_SH4)
8535 qemu_register_machine(&shix_machine);
8536 qemu_register_machine(&r2d_machine);
8537 #elif defined(TARGET_ALPHA)
8538 /* XXX: TODO */
8539 #elif defined(TARGET_M68K)
8540 qemu_register_machine(&mcf5208evb_machine);
8541 qemu_register_machine(&an5206_machine);
8542 qemu_register_machine(&dummy_m68k_machine);
8543 #elif defined(TARGET_CRIS)
8544 qemu_register_machine(&bareetraxfs_machine);
8545 #elif defined(TARGET_IA64)
8546 qemu_register_machine(&ipf_machine);
8547 #else
8548 #error unsupported CPU
8549 #endif
8552 #ifdef HAS_AUDIO
8553 struct soundhw soundhw[] = {
8554 #ifdef HAS_AUDIO_CHOICE
8555 #ifdef TARGET_I386
8557 "pcspk",
8558 "PC speaker",
8561 { .init_isa = pcspk_audio_init }
8563 #endif
8565 "sb16",
8566 "Creative Sound Blaster 16",
8569 { .init_isa = SB16_init }
8572 #ifdef CONFIG_ADLIB
8574 "adlib",
8575 #ifdef HAS_YMF262
8576 "Yamaha YMF262 (OPL3)",
8577 #else
8578 "Yamaha YM3812 (OPL2)",
8579 #endif
8582 { .init_isa = Adlib_init }
8584 #endif
8586 #ifdef CONFIG_GUS
8588 "gus",
8589 "Gravis Ultrasound GF1",
8592 { .init_isa = GUS_init }
8594 #endif
8596 #ifdef CONFIG_AC97
8598 "ac97",
8599 "Intel 82801AA AC97 Audio",
8602 { .init_pci = ac97_init }
8604 #endif
8607 "es1370",
8608 "ENSONIQ AudioPCI ES1370",
8611 { .init_pci = es1370_init }
8613 #endif
8615 { NULL, NULL, 0, 0, { NULL } }
8618 static void select_soundhw (const char *optarg)
8620 struct soundhw *c;
8622 if (*optarg == '?') {
8623 show_valid_cards:
8625 printf ("Valid sound card names (comma separated):\n");
8626 for (c = soundhw; c->name; ++c) {
8627 printf ("%-11s %s\n", c->name, c->descr);
8629 printf ("\n-soundhw all will enable all of the above\n");
8630 exit (*optarg != '?');
8632 else {
8633 size_t l;
8634 const char *p;
8635 char *e;
8636 int bad_card = 0;
8638 if (!strcmp (optarg, "all")) {
8639 for (c = soundhw; c->name; ++c) {
8640 c->enabled = 1;
8642 return;
8645 p = optarg;
8646 while (*p) {
8647 e = strchr (p, ',');
8648 l = !e ? strlen (p) : (size_t) (e - p);
8650 for (c = soundhw; c->name; ++c) {
8651 if (!strncmp (c->name, p, l)) {
8652 c->enabled = 1;
8653 break;
8657 if (!c->name) {
8658 if (l > 80) {
8659 fprintf (stderr,
8660 "Unknown sound card name (too big to show)\n");
8662 else {
8663 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8664 (int) l, p);
8666 bad_card = 1;
8668 p += l + (e != NULL);
8671 if (bad_card)
8672 goto show_valid_cards;
8675 #endif
8677 #ifdef _WIN32
8678 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8680 exit(STATUS_CONTROL_C_EXIT);
8681 return TRUE;
8683 #endif
8685 #define MAX_NET_CLIENTS 32
8687 static int saved_argc;
8688 static char **saved_argv;
8690 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8692 *argc = saved_argc;
8693 *argv = saved_argv;
8694 *opt_daemonize = daemonize;
8695 *opt_incoming = incoming;
8699 static int gethugepagesize(void)
8701 int ret, fd;
8702 char buf[4096];
8703 char *needle = "Hugepagesize:";
8704 char *size;
8705 unsigned long hugepagesize;
8707 fd = open("/proc/meminfo", O_RDONLY);
8708 if (fd < 0) {
8709 perror("open");
8710 exit(0);
8713 ret = read(fd, buf, sizeof(buf));
8714 if (ret < 0) {
8715 perror("read");
8716 exit(0);
8719 size = strstr(buf, needle);
8720 if (!size)
8721 return 0;
8722 size += strlen(needle);
8723 hugepagesize = strtol(size, NULL, 0);
8724 return hugepagesize;
8727 void *alloc_mem_area(unsigned long memory, const char *path)
8729 char *filename;
8730 void *area;
8731 int fd;
8733 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8734 return NULL;
8736 hpagesize = gethugepagesize() * 1024;
8737 if (!hpagesize)
8738 return NULL;
8740 fd = mkstemp(filename);
8741 if (fd < 0) {
8742 perror("mkstemp");
8743 free(filename);
8744 return NULL;
8746 unlink(filename);
8747 free(filename);
8749 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8752 * ftruncate is not supported by hugetlbfs in older
8753 * hosts, so don't bother checking for errors.
8754 * If anything goes wrong with it under other filesystems,
8755 * mmap will fail.
8757 ftruncate(fd, memory);
8759 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8760 if (area == MAP_FAILED) {
8761 perror("mmap");
8762 close(fd);
8763 return NULL;
8766 return area;
8769 void *qemu_alloc_physram(unsigned long memory)
8771 void *area = NULL;
8773 if (mem_path)
8774 area = alloc_mem_area(memory, mem_path);
8775 if (!area)
8776 area = qemu_vmalloc(memory);
8778 return area;
8781 int main(int argc, char **argv)
8783 #ifdef CONFIG_GDBSTUB
8784 int use_gdbstub;
8785 const char *gdbstub_port;
8786 #endif
8787 uint32_t boot_devices_bitmap = 0;
8788 int i;
8789 int snapshot, linux_boot, net_boot;
8790 const char *initrd_filename;
8791 const char *kernel_filename, *kernel_cmdline;
8792 const char *boot_devices = "";
8793 DisplayState *ds = &display_state;
8794 int cyls, heads, secs, translation;
8795 char net_clients[MAX_NET_CLIENTS][256];
8796 int nb_net_clients;
8797 int hda_index;
8798 int optind;
8799 const char *r, *optarg;
8800 CharDriverState *monitor_hd;
8801 char monitor_device[128];
8802 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8803 int vmchannel_device_index;
8804 char serial_devices[MAX_SERIAL_PORTS][128];
8805 int serial_device_index;
8806 char parallel_devices[MAX_PARALLEL_PORTS][128];
8807 int parallel_device_index;
8808 const char *loadvm = NULL;
8809 QEMUMachine *machine;
8810 const char *cpu_model;
8811 char usb_devices[MAX_USB_CMDLINE][128];
8812 int usb_devices_index;
8813 int fds[2];
8814 const char *pid_file = NULL;
8815 VLANState *vlan;
8817 saved_argc = argc;
8818 saved_argv = argv;
8820 LIST_INIT (&vm_change_state_head);
8821 #ifndef _WIN32
8823 struct sigaction act;
8824 sigfillset(&act.sa_mask);
8825 act.sa_flags = 0;
8826 act.sa_handler = SIG_IGN;
8827 sigaction(SIGPIPE, &act, NULL);
8829 #else
8830 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8831 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8832 QEMU to run on a single CPU */
8834 HANDLE h;
8835 DWORD mask, smask;
8836 int i;
8837 h = GetCurrentProcess();
8838 if (GetProcessAffinityMask(h, &mask, &smask)) {
8839 for(i = 0; i < 32; i++) {
8840 if (mask & (1 << i))
8841 break;
8843 if (i != 32) {
8844 mask = 1 << i;
8845 SetProcessAffinityMask(h, mask);
8849 #endif
8851 register_machines();
8852 machine = first_machine;
8853 cpu_model = NULL;
8854 initrd_filename = NULL;
8855 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8856 vga_ram_size = VGA_RAM_SIZE;
8857 #ifdef CONFIG_GDBSTUB
8858 use_gdbstub = 0;
8859 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8860 #endif
8861 snapshot = 0;
8862 nographic = 0;
8863 curses = 0;
8864 kernel_filename = NULL;
8865 kernel_cmdline = "";
8866 cyls = heads = secs = 0;
8867 translation = BIOS_ATA_TRANSLATION_AUTO;
8868 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8870 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8871 vmchannel_devices[i][0] = '\0';
8872 vmchannel_device_index = 0;
8874 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8875 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8876 serial_devices[i][0] = '\0';
8877 serial_device_index = 0;
8879 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8880 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8881 parallel_devices[i][0] = '\0';
8882 parallel_device_index = 0;
8884 usb_devices_index = 0;
8886 nb_net_clients = 0;
8887 nb_drives = 0;
8888 nb_drives_opt = 0;
8889 hda_index = -1;
8891 nb_nics = 0;
8892 /* default mac address of the first network interface */
8894 optind = 1;
8895 for(;;) {
8896 if (optind >= argc)
8897 break;
8898 r = argv[optind];
8899 if (r[0] != '-') {
8900 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8901 } else {
8902 const QEMUOption *popt;
8904 optind++;
8905 /* Treat --foo the same as -foo. */
8906 if (r[1] == '-')
8907 r++;
8908 popt = qemu_options;
8909 for(;;) {
8910 if (!popt->name) {
8911 fprintf(stderr, "%s: invalid option -- '%s'\n",
8912 argv[0], r);
8913 exit(1);
8915 if (!strcmp(popt->name, r + 1))
8916 break;
8917 popt++;
8919 if (popt->flags & HAS_ARG) {
8920 if (optind >= argc) {
8921 fprintf(stderr, "%s: option '%s' requires an argument\n",
8922 argv[0], r);
8923 exit(1);
8925 optarg = argv[optind++];
8926 } else {
8927 optarg = NULL;
8930 switch(popt->index) {
8931 case QEMU_OPTION_M:
8932 machine = find_machine(optarg);
8933 if (!machine) {
8934 QEMUMachine *m;
8935 printf("Supported machines are:\n");
8936 for(m = first_machine; m != NULL; m = m->next) {
8937 printf("%-10s %s%s\n",
8938 m->name, m->desc,
8939 m == first_machine ? " (default)" : "");
8941 exit(*optarg != '?');
8943 break;
8944 case QEMU_OPTION_cpu:
8945 /* hw initialization will check this */
8946 if (*optarg == '?') {
8947 /* XXX: implement xxx_cpu_list for targets that still miss it */
8948 #if defined(cpu_list)
8949 cpu_list(stdout, &fprintf);
8950 #endif
8951 exit(0);
8952 } else {
8953 cpu_model = optarg;
8955 break;
8956 case QEMU_OPTION_initrd:
8957 initrd_filename = optarg;
8958 break;
8959 case QEMU_OPTION_hda:
8960 if (cyls == 0)
8961 hda_index = drive_add(optarg, HD_ALIAS, 0);
8962 else
8963 hda_index = drive_add(optarg, HD_ALIAS
8964 ",cyls=%d,heads=%d,secs=%d%s",
8965 0, cyls, heads, secs,
8966 translation == BIOS_ATA_TRANSLATION_LBA ?
8967 ",trans=lba" :
8968 translation == BIOS_ATA_TRANSLATION_NONE ?
8969 ",trans=none" : "");
8970 break;
8971 case QEMU_OPTION_hdb:
8972 case QEMU_OPTION_hdc:
8973 case QEMU_OPTION_hdd:
8974 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8975 break;
8976 case QEMU_OPTION_drive:
8977 drive_add(NULL, "%s", optarg);
8978 break;
8979 case QEMU_OPTION_mtdblock:
8980 drive_add(optarg, MTD_ALIAS);
8981 break;
8982 case QEMU_OPTION_sd:
8983 drive_add(optarg, SD_ALIAS);
8984 break;
8985 case QEMU_OPTION_pflash:
8986 drive_add(optarg, PFLASH_ALIAS);
8987 break;
8988 case QEMU_OPTION_snapshot:
8989 snapshot = 1;
8990 break;
8991 case QEMU_OPTION_hdachs:
8993 const char *p;
8994 p = optarg;
8995 cyls = strtol(p, (char **)&p, 0);
8996 if (cyls < 1 || cyls > 16383)
8997 goto chs_fail;
8998 if (*p != ',')
8999 goto chs_fail;
9000 p++;
9001 heads = strtol(p, (char **)&p, 0);
9002 if (heads < 1 || heads > 16)
9003 goto chs_fail;
9004 if (*p != ',')
9005 goto chs_fail;
9006 p++;
9007 secs = strtol(p, (char **)&p, 0);
9008 if (secs < 1 || secs > 63)
9009 goto chs_fail;
9010 if (*p == ',') {
9011 p++;
9012 if (!strcmp(p, "none"))
9013 translation = BIOS_ATA_TRANSLATION_NONE;
9014 else if (!strcmp(p, "lba"))
9015 translation = BIOS_ATA_TRANSLATION_LBA;
9016 else if (!strcmp(p, "auto"))
9017 translation = BIOS_ATA_TRANSLATION_AUTO;
9018 else
9019 goto chs_fail;
9020 } else if (*p != '\0') {
9021 chs_fail:
9022 fprintf(stderr, "qemu: invalid physical CHS format\n");
9023 exit(1);
9025 if (hda_index != -1)
9026 snprintf(drives_opt[hda_index].opt,
9027 sizeof(drives_opt[hda_index].opt),
9028 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
9029 0, cyls, heads, secs,
9030 translation == BIOS_ATA_TRANSLATION_LBA ?
9031 ",trans=lba" :
9032 translation == BIOS_ATA_TRANSLATION_NONE ?
9033 ",trans=none" : "");
9035 break;
9036 case QEMU_OPTION_nographic:
9037 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
9038 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
9039 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
9040 nographic = 1;
9041 break;
9042 #ifdef CONFIG_CURSES
9043 case QEMU_OPTION_curses:
9044 curses = 1;
9045 break;
9046 #endif
9047 case QEMU_OPTION_portrait:
9048 graphic_rotate = 1;
9049 break;
9050 case QEMU_OPTION_kernel:
9051 kernel_filename = optarg;
9052 break;
9053 case QEMU_OPTION_append:
9054 kernel_cmdline = optarg;
9055 break;
9056 case QEMU_OPTION_cdrom:
9057 drive_add(optarg, CDROM_ALIAS);
9058 break;
9059 case QEMU_OPTION_boot:
9060 boot_devices = optarg;
9061 /* We just do some generic consistency checks */
9063 /* Could easily be extended to 64 devices if needed */
9064 const char *p;
9066 boot_devices_bitmap = 0;
9067 for (p = boot_devices; *p != '\0'; p++) {
9068 /* Allowed boot devices are:
9069 * a b : floppy disk drives
9070 * c ... f : IDE disk drives
9071 * g ... m : machine implementation dependant drives
9072 * n ... p : network devices
9073 * It's up to each machine implementation to check
9074 * if the given boot devices match the actual hardware
9075 * implementation and firmware features.
9077 if (*p < 'a' || *p > 'q') {
9078 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9079 exit(1);
9081 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9082 fprintf(stderr,
9083 "Boot device '%c' was given twice\n",*p);
9084 exit(1);
9086 boot_devices_bitmap |= 1 << (*p - 'a');
9089 break;
9090 case QEMU_OPTION_fda:
9091 case QEMU_OPTION_fdb:
9092 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9093 break;
9094 #ifdef TARGET_I386
9095 case QEMU_OPTION_no_fd_bootchk:
9096 fd_bootchk = 0;
9097 break;
9098 #endif
9099 case QEMU_OPTION_no_code_copy:
9100 code_copy_enabled = 0;
9101 break;
9102 case QEMU_OPTION_net:
9103 if (nb_net_clients >= MAX_NET_CLIENTS) {
9104 fprintf(stderr, "qemu: too many network clients\n");
9105 exit(1);
9107 pstrcpy(net_clients[nb_net_clients],
9108 sizeof(net_clients[0]),
9109 optarg);
9110 nb_net_clients++;
9111 break;
9112 #ifdef CONFIG_SLIRP
9113 case QEMU_OPTION_tftp:
9114 tftp_prefix = optarg;
9115 break;
9116 case QEMU_OPTION_bootp:
9117 bootp_filename = optarg;
9118 break;
9119 #ifndef _WIN32
9120 case QEMU_OPTION_smb:
9121 net_slirp_smb(optarg);
9122 break;
9123 #endif
9124 case QEMU_OPTION_redir:
9125 net_slirp_redir(optarg);
9126 break;
9127 #endif
9128 #ifdef HAS_AUDIO
9129 case QEMU_OPTION_audio_help:
9130 AUD_help ();
9131 exit (0);
9132 break;
9133 case QEMU_OPTION_soundhw:
9134 select_soundhw (optarg);
9135 break;
9136 #endif
9137 case QEMU_OPTION_h:
9138 help(0);
9139 break;
9140 case QEMU_OPTION_m:
9141 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
9142 if (ram_size <= 0)
9143 help(1);
9144 if (ram_size > PHYS_RAM_MAX_SIZE) {
9145 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
9146 PHYS_RAM_MAX_SIZE / (1024 * 1024));
9147 exit(1);
9149 break;
9150 case QEMU_OPTION_d:
9152 int mask;
9153 CPULogItem *item;
9155 mask = cpu_str_to_log_mask(optarg);
9156 if (!mask) {
9157 printf("Log items (comma separated):\n");
9158 for(item = cpu_log_items; item->mask != 0; item++) {
9159 printf("%-10s %s\n", item->name, item->help);
9161 exit(1);
9163 cpu_set_log(mask);
9165 break;
9166 #ifdef CONFIG_GDBSTUB
9167 case QEMU_OPTION_s:
9168 use_gdbstub = 1;
9169 break;
9170 case QEMU_OPTION_p:
9171 gdbstub_port = optarg;
9172 break;
9173 #endif
9174 case QEMU_OPTION_L:
9175 bios_dir = optarg;
9176 break;
9177 case QEMU_OPTION_bios:
9178 bios_name = optarg;
9179 break;
9180 case QEMU_OPTION_S:
9181 autostart = 0;
9182 break;
9183 case QEMU_OPTION_k:
9184 keyboard_layout = optarg;
9185 break;
9186 case QEMU_OPTION_localtime:
9187 rtc_utc = 0;
9188 break;
9189 case QEMU_OPTION_cirrusvga:
9190 cirrus_vga_enabled = 1;
9191 vmsvga_enabled = 0;
9192 break;
9193 case QEMU_OPTION_vmsvga:
9194 cirrus_vga_enabled = 0;
9195 vmsvga_enabled = 1;
9196 break;
9197 case QEMU_OPTION_std_vga:
9198 cirrus_vga_enabled = 0;
9199 vmsvga_enabled = 0;
9200 break;
9201 case QEMU_OPTION_g:
9203 const char *p;
9204 int w, h, depth;
9205 p = optarg;
9206 w = strtol(p, (char **)&p, 10);
9207 if (w <= 0) {
9208 graphic_error:
9209 fprintf(stderr, "qemu: invalid resolution or depth\n");
9210 exit(1);
9212 if (*p != 'x')
9213 goto graphic_error;
9214 p++;
9215 h = strtol(p, (char **)&p, 10);
9216 if (h <= 0)
9217 goto graphic_error;
9218 if (*p == 'x') {
9219 p++;
9220 depth = strtol(p, (char **)&p, 10);
9221 if (depth != 8 && depth != 15 && depth != 16 &&
9222 depth != 24 && depth != 32)
9223 goto graphic_error;
9224 } else if (*p == '\0') {
9225 depth = graphic_depth;
9226 } else {
9227 goto graphic_error;
9230 graphic_width = w;
9231 graphic_height = h;
9232 graphic_depth = depth;
9234 break;
9235 case QEMU_OPTION_echr:
9237 char *r;
9238 term_escape_char = strtol(optarg, &r, 0);
9239 if (r == optarg)
9240 printf("Bad argument to echr\n");
9241 break;
9243 case QEMU_OPTION_monitor:
9244 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
9245 break;
9246 case QEMU_OPTION_balloon:
9247 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9248 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9249 exit(1);
9251 if (balloon_used) {
9252 fprintf(stderr, "qemu: only one balloon device can be used\n");
9253 exit(1);
9255 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
9256 vmchannel_device_index++;
9257 balloon_used = 1;
9258 break;
9259 case QEMU_OPTION_vmchannel:
9260 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9261 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9262 exit(1);
9264 pstrcpy(vmchannel_devices[vmchannel_device_index],
9265 sizeof(vmchannel_devices[0]), optarg);
9266 vmchannel_device_index++;
9267 break;
9268 case QEMU_OPTION_serial:
9269 if (serial_device_index >= MAX_SERIAL_PORTS) {
9270 fprintf(stderr, "qemu: too many serial ports\n");
9271 exit(1);
9273 pstrcpy(serial_devices[serial_device_index],
9274 sizeof(serial_devices[0]), optarg);
9275 serial_device_index++;
9276 break;
9277 case QEMU_OPTION_parallel:
9278 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9279 fprintf(stderr, "qemu: too many parallel ports\n");
9280 exit(1);
9282 pstrcpy(parallel_devices[parallel_device_index],
9283 sizeof(parallel_devices[0]), optarg);
9284 parallel_device_index++;
9285 break;
9286 case QEMU_OPTION_loadvm:
9287 loadvm = optarg;
9288 break;
9289 case QEMU_OPTION_incoming:
9290 incoming = optarg;
9291 break;
9292 case QEMU_OPTION_full_screen:
9293 full_screen = 1;
9294 break;
9295 #ifdef CONFIG_SDL
9296 case QEMU_OPTION_no_frame:
9297 no_frame = 1;
9298 break;
9299 case QEMU_OPTION_alt_grab:
9300 alt_grab = 1;
9301 break;
9302 case QEMU_OPTION_no_quit:
9303 no_quit = 1;
9304 break;
9305 #endif
9306 case QEMU_OPTION_pidfile:
9307 pid_file = optarg;
9308 break;
9309 #ifdef TARGET_I386
9310 case QEMU_OPTION_win2k_hack:
9311 win2k_install_hack = 1;
9312 break;
9313 #endif
9314 #ifdef USE_KQEMU
9315 case QEMU_OPTION_no_kqemu:
9316 kqemu_allowed = 0;
9317 break;
9318 case QEMU_OPTION_kernel_kqemu:
9319 kqemu_allowed = 2;
9320 break;
9321 #endif
9322 #ifdef USE_KVM
9323 case QEMU_OPTION_no_kvm:
9324 kvm_allowed = 0;
9325 break;
9326 case QEMU_OPTION_no_kvm_irqchip: {
9327 extern int kvm_irqchip, kvm_pit;
9328 kvm_irqchip = 0;
9329 kvm_pit = 0;
9330 break;
9332 case QEMU_OPTION_no_kvm_pit: {
9333 extern int kvm_pit;
9334 kvm_pit = 0;
9335 break;
9337 #endif
9338 case QEMU_OPTION_usb:
9339 usb_enabled = 1;
9340 break;
9341 case QEMU_OPTION_usbdevice:
9342 usb_enabled = 1;
9343 if (usb_devices_index >= MAX_USB_CMDLINE) {
9344 fprintf(stderr, "Too many USB devices\n");
9345 exit(1);
9347 pstrcpy(usb_devices[usb_devices_index],
9348 sizeof(usb_devices[usb_devices_index]),
9349 optarg);
9350 usb_devices_index++;
9351 break;
9352 case QEMU_OPTION_smp:
9353 smp_cpus = atoi(optarg);
9354 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9355 fprintf(stderr, "Invalid number of CPUs\n");
9356 exit(1);
9358 break;
9359 case QEMU_OPTION_vnc:
9360 vnc_display = optarg;
9361 break;
9362 case QEMU_OPTION_no_acpi:
9363 acpi_enabled = 0;
9364 break;
9365 case QEMU_OPTION_no_reboot:
9366 no_reboot = 1;
9367 break;
9368 case QEMU_OPTION_show_cursor:
9369 cursor_hide = 0;
9370 break;
9371 case QEMU_OPTION_daemonize:
9372 daemonize = 1;
9373 break;
9374 case QEMU_OPTION_option_rom:
9375 if (nb_option_roms >= MAX_OPTION_ROMS) {
9376 fprintf(stderr, "Too many option ROMs\n");
9377 exit(1);
9379 option_rom[nb_option_roms] = optarg;
9380 nb_option_roms++;
9381 break;
9382 case QEMU_OPTION_semihosting:
9383 semihosting_enabled = 1;
9384 break;
9385 case QEMU_OPTION_tdf:
9386 time_drift_fix = 1;
9387 break;
9388 case QEMU_OPTION_kvm_shadow_memory:
9389 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9390 break;
9391 case QEMU_OPTION_mempath:
9392 mem_path = optarg;
9393 break;
9394 case QEMU_OPTION_name:
9395 qemu_name = optarg;
9396 break;
9397 #ifdef TARGET_SPARC
9398 case QEMU_OPTION_prom_env:
9399 if (nb_prom_envs >= MAX_PROM_ENVS) {
9400 fprintf(stderr, "Too many prom variables\n");
9401 exit(1);
9403 prom_envs[nb_prom_envs] = optarg;
9404 nb_prom_envs++;
9405 break;
9406 #endif
9407 case QEMU_OPTION_cpu_vendor:
9408 cpu_vendor_string = optarg;
9409 break;
9410 #ifdef TARGET_ARM
9411 case QEMU_OPTION_old_param:
9412 old_param = 1;
9413 break;
9414 #endif
9415 case QEMU_OPTION_clock:
9416 configure_alarms(optarg);
9417 break;
9418 case QEMU_OPTION_startdate:
9420 struct tm tm;
9421 time_t rtc_start_date;
9422 if (!strcmp(optarg, "now")) {
9423 rtc_date_offset = -1;
9424 } else {
9425 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9426 &tm.tm_year,
9427 &tm.tm_mon,
9428 &tm.tm_mday,
9429 &tm.tm_hour,
9430 &tm.tm_min,
9431 &tm.tm_sec) == 6) {
9432 /* OK */
9433 } else if (sscanf(optarg, "%d-%d-%d",
9434 &tm.tm_year,
9435 &tm.tm_mon,
9436 &tm.tm_mday) == 3) {
9437 tm.tm_hour = 0;
9438 tm.tm_min = 0;
9439 tm.tm_sec = 0;
9440 } else {
9441 goto date_fail;
9443 tm.tm_year -= 1900;
9444 tm.tm_mon--;
9445 rtc_start_date = mktimegm(&tm);
9446 if (rtc_start_date == -1) {
9447 date_fail:
9448 fprintf(stderr, "Invalid date format. Valid format are:\n"
9449 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9450 exit(1);
9452 rtc_date_offset = time(NULL) - rtc_start_date;
9455 break;
9460 #ifndef _WIN32
9461 if (daemonize) {
9462 pid_t pid;
9464 if (pipe(fds) == -1)
9465 exit(1);
9467 pid = fork();
9468 if (pid > 0) {
9469 uint8_t status;
9470 ssize_t len;
9472 close(fds[1]);
9474 again:
9475 len = read(fds[0], &status, 1);
9476 if (len == -1 && (errno == EINTR))
9477 goto again;
9479 if (len != 1)
9480 exit(1);
9481 else if (status == 1) {
9482 fprintf(stderr, "Could not acquire pidfile\n");
9483 exit(1);
9484 } else
9485 exit(0);
9486 } else if (pid < 0)
9487 exit(1);
9489 setsid();
9491 pid = fork();
9492 if (pid > 0)
9493 exit(0);
9494 else if (pid < 0)
9495 exit(1);
9497 umask(027);
9499 signal(SIGTSTP, SIG_IGN);
9500 signal(SIGTTOU, SIG_IGN);
9501 signal(SIGTTIN, SIG_IGN);
9503 #endif
9505 #if USE_KVM
9506 if (kvm_enabled()) {
9507 if (kvm_qemu_init() < 0) {
9508 extern int kvm_allowed;
9509 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9510 #ifdef NO_CPU_EMULATION
9511 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9512 exit(1);
9513 #endif
9514 kvm_allowed = 0;
9517 #endif
9519 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9520 if (daemonize) {
9521 uint8_t status = 1;
9522 write(fds[1], &status, 1);
9523 } else
9524 fprintf(stderr, "Could not acquire pid file\n");
9525 exit(1);
9528 #ifdef USE_KQEMU
9529 if (smp_cpus > 1)
9530 kqemu_allowed = 0;
9531 #endif
9532 linux_boot = (kernel_filename != NULL);
9533 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9535 /* XXX: this should not be: some embedded targets just have flash */
9536 if (!linux_boot && net_boot == 0 &&
9537 nb_drives_opt == 0)
9538 help(1);
9540 /* boot to floppy or the default cd if no hard disk defined yet */
9541 if (!boot_devices[0]) {
9542 boot_devices = "cad";
9544 setvbuf(stdout, NULL, _IOLBF, 0);
9546 init_timers();
9547 init_timer_alarm();
9548 qemu_aio_init();
9550 #ifdef _WIN32
9551 socket_init();
9552 #endif
9554 /* init network clients */
9555 if (nb_net_clients == 0) {
9556 /* if no clients, we use a default config */
9557 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9558 "nic");
9559 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9560 "user");
9561 nb_net_clients = 2;
9564 for(i = 0;i < nb_net_clients; i++) {
9565 if (net_client_init(net_clients[i]) < 0)
9566 exit(1);
9568 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9569 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9570 continue;
9571 if (vlan->nb_guest_devs == 0) {
9572 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9573 exit(1);
9575 if (vlan->nb_host_devs == 0)
9576 fprintf(stderr,
9577 "Warning: vlan %d is not connected to host network\n",
9578 vlan->id);
9581 #ifdef TARGET_I386
9582 /* XXX: this should be moved in the PC machine instantiation code */
9583 if (net_boot != 0) {
9584 int netroms = 0;
9585 for (i = 0; i < nb_nics && i < 4; i++) {
9586 const char *model = nd_table[i].model;
9587 char buf[1024];
9588 if (net_boot & (1 << i)) {
9589 if (model == NULL)
9590 model = "rtl8139";
9591 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9592 if (get_image_size(buf) > 0) {
9593 if (nb_option_roms >= MAX_OPTION_ROMS) {
9594 fprintf(stderr, "Too many option ROMs\n");
9595 exit(1);
9597 option_rom[nb_option_roms] = strdup(buf);
9598 nb_option_roms++;
9599 netroms++;
9603 if (netroms == 0) {
9604 fprintf(stderr, "No valid PXE rom found for network device\n");
9605 exit(1);
9608 #endif
9610 /* init the memory */
9611 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9613 /* Initialize kvm */
9614 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9615 #define KVM_EXTRA_PAGES 3
9616 #else
9617 #define KVM_EXTRA_PAGES 0
9618 #endif
9619 if (kvm_enabled()) {
9620 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9621 if (kvm_qemu_create_context() < 0) {
9622 fprintf(stderr, "Could not create KVM context\n");
9623 exit(1);
9625 #ifdef KVM_CAP_USER_MEMORY
9627 int ret;
9629 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9630 if (ret) {
9631 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9632 if (!phys_ram_base) {
9633 fprintf(stderr, "Could not allocate physical memory\n");
9634 exit(1);
9638 #endif
9639 } else {
9640 phys_ram_base = qemu_vmalloc(phys_ram_size);
9641 if (!phys_ram_base) {
9642 fprintf(stderr, "Could not allocate physical memory\n");
9643 exit(1);
9647 bdrv_init();
9649 /* we always create the cdrom drive, even if no disk is there */
9651 if (nb_drives_opt < MAX_DRIVES)
9652 drive_add(NULL, CDROM_ALIAS);
9654 /* we always create at least one floppy */
9656 if (nb_drives_opt < MAX_DRIVES)
9657 drive_add(NULL, FD_ALIAS, 0);
9659 /* we always create one sd slot, even if no card is in it */
9661 if (nb_drives_opt < MAX_DRIVES)
9662 drive_add(NULL, SD_ALIAS);
9664 /* open the virtual block devices
9665 * note that migration with device
9666 * hot add/remove is broken.
9668 for(i = 0; i < nb_drives_opt; i++)
9669 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9670 exit(1);
9672 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9673 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9675 init_ioports();
9677 /* terminal init */
9678 memset(&display_state, 0, sizeof(display_state));
9679 if (nographic) {
9680 if (curses) {
9681 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9682 exit(1);
9684 /* nearly nothing to do */
9685 dumb_display_init(ds);
9686 } else if (vnc_display != NULL) {
9687 vnc_display_init(ds);
9688 if (vnc_display_open(ds, vnc_display) < 0)
9689 exit(1);
9690 } else
9691 #if defined(CONFIG_CURSES)
9692 if (curses) {
9693 curses_display_init(ds, full_screen);
9694 } else
9695 #endif
9697 #if defined(CONFIG_SDL)
9698 sdl_display_init(ds, full_screen, no_frame);
9699 #elif defined(CONFIG_COCOA)
9700 cocoa_display_init(ds, full_screen);
9701 #else
9702 dumb_display_init(ds);
9703 #endif
9706 /* Maintain compatibility with multiple stdio monitors */
9707 if (!strcmp(monitor_device,"stdio")) {
9708 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9709 if (!strcmp(serial_devices[i],"mon:stdio")) {
9710 monitor_device[0] = '\0';
9711 break;
9712 } else if (!strcmp(serial_devices[i],"stdio")) {
9713 monitor_device[0] = '\0';
9714 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9715 break;
9719 if (monitor_device[0] != '\0') {
9720 monitor_hd = qemu_chr_open(monitor_device);
9721 if (!monitor_hd) {
9722 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9723 exit(1);
9725 monitor_init(monitor_hd, !nographic);
9728 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9729 const char *devname = vmchannel_devices[i];
9730 if (devname[0] != '\0' && strcmp(devname, "none")) {
9731 int devid;
9732 char *termn;
9734 if (strstart(devname, "di:", &devname)) {
9735 devid = strtol(devname, &termn, 16);
9736 devname = termn + 1;
9738 else {
9739 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9740 devname);
9741 exit(1);
9743 vmchannel_hds[i] = qemu_chr_open(devname);
9744 if (!vmchannel_hds[i]) {
9745 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9746 devname);
9747 exit(1);
9749 vmchannel_init(vmchannel_hds[i], devid, i);
9753 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9754 const char *devname = serial_devices[i];
9755 if (devname[0] != '\0' && strcmp(devname, "none")) {
9756 serial_hds[i] = qemu_chr_open(devname);
9757 if (!serial_hds[i]) {
9758 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9759 devname);
9760 exit(1);
9762 if (strstart(devname, "vc", 0))
9763 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9767 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9768 const char *devname = parallel_devices[i];
9769 if (devname[0] != '\0' && strcmp(devname, "none")) {
9770 parallel_hds[i] = qemu_chr_open(devname);
9771 if (!parallel_hds[i]) {
9772 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9773 devname);
9774 exit(1);
9776 if (strstart(devname, "vc", 0))
9777 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9781 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9782 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9784 current_machine = machine;
9786 /* init USB devices */
9787 if (usb_enabled) {
9788 for(i = 0; i < usb_devices_index; i++) {
9789 if (usb_device_add(usb_devices[i]) < 0) {
9790 fprintf(stderr, "Warning: could not add USB device %s\n",
9791 usb_devices[i]);
9796 if (display_state.dpy_refresh) {
9797 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9798 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9801 if (kvm_enabled())
9802 kvm_init_ap();
9804 #ifdef CONFIG_GDBSTUB
9805 if (use_gdbstub) {
9806 /* XXX: use standard host:port notation and modify options
9807 accordingly. */
9808 if (gdbserver_start(gdbstub_port) < 0) {
9809 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9810 gdbstub_port);
9811 exit(1);
9814 #endif
9815 if (loadvm)
9816 do_loadvm(loadvm);
9818 if (incoming) {
9819 int rc;
9821 rc = migrate_incoming(incoming);
9822 if (rc != 0) {
9823 fprintf(stderr, "Migration failed rc=%d\n", rc);
9824 exit(rc);
9829 /* XXX: simplify init */
9830 read_passwords();
9831 if (autostart) {
9832 vm_start();
9836 if (daemonize) {
9837 uint8_t status = 0;
9838 ssize_t len;
9839 int fd;
9841 again1:
9842 len = write(fds[1], &status, 1);
9843 if (len == -1 && (errno == EINTR))
9844 goto again1;
9846 if (len != 1)
9847 exit(1);
9849 chdir("/");
9850 TFR(fd = open("/dev/null", O_RDWR));
9851 if (fd == -1)
9852 exit(1);
9854 dup2(fd, 0);
9855 dup2(fd, 1);
9856 dup2(fd, 2);
9858 close(fd);
9861 main_loop();
9862 quit_timers();
9864 #if !defined(_WIN32)
9865 /* close network clients */
9866 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9867 VLANClientState *vc;
9869 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9870 if (vc->fd_read == tap_receive) {
9871 char ifname[64];
9872 TAPState *s = vc->opaque;
9874 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9875 s->down_script[0])
9876 launch_script(s->down_script, ifname, s->fd);
9880 #endif
9881 return 0;