kvm: libkvm: fix mmio callback signature mismatch
[qemu-kvm/fedora.git] / vl.c
blobc488539f392c0224cdc7e1ea5fdaf779f5a72006
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "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 #if USE_KVM
137 #include "qemu-kvm.h"
138 #endif
140 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
141 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
142 #ifdef __sun__
143 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
144 #else
145 #define SMBD_COMMAND "/usr/sbin/smbd"
146 #endif
148 //#define DEBUG_UNUSED_IOPORT
149 //#define DEBUG_IOPORT
151 #if HOST_LONG_BITS < 64
152 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
153 #else
154 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024 * 1024ULL)
155 #endif
157 #ifdef TARGET_PPC
158 #define DEFAULT_RAM_SIZE 144
159 #else
160 #define DEFAULT_RAM_SIZE 128
161 #endif
162 /* in ms */
163 #define GUI_REFRESH_INTERVAL 30
165 /* Max number of USB devices that can be specified on the commandline. */
166 #define MAX_USB_CMDLINE 8
168 /* XXX: use a two level table to limit memory usage */
169 #define MAX_IOPORTS 65536
171 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
172 const char *bios_name = NULL;
173 void *ioport_opaque[MAX_IOPORTS];
174 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
175 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
176 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
177 to store the VM snapshots */
178 DriveInfo drives_table[MAX_DRIVES+1];
179 int nb_drives;
180 /* point to the block driver where the snapshots are managed */
181 BlockDriverState *bs_snapshots;
182 int vga_ram_size;
183 static DisplayState display_state;
184 int nographic;
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 int rtc_utc = 1;
193 int rtc_start_date = -1; /* -1 means now */
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 #else
224 #define MAX_CPUS 1
225 #endif
226 int acpi_enabled = 1;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int cursor_hide = 1;
230 int graphic_rotate = 0;
231 int daemonize = 0;
232 const char *incoming;
233 const char *option_rom[MAX_OPTION_ROMS];
234 int nb_option_roms;
235 int semihosting_enabled = 0;
236 int autostart = 1;
237 int time_drift_fix = 0;
238 unsigned int kvm_shadow_memory = 0;
239 const char *cpu_vendor_string;
240 #ifdef TARGET_ARM
241 int old_param = 0;
242 #endif
243 const char *qemu_name;
244 int alt_grab = 0;
245 #ifdef TARGET_SPARC
246 unsigned int nb_prom_envs = 0;
247 const char *prom_envs[MAX_PROM_ENVS];
248 #endif
249 int nb_drives_opt;
250 char drives_opt[MAX_DRIVES][1024];
252 static CPUState *cur_cpu;
253 static CPUState *next_cpu;
254 static int event_pending = 1;
256 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
258 void decorate_application_name(char *appname, int max_len)
260 #if USE_KVM
261 if (kvm_allowed)
263 int remain = max_len - strlen(appname) - 1;
265 if (remain > 0)
266 strncat(appname, "/KVM", remain);
268 #endif
271 /***********************************************************/
272 /* x86 ISA bus support */
274 target_phys_addr_t isa_mem_base = 0;
275 PicState2 *isa_pic;
277 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
279 #ifdef DEBUG_UNUSED_IOPORT
280 fprintf(stderr, "unused inb: port=0x%04x\n", address);
281 #endif
282 return 0xff;
285 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
287 #ifdef DEBUG_UNUSED_IOPORT
288 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
289 #endif
292 /* default is to make two byte accesses */
293 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
295 uint32_t data;
296 data = ioport_read_table[0][address](ioport_opaque[address], address);
297 address = (address + 1) & (MAX_IOPORTS - 1);
298 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
299 return data;
302 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
304 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
305 address = (address + 1) & (MAX_IOPORTS - 1);
306 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
309 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
311 #ifdef DEBUG_UNUSED_IOPORT
312 fprintf(stderr, "unused inl: port=0x%04x\n", address);
313 #endif
314 return 0xffffffff;
317 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
319 #ifdef DEBUG_UNUSED_IOPORT
320 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
321 #endif
324 static void init_ioports(void)
326 int i;
328 for(i = 0; i < MAX_IOPORTS; i++) {
329 ioport_read_table[0][i] = default_ioport_readb;
330 ioport_write_table[0][i] = default_ioport_writeb;
331 ioport_read_table[1][i] = default_ioport_readw;
332 ioport_write_table[1][i] = default_ioport_writew;
333 ioport_read_table[2][i] = default_ioport_readl;
334 ioport_write_table[2][i] = default_ioport_writel;
338 /* size is the word size in byte */
339 int register_ioport_read(int start, int length, int size,
340 IOPortReadFunc *func, void *opaque)
342 int i, bsize;
344 if (size == 1) {
345 bsize = 0;
346 } else if (size == 2) {
347 bsize = 1;
348 } else if (size == 4) {
349 bsize = 2;
350 } else {
351 hw_error("register_ioport_read: invalid size");
352 return -1;
354 for(i = start; i < start + length; i += size) {
355 ioport_read_table[bsize][i] = func;
356 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
357 hw_error("register_ioport_read: invalid opaque");
358 ioport_opaque[i] = opaque;
360 return 0;
363 /* size is the word size in byte */
364 int register_ioport_write(int start, int length, int size,
365 IOPortWriteFunc *func, void *opaque)
367 int i, bsize;
369 if (size == 1) {
370 bsize = 0;
371 } else if (size == 2) {
372 bsize = 1;
373 } else if (size == 4) {
374 bsize = 2;
375 } else {
376 hw_error("register_ioport_write: invalid size");
377 return -1;
379 for(i = start; i < start + length; i += size) {
380 ioport_write_table[bsize][i] = func;
381 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
382 hw_error("register_ioport_write: invalid opaque");
383 ioport_opaque[i] = opaque;
385 return 0;
388 void isa_unassign_ioport(int start, int length)
390 int i;
392 for(i = start; i < start + length; i++) {
393 ioport_read_table[0][i] = default_ioport_readb;
394 ioport_read_table[1][i] = default_ioport_readw;
395 ioport_read_table[2][i] = default_ioport_readl;
397 ioport_write_table[0][i] = default_ioport_writeb;
398 ioport_write_table[1][i] = default_ioport_writew;
399 ioport_write_table[2][i] = default_ioport_writel;
403 /***********************************************************/
405 void cpu_outb(CPUState *env, int addr, int val)
407 #ifdef DEBUG_IOPORT
408 if (loglevel & CPU_LOG_IOPORT)
409 fprintf(logfile, "outb: %04x %02x\n", addr, val);
410 #endif
411 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
412 #ifdef USE_KQEMU
413 if (env)
414 env->last_io_time = cpu_get_time_fast();
415 #endif
418 void cpu_outw(CPUState *env, int addr, int val)
420 #ifdef DEBUG_IOPORT
421 if (loglevel & CPU_LOG_IOPORT)
422 fprintf(logfile, "outw: %04x %04x\n", addr, val);
423 #endif
424 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
425 #ifdef USE_KQEMU
426 if (env)
427 env->last_io_time = cpu_get_time_fast();
428 #endif
431 void cpu_outl(CPUState *env, int addr, int val)
433 #ifdef DEBUG_IOPORT
434 if (loglevel & CPU_LOG_IOPORT)
435 fprintf(logfile, "outl: %04x %08x\n", addr, val);
436 #endif
437 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
438 #ifdef USE_KQEMU
439 if (env)
440 env->last_io_time = cpu_get_time_fast();
441 #endif
444 int cpu_inb(CPUState *env, int addr)
446 int val;
447 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
448 #ifdef DEBUG_IOPORT
449 if (loglevel & CPU_LOG_IOPORT)
450 fprintf(logfile, "inb : %04x %02x\n", addr, val);
451 #endif
452 #ifdef USE_KQEMU
453 if (env)
454 env->last_io_time = cpu_get_time_fast();
455 #endif
456 return val;
459 int cpu_inw(CPUState *env, int addr)
461 int val;
462 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
463 #ifdef DEBUG_IOPORT
464 if (loglevel & CPU_LOG_IOPORT)
465 fprintf(logfile, "inw : %04x %04x\n", addr, val);
466 #endif
467 #ifdef USE_KQEMU
468 if (env)
469 env->last_io_time = cpu_get_time_fast();
470 #endif
471 return val;
474 int cpu_inl(CPUState *env, int addr)
476 int val;
477 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
478 #ifdef DEBUG_IOPORT
479 if (loglevel & CPU_LOG_IOPORT)
480 fprintf(logfile, "inl : %04x %08x\n", addr, val);
481 #endif
482 #ifdef USE_KQEMU
483 if (env)
484 env->last_io_time = cpu_get_time_fast();
485 #endif
486 return val;
489 /***********************************************************/
490 void hw_error(const char *fmt, ...)
492 va_list ap;
493 CPUState *env;
495 va_start(ap, fmt);
496 fprintf(stderr, "qemu: hardware error: ");
497 vfprintf(stderr, fmt, ap);
498 fprintf(stderr, "\n");
499 for(env = first_cpu; env != NULL; env = env->next_cpu) {
500 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
501 #ifdef TARGET_I386
502 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
503 #else
504 cpu_dump_state(env, stderr, fprintf, 0);
505 #endif
507 va_end(ap);
508 abort();
511 /***********************************************************/
512 /* keyboard/mouse */
514 static QEMUPutKBDEvent *qemu_put_kbd_event;
515 static void *qemu_put_kbd_event_opaque;
516 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
517 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
519 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
521 qemu_put_kbd_event_opaque = opaque;
522 qemu_put_kbd_event = func;
525 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
526 void *opaque, int absolute,
527 const char *name)
529 QEMUPutMouseEntry *s, *cursor;
531 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
532 if (!s)
533 return NULL;
535 s->qemu_put_mouse_event = func;
536 s->qemu_put_mouse_event_opaque = opaque;
537 s->qemu_put_mouse_event_absolute = absolute;
538 s->qemu_put_mouse_event_name = qemu_strdup(name);
539 s->next = NULL;
541 if (!qemu_put_mouse_event_head) {
542 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
543 return s;
546 cursor = qemu_put_mouse_event_head;
547 while (cursor->next != NULL)
548 cursor = cursor->next;
550 cursor->next = s;
551 qemu_put_mouse_event_current = s;
553 return s;
556 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
558 QEMUPutMouseEntry *prev = NULL, *cursor;
560 if (!qemu_put_mouse_event_head || entry == NULL)
561 return;
563 cursor = qemu_put_mouse_event_head;
564 while (cursor != NULL && cursor != entry) {
565 prev = cursor;
566 cursor = cursor->next;
569 if (cursor == NULL) // does not exist or list empty
570 return;
571 else if (prev == NULL) { // entry is head
572 qemu_put_mouse_event_head = cursor->next;
573 if (qemu_put_mouse_event_current == entry)
574 qemu_put_mouse_event_current = cursor->next;
575 qemu_free(entry->qemu_put_mouse_event_name);
576 qemu_free(entry);
577 return;
580 prev->next = entry->next;
582 if (qemu_put_mouse_event_current == entry)
583 qemu_put_mouse_event_current = prev;
585 qemu_free(entry->qemu_put_mouse_event_name);
586 qemu_free(entry);
589 void kbd_put_keycode(int keycode)
591 if (qemu_put_kbd_event) {
592 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
596 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
598 QEMUPutMouseEvent *mouse_event;
599 void *mouse_event_opaque;
600 int width;
602 if (!qemu_put_mouse_event_current) {
603 return;
606 mouse_event =
607 qemu_put_mouse_event_current->qemu_put_mouse_event;
608 mouse_event_opaque =
609 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
611 if (mouse_event) {
612 if (graphic_rotate) {
613 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
614 width = 0x7fff;
615 else
616 width = graphic_width;
617 mouse_event(mouse_event_opaque,
618 width - dy, dx, dz, buttons_state);
619 } else
620 mouse_event(mouse_event_opaque,
621 dx, dy, dz, buttons_state);
625 int kbd_mouse_is_absolute(void)
627 if (!qemu_put_mouse_event_current)
628 return 0;
630 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
633 void do_info_mice(void)
635 QEMUPutMouseEntry *cursor;
636 int index = 0;
638 if (!qemu_put_mouse_event_head) {
639 term_printf("No mouse devices connected\n");
640 return;
643 term_printf("Mouse devices available:\n");
644 cursor = qemu_put_mouse_event_head;
645 while (cursor != NULL) {
646 term_printf("%c Mouse #%d: %s\n",
647 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
648 index, cursor->qemu_put_mouse_event_name);
649 index++;
650 cursor = cursor->next;
654 void do_mouse_set(int index)
656 QEMUPutMouseEntry *cursor;
657 int i = 0;
659 if (!qemu_put_mouse_event_head) {
660 term_printf("No mouse devices connected\n");
661 return;
664 cursor = qemu_put_mouse_event_head;
665 while (cursor != NULL && index != i) {
666 i++;
667 cursor = cursor->next;
670 if (cursor != NULL)
671 qemu_put_mouse_event_current = cursor;
672 else
673 term_printf("Mouse at given index not found\n");
676 /* compute with 96 bit intermediate result: (a*b)/c */
677 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
679 union {
680 uint64_t ll;
681 struct {
682 #ifdef WORDS_BIGENDIAN
683 uint32_t high, low;
684 #else
685 uint32_t low, high;
686 #endif
687 } l;
688 } u, res;
689 uint64_t rl, rh;
691 u.ll = a;
692 rl = (uint64_t)u.l.low * (uint64_t)b;
693 rh = (uint64_t)u.l.high * (uint64_t)b;
694 rh += (rl >> 32);
695 res.l.high = rh / c;
696 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
697 return res.ll;
700 /***********************************************************/
701 /* real time host monotonic timer */
703 #define QEMU_TIMER_BASE 1000000000LL
705 #ifdef WIN32
707 static int64_t clock_freq;
709 static void init_get_clock(void)
711 LARGE_INTEGER freq;
712 int ret;
713 ret = QueryPerformanceFrequency(&freq);
714 if (ret == 0) {
715 fprintf(stderr, "Could not calibrate ticks\n");
716 exit(1);
718 clock_freq = freq.QuadPart;
721 static int64_t get_clock(void)
723 LARGE_INTEGER ti;
724 QueryPerformanceCounter(&ti);
725 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
728 #else
730 static int use_rt_clock;
732 static void init_get_clock(void)
734 use_rt_clock = 0;
735 #if defined(__linux__)
737 struct timespec ts;
738 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
739 use_rt_clock = 1;
742 #endif
745 static int64_t get_clock(void)
747 #if defined(__linux__)
748 if (use_rt_clock) {
749 struct timespec ts;
750 clock_gettime(CLOCK_MONOTONIC, &ts);
751 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
752 } else
753 #endif
755 /* XXX: using gettimeofday leads to problems if the date
756 changes, so it should be avoided. */
757 struct timeval tv;
758 gettimeofday(&tv, NULL);
759 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
763 #endif
765 /***********************************************************/
766 /* guest cycle counter */
768 static int64_t cpu_ticks_prev;
769 static int64_t cpu_ticks_offset;
770 static int64_t cpu_clock_offset;
771 static int cpu_ticks_enabled;
773 /* return the host CPU cycle counter and handle stop/restart */
774 int64_t cpu_get_ticks(void)
776 if (!cpu_ticks_enabled) {
777 return cpu_ticks_offset;
778 } else {
779 int64_t ticks;
780 ticks = cpu_get_real_ticks();
781 if (cpu_ticks_prev > ticks) {
782 /* Note: non increasing ticks may happen if the host uses
783 software suspend */
784 cpu_ticks_offset += cpu_ticks_prev - ticks;
786 cpu_ticks_prev = ticks;
787 return ticks + cpu_ticks_offset;
791 /* return the host CPU monotonic timer and handle stop/restart */
792 static int64_t cpu_get_clock(void)
794 int64_t ti;
795 if (!cpu_ticks_enabled) {
796 return cpu_clock_offset;
797 } else {
798 ti = get_clock();
799 return ti + cpu_clock_offset;
803 /* enable cpu_get_ticks() */
804 void cpu_enable_ticks(void)
806 if (!cpu_ticks_enabled) {
807 cpu_ticks_offset -= cpu_get_real_ticks();
808 cpu_clock_offset -= get_clock();
809 cpu_ticks_enabled = 1;
813 /* disable cpu_get_ticks() : the clock is stopped. You must not call
814 cpu_get_ticks() after that. */
815 void cpu_disable_ticks(void)
817 if (cpu_ticks_enabled) {
818 cpu_ticks_offset = cpu_get_ticks();
819 cpu_clock_offset = cpu_get_clock();
820 cpu_ticks_enabled = 0;
824 /***********************************************************/
825 /* timers */
827 #define QEMU_TIMER_REALTIME 0
828 #define QEMU_TIMER_VIRTUAL 1
830 struct QEMUClock {
831 int type;
832 /* XXX: add frequency */
835 struct QEMUTimer {
836 QEMUClock *clock;
837 int64_t expire_time;
838 QEMUTimerCB *cb;
839 void *opaque;
840 struct QEMUTimer *next;
843 struct qemu_alarm_timer {
844 char const *name;
845 unsigned int flags;
847 int (*start)(struct qemu_alarm_timer *t);
848 void (*stop)(struct qemu_alarm_timer *t);
849 void (*rearm)(struct qemu_alarm_timer *t);
850 void *priv;
853 #define ALARM_FLAG_DYNTICKS 0x1
855 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
857 return t->flags & ALARM_FLAG_DYNTICKS;
860 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
862 if (!alarm_has_dynticks(t))
863 return;
865 t->rearm(t);
868 /* TODO: MIN_TIMER_REARM_US should be optimized */
869 #define MIN_TIMER_REARM_US 250
871 static struct qemu_alarm_timer *alarm_timer;
873 #ifdef _WIN32
875 struct qemu_alarm_win32 {
876 MMRESULT timerId;
877 HANDLE host_alarm;
878 unsigned int period;
879 } alarm_win32_data = {0, NULL, -1};
881 static int win32_start_timer(struct qemu_alarm_timer *t);
882 static void win32_stop_timer(struct qemu_alarm_timer *t);
883 static void win32_rearm_timer(struct qemu_alarm_timer *t);
885 #else
887 static int unix_start_timer(struct qemu_alarm_timer *t);
888 static void unix_stop_timer(struct qemu_alarm_timer *t);
890 #ifdef __linux__
892 static int dynticks_start_timer(struct qemu_alarm_timer *t);
893 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
894 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
896 static int hpet_start_timer(struct qemu_alarm_timer *t);
897 static void hpet_stop_timer(struct qemu_alarm_timer *t);
899 static int rtc_start_timer(struct qemu_alarm_timer *t);
900 static void rtc_stop_timer(struct qemu_alarm_timer *t);
902 #endif /* __linux__ */
904 #endif /* _WIN32 */
906 static struct qemu_alarm_timer alarm_timers[] = {
907 #ifndef _WIN32
908 #ifdef __linux__
909 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
910 dynticks_stop_timer, dynticks_rearm_timer, NULL},
911 /* HPET - if available - is preferred */
912 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
913 /* ...otherwise try RTC */
914 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
915 #endif
916 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
917 #else
918 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
919 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
920 {"win32", 0, win32_start_timer,
921 win32_stop_timer, NULL, &alarm_win32_data},
922 #endif
923 {NULL, }
926 static void show_available_alarms()
928 int i;
930 printf("Available alarm timers, in order of precedence:\n");
931 for (i = 0; alarm_timers[i].name; i++)
932 printf("%s\n", alarm_timers[i].name);
935 static void configure_alarms(char const *opt)
937 int i;
938 int cur = 0;
939 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
940 char *arg;
941 char *name;
943 if (!strcmp(opt, "help")) {
944 show_available_alarms();
945 exit(0);
948 arg = strdup(opt);
950 /* Reorder the array */
951 name = strtok(arg, ",");
952 while (name) {
953 struct qemu_alarm_timer tmp;
955 for (i = 0; i < count && alarm_timers[i].name; i++) {
956 if (!strcmp(alarm_timers[i].name, name))
957 break;
960 if (i == count) {
961 fprintf(stderr, "Unknown clock %s\n", name);
962 goto next;
965 if (i < cur)
966 /* Ignore */
967 goto next;
969 /* Swap */
970 tmp = alarm_timers[i];
971 alarm_timers[i] = alarm_timers[cur];
972 alarm_timers[cur] = tmp;
974 cur++;
975 next:
976 name = strtok(NULL, ",");
979 free(arg);
981 if (cur) {
982 /* Disable remaining timers */
983 for (i = cur; i < count; i++)
984 alarm_timers[i].name = NULL;
987 /* debug */
988 show_available_alarms();
991 QEMUClock *rt_clock;
992 QEMUClock *vm_clock;
994 static QEMUTimer *active_timers[2];
996 static QEMUClock *qemu_new_clock(int type)
998 QEMUClock *clock;
999 clock = qemu_mallocz(sizeof(QEMUClock));
1000 if (!clock)
1001 return NULL;
1002 clock->type = type;
1003 return clock;
1006 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1008 QEMUTimer *ts;
1010 ts = qemu_mallocz(sizeof(QEMUTimer));
1011 ts->clock = clock;
1012 ts->cb = cb;
1013 ts->opaque = opaque;
1014 return ts;
1017 void qemu_free_timer(QEMUTimer *ts)
1019 qemu_free(ts);
1022 /* stop a timer, but do not dealloc it */
1023 void qemu_del_timer(QEMUTimer *ts)
1025 QEMUTimer **pt, *t;
1027 /* NOTE: this code must be signal safe because
1028 qemu_timer_expired() can be called from a signal. */
1029 pt = &active_timers[ts->clock->type];
1030 for(;;) {
1031 t = *pt;
1032 if (!t)
1033 break;
1034 if (t == ts) {
1035 *pt = t->next;
1036 break;
1038 pt = &t->next;
1042 /* modify the current timer so that it will be fired when current_time
1043 >= expire_time. The corresponding callback will be called. */
1044 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1046 QEMUTimer **pt, *t;
1048 qemu_del_timer(ts);
1050 /* add the timer in the sorted list */
1051 /* NOTE: this code must be signal safe because
1052 qemu_timer_expired() can be called from a signal. */
1053 pt = &active_timers[ts->clock->type];
1054 for(;;) {
1055 t = *pt;
1056 if (!t)
1057 break;
1058 if (t->expire_time > expire_time)
1059 break;
1060 pt = &t->next;
1062 ts->expire_time = expire_time;
1063 ts->next = *pt;
1064 *pt = ts;
1067 int qemu_timer_pending(QEMUTimer *ts)
1069 QEMUTimer *t;
1070 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1071 if (t == ts)
1072 return 1;
1074 return 0;
1077 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1079 if (!timer_head)
1080 return 0;
1081 return (timer_head->expire_time <= current_time);
1084 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1086 QEMUTimer *ts;
1088 for(;;) {
1089 ts = *ptimer_head;
1090 if (!ts || ts->expire_time > current_time)
1091 break;
1092 /* remove timer from the list before calling the callback */
1093 *ptimer_head = ts->next;
1094 ts->next = NULL;
1096 /* run the callback (the timer list can be modified) */
1097 ts->cb(ts->opaque);
1099 qemu_rearm_alarm_timer(alarm_timer);
1102 int64_t qemu_get_clock(QEMUClock *clock)
1104 switch(clock->type) {
1105 case QEMU_TIMER_REALTIME:
1106 return get_clock() / 1000000;
1107 default:
1108 case QEMU_TIMER_VIRTUAL:
1109 return cpu_get_clock();
1113 static void init_timers(void)
1115 init_get_clock();
1116 ticks_per_sec = QEMU_TIMER_BASE;
1117 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1118 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1121 /* save a timer */
1122 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1124 uint64_t expire_time;
1126 if (qemu_timer_pending(ts)) {
1127 expire_time = ts->expire_time;
1128 } else {
1129 expire_time = -1;
1131 qemu_put_be64(f, expire_time);
1134 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1136 uint64_t expire_time;
1138 expire_time = qemu_get_be64(f);
1139 if (expire_time != -1) {
1140 qemu_mod_timer(ts, expire_time);
1141 } else {
1142 qemu_del_timer(ts);
1146 static void timer_save(QEMUFile *f, void *opaque)
1148 if (cpu_ticks_enabled) {
1149 hw_error("cannot save state if virtual timers are running");
1151 qemu_put_be64(f, cpu_ticks_offset);
1152 qemu_put_be64(f, ticks_per_sec);
1153 qemu_put_be64(f, cpu_clock_offset);
1156 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1158 if (version_id != 1 && version_id != 2)
1159 return -EINVAL;
1160 if (cpu_ticks_enabled) {
1161 return -EINVAL;
1163 cpu_ticks_offset=qemu_get_be64(f);
1164 ticks_per_sec=qemu_get_be64(f);
1165 if (version_id == 2) {
1166 cpu_clock_offset=qemu_get_be64(f);
1168 return 0;
1171 #ifdef _WIN32
1172 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1173 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1174 #else
1175 static void host_alarm_handler(int host_signum)
1176 #endif
1178 #if 0
1179 #define DISP_FREQ 1000
1181 static int64_t delta_min = INT64_MAX;
1182 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1183 static int count;
1184 ti = qemu_get_clock(vm_clock);
1185 if (last_clock != 0) {
1186 delta = ti - last_clock;
1187 if (delta < delta_min)
1188 delta_min = delta;
1189 if (delta > delta_max)
1190 delta_max = delta;
1191 delta_cum += delta;
1192 if (++count == DISP_FREQ) {
1193 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1194 muldiv64(delta_min, 1000000, ticks_per_sec),
1195 muldiv64(delta_max, 1000000, ticks_per_sec),
1196 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1197 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1198 count = 0;
1199 delta_min = INT64_MAX;
1200 delta_max = 0;
1201 delta_cum = 0;
1204 last_clock = ti;
1206 #endif
1207 if (1 ||
1208 alarm_has_dynticks(alarm_timer) ||
1209 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1210 qemu_get_clock(vm_clock)) ||
1211 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1212 qemu_get_clock(rt_clock))) {
1213 #ifdef _WIN32
1214 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1215 SetEvent(data->host_alarm);
1216 #endif
1217 CPUState *env = next_cpu;
1219 if (env) {
1220 /* stop the currently executing cpu because a timer occured */
1221 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1222 #ifdef USE_KQEMU
1223 if (env->kqemu_enabled) {
1224 kqemu_cpu_interrupt(env);
1226 #endif
1228 event_pending = 1;
1232 static uint64_t qemu_next_deadline(void)
1234 int64_t nearest_delta_us = INT64_MAX;
1235 int64_t vmdelta_us;
1237 if (active_timers[QEMU_TIMER_REALTIME])
1238 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1239 qemu_get_clock(rt_clock))*1000;
1241 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1242 /* round up */
1243 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1244 qemu_get_clock(vm_clock)+999)/1000;
1245 if (vmdelta_us < nearest_delta_us)
1246 nearest_delta_us = vmdelta_us;
1249 /* Avoid arming the timer to negative, zero, or too low values */
1250 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1251 nearest_delta_us = MIN_TIMER_REARM_US;
1253 return nearest_delta_us;
1256 #ifndef _WIN32
1258 #if defined(__linux__)
1260 #define RTC_FREQ 1024
1262 static void enable_sigio_timer(int fd)
1264 struct sigaction act;
1266 /* timer signal */
1267 sigfillset(&act.sa_mask);
1268 act.sa_flags = 0;
1269 act.sa_handler = host_alarm_handler;
1271 sigaction(SIGIO, &act, NULL);
1272 fcntl(fd, F_SETFL, O_ASYNC);
1273 fcntl(fd, F_SETOWN, getpid());
1276 static int hpet_start_timer(struct qemu_alarm_timer *t)
1278 struct hpet_info info;
1279 int r, fd;
1281 fd = open("/dev/hpet", O_RDONLY);
1282 if (fd < 0)
1283 return -1;
1285 /* Set frequency */
1286 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1287 if (r < 0) {
1288 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1289 "error, but for better emulation accuracy type:\n"
1290 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1291 goto fail;
1294 /* Check capabilities */
1295 r = ioctl(fd, HPET_INFO, &info);
1296 if (r < 0)
1297 goto fail;
1299 /* Enable periodic mode */
1300 r = ioctl(fd, HPET_EPI, 0);
1301 if (info.hi_flags && (r < 0))
1302 goto fail;
1304 /* Enable interrupt */
1305 r = ioctl(fd, HPET_IE_ON, 0);
1306 if (r < 0)
1307 goto fail;
1309 enable_sigio_timer(fd);
1310 t->priv = (void *)(long)fd;
1312 return 0;
1313 fail:
1314 close(fd);
1315 return -1;
1318 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1320 int fd = (long)t->priv;
1322 close(fd);
1325 static int rtc_start_timer(struct qemu_alarm_timer *t)
1327 int rtc_fd;
1329 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1330 if (rtc_fd < 0)
1331 return -1;
1332 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1333 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1334 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1335 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1336 goto fail;
1338 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1339 fail:
1340 close(rtc_fd);
1341 return -1;
1344 enable_sigio_timer(rtc_fd);
1346 t->priv = (void *)(long)rtc_fd;
1348 return 0;
1351 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1353 int rtc_fd = (long)t->priv;
1355 close(rtc_fd);
1358 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1360 struct sigevent ev;
1361 timer_t host_timer;
1362 struct sigaction act;
1364 sigfillset(&act.sa_mask);
1365 act.sa_flags = 0;
1366 act.sa_handler = host_alarm_handler;
1368 sigaction(SIGALRM, &act, NULL);
1370 ev.sigev_value.sival_int = 0;
1371 ev.sigev_notify = SIGEV_SIGNAL;
1372 ev.sigev_signo = SIGALRM;
1374 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1375 perror("timer_create");
1377 /* disable dynticks */
1378 fprintf(stderr, "Dynamic Ticks disabled\n");
1380 return -1;
1383 t->priv = (void *)host_timer;
1385 return 0;
1388 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1390 timer_t host_timer = (timer_t)t->priv;
1392 timer_delete(host_timer);
1395 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1397 timer_t host_timer = (timer_t)t->priv;
1398 struct itimerspec timeout;
1399 int64_t nearest_delta_us = INT64_MAX;
1400 int64_t current_us;
1402 if (!active_timers[QEMU_TIMER_REALTIME] &&
1403 !active_timers[QEMU_TIMER_VIRTUAL])
1404 return;
1406 nearest_delta_us = qemu_next_deadline();
1408 /* check whether a timer is already running */
1409 if (timer_gettime(host_timer, &timeout)) {
1410 perror("gettime");
1411 fprintf(stderr, "Internal timer error: aborting\n");
1412 exit(1);
1414 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1415 if (current_us && current_us <= nearest_delta_us)
1416 return;
1418 timeout.it_interval.tv_sec = 0;
1419 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1420 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1421 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1422 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1423 perror("settime");
1424 fprintf(stderr, "Internal timer error: aborting\n");
1425 exit(1);
1429 #endif /* defined(__linux__) */
1431 static int unix_start_timer(struct qemu_alarm_timer *t)
1433 struct sigaction act;
1434 struct itimerval itv;
1435 int err;
1437 /* timer signal */
1438 sigfillset(&act.sa_mask);
1439 act.sa_flags = 0;
1440 act.sa_handler = host_alarm_handler;
1442 sigaction(SIGALRM, &act, NULL);
1444 itv.it_interval.tv_sec = 0;
1445 /* for i386 kernel 2.6 to get 1 ms */
1446 itv.it_interval.tv_usec = 999;
1447 itv.it_value.tv_sec = 0;
1448 itv.it_value.tv_usec = 10 * 1000;
1450 err = setitimer(ITIMER_REAL, &itv, NULL);
1451 if (err)
1452 return -1;
1454 return 0;
1457 static void unix_stop_timer(struct qemu_alarm_timer *t)
1459 struct itimerval itv;
1461 memset(&itv, 0, sizeof(itv));
1462 setitimer(ITIMER_REAL, &itv, NULL);
1465 #endif /* !defined(_WIN32) */
1467 #ifdef _WIN32
1469 static int win32_start_timer(struct qemu_alarm_timer *t)
1471 TIMECAPS tc;
1472 struct qemu_alarm_win32 *data = t->priv;
1473 UINT flags;
1475 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1476 if (!data->host_alarm) {
1477 perror("Failed CreateEvent");
1478 return -1;
1481 memset(&tc, 0, sizeof(tc));
1482 timeGetDevCaps(&tc, sizeof(tc));
1484 if (data->period < tc.wPeriodMin)
1485 data->period = tc.wPeriodMin;
1487 timeBeginPeriod(data->period);
1489 flags = TIME_CALLBACK_FUNCTION;
1490 if (alarm_has_dynticks(t))
1491 flags |= TIME_ONESHOT;
1492 else
1493 flags |= TIME_PERIODIC;
1495 data->timerId = timeSetEvent(1, // interval (ms)
1496 data->period, // resolution
1497 host_alarm_handler, // function
1498 (DWORD)t, // parameter
1499 flags);
1501 if (!data->timerId) {
1502 perror("Failed to initialize win32 alarm timer");
1504 timeEndPeriod(data->period);
1505 CloseHandle(data->host_alarm);
1506 return -1;
1509 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1511 return 0;
1514 static void win32_stop_timer(struct qemu_alarm_timer *t)
1516 struct qemu_alarm_win32 *data = t->priv;
1518 timeKillEvent(data->timerId);
1519 timeEndPeriod(data->period);
1521 CloseHandle(data->host_alarm);
1524 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1526 struct qemu_alarm_win32 *data = t->priv;
1527 uint64_t nearest_delta_us;
1529 if (!active_timers[QEMU_TIMER_REALTIME] &&
1530 !active_timers[QEMU_TIMER_VIRTUAL])
1531 return;
1533 nearest_delta_us = qemu_next_deadline();
1534 nearest_delta_us /= 1000;
1536 timeKillEvent(data->timerId);
1538 data->timerId = timeSetEvent(1,
1539 data->period,
1540 host_alarm_handler,
1541 (DWORD)t,
1542 TIME_ONESHOT | TIME_PERIODIC);
1544 if (!data->timerId) {
1545 perror("Failed to re-arm win32 alarm timer");
1547 timeEndPeriod(data->period);
1548 CloseHandle(data->host_alarm);
1549 exit(1);
1553 #endif /* _WIN32 */
1555 static void init_timer_alarm(void)
1557 struct qemu_alarm_timer *t;
1558 int i, err = -1;
1560 for (i = 0; alarm_timers[i].name; i++) {
1561 t = &alarm_timers[i];
1563 err = t->start(t);
1564 if (!err)
1565 break;
1568 if (err) {
1569 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1570 fprintf(stderr, "Terminating\n");
1571 exit(1);
1574 alarm_timer = t;
1577 static void quit_timers(void)
1579 alarm_timer->stop(alarm_timer);
1580 alarm_timer = NULL;
1583 /***********************************************************/
1584 /* character device */
1586 static void qemu_chr_event(CharDriverState *s, int event)
1588 if (!s->chr_event)
1589 return;
1590 s->chr_event(s->handler_opaque, event);
1593 static void qemu_chr_reset_bh(void *opaque)
1595 CharDriverState *s = opaque;
1596 qemu_chr_event(s, CHR_EVENT_RESET);
1597 qemu_bh_delete(s->bh);
1598 s->bh = NULL;
1601 void qemu_chr_reset(CharDriverState *s)
1603 if (s->bh == NULL) {
1604 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1605 qemu_bh_schedule(s->bh);
1609 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1611 return s->chr_write(s, buf, len);
1614 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1616 if (!s->chr_ioctl)
1617 return -ENOTSUP;
1618 return s->chr_ioctl(s, cmd, arg);
1621 int qemu_chr_can_read(CharDriverState *s)
1623 if (!s->chr_can_read)
1624 return 0;
1625 return s->chr_can_read(s->handler_opaque);
1628 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1630 s->chr_read(s->handler_opaque, buf, len);
1633 void qemu_chr_accept_input(CharDriverState *s)
1635 if (s->chr_accept_input)
1636 s->chr_accept_input(s);
1639 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1641 char buf[4096];
1642 va_list ap;
1643 va_start(ap, fmt);
1644 vsnprintf(buf, sizeof(buf), fmt, ap);
1645 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1646 va_end(ap);
1649 void qemu_chr_send_event(CharDriverState *s, int event)
1651 if (s->chr_send_event)
1652 s->chr_send_event(s, event);
1655 void qemu_chr_add_handlers(CharDriverState *s,
1656 IOCanRWHandler *fd_can_read,
1657 IOReadHandler *fd_read,
1658 IOEventHandler *fd_event,
1659 void *opaque)
1661 s->chr_can_read = fd_can_read;
1662 s->chr_read = fd_read;
1663 s->chr_event = fd_event;
1664 s->handler_opaque = opaque;
1665 if (s->chr_update_read_handler)
1666 s->chr_update_read_handler(s);
1669 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1671 return len;
1674 static CharDriverState *qemu_chr_open_null(void)
1676 CharDriverState *chr;
1678 chr = qemu_mallocz(sizeof(CharDriverState));
1679 if (!chr)
1680 return NULL;
1681 chr->chr_write = null_chr_write;
1682 return chr;
1685 /* MUX driver for serial I/O splitting */
1686 static int term_timestamps;
1687 static int64_t term_timestamps_start;
1688 #define MAX_MUX 4
1689 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1690 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1691 typedef struct {
1692 IOCanRWHandler *chr_can_read[MAX_MUX];
1693 IOReadHandler *chr_read[MAX_MUX];
1694 IOEventHandler *chr_event[MAX_MUX];
1695 void *ext_opaque[MAX_MUX];
1696 CharDriverState *drv;
1697 unsigned char buffer[MUX_BUFFER_SIZE];
1698 int prod;
1699 int cons;
1700 int mux_cnt;
1701 int term_got_escape;
1702 int max_size;
1703 } MuxDriver;
1706 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1708 MuxDriver *d = chr->opaque;
1709 int ret;
1710 if (!term_timestamps) {
1711 ret = d->drv->chr_write(d->drv, buf, len);
1712 } else {
1713 int i;
1715 ret = 0;
1716 for(i = 0; i < len; i++) {
1717 ret += d->drv->chr_write(d->drv, buf+i, 1);
1718 if (buf[i] == '\n') {
1719 char buf1[64];
1720 int64_t ti;
1721 int secs;
1723 ti = get_clock();
1724 if (term_timestamps_start == -1)
1725 term_timestamps_start = ti;
1726 ti -= term_timestamps_start;
1727 secs = ti / 1000000000;
1728 snprintf(buf1, sizeof(buf1),
1729 "[%02d:%02d:%02d.%03d] ",
1730 secs / 3600,
1731 (secs / 60) % 60,
1732 secs % 60,
1733 (int)((ti / 1000000) % 1000));
1734 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1738 return ret;
1741 static char *mux_help[] = {
1742 "% h print this help\n\r",
1743 "% x exit emulator\n\r",
1744 "% s save disk data back to file (if -snapshot)\n\r",
1745 "% t toggle console timestamps\n\r"
1746 "% b send break (magic sysrq)\n\r",
1747 "% c switch between console and monitor\n\r",
1748 "% % sends %\n\r",
1749 NULL
1752 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1753 static void mux_print_help(CharDriverState *chr)
1755 int i, j;
1756 char ebuf[15] = "Escape-Char";
1757 char cbuf[50] = "\n\r";
1759 if (term_escape_char > 0 && term_escape_char < 26) {
1760 sprintf(cbuf,"\n\r");
1761 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1762 } else {
1763 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1764 term_escape_char);
1766 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1767 for (i = 0; mux_help[i] != NULL; i++) {
1768 for (j=0; mux_help[i][j] != '\0'; j++) {
1769 if (mux_help[i][j] == '%')
1770 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1771 else
1772 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1777 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1779 if (d->term_got_escape) {
1780 d->term_got_escape = 0;
1781 if (ch == term_escape_char)
1782 goto send_char;
1783 switch(ch) {
1784 case '?':
1785 case 'h':
1786 mux_print_help(chr);
1787 break;
1788 case 'x':
1790 char *term = "QEMU: Terminated\n\r";
1791 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1792 exit(0);
1793 break;
1795 case 's':
1797 int i;
1798 for (i = 0; i < nb_drives; i++) {
1799 bdrv_commit(drives_table[i].bdrv);
1802 break;
1803 case 'b':
1804 qemu_chr_event(chr, CHR_EVENT_BREAK);
1805 break;
1806 case 'c':
1807 /* Switch to the next registered device */
1808 chr->focus++;
1809 if (chr->focus >= d->mux_cnt)
1810 chr->focus = 0;
1811 break;
1812 case 't':
1813 term_timestamps = !term_timestamps;
1814 term_timestamps_start = -1;
1815 break;
1817 } else if (ch == term_escape_char) {
1818 d->term_got_escape = 1;
1819 } else {
1820 send_char:
1821 return 1;
1823 return 0;
1826 static void mux_chr_accept_input(CharDriverState *chr)
1828 int m = chr->focus;
1829 MuxDriver *d = chr->opaque;
1831 while (d->prod != d->cons &&
1832 d->chr_can_read[m] &&
1833 d->chr_can_read[m](d->ext_opaque[m])) {
1834 d->chr_read[m](d->ext_opaque[m],
1835 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1839 static int mux_chr_can_read(void *opaque)
1841 CharDriverState *chr = opaque;
1842 MuxDriver *d = chr->opaque;
1844 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1845 return 1;
1846 if (d->chr_can_read[chr->focus])
1847 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1848 return 0;
1851 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1853 CharDriverState *chr = opaque;
1854 MuxDriver *d = chr->opaque;
1855 int m = chr->focus;
1856 int i;
1858 mux_chr_accept_input (opaque);
1860 for(i = 0; i < size; i++)
1861 if (mux_proc_byte(chr, d, buf[i])) {
1862 if (d->prod == d->cons &&
1863 d->chr_can_read[m] &&
1864 d->chr_can_read[m](d->ext_opaque[m]))
1865 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1866 else
1867 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1871 static void mux_chr_event(void *opaque, int event)
1873 CharDriverState *chr = opaque;
1874 MuxDriver *d = chr->opaque;
1875 int i;
1877 /* Send the event to all registered listeners */
1878 for (i = 0; i < d->mux_cnt; i++)
1879 if (d->chr_event[i])
1880 d->chr_event[i](d->ext_opaque[i], event);
1883 static void mux_chr_update_read_handler(CharDriverState *chr)
1885 MuxDriver *d = chr->opaque;
1887 if (d->mux_cnt >= MAX_MUX) {
1888 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1889 return;
1891 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1892 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1893 d->chr_read[d->mux_cnt] = chr->chr_read;
1894 d->chr_event[d->mux_cnt] = chr->chr_event;
1895 /* Fix up the real driver with mux routines */
1896 if (d->mux_cnt == 0) {
1897 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1898 mux_chr_event, chr);
1900 chr->focus = d->mux_cnt;
1901 d->mux_cnt++;
1904 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1906 CharDriverState *chr;
1907 MuxDriver *d;
1909 chr = qemu_mallocz(sizeof(CharDriverState));
1910 if (!chr)
1911 return NULL;
1912 d = qemu_mallocz(sizeof(MuxDriver));
1913 if (!d) {
1914 free(chr);
1915 return NULL;
1918 chr->opaque = d;
1919 d->drv = drv;
1920 chr->focus = -1;
1921 chr->chr_write = mux_chr_write;
1922 chr->chr_update_read_handler = mux_chr_update_read_handler;
1923 chr->chr_accept_input = mux_chr_accept_input;
1924 return chr;
1928 #ifdef _WIN32
1930 static void socket_cleanup(void)
1932 WSACleanup();
1935 static int socket_init(void)
1937 WSADATA Data;
1938 int ret, err;
1940 ret = WSAStartup(MAKEWORD(2,2), &Data);
1941 if (ret != 0) {
1942 err = WSAGetLastError();
1943 fprintf(stderr, "WSAStartup: %d\n", err);
1944 return -1;
1946 atexit(socket_cleanup);
1947 return 0;
1950 static int send_all(int fd, const uint8_t *buf, int len1)
1952 int ret, len;
1954 len = len1;
1955 while (len > 0) {
1956 ret = send(fd, buf, len, 0);
1957 if (ret < 0) {
1958 int errno;
1959 errno = WSAGetLastError();
1960 if (errno != WSAEWOULDBLOCK) {
1961 return -1;
1963 } else if (ret == 0) {
1964 break;
1965 } else {
1966 buf += ret;
1967 len -= ret;
1970 return len1 - len;
1973 void socket_set_nonblock(int fd)
1975 unsigned long opt = 1;
1976 ioctlsocket(fd, FIONBIO, &opt);
1979 #else
1981 static int unix_write(int fd, const uint8_t *buf, int len1)
1983 int ret, len;
1985 len = len1;
1986 while (len > 0) {
1987 ret = write(fd, buf, len);
1988 if (ret < 0) {
1989 if (errno != EINTR && errno != EAGAIN)
1990 return -1;
1991 } else if (ret == 0) {
1992 break;
1993 } else {
1994 buf += ret;
1995 len -= ret;
1998 return len1 - len;
2001 static inline int send_all(int fd, const uint8_t *buf, int len1)
2003 return unix_write(fd, buf, len1);
2006 void socket_set_nonblock(int fd)
2008 fcntl(fd, F_SETFL, O_NONBLOCK);
2010 #endif /* !_WIN32 */
2012 #ifndef _WIN32
2014 typedef struct {
2015 int fd_in, fd_out;
2016 int max_size;
2017 } FDCharDriver;
2019 #define STDIO_MAX_CLIENTS 1
2020 static int stdio_nb_clients = 0;
2022 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2024 FDCharDriver *s = chr->opaque;
2025 return unix_write(s->fd_out, buf, len);
2028 static int fd_chr_read_poll(void *opaque)
2030 CharDriverState *chr = opaque;
2031 FDCharDriver *s = chr->opaque;
2033 s->max_size = qemu_chr_can_read(chr);
2034 return s->max_size;
2037 static void fd_chr_read(void *opaque)
2039 CharDriverState *chr = opaque;
2040 FDCharDriver *s = chr->opaque;
2041 int size, len;
2042 uint8_t buf[1024];
2044 len = sizeof(buf);
2045 if (len > s->max_size)
2046 len = s->max_size;
2047 if (len == 0)
2048 return;
2049 size = read(s->fd_in, buf, len);
2050 if (size == 0) {
2051 /* FD has been closed. Remove it from the active list. */
2052 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2053 return;
2055 if (size > 0) {
2056 qemu_chr_read(chr, buf, size);
2060 static void fd_chr_update_read_handler(CharDriverState *chr)
2062 FDCharDriver *s = chr->opaque;
2064 if (s->fd_in >= 0) {
2065 if (nographic && s->fd_in == 0) {
2066 } else {
2067 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2068 fd_chr_read, NULL, chr);
2073 /* open a character device to a unix fd */
2074 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2076 CharDriverState *chr;
2077 FDCharDriver *s;
2079 chr = qemu_mallocz(sizeof(CharDriverState));
2080 if (!chr)
2081 return NULL;
2082 s = qemu_mallocz(sizeof(FDCharDriver));
2083 if (!s) {
2084 free(chr);
2085 return NULL;
2087 s->fd_in = fd_in;
2088 s->fd_out = fd_out;
2089 chr->opaque = s;
2090 chr->chr_write = fd_chr_write;
2091 chr->chr_update_read_handler = fd_chr_update_read_handler;
2093 qemu_chr_reset(chr);
2095 return chr;
2098 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2100 int fd_out;
2102 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2103 if (fd_out < 0)
2104 return NULL;
2105 return qemu_chr_open_fd(-1, fd_out);
2108 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2110 int fd_in, fd_out;
2111 char filename_in[256], filename_out[256];
2113 snprintf(filename_in, 256, "%s.in", filename);
2114 snprintf(filename_out, 256, "%s.out", filename);
2115 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2116 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2117 if (fd_in < 0 || fd_out < 0) {
2118 if (fd_in >= 0)
2119 close(fd_in);
2120 if (fd_out >= 0)
2121 close(fd_out);
2122 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2123 if (fd_in < 0)
2124 return NULL;
2126 return qemu_chr_open_fd(fd_in, fd_out);
2130 /* for STDIO, we handle the case where several clients use it
2131 (nographic mode) */
2133 #define TERM_FIFO_MAX_SIZE 1
2135 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2136 static int term_fifo_size;
2138 static int stdio_read_poll(void *opaque)
2140 CharDriverState *chr = opaque;
2142 /* try to flush the queue if needed */
2143 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2144 qemu_chr_read(chr, term_fifo, 1);
2145 term_fifo_size = 0;
2147 /* see if we can absorb more chars */
2148 if (term_fifo_size == 0)
2149 return 1;
2150 else
2151 return 0;
2154 static void stdio_read(void *opaque)
2156 int size;
2157 uint8_t buf[1];
2158 CharDriverState *chr = opaque;
2160 size = read(0, buf, 1);
2161 if (size == 0) {
2162 /* stdin has been closed. Remove it from the active list. */
2163 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2164 return;
2166 if (size > 0) {
2167 if (qemu_chr_can_read(chr) > 0) {
2168 qemu_chr_read(chr, buf, 1);
2169 } else if (term_fifo_size == 0) {
2170 term_fifo[term_fifo_size++] = buf[0];
2175 /* init terminal so that we can grab keys */
2176 static struct termios oldtty;
2177 static int old_fd0_flags;
2179 static void term_exit(void)
2181 tcsetattr (0, TCSANOW, &oldtty);
2182 fcntl(0, F_SETFL, old_fd0_flags);
2185 static void term_init(void)
2187 struct termios tty;
2189 tcgetattr (0, &tty);
2190 oldtty = tty;
2191 old_fd0_flags = fcntl(0, F_GETFL);
2193 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2194 |INLCR|IGNCR|ICRNL|IXON);
2195 tty.c_oflag |= OPOST;
2196 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2197 /* if graphical mode, we allow Ctrl-C handling */
2198 if (nographic)
2199 tty.c_lflag &= ~ISIG;
2200 tty.c_cflag &= ~(CSIZE|PARENB);
2201 tty.c_cflag |= CS8;
2202 tty.c_cc[VMIN] = 1;
2203 tty.c_cc[VTIME] = 0;
2205 tcsetattr (0, TCSANOW, &tty);
2207 atexit(term_exit);
2209 fcntl(0, F_SETFL, O_NONBLOCK);
2212 static CharDriverState *qemu_chr_open_stdio(void)
2214 CharDriverState *chr;
2216 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2217 return NULL;
2218 chr = qemu_chr_open_fd(0, 1);
2219 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2220 stdio_nb_clients++;
2221 term_init();
2223 return chr;
2226 #if defined(__linux__) || defined(__sun__)
2227 static CharDriverState *qemu_chr_open_pty(void)
2229 struct termios tty;
2230 char slave_name[1024];
2231 int master_fd, slave_fd;
2233 #if defined(__linux__)
2234 /* Not satisfying */
2235 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2236 return NULL;
2238 #endif
2240 /* Disabling local echo and line-buffered output */
2241 tcgetattr (master_fd, &tty);
2242 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2243 tty.c_cc[VMIN] = 1;
2244 tty.c_cc[VTIME] = 0;
2245 tcsetattr (master_fd, TCSAFLUSH, &tty);
2247 fprintf(stderr, "char device redirected to %s\n", slave_name);
2248 return qemu_chr_open_fd(master_fd, master_fd);
2251 static void tty_serial_init(int fd, int speed,
2252 int parity, int data_bits, int stop_bits)
2254 struct termios tty;
2255 speed_t spd;
2257 #if 0
2258 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2259 speed, parity, data_bits, stop_bits);
2260 #endif
2261 tcgetattr (fd, &tty);
2263 switch(speed) {
2264 case 50:
2265 spd = B50;
2266 break;
2267 case 75:
2268 spd = B75;
2269 break;
2270 case 300:
2271 spd = B300;
2272 break;
2273 case 600:
2274 spd = B600;
2275 break;
2276 case 1200:
2277 spd = B1200;
2278 break;
2279 case 2400:
2280 spd = B2400;
2281 break;
2282 case 4800:
2283 spd = B4800;
2284 break;
2285 case 9600:
2286 spd = B9600;
2287 break;
2288 case 19200:
2289 spd = B19200;
2290 break;
2291 case 38400:
2292 spd = B38400;
2293 break;
2294 case 57600:
2295 spd = B57600;
2296 break;
2297 default:
2298 case 115200:
2299 spd = B115200;
2300 break;
2303 cfsetispeed(&tty, spd);
2304 cfsetospeed(&tty, spd);
2306 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2307 |INLCR|IGNCR|ICRNL|IXON);
2308 tty.c_oflag |= OPOST;
2309 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2310 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2311 switch(data_bits) {
2312 default:
2313 case 8:
2314 tty.c_cflag |= CS8;
2315 break;
2316 case 7:
2317 tty.c_cflag |= CS7;
2318 break;
2319 case 6:
2320 tty.c_cflag |= CS6;
2321 break;
2322 case 5:
2323 tty.c_cflag |= CS5;
2324 break;
2326 switch(parity) {
2327 default:
2328 case 'N':
2329 break;
2330 case 'E':
2331 tty.c_cflag |= PARENB;
2332 break;
2333 case 'O':
2334 tty.c_cflag |= PARENB | PARODD;
2335 break;
2337 if (stop_bits == 2)
2338 tty.c_cflag |= CSTOPB;
2340 tcsetattr (fd, TCSANOW, &tty);
2343 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2345 FDCharDriver *s = chr->opaque;
2347 switch(cmd) {
2348 case CHR_IOCTL_SERIAL_SET_PARAMS:
2350 QEMUSerialSetParams *ssp = arg;
2351 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2352 ssp->data_bits, ssp->stop_bits);
2354 break;
2355 case CHR_IOCTL_SERIAL_SET_BREAK:
2357 int enable = *(int *)arg;
2358 if (enable)
2359 tcsendbreak(s->fd_in, 1);
2361 break;
2362 default:
2363 return -ENOTSUP;
2365 return 0;
2368 static CharDriverState *qemu_chr_open_tty(const char *filename)
2370 CharDriverState *chr;
2371 int fd;
2373 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2374 fcntl(fd, F_SETFL, O_NONBLOCK);
2375 tty_serial_init(fd, 115200, 'N', 8, 1);
2376 chr = qemu_chr_open_fd(fd, fd);
2377 if (!chr) {
2378 close(fd);
2379 return NULL;
2381 chr->chr_ioctl = tty_serial_ioctl;
2382 qemu_chr_reset(chr);
2383 return chr;
2385 #else /* ! __linux__ && ! __sun__ */
2386 static CharDriverState *qemu_chr_open_pty(void)
2388 return NULL;
2390 #endif /* __linux__ || __sun__ */
2392 #if defined(__linux__)
2393 typedef struct {
2394 int fd;
2395 int mode;
2396 } ParallelCharDriver;
2398 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2400 if (s->mode != mode) {
2401 int m = mode;
2402 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2403 return 0;
2404 s->mode = mode;
2406 return 1;
2409 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2411 ParallelCharDriver *drv = chr->opaque;
2412 int fd = drv->fd;
2413 uint8_t b;
2415 switch(cmd) {
2416 case CHR_IOCTL_PP_READ_DATA:
2417 if (ioctl(fd, PPRDATA, &b) < 0)
2418 return -ENOTSUP;
2419 *(uint8_t *)arg = b;
2420 break;
2421 case CHR_IOCTL_PP_WRITE_DATA:
2422 b = *(uint8_t *)arg;
2423 if (ioctl(fd, PPWDATA, &b) < 0)
2424 return -ENOTSUP;
2425 break;
2426 case CHR_IOCTL_PP_READ_CONTROL:
2427 if (ioctl(fd, PPRCONTROL, &b) < 0)
2428 return -ENOTSUP;
2429 /* Linux gives only the lowest bits, and no way to know data
2430 direction! For better compatibility set the fixed upper
2431 bits. */
2432 *(uint8_t *)arg = b | 0xc0;
2433 break;
2434 case CHR_IOCTL_PP_WRITE_CONTROL:
2435 b = *(uint8_t *)arg;
2436 if (ioctl(fd, PPWCONTROL, &b) < 0)
2437 return -ENOTSUP;
2438 break;
2439 case CHR_IOCTL_PP_READ_STATUS:
2440 if (ioctl(fd, PPRSTATUS, &b) < 0)
2441 return -ENOTSUP;
2442 *(uint8_t *)arg = b;
2443 break;
2444 case CHR_IOCTL_PP_EPP_READ_ADDR:
2445 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2446 struct ParallelIOArg *parg = arg;
2447 int n = read(fd, parg->buffer, parg->count);
2448 if (n != parg->count) {
2449 return -EIO;
2452 break;
2453 case CHR_IOCTL_PP_EPP_READ:
2454 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2455 struct ParallelIOArg *parg = arg;
2456 int n = read(fd, parg->buffer, parg->count);
2457 if (n != parg->count) {
2458 return -EIO;
2461 break;
2462 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2463 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2464 struct ParallelIOArg *parg = arg;
2465 int n = write(fd, parg->buffer, parg->count);
2466 if (n != parg->count) {
2467 return -EIO;
2470 break;
2471 case CHR_IOCTL_PP_EPP_WRITE:
2472 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2473 struct ParallelIOArg *parg = arg;
2474 int n = write(fd, parg->buffer, parg->count);
2475 if (n != parg->count) {
2476 return -EIO;
2479 break;
2480 default:
2481 return -ENOTSUP;
2483 return 0;
2486 static void pp_close(CharDriverState *chr)
2488 ParallelCharDriver *drv = chr->opaque;
2489 int fd = drv->fd;
2491 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2492 ioctl(fd, PPRELEASE);
2493 close(fd);
2494 qemu_free(drv);
2497 static CharDriverState *qemu_chr_open_pp(const char *filename)
2499 CharDriverState *chr;
2500 ParallelCharDriver *drv;
2501 int fd;
2503 TFR(fd = open(filename, O_RDWR));
2504 if (fd < 0)
2505 return NULL;
2507 if (ioctl(fd, PPCLAIM) < 0) {
2508 close(fd);
2509 return NULL;
2512 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2513 if (!drv) {
2514 close(fd);
2515 return NULL;
2517 drv->fd = fd;
2518 drv->mode = IEEE1284_MODE_COMPAT;
2520 chr = qemu_mallocz(sizeof(CharDriverState));
2521 if (!chr) {
2522 qemu_free(drv);
2523 close(fd);
2524 return NULL;
2526 chr->chr_write = null_chr_write;
2527 chr->chr_ioctl = pp_ioctl;
2528 chr->chr_close = pp_close;
2529 chr->opaque = drv;
2531 qemu_chr_reset(chr);
2533 return chr;
2535 #endif /* __linux__ */
2537 #else /* _WIN32 */
2539 typedef struct {
2540 int max_size;
2541 HANDLE hcom, hrecv, hsend;
2542 OVERLAPPED orecv, osend;
2543 BOOL fpipe;
2544 DWORD len;
2545 } WinCharState;
2547 #define NSENDBUF 2048
2548 #define NRECVBUF 2048
2549 #define MAXCONNECT 1
2550 #define NTIMEOUT 5000
2552 static int win_chr_poll(void *opaque);
2553 static int win_chr_pipe_poll(void *opaque);
2555 static void win_chr_close(CharDriverState *chr)
2557 WinCharState *s = chr->opaque;
2559 if (s->hsend) {
2560 CloseHandle(s->hsend);
2561 s->hsend = NULL;
2563 if (s->hrecv) {
2564 CloseHandle(s->hrecv);
2565 s->hrecv = NULL;
2567 if (s->hcom) {
2568 CloseHandle(s->hcom);
2569 s->hcom = NULL;
2571 if (s->fpipe)
2572 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2573 else
2574 qemu_del_polling_cb(win_chr_poll, chr);
2577 static int win_chr_init(CharDriverState *chr, const char *filename)
2579 WinCharState *s = chr->opaque;
2580 COMMCONFIG comcfg;
2581 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2582 COMSTAT comstat;
2583 DWORD size;
2584 DWORD err;
2586 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2587 if (!s->hsend) {
2588 fprintf(stderr, "Failed CreateEvent\n");
2589 goto fail;
2591 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2592 if (!s->hrecv) {
2593 fprintf(stderr, "Failed CreateEvent\n");
2594 goto fail;
2597 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2598 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2599 if (s->hcom == INVALID_HANDLE_VALUE) {
2600 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2601 s->hcom = NULL;
2602 goto fail;
2605 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2606 fprintf(stderr, "Failed SetupComm\n");
2607 goto fail;
2610 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2611 size = sizeof(COMMCONFIG);
2612 GetDefaultCommConfig(filename, &comcfg, &size);
2613 comcfg.dcb.DCBlength = sizeof(DCB);
2614 CommConfigDialog(filename, NULL, &comcfg);
2616 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2617 fprintf(stderr, "Failed SetCommState\n");
2618 goto fail;
2621 if (!SetCommMask(s->hcom, EV_ERR)) {
2622 fprintf(stderr, "Failed SetCommMask\n");
2623 goto fail;
2626 cto.ReadIntervalTimeout = MAXDWORD;
2627 if (!SetCommTimeouts(s->hcom, &cto)) {
2628 fprintf(stderr, "Failed SetCommTimeouts\n");
2629 goto fail;
2632 if (!ClearCommError(s->hcom, &err, &comstat)) {
2633 fprintf(stderr, "Failed ClearCommError\n");
2634 goto fail;
2636 qemu_add_polling_cb(win_chr_poll, chr);
2637 return 0;
2639 fail:
2640 win_chr_close(chr);
2641 return -1;
2644 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2646 WinCharState *s = chr->opaque;
2647 DWORD len, ret, size, err;
2649 len = len1;
2650 ZeroMemory(&s->osend, sizeof(s->osend));
2651 s->osend.hEvent = s->hsend;
2652 while (len > 0) {
2653 if (s->hsend)
2654 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2655 else
2656 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2657 if (!ret) {
2658 err = GetLastError();
2659 if (err == ERROR_IO_PENDING) {
2660 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2661 if (ret) {
2662 buf += size;
2663 len -= size;
2664 } else {
2665 break;
2667 } else {
2668 break;
2670 } else {
2671 buf += size;
2672 len -= size;
2675 return len1 - len;
2678 static int win_chr_read_poll(CharDriverState *chr)
2680 WinCharState *s = chr->opaque;
2682 s->max_size = qemu_chr_can_read(chr);
2683 return s->max_size;
2686 static void win_chr_readfile(CharDriverState *chr)
2688 WinCharState *s = chr->opaque;
2689 int ret, err;
2690 uint8_t buf[1024];
2691 DWORD size;
2693 ZeroMemory(&s->orecv, sizeof(s->orecv));
2694 s->orecv.hEvent = s->hrecv;
2695 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2696 if (!ret) {
2697 err = GetLastError();
2698 if (err == ERROR_IO_PENDING) {
2699 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2703 if (size > 0) {
2704 qemu_chr_read(chr, buf, size);
2708 static void win_chr_read(CharDriverState *chr)
2710 WinCharState *s = chr->opaque;
2712 if (s->len > s->max_size)
2713 s->len = s->max_size;
2714 if (s->len == 0)
2715 return;
2717 win_chr_readfile(chr);
2720 static int win_chr_poll(void *opaque)
2722 CharDriverState *chr = opaque;
2723 WinCharState *s = chr->opaque;
2724 COMSTAT status;
2725 DWORD comerr;
2727 ClearCommError(s->hcom, &comerr, &status);
2728 if (status.cbInQue > 0) {
2729 s->len = status.cbInQue;
2730 win_chr_read_poll(chr);
2731 win_chr_read(chr);
2732 return 1;
2734 return 0;
2737 static CharDriverState *qemu_chr_open_win(const char *filename)
2739 CharDriverState *chr;
2740 WinCharState *s;
2742 chr = qemu_mallocz(sizeof(CharDriverState));
2743 if (!chr)
2744 return NULL;
2745 s = qemu_mallocz(sizeof(WinCharState));
2746 if (!s) {
2747 free(chr);
2748 return NULL;
2750 chr->opaque = s;
2751 chr->chr_write = win_chr_write;
2752 chr->chr_close = win_chr_close;
2754 if (win_chr_init(chr, filename) < 0) {
2755 free(s);
2756 free(chr);
2757 return NULL;
2759 qemu_chr_reset(chr);
2760 return chr;
2763 static int win_chr_pipe_poll(void *opaque)
2765 CharDriverState *chr = opaque;
2766 WinCharState *s = chr->opaque;
2767 DWORD size;
2769 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2770 if (size > 0) {
2771 s->len = size;
2772 win_chr_read_poll(chr);
2773 win_chr_read(chr);
2774 return 1;
2776 return 0;
2779 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2781 WinCharState *s = chr->opaque;
2782 OVERLAPPED ov;
2783 int ret;
2784 DWORD size;
2785 char openname[256];
2787 s->fpipe = TRUE;
2789 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2790 if (!s->hsend) {
2791 fprintf(stderr, "Failed CreateEvent\n");
2792 goto fail;
2794 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2795 if (!s->hrecv) {
2796 fprintf(stderr, "Failed CreateEvent\n");
2797 goto fail;
2800 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2801 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2802 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2803 PIPE_WAIT,
2804 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2805 if (s->hcom == INVALID_HANDLE_VALUE) {
2806 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2807 s->hcom = NULL;
2808 goto fail;
2811 ZeroMemory(&ov, sizeof(ov));
2812 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2813 ret = ConnectNamedPipe(s->hcom, &ov);
2814 if (ret) {
2815 fprintf(stderr, "Failed ConnectNamedPipe\n");
2816 goto fail;
2819 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2820 if (!ret) {
2821 fprintf(stderr, "Failed GetOverlappedResult\n");
2822 if (ov.hEvent) {
2823 CloseHandle(ov.hEvent);
2824 ov.hEvent = NULL;
2826 goto fail;
2829 if (ov.hEvent) {
2830 CloseHandle(ov.hEvent);
2831 ov.hEvent = NULL;
2833 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2834 return 0;
2836 fail:
2837 win_chr_close(chr);
2838 return -1;
2842 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2844 CharDriverState *chr;
2845 WinCharState *s;
2847 chr = qemu_mallocz(sizeof(CharDriverState));
2848 if (!chr)
2849 return NULL;
2850 s = qemu_mallocz(sizeof(WinCharState));
2851 if (!s) {
2852 free(chr);
2853 return NULL;
2855 chr->opaque = s;
2856 chr->chr_write = win_chr_write;
2857 chr->chr_close = win_chr_close;
2859 if (win_chr_pipe_init(chr, filename) < 0) {
2860 free(s);
2861 free(chr);
2862 return NULL;
2864 qemu_chr_reset(chr);
2865 return chr;
2868 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2870 CharDriverState *chr;
2871 WinCharState *s;
2873 chr = qemu_mallocz(sizeof(CharDriverState));
2874 if (!chr)
2875 return NULL;
2876 s = qemu_mallocz(sizeof(WinCharState));
2877 if (!s) {
2878 free(chr);
2879 return NULL;
2881 s->hcom = fd_out;
2882 chr->opaque = s;
2883 chr->chr_write = win_chr_write;
2884 qemu_chr_reset(chr);
2885 return chr;
2888 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2890 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2893 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2895 HANDLE fd_out;
2897 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2898 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2899 if (fd_out == INVALID_HANDLE_VALUE)
2900 return NULL;
2902 return qemu_chr_open_win_file(fd_out);
2904 #endif /* !_WIN32 */
2906 /***********************************************************/
2907 /* UDP Net console */
2909 typedef struct {
2910 int fd;
2911 struct sockaddr_in daddr;
2912 uint8_t buf[1024];
2913 int bufcnt;
2914 int bufptr;
2915 int max_size;
2916 } NetCharDriver;
2918 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2920 NetCharDriver *s = chr->opaque;
2922 return sendto(s->fd, buf, len, 0,
2923 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2926 static int udp_chr_read_poll(void *opaque)
2928 CharDriverState *chr = opaque;
2929 NetCharDriver *s = chr->opaque;
2931 s->max_size = qemu_chr_can_read(chr);
2933 /* If there were any stray characters in the queue process them
2934 * first
2936 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2937 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2938 s->bufptr++;
2939 s->max_size = qemu_chr_can_read(chr);
2941 return s->max_size;
2944 static void udp_chr_read(void *opaque)
2946 CharDriverState *chr = opaque;
2947 NetCharDriver *s = chr->opaque;
2949 if (s->max_size == 0)
2950 return;
2951 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2952 s->bufptr = s->bufcnt;
2953 if (s->bufcnt <= 0)
2954 return;
2956 s->bufptr = 0;
2957 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2958 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2959 s->bufptr++;
2960 s->max_size = qemu_chr_can_read(chr);
2964 static void udp_chr_update_read_handler(CharDriverState *chr)
2966 NetCharDriver *s = chr->opaque;
2968 if (s->fd >= 0) {
2969 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2970 udp_chr_read, NULL, chr);
2974 #ifndef _WIN32
2975 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2976 #endif
2977 int parse_host_src_port(struct sockaddr_in *haddr,
2978 struct sockaddr_in *saddr,
2979 const char *str);
2981 static CharDriverState *qemu_chr_open_udp(const char *def)
2983 CharDriverState *chr = NULL;
2984 NetCharDriver *s = NULL;
2985 int fd = -1;
2986 struct sockaddr_in saddr;
2988 chr = qemu_mallocz(sizeof(CharDriverState));
2989 if (!chr)
2990 goto return_err;
2991 s = qemu_mallocz(sizeof(NetCharDriver));
2992 if (!s)
2993 goto return_err;
2995 fd = socket(PF_INET, SOCK_DGRAM, 0);
2996 if (fd < 0) {
2997 perror("socket(PF_INET, SOCK_DGRAM)");
2998 goto return_err;
3001 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3002 printf("Could not parse: %s\n", def);
3003 goto return_err;
3006 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3008 perror("bind");
3009 goto return_err;
3012 s->fd = fd;
3013 s->bufcnt = 0;
3014 s->bufptr = 0;
3015 chr->opaque = s;
3016 chr->chr_write = udp_chr_write;
3017 chr->chr_update_read_handler = udp_chr_update_read_handler;
3018 return chr;
3020 return_err:
3021 if (chr)
3022 free(chr);
3023 if (s)
3024 free(s);
3025 if (fd >= 0)
3026 closesocket(fd);
3027 return NULL;
3030 /***********************************************************/
3031 /* TCP Net console */
3033 typedef struct {
3034 int fd, listen_fd;
3035 int connected;
3036 int max_size;
3037 int do_telnetopt;
3038 int do_nodelay;
3039 int is_unix;
3040 } TCPCharDriver;
3042 static void tcp_chr_accept(void *opaque);
3044 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3046 TCPCharDriver *s = chr->opaque;
3047 if (s->connected) {
3048 return send_all(s->fd, buf, len);
3049 } else {
3050 /* XXX: indicate an error ? */
3051 return len;
3055 static int tcp_chr_read_poll(void *opaque)
3057 CharDriverState *chr = opaque;
3058 TCPCharDriver *s = chr->opaque;
3059 if (!s->connected)
3060 return 0;
3061 s->max_size = qemu_chr_can_read(chr);
3062 return s->max_size;
3065 #define IAC 255
3066 #define IAC_BREAK 243
3067 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3068 TCPCharDriver *s,
3069 uint8_t *buf, int *size)
3071 /* Handle any telnet client's basic IAC options to satisfy char by
3072 * char mode with no echo. All IAC options will be removed from
3073 * the buf and the do_telnetopt variable will be used to track the
3074 * state of the width of the IAC information.
3076 * IAC commands come in sets of 3 bytes with the exception of the
3077 * "IAC BREAK" command and the double IAC.
3080 int i;
3081 int j = 0;
3083 for (i = 0; i < *size; i++) {
3084 if (s->do_telnetopt > 1) {
3085 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3086 /* Double IAC means send an IAC */
3087 if (j != i)
3088 buf[j] = buf[i];
3089 j++;
3090 s->do_telnetopt = 1;
3091 } else {
3092 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3093 /* Handle IAC break commands by sending a serial break */
3094 qemu_chr_event(chr, CHR_EVENT_BREAK);
3095 s->do_telnetopt++;
3097 s->do_telnetopt++;
3099 if (s->do_telnetopt >= 4) {
3100 s->do_telnetopt = 1;
3102 } else {
3103 if ((unsigned char)buf[i] == IAC) {
3104 s->do_telnetopt = 2;
3105 } else {
3106 if (j != i)
3107 buf[j] = buf[i];
3108 j++;
3112 *size = j;
3115 static void tcp_chr_read(void *opaque)
3117 CharDriverState *chr = opaque;
3118 TCPCharDriver *s = chr->opaque;
3119 uint8_t buf[1024];
3120 int len, size;
3122 if (!s->connected || s->max_size <= 0)
3123 return;
3124 len = sizeof(buf);
3125 if (len > s->max_size)
3126 len = s->max_size;
3127 size = recv(s->fd, buf, len, 0);
3128 if (size == 0) {
3129 /* connection closed */
3130 s->connected = 0;
3131 if (s->listen_fd >= 0) {
3132 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3134 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3135 closesocket(s->fd);
3136 s->fd = -1;
3137 } else if (size > 0) {
3138 if (s->do_telnetopt)
3139 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3140 if (size > 0)
3141 qemu_chr_read(chr, buf, size);
3145 static void tcp_chr_connect(void *opaque)
3147 CharDriverState *chr = opaque;
3148 TCPCharDriver *s = chr->opaque;
3150 s->connected = 1;
3151 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3152 tcp_chr_read, NULL, chr);
3153 qemu_chr_reset(chr);
3156 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3157 static void tcp_chr_telnet_init(int fd)
3159 char buf[3];
3160 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3161 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3162 send(fd, (char *)buf, 3, 0);
3163 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3164 send(fd, (char *)buf, 3, 0);
3165 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3166 send(fd, (char *)buf, 3, 0);
3167 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3168 send(fd, (char *)buf, 3, 0);
3171 static void socket_set_nodelay(int fd)
3173 int val = 1;
3174 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3177 static void tcp_chr_accept(void *opaque)
3179 CharDriverState *chr = opaque;
3180 TCPCharDriver *s = chr->opaque;
3181 struct sockaddr_in saddr;
3182 #ifndef _WIN32
3183 struct sockaddr_un uaddr;
3184 #endif
3185 struct sockaddr *addr;
3186 socklen_t len;
3187 int fd;
3189 for(;;) {
3190 #ifndef _WIN32
3191 if (s->is_unix) {
3192 len = sizeof(uaddr);
3193 addr = (struct sockaddr *)&uaddr;
3194 } else
3195 #endif
3197 len = sizeof(saddr);
3198 addr = (struct sockaddr *)&saddr;
3200 fd = accept(s->listen_fd, addr, &len);
3201 if (fd < 0 && errno != EINTR) {
3202 return;
3203 } else if (fd >= 0) {
3204 if (s->do_telnetopt)
3205 tcp_chr_telnet_init(fd);
3206 break;
3209 socket_set_nonblock(fd);
3210 if (s->do_nodelay)
3211 socket_set_nodelay(fd);
3212 s->fd = fd;
3213 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3214 tcp_chr_connect(chr);
3217 static void tcp_chr_close(CharDriverState *chr)
3219 TCPCharDriver *s = chr->opaque;
3220 if (s->fd >= 0)
3221 closesocket(s->fd);
3222 if (s->listen_fd >= 0)
3223 closesocket(s->listen_fd);
3224 qemu_free(s);
3227 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3228 int is_telnet,
3229 int is_unix)
3231 CharDriverState *chr = NULL;
3232 TCPCharDriver *s = NULL;
3233 int fd = -1, ret, err, val;
3234 int is_listen = 0;
3235 int is_waitconnect = 1;
3236 int do_nodelay = 0;
3237 const char *ptr;
3238 struct sockaddr_in saddr;
3239 #ifndef _WIN32
3240 struct sockaddr_un uaddr;
3241 #endif
3242 struct sockaddr *addr;
3243 socklen_t addrlen;
3245 #ifndef _WIN32
3246 if (is_unix) {
3247 addr = (struct sockaddr *)&uaddr;
3248 addrlen = sizeof(uaddr);
3249 if (parse_unix_path(&uaddr, host_str) < 0)
3250 goto fail;
3251 } else
3252 #endif
3254 addr = (struct sockaddr *)&saddr;
3255 addrlen = sizeof(saddr);
3256 if (parse_host_port(&saddr, host_str) < 0)
3257 goto fail;
3260 ptr = host_str;
3261 while((ptr = strchr(ptr,','))) {
3262 ptr++;
3263 if (!strncmp(ptr,"server",6)) {
3264 is_listen = 1;
3265 } else if (!strncmp(ptr,"nowait",6)) {
3266 is_waitconnect = 0;
3267 } else if (!strncmp(ptr,"nodelay",6)) {
3268 do_nodelay = 1;
3269 } else {
3270 printf("Unknown option: %s\n", ptr);
3271 goto fail;
3274 if (!is_listen)
3275 is_waitconnect = 0;
3277 chr = qemu_mallocz(sizeof(CharDriverState));
3278 if (!chr)
3279 goto fail;
3280 s = qemu_mallocz(sizeof(TCPCharDriver));
3281 if (!s)
3282 goto fail;
3284 #ifndef _WIN32
3285 if (is_unix)
3286 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3287 else
3288 #endif
3289 fd = socket(PF_INET, SOCK_STREAM, 0);
3291 if (fd < 0)
3292 goto fail;
3294 if (!is_waitconnect)
3295 socket_set_nonblock(fd);
3297 s->connected = 0;
3298 s->fd = -1;
3299 s->listen_fd = -1;
3300 s->is_unix = is_unix;
3301 s->do_nodelay = do_nodelay && !is_unix;
3303 chr->opaque = s;
3304 chr->chr_write = tcp_chr_write;
3305 chr->chr_close = tcp_chr_close;
3307 if (is_listen) {
3308 /* allow fast reuse */
3309 #ifndef _WIN32
3310 if (is_unix) {
3311 char path[109];
3312 strncpy(path, uaddr.sun_path, 108);
3313 path[108] = 0;
3314 unlink(path);
3315 } else
3316 #endif
3318 val = 1;
3319 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3322 ret = bind(fd, addr, addrlen);
3323 if (ret < 0)
3324 goto fail;
3326 ret = listen(fd, 0);
3327 if (ret < 0)
3328 goto fail;
3330 s->listen_fd = fd;
3331 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3332 if (is_telnet)
3333 s->do_telnetopt = 1;
3334 } else {
3335 for(;;) {
3336 ret = connect(fd, addr, addrlen);
3337 if (ret < 0) {
3338 err = socket_error();
3339 if (err == EINTR || err == EWOULDBLOCK) {
3340 } else if (err == EINPROGRESS) {
3341 break;
3342 #ifdef _WIN32
3343 } else if (err == WSAEALREADY) {
3344 break;
3345 #endif
3346 } else {
3347 goto fail;
3349 } else {
3350 s->connected = 1;
3351 break;
3354 s->fd = fd;
3355 socket_set_nodelay(fd);
3356 if (s->connected)
3357 tcp_chr_connect(chr);
3358 else
3359 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3362 if (is_listen && is_waitconnect) {
3363 printf("QEMU waiting for connection on: %s\n", host_str);
3364 tcp_chr_accept(chr);
3365 socket_set_nonblock(s->listen_fd);
3368 return chr;
3369 fail:
3370 if (fd >= 0)
3371 closesocket(fd);
3372 qemu_free(s);
3373 qemu_free(chr);
3374 return NULL;
3377 CharDriverState *qemu_chr_open(const char *filename)
3379 const char *p;
3381 if (!strcmp(filename, "vc")) {
3382 return text_console_init(&display_state, 0);
3383 } else if (strstart(filename, "vc:", &p)) {
3384 return text_console_init(&display_state, p);
3385 } else if (!strcmp(filename, "null")) {
3386 return qemu_chr_open_null();
3387 } else
3388 if (strstart(filename, "tcp:", &p)) {
3389 return qemu_chr_open_tcp(p, 0, 0);
3390 } else
3391 if (strstart(filename, "telnet:", &p)) {
3392 return qemu_chr_open_tcp(p, 1, 0);
3393 } else
3394 if (strstart(filename, "udp:", &p)) {
3395 return qemu_chr_open_udp(p);
3396 } else
3397 if (strstart(filename, "mon:", &p)) {
3398 CharDriverState *drv = qemu_chr_open(p);
3399 if (drv) {
3400 drv = qemu_chr_open_mux(drv);
3401 monitor_init(drv, !nographic);
3402 return drv;
3404 printf("Unable to open driver: %s\n", p);
3405 return 0;
3406 } else
3407 #ifndef _WIN32
3408 if (strstart(filename, "unix:", &p)) {
3409 return qemu_chr_open_tcp(p, 0, 1);
3410 } else if (strstart(filename, "file:", &p)) {
3411 return qemu_chr_open_file_out(p);
3412 } else if (strstart(filename, "pipe:", &p)) {
3413 return qemu_chr_open_pipe(p);
3414 } else if (!strcmp(filename, "pty")) {
3415 return qemu_chr_open_pty();
3416 } else if (!strcmp(filename, "stdio")) {
3417 return qemu_chr_open_stdio();
3418 } else
3419 #if defined(__linux__)
3420 if (strstart(filename, "/dev/parport", NULL)) {
3421 return qemu_chr_open_pp(filename);
3422 } else
3423 #endif
3424 #if defined(__linux__) || defined(__sun__)
3425 if (strstart(filename, "/dev/", NULL)) {
3426 return qemu_chr_open_tty(filename);
3427 } else
3428 #endif
3429 #else /* !_WIN32 */
3430 if (strstart(filename, "COM", NULL)) {
3431 return qemu_chr_open_win(filename);
3432 } else
3433 if (strstart(filename, "pipe:", &p)) {
3434 return qemu_chr_open_win_pipe(p);
3435 } else
3436 if (strstart(filename, "con:", NULL)) {
3437 return qemu_chr_open_win_con(filename);
3438 } else
3439 if (strstart(filename, "file:", &p)) {
3440 return qemu_chr_open_win_file_out(p);
3442 #endif
3444 return NULL;
3448 void qemu_chr_close(CharDriverState *chr)
3450 if (chr->chr_close)
3451 chr->chr_close(chr);
3454 /***********************************************************/
3455 /* network device redirectors */
3457 __attribute__ (( unused ))
3458 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3460 int len, i, j, c;
3462 for(i=0;i<size;i+=16) {
3463 len = size - i;
3464 if (len > 16)
3465 len = 16;
3466 fprintf(f, "%08x ", i);
3467 for(j=0;j<16;j++) {
3468 if (j < len)
3469 fprintf(f, " %02x", buf[i+j]);
3470 else
3471 fprintf(f, " ");
3473 fprintf(f, " ");
3474 for(j=0;j<len;j++) {
3475 c = buf[i+j];
3476 if (c < ' ' || c > '~')
3477 c = '.';
3478 fprintf(f, "%c", c);
3480 fprintf(f, "\n");
3484 static int parse_macaddr(uint8_t *macaddr, const char *p)
3486 int i;
3487 char *last_char;
3488 long int offset;
3490 errno = 0;
3491 offset = strtol(p, &last_char, 0);
3492 if (0 == errno && '\0' == *last_char &&
3493 offset >= 0 && offset <= 0xFFFFFF) {
3494 macaddr[3] = (offset & 0xFF0000) >> 16;
3495 macaddr[4] = (offset & 0xFF00) >> 8;
3496 macaddr[5] = offset & 0xFF;
3497 return 0;
3498 } else {
3499 for(i = 0; i < 6; i++) {
3500 macaddr[i] = strtol(p, (char **)&p, 16);
3501 if (i == 5) {
3502 if (*p != '\0')
3503 return -1;
3504 } else {
3505 if (*p != ':' && *p != '-')
3506 return -1;
3507 p++;
3510 return 0;
3513 return -1;
3516 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3518 const char *p, *p1;
3519 int len;
3520 p = *pp;
3521 p1 = strchr(p, sep);
3522 if (!p1)
3523 return -1;
3524 len = p1 - p;
3525 p1++;
3526 if (buf_size > 0) {
3527 if (len > buf_size - 1)
3528 len = buf_size - 1;
3529 memcpy(buf, p, len);
3530 buf[len] = '\0';
3532 *pp = p1;
3533 return 0;
3536 int parse_host_src_port(struct sockaddr_in *haddr,
3537 struct sockaddr_in *saddr,
3538 const char *input_str)
3540 char *str = strdup(input_str);
3541 char *host_str = str;
3542 char *src_str;
3543 char *ptr;
3546 * Chop off any extra arguments at the end of the string which
3547 * would start with a comma, then fill in the src port information
3548 * if it was provided else use the "any address" and "any port".
3550 if ((ptr = strchr(str,',')))
3551 *ptr = '\0';
3553 if ((src_str = strchr(input_str,'@'))) {
3554 *src_str = '\0';
3555 src_str++;
3558 if (parse_host_port(haddr, host_str) < 0)
3559 goto fail;
3561 if (!src_str || *src_str == '\0')
3562 src_str = ":0";
3564 if (parse_host_port(saddr, src_str) < 0)
3565 goto fail;
3567 free(str);
3568 return(0);
3570 fail:
3571 free(str);
3572 return -1;
3575 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3577 char buf[512];
3578 struct hostent *he;
3579 const char *p, *r;
3580 int port;
3582 p = str;
3583 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3584 return -1;
3585 saddr->sin_family = AF_INET;
3586 if (buf[0] == '\0') {
3587 saddr->sin_addr.s_addr = 0;
3588 } else {
3589 if (isdigit(buf[0])) {
3590 if (!inet_aton(buf, &saddr->sin_addr))
3591 return -1;
3592 } else {
3593 if ((he = gethostbyname(buf)) == NULL)
3594 return - 1;
3595 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3598 port = strtol(p, (char **)&r, 0);
3599 if (r == p)
3600 return -1;
3601 saddr->sin_port = htons(port);
3602 return 0;
3605 #ifndef _WIN32
3606 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3608 const char *p;
3609 int len;
3611 len = MIN(108, strlen(str));
3612 p = strchr(str, ',');
3613 if (p)
3614 len = MIN(len, p - str);
3616 memset(uaddr, 0, sizeof(*uaddr));
3618 uaddr->sun_family = AF_UNIX;
3619 memcpy(uaddr->sun_path, str, len);
3621 return 0;
3623 #endif
3625 /* find or alloc a new VLAN */
3626 VLANState *qemu_find_vlan(int id)
3628 VLANState **pvlan, *vlan;
3629 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3630 if (vlan->id == id)
3631 return vlan;
3633 vlan = qemu_mallocz(sizeof(VLANState));
3634 if (!vlan)
3635 return NULL;
3636 vlan->id = id;
3637 vlan->next = NULL;
3638 pvlan = &first_vlan;
3639 while (*pvlan != NULL)
3640 pvlan = &(*pvlan)->next;
3641 *pvlan = vlan;
3642 return vlan;
3645 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3646 IOReadHandler *fd_read,
3647 IOCanRWHandler *fd_can_read,
3648 void *opaque)
3650 VLANClientState *vc, **pvc;
3651 vc = qemu_mallocz(sizeof(VLANClientState));
3652 if (!vc)
3653 return NULL;
3654 vc->fd_read = fd_read;
3655 vc->fd_can_read = fd_can_read;
3656 vc->opaque = opaque;
3657 vc->vlan = vlan;
3659 vc->next = NULL;
3660 pvc = &vlan->first_client;
3661 while (*pvc != NULL)
3662 pvc = &(*pvc)->next;
3663 *pvc = vc;
3664 return vc;
3667 int qemu_can_send_packet(VLANClientState *vc1)
3669 VLANState *vlan = vc1->vlan;
3670 VLANClientState *vc;
3672 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3673 if (vc != vc1) {
3674 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3675 return 1;
3678 return 0;
3681 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3683 VLANState *vlan = vc1->vlan;
3684 VLANClientState *vc;
3686 #if 0
3687 printf("vlan %d send:\n", vlan->id);
3688 hex_dump(stdout, buf, size);
3689 #endif
3690 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3691 if (vc != vc1) {
3692 vc->fd_read(vc->opaque, buf, size);
3697 #if defined(CONFIG_SLIRP)
3699 /* slirp network adapter */
3701 static int slirp_inited;
3702 static VLANClientState *slirp_vc;
3704 int slirp_can_output(void)
3706 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3709 void slirp_output(const uint8_t *pkt, int pkt_len)
3711 #if 0
3712 printf("slirp output:\n");
3713 hex_dump(stdout, pkt, pkt_len);
3714 #endif
3715 if (!slirp_vc)
3716 return;
3717 qemu_send_packet(slirp_vc, pkt, pkt_len);
3720 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3722 #if 0
3723 printf("slirp input:\n");
3724 hex_dump(stdout, buf, size);
3725 #endif
3726 slirp_input(buf, size);
3729 static int net_slirp_init(VLANState *vlan)
3731 if (!slirp_inited) {
3732 slirp_inited = 1;
3733 slirp_init();
3735 slirp_vc = qemu_new_vlan_client(vlan,
3736 slirp_receive, NULL, NULL);
3737 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3738 return 0;
3741 static void net_slirp_redir(const char *redir_str)
3743 int is_udp;
3744 char buf[256], *r;
3745 const char *p;
3746 struct in_addr guest_addr;
3747 int host_port, guest_port;
3749 if (!slirp_inited) {
3750 slirp_inited = 1;
3751 slirp_init();
3754 p = redir_str;
3755 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3756 goto fail;
3757 if (!strcmp(buf, "tcp")) {
3758 is_udp = 0;
3759 } else if (!strcmp(buf, "udp")) {
3760 is_udp = 1;
3761 } else {
3762 goto fail;
3765 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3766 goto fail;
3767 host_port = strtol(buf, &r, 0);
3768 if (r == buf)
3769 goto fail;
3771 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3772 goto fail;
3773 if (buf[0] == '\0') {
3774 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3776 if (!inet_aton(buf, &guest_addr))
3777 goto fail;
3779 guest_port = strtol(p, &r, 0);
3780 if (r == p)
3781 goto fail;
3783 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3784 fprintf(stderr, "qemu: could not set up redirection\n");
3785 exit(1);
3787 return;
3788 fail:
3789 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3790 exit(1);
3793 #ifndef _WIN32
3795 char smb_dir[1024];
3797 static void smb_exit(void)
3799 DIR *d;
3800 struct dirent *de;
3801 char filename[1024];
3803 /* erase all the files in the directory */
3804 d = opendir(smb_dir);
3805 for(;;) {
3806 de = readdir(d);
3807 if (!de)
3808 break;
3809 if (strcmp(de->d_name, ".") != 0 &&
3810 strcmp(de->d_name, "..") != 0) {
3811 snprintf(filename, sizeof(filename), "%s/%s",
3812 smb_dir, de->d_name);
3813 unlink(filename);
3816 closedir(d);
3817 rmdir(smb_dir);
3820 /* automatic user mode samba server configuration */
3821 static void net_slirp_smb(const char *exported_dir)
3823 char smb_conf[1024];
3824 char smb_cmdline[1024];
3825 FILE *f;
3827 if (!slirp_inited) {
3828 slirp_inited = 1;
3829 slirp_init();
3832 /* XXX: better tmp dir construction */
3833 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3834 if (mkdir(smb_dir, 0700) < 0) {
3835 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3836 exit(1);
3838 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3840 f = fopen(smb_conf, "w");
3841 if (!f) {
3842 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3843 exit(1);
3845 fprintf(f,
3846 "[global]\n"
3847 "private dir=%s\n"
3848 "smb ports=0\n"
3849 "socket address=127.0.0.1\n"
3850 "pid directory=%s\n"
3851 "lock directory=%s\n"
3852 "log file=%s/log.smbd\n"
3853 "smb passwd file=%s/smbpasswd\n"
3854 "security = share\n"
3855 "[qemu]\n"
3856 "path=%s\n"
3857 "read only=no\n"
3858 "guest ok=yes\n",
3859 smb_dir,
3860 smb_dir,
3861 smb_dir,
3862 smb_dir,
3863 smb_dir,
3864 exported_dir
3866 fclose(f);
3867 atexit(smb_exit);
3869 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3870 SMBD_COMMAND, smb_conf);
3872 slirp_add_exec(0, smb_cmdline, 4, 139);
3875 #endif /* !defined(_WIN32) */
3876 void do_info_slirp(void)
3878 slirp_stats();
3881 #endif /* CONFIG_SLIRP */
3883 #if !defined(_WIN32)
3885 typedef struct TAPState {
3886 VLANClientState *vc;
3887 int fd;
3888 char down_script[1024];
3889 } TAPState;
3891 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3893 TAPState *s = opaque;
3894 int ret;
3895 for(;;) {
3896 ret = write(s->fd, buf, size);
3897 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3898 } else {
3899 break;
3904 static void tap_send(void *opaque)
3906 TAPState *s = opaque;
3907 uint8_t buf[4096];
3908 int size;
3910 #ifdef __sun__
3911 struct strbuf sbuf;
3912 int f = 0;
3913 sbuf.maxlen = sizeof(buf);
3914 sbuf.buf = buf;
3915 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3916 #else
3917 size = read(s->fd, buf, sizeof(buf));
3918 #endif
3919 if (size > 0) {
3920 qemu_send_packet(s->vc, buf, size);
3924 /* fd support */
3926 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3928 TAPState *s;
3930 s = qemu_mallocz(sizeof(TAPState));
3931 if (!s)
3932 return NULL;
3933 s->fd = fd;
3934 enable_sigio_timer(fd);
3935 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3936 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3937 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3938 return s;
3941 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3942 static int tap_open(char *ifname, int ifname_size)
3944 int fd;
3945 char *dev;
3946 struct stat s;
3948 TFR(fd = open("/dev/tap", O_RDWR));
3949 if (fd < 0) {
3950 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3951 return -1;
3954 fstat(fd, &s);
3955 dev = devname(s.st_rdev, S_IFCHR);
3956 pstrcpy(ifname, ifname_size, dev);
3958 fcntl(fd, F_SETFL, O_NONBLOCK);
3959 return fd;
3961 #elif defined(__sun__)
3962 #define TUNNEWPPA (('T'<<16) | 0x0001)
3964 * Allocate TAP device, returns opened fd.
3965 * Stores dev name in the first arg(must be large enough).
3967 int tap_alloc(char *dev)
3969 int tap_fd, if_fd, ppa = -1;
3970 static int ip_fd = 0;
3971 char *ptr;
3973 static int arp_fd = 0;
3974 int ip_muxid, arp_muxid;
3975 struct strioctl strioc_if, strioc_ppa;
3976 int link_type = I_PLINK;;
3977 struct lifreq ifr;
3978 char actual_name[32] = "";
3980 memset(&ifr, 0x0, sizeof(ifr));
3982 if( *dev ){
3983 ptr = dev;
3984 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3985 ppa = atoi(ptr);
3988 /* Check if IP device was opened */
3989 if( ip_fd )
3990 close(ip_fd);
3992 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3993 if (ip_fd < 0) {
3994 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3995 return -1;
3998 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3999 if (tap_fd < 0) {
4000 syslog(LOG_ERR, "Can't open /dev/tap");
4001 return -1;
4004 /* Assign a new PPA and get its unit number. */
4005 strioc_ppa.ic_cmd = TUNNEWPPA;
4006 strioc_ppa.ic_timout = 0;
4007 strioc_ppa.ic_len = sizeof(ppa);
4008 strioc_ppa.ic_dp = (char *)&ppa;
4009 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4010 syslog (LOG_ERR, "Can't assign new interface");
4012 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4013 if (if_fd < 0) {
4014 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4015 return -1;
4017 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4018 syslog(LOG_ERR, "Can't push IP module");
4019 return -1;
4022 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4023 syslog(LOG_ERR, "Can't get flags\n");
4025 snprintf (actual_name, 32, "tap%d", ppa);
4026 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4028 ifr.lifr_ppa = ppa;
4029 /* Assign ppa according to the unit number returned by tun device */
4031 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4032 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4033 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4034 syslog (LOG_ERR, "Can't get flags\n");
4035 /* Push arp module to if_fd */
4036 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4037 syslog (LOG_ERR, "Can't push ARP module (2)");
4039 /* Push arp module to ip_fd */
4040 if (ioctl (ip_fd, I_POP, NULL) < 0)
4041 syslog (LOG_ERR, "I_POP failed\n");
4042 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4043 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4044 /* Open arp_fd */
4045 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4046 if (arp_fd < 0)
4047 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4049 /* Set ifname to arp */
4050 strioc_if.ic_cmd = SIOCSLIFNAME;
4051 strioc_if.ic_timout = 0;
4052 strioc_if.ic_len = sizeof(ifr);
4053 strioc_if.ic_dp = (char *)&ifr;
4054 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4055 syslog (LOG_ERR, "Can't set ifname to arp\n");
4058 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4059 syslog(LOG_ERR, "Can't link TAP device to IP");
4060 return -1;
4063 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4064 syslog (LOG_ERR, "Can't link TAP device to ARP");
4066 close (if_fd);
4068 memset(&ifr, 0x0, sizeof(ifr));
4069 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4070 ifr.lifr_ip_muxid = ip_muxid;
4071 ifr.lifr_arp_muxid = arp_muxid;
4073 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4075 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4076 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4077 syslog (LOG_ERR, "Can't set multiplexor id");
4080 sprintf(dev, "tap%d", ppa);
4081 return tap_fd;
4084 static int tap_open(char *ifname, int ifname_size)
4086 char dev[10]="";
4087 int fd;
4088 if( (fd = tap_alloc(dev)) < 0 ){
4089 fprintf(stderr, "Cannot allocate TAP device\n");
4090 return -1;
4092 pstrcpy(ifname, ifname_size, dev);
4093 fcntl(fd, F_SETFL, O_NONBLOCK);
4094 return fd;
4096 #else
4097 static int tap_open(char *ifname, int ifname_size)
4099 struct ifreq ifr;
4100 int fd, ret;
4102 TFR(fd = open("/dev/net/tun", O_RDWR));
4103 if (fd < 0) {
4104 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4105 return -1;
4107 memset(&ifr, 0, sizeof(ifr));
4108 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4109 if (ifname[0] != '\0')
4110 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4111 else
4112 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4113 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4114 if (ret != 0) {
4115 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4116 close(fd);
4117 return -1;
4119 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4120 fcntl(fd, F_SETFL, O_NONBLOCK);
4121 return fd;
4123 #endif
4125 static int launch_script(const char *setup_script, const char *ifname, int fd)
4127 int pid, status;
4128 char *args[3];
4129 char **parg;
4131 /* try to launch network script */
4132 pid = fork();
4133 if (pid >= 0) {
4134 if (pid == 0) {
4135 int open_max = sysconf (_SC_OPEN_MAX), i;
4136 for (i = 0; i < open_max; i++)
4137 if (i != STDIN_FILENO &&
4138 i != STDOUT_FILENO &&
4139 i != STDERR_FILENO &&
4140 i != fd)
4141 close(i);
4143 parg = args;
4144 *parg++ = (char *)setup_script;
4145 *parg++ = (char *)ifname;
4146 *parg++ = NULL;
4147 execv(setup_script, args);
4148 _exit(1);
4150 while (waitpid(pid, &status, 0) != pid);
4151 if (!WIFEXITED(status) ||
4152 WEXITSTATUS(status) != 0) {
4153 fprintf(stderr, "%s: could not launch network script\n",
4154 setup_script);
4155 return -1;
4158 return 0;
4161 static int net_tap_init(VLANState *vlan, const char *ifname1,
4162 const char *setup_script, const char *down_script)
4164 TAPState *s;
4165 int fd;
4166 char ifname[128];
4168 if (ifname1 != NULL)
4169 pstrcpy(ifname, sizeof(ifname), ifname1);
4170 else
4171 ifname[0] = '\0';
4172 TFR(fd = tap_open(ifname, sizeof(ifname)));
4173 if (fd < 0)
4174 return -1;
4176 if (!setup_script || !strcmp(setup_script, "no"))
4177 setup_script = "";
4178 if (setup_script[0] != '\0') {
4179 if (launch_script(setup_script, ifname, fd))
4180 return -1;
4182 s = net_tap_fd_init(vlan, fd);
4183 if (!s)
4184 return -1;
4185 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4186 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4187 if (down_script && strcmp(down_script, "no"))
4188 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4189 return 0;
4192 #endif /* !_WIN32 */
4194 /* network connection */
4195 typedef struct NetSocketState {
4196 VLANClientState *vc;
4197 int fd;
4198 int state; /* 0 = getting length, 1 = getting data */
4199 int index;
4200 int packet_len;
4201 uint8_t buf[4096];
4202 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4203 } NetSocketState;
4205 typedef struct NetSocketListenState {
4206 VLANState *vlan;
4207 int fd;
4208 } NetSocketListenState;
4210 /* XXX: we consider we can send the whole packet without blocking */
4211 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4213 NetSocketState *s = opaque;
4214 uint32_t len;
4215 len = htonl(size);
4217 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4218 send_all(s->fd, buf, size);
4221 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4223 NetSocketState *s = opaque;
4224 sendto(s->fd, buf, size, 0,
4225 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4228 static void net_socket_send(void *opaque)
4230 NetSocketState *s = opaque;
4231 int l, size, err;
4232 uint8_t buf1[4096];
4233 const uint8_t *buf;
4235 size = recv(s->fd, buf1, sizeof(buf1), 0);
4236 if (size < 0) {
4237 err = socket_error();
4238 if (err != EWOULDBLOCK)
4239 goto eoc;
4240 } else if (size == 0) {
4241 /* end of connection */
4242 eoc:
4243 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4244 closesocket(s->fd);
4245 return;
4247 buf = buf1;
4248 while (size > 0) {
4249 /* reassemble a packet from the network */
4250 switch(s->state) {
4251 case 0:
4252 l = 4 - s->index;
4253 if (l > size)
4254 l = size;
4255 memcpy(s->buf + s->index, buf, l);
4256 buf += l;
4257 size -= l;
4258 s->index += l;
4259 if (s->index == 4) {
4260 /* got length */
4261 s->packet_len = ntohl(*(uint32_t *)s->buf);
4262 s->index = 0;
4263 s->state = 1;
4265 break;
4266 case 1:
4267 l = s->packet_len - s->index;
4268 if (l > size)
4269 l = size;
4270 memcpy(s->buf + s->index, buf, l);
4271 s->index += l;
4272 buf += l;
4273 size -= l;
4274 if (s->index >= s->packet_len) {
4275 qemu_send_packet(s->vc, s->buf, s->packet_len);
4276 s->index = 0;
4277 s->state = 0;
4279 break;
4284 static void net_socket_send_dgram(void *opaque)
4286 NetSocketState *s = opaque;
4287 int size;
4289 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4290 if (size < 0)
4291 return;
4292 if (size == 0) {
4293 /* end of connection */
4294 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4295 return;
4297 qemu_send_packet(s->vc, s->buf, size);
4300 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4302 struct ip_mreq imr;
4303 int fd;
4304 int val, ret;
4305 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4306 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4307 inet_ntoa(mcastaddr->sin_addr),
4308 (int)ntohl(mcastaddr->sin_addr.s_addr));
4309 return -1;
4312 fd = socket(PF_INET, SOCK_DGRAM, 0);
4313 if (fd < 0) {
4314 perror("socket(PF_INET, SOCK_DGRAM)");
4315 return -1;
4318 val = 1;
4319 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4320 (const char *)&val, sizeof(val));
4321 if (ret < 0) {
4322 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4323 goto fail;
4326 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4327 if (ret < 0) {
4328 perror("bind");
4329 goto fail;
4332 /* Add host to multicast group */
4333 imr.imr_multiaddr = mcastaddr->sin_addr;
4334 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4336 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4337 (const char *)&imr, sizeof(struct ip_mreq));
4338 if (ret < 0) {
4339 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4340 goto fail;
4343 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4344 val = 1;
4345 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4346 (const char *)&val, sizeof(val));
4347 if (ret < 0) {
4348 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4349 goto fail;
4352 socket_set_nonblock(fd);
4353 return fd;
4354 fail:
4355 if (fd >= 0)
4356 closesocket(fd);
4357 return -1;
4360 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4361 int is_connected)
4363 struct sockaddr_in saddr;
4364 int newfd;
4365 socklen_t saddr_len;
4366 NetSocketState *s;
4368 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4369 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4370 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4373 if (is_connected) {
4374 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4375 /* must be bound */
4376 if (saddr.sin_addr.s_addr==0) {
4377 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4378 fd);
4379 return NULL;
4381 /* clone dgram socket */
4382 newfd = net_socket_mcast_create(&saddr);
4383 if (newfd < 0) {
4384 /* error already reported by net_socket_mcast_create() */
4385 close(fd);
4386 return NULL;
4388 /* clone newfd to fd, close newfd */
4389 dup2(newfd, fd);
4390 close(newfd);
4392 } else {
4393 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4394 fd, strerror(errno));
4395 return NULL;
4399 s = qemu_mallocz(sizeof(NetSocketState));
4400 if (!s)
4401 return NULL;
4402 s->fd = fd;
4404 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4405 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4407 /* mcast: save bound address as dst */
4408 if (is_connected) s->dgram_dst=saddr;
4410 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4411 "socket: fd=%d (%s mcast=%s:%d)",
4412 fd, is_connected? "cloned" : "",
4413 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4414 return s;
4417 static void net_socket_connect(void *opaque)
4419 NetSocketState *s = opaque;
4420 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4423 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4424 int is_connected)
4426 NetSocketState *s;
4427 s = qemu_mallocz(sizeof(NetSocketState));
4428 if (!s)
4429 return NULL;
4430 s->fd = fd;
4431 s->vc = qemu_new_vlan_client(vlan,
4432 net_socket_receive, NULL, s);
4433 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4434 "socket: fd=%d", fd);
4435 if (is_connected) {
4436 net_socket_connect(s);
4437 } else {
4438 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4440 return s;
4443 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4444 int is_connected)
4446 int so_type=-1, optlen=sizeof(so_type);
4448 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4449 (socklen_t *)&optlen)< 0) {
4450 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4451 return NULL;
4453 switch(so_type) {
4454 case SOCK_DGRAM:
4455 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4456 case SOCK_STREAM:
4457 return net_socket_fd_init_stream(vlan, fd, is_connected);
4458 default:
4459 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4460 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4461 return net_socket_fd_init_stream(vlan, fd, is_connected);
4463 return NULL;
4466 static void net_socket_accept(void *opaque)
4468 NetSocketListenState *s = opaque;
4469 NetSocketState *s1;
4470 struct sockaddr_in saddr;
4471 socklen_t len;
4472 int fd;
4474 for(;;) {
4475 len = sizeof(saddr);
4476 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4477 if (fd < 0 && errno != EINTR) {
4478 return;
4479 } else if (fd >= 0) {
4480 break;
4483 s1 = net_socket_fd_init(s->vlan, fd, 1);
4484 if (!s1) {
4485 closesocket(fd);
4486 } else {
4487 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4488 "socket: connection from %s:%d",
4489 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4493 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4495 NetSocketListenState *s;
4496 int fd, val, ret;
4497 struct sockaddr_in saddr;
4499 if (parse_host_port(&saddr, host_str) < 0)
4500 return -1;
4502 s = qemu_mallocz(sizeof(NetSocketListenState));
4503 if (!s)
4504 return -1;
4506 fd = socket(PF_INET, SOCK_STREAM, 0);
4507 if (fd < 0) {
4508 perror("socket");
4509 return -1;
4511 socket_set_nonblock(fd);
4513 /* allow fast reuse */
4514 val = 1;
4515 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4517 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4518 if (ret < 0) {
4519 perror("bind");
4520 return -1;
4522 ret = listen(fd, 0);
4523 if (ret < 0) {
4524 perror("listen");
4525 return -1;
4527 s->vlan = vlan;
4528 s->fd = fd;
4529 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4530 return 0;
4533 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4535 NetSocketState *s;
4536 int fd, connected, ret, err;
4537 struct sockaddr_in saddr;
4539 if (parse_host_port(&saddr, host_str) < 0)
4540 return -1;
4542 fd = socket(PF_INET, SOCK_STREAM, 0);
4543 if (fd < 0) {
4544 perror("socket");
4545 return -1;
4547 socket_set_nonblock(fd);
4549 connected = 0;
4550 for(;;) {
4551 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4552 if (ret < 0) {
4553 err = socket_error();
4554 if (err == EINTR || err == EWOULDBLOCK) {
4555 } else if (err == EINPROGRESS) {
4556 break;
4557 #ifdef _WIN32
4558 } else if (err == WSAEALREADY) {
4559 break;
4560 #endif
4561 } else {
4562 perror("connect");
4563 closesocket(fd);
4564 return -1;
4566 } else {
4567 connected = 1;
4568 break;
4571 s = net_socket_fd_init(vlan, fd, connected);
4572 if (!s)
4573 return -1;
4574 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4575 "socket: connect to %s:%d",
4576 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4577 return 0;
4580 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4582 NetSocketState *s;
4583 int fd;
4584 struct sockaddr_in saddr;
4586 if (parse_host_port(&saddr, host_str) < 0)
4587 return -1;
4590 fd = net_socket_mcast_create(&saddr);
4591 if (fd < 0)
4592 return -1;
4594 s = net_socket_fd_init(vlan, fd, 0);
4595 if (!s)
4596 return -1;
4598 s->dgram_dst = saddr;
4600 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4601 "socket: mcast=%s:%d",
4602 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4603 return 0;
4607 static const char *get_word(char *buf, int buf_size, const char *p)
4609 char *q;
4610 int substring;
4612 substring = 0;
4613 q = buf;
4614 while (*p != '\0') {
4615 if (*p == '\\') {
4616 p++;
4617 if (*p == '\0')
4618 break;
4619 } else if (*p == '\"') {
4620 substring = !substring;
4621 p++;
4622 continue;
4623 } else if (!substring && (*p == ',' || *p == '='))
4624 break;
4625 if (q && (q - buf) < buf_size - 1)
4626 *q++ = *p;
4627 p++;
4629 if (q)
4630 *q = '\0';
4632 return p;
4635 static int get_param_value(char *buf, int buf_size,
4636 const char *tag, const char *str)
4638 const char *p;
4639 char option[128];
4641 p = str;
4642 for(;;) {
4643 p = get_word(option, sizeof(option), p);
4644 if (*p != '=')
4645 break;
4646 p++;
4647 if (!strcmp(tag, option)) {
4648 (void)get_word(buf, buf_size, p);
4649 return strlen(buf);
4650 } else {
4651 p = get_word(NULL, 0, p);
4653 if (*p != ',')
4654 break;
4655 p++;
4657 return 0;
4660 static int check_params(char *buf, int buf_size,
4661 char **params, const char *str)
4663 const char *p;
4664 int i;
4666 p = str;
4667 for(;;) {
4668 p = get_word(buf, buf_size, p);
4669 if (*p != '=')
4670 return -1;
4671 p++;
4672 for(i = 0; params[i] != NULL; i++)
4673 if (!strcmp(params[i], buf))
4674 break;
4675 if (params[i] == NULL)
4676 return -1;
4677 p = get_word(NULL, 0, p);
4678 if (*p != ',')
4679 break;
4680 p++;
4682 return 0;
4686 static int net_client_init(const char *str)
4688 const char *p;
4689 char *q;
4690 char device[64];
4691 char buf[1024];
4692 int vlan_id, ret;
4693 VLANState *vlan;
4695 p = str;
4696 q = device;
4697 while (*p != '\0' && *p != ',') {
4698 if ((q - device) < sizeof(device) - 1)
4699 *q++ = *p;
4700 p++;
4702 *q = '\0';
4703 if (*p == ',')
4704 p++;
4705 vlan_id = 0;
4706 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4707 vlan_id = strtol(buf, NULL, 0);
4709 vlan = qemu_find_vlan(vlan_id);
4710 if (!vlan) {
4711 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4712 return -1;
4714 if (!strcmp(device, "nic")) {
4715 NICInfo *nd;
4716 uint8_t *macaddr;
4718 if (nb_nics >= MAX_NICS) {
4719 fprintf(stderr, "Too Many NICs\n");
4720 return -1;
4722 nd = &nd_table[nb_nics];
4723 macaddr = nd->macaddr;
4724 macaddr[0] = 0x52;
4725 macaddr[1] = 0x54;
4726 macaddr[2] = 0x00;
4727 macaddr[3] = 0x12;
4728 macaddr[4] = 0x34;
4729 macaddr[5] = 0x56 + nb_nics;
4731 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4732 if (parse_macaddr(macaddr, buf) < 0) {
4733 fprintf(stderr, "invalid syntax for ethernet address\n");
4734 return -1;
4737 if (get_param_value(buf, sizeof(buf), "model", p)) {
4738 nd->model = strdup(buf);
4740 nd->vlan = vlan;
4741 nb_nics++;
4742 vlan->nb_guest_devs++;
4743 ret = 0;
4744 } else
4745 if (!strcmp(device, "none")) {
4746 /* does nothing. It is needed to signal that no network cards
4747 are wanted */
4748 ret = 0;
4749 } else
4750 #ifdef CONFIG_SLIRP
4751 if (!strcmp(device, "user")) {
4752 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4753 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4755 vlan->nb_host_devs++;
4756 ret = net_slirp_init(vlan);
4757 } else
4758 #endif
4759 #ifdef _WIN32
4760 if (!strcmp(device, "tap")) {
4761 char ifname[64];
4762 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4763 fprintf(stderr, "tap: no interface name\n");
4764 return -1;
4766 vlan->nb_host_devs++;
4767 ret = tap_win32_init(vlan, ifname);
4768 } else
4769 #else
4770 if (!strcmp(device, "tap")) {
4771 char ifname[64];
4772 char setup_script[1024], down_script[1024];
4773 int fd;
4774 vlan->nb_host_devs++;
4775 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4776 fd = strtol(buf, NULL, 0);
4777 ret = -1;
4778 if (net_tap_fd_init(vlan, fd))
4779 ret = 0;
4780 } else {
4781 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4782 ifname[0] = '\0';
4784 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4785 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4787 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4788 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4790 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4792 } else
4793 #endif
4794 if (!strcmp(device, "socket")) {
4795 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4796 int fd;
4797 fd = strtol(buf, NULL, 0);
4798 ret = -1;
4799 if (net_socket_fd_init(vlan, fd, 1))
4800 ret = 0;
4801 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4802 ret = net_socket_listen_init(vlan, buf);
4803 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4804 ret = net_socket_connect_init(vlan, buf);
4805 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4806 ret = net_socket_mcast_init(vlan, buf);
4807 } else {
4808 fprintf(stderr, "Unknown socket options: %s\n", p);
4809 return -1;
4811 vlan->nb_host_devs++;
4812 } else
4814 fprintf(stderr, "Unknown network device: %s\n", device);
4815 return -1;
4817 if (ret < 0) {
4818 fprintf(stderr, "Could not initialize device '%s'\n", device);
4821 return ret;
4824 void do_info_network(void)
4826 VLANState *vlan;
4827 VLANClientState *vc;
4829 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4830 term_printf("VLAN %d devices:\n", vlan->id);
4831 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4832 term_printf(" %s\n", vc->info_str);
4836 #define HD_ALIAS "file=\"%s\",index=%d,media=disk"
4837 #ifdef TARGET_PPC
4838 #define CDROM_ALIAS "index=1,media=cdrom"
4839 #else
4840 #define CDROM_ALIAS "index=2,media=cdrom"
4841 #endif
4842 #define FD_ALIAS "index=%d,if=floppy"
4843 #define PFLASH_ALIAS "file=\"%s\",if=pflash"
4844 #define MTD_ALIAS "file=\"%s\",if=mtd"
4845 #define SD_ALIAS "index=0,if=sd"
4847 static int drive_add(const char *fmt, ...)
4849 va_list ap;
4851 if (nb_drives_opt >= MAX_DRIVES) {
4852 fprintf(stderr, "qemu: too many drives\n");
4853 exit(1);
4856 va_start(ap, fmt);
4857 vsnprintf(drives_opt[nb_drives_opt], sizeof(drives_opt[0]), fmt, ap);
4858 va_end(ap);
4860 return nb_drives_opt++;
4863 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4865 int index;
4867 /* seek interface, bus and unit */
4869 for (index = 0; index < nb_drives; index++)
4870 if (drives_table[index].type == type &&
4871 drives_table[index].bus == bus &&
4872 drives_table[index].unit == unit)
4873 return index;
4875 return -1;
4878 int drive_get_max_bus(BlockInterfaceType type)
4880 int max_bus;
4881 int index;
4883 max_bus = -1;
4884 for (index = 0; index < nb_drives; index++) {
4885 if(drives_table[index].type == type &&
4886 drives_table[index].bus > max_bus)
4887 max_bus = drives_table[index].bus;
4889 return max_bus;
4892 static int drive_init(const char *str, int snapshot, QEMUMachine *machine)
4894 char buf[128];
4895 char file[1024];
4896 char devname[128];
4897 const char *mediastr = "";
4898 BlockInterfaceType type;
4899 enum { MEDIA_DISK, MEDIA_CDROM } media;
4900 int bus_id, unit_id;
4901 int cyls, heads, secs, translation;
4902 BlockDriverState *bdrv;
4903 int max_devs;
4904 int index;
4905 int cache;
4906 int bdrv_flags;
4907 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4908 "secs", "trans", "media", "snapshot", "file",
4909 "cache", NULL };
4911 if (check_params(buf, sizeof(buf), params, str) < 0) {
4912 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4913 buf, str);
4914 return -1;
4917 file[0] = 0;
4918 cyls = heads = secs = 0;
4919 bus_id = 0;
4920 unit_id = -1;
4921 translation = BIOS_ATA_TRANSLATION_AUTO;
4922 index = -1;
4923 cache = 1;
4925 if (!strcmp(machine->name, "realview") ||
4926 !strcmp(machine->name, "SS-5") ||
4927 !strcmp(machine->name, "SS-10") ||
4928 !strcmp(machine->name, "SS-600MP") ||
4929 !strcmp(machine->name, "versatilepb") ||
4930 !strcmp(machine->name, "versatileab")) {
4931 type = IF_SCSI;
4932 max_devs = MAX_SCSI_DEVS;
4933 strcpy(devname, "scsi");
4934 } else {
4935 type = IF_IDE;
4936 max_devs = MAX_IDE_DEVS;
4937 strcpy(devname, "ide");
4939 media = MEDIA_DISK;
4941 /* extract parameters */
4943 if (get_param_value(buf, sizeof(buf), "bus", str)) {
4944 bus_id = strtol(buf, NULL, 0);
4945 if (bus_id < 0) {
4946 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4947 return -1;
4951 if (get_param_value(buf, sizeof(buf), "unit", str)) {
4952 unit_id = strtol(buf, NULL, 0);
4953 if (unit_id < 0) {
4954 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4955 return -1;
4959 if (get_param_value(buf, sizeof(buf), "if", str)) {
4960 strncpy(devname, buf, sizeof(devname));
4961 if (!strcmp(buf, "ide")) {
4962 type = IF_IDE;
4963 max_devs = MAX_IDE_DEVS;
4964 } else if (!strcmp(buf, "scsi")) {
4965 type = IF_SCSI;
4966 max_devs = MAX_SCSI_DEVS;
4967 } else if (!strcmp(buf, "floppy")) {
4968 type = IF_FLOPPY;
4969 max_devs = 0;
4970 } else if (!strcmp(buf, "pflash")) {
4971 type = IF_PFLASH;
4972 max_devs = 0;
4973 } else if (!strcmp(buf, "mtd")) {
4974 type = IF_MTD;
4975 max_devs = 0;
4976 } else if (!strcmp(buf, "sd")) {
4977 type = IF_SD;
4978 max_devs = 0;
4979 } else {
4980 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
4981 return -1;
4985 if (get_param_value(buf, sizeof(buf), "index", str)) {
4986 index = strtol(buf, NULL, 0);
4987 if (index < 0) {
4988 fprintf(stderr, "qemu: '%s' invalid index\n", str);
4989 return -1;
4993 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
4994 cyls = strtol(buf, NULL, 0);
4997 if (get_param_value(buf, sizeof(buf), "heads", str)) {
4998 heads = strtol(buf, NULL, 0);
5001 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5002 secs = strtol(buf, NULL, 0);
5005 if (cyls || heads || secs) {
5006 if (cyls < 1 || cyls > 16383) {
5007 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5008 return -1;
5010 if (heads < 1 || heads > 16) {
5011 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5012 return -1;
5014 if (secs < 1 || secs > 63) {
5015 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5016 return -1;
5020 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5021 if (!cyls) {
5022 fprintf(stderr,
5023 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5024 str);
5025 return -1;
5027 if (!strcmp(buf, "none"))
5028 translation = BIOS_ATA_TRANSLATION_NONE;
5029 else if (!strcmp(buf, "lba"))
5030 translation = BIOS_ATA_TRANSLATION_LBA;
5031 else if (!strcmp(buf, "auto"))
5032 translation = BIOS_ATA_TRANSLATION_AUTO;
5033 else {
5034 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5035 return -1;
5039 if (get_param_value(buf, sizeof(buf), "media", str)) {
5040 if (!strcmp(buf, "disk")) {
5041 media = MEDIA_DISK;
5042 } else if (!strcmp(buf, "cdrom")) {
5043 if (cyls || secs || heads) {
5044 fprintf(stderr,
5045 "qemu: '%s' invalid physical CHS format\n", str);
5046 return -1;
5048 media = MEDIA_CDROM;
5049 } else {
5050 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5051 return -1;
5055 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5056 if (!strcmp(buf, "on"))
5057 snapshot = 1;
5058 else if (!strcmp(buf, "off"))
5059 snapshot = 0;
5060 else {
5061 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5062 return -1;
5066 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5067 if (!strcmp(buf, "off"))
5068 cache = 0;
5069 else if (!strcmp(buf, "on"))
5070 cache = 1;
5071 else {
5072 fprintf(stderr, "qemu: invalid cache option\n");
5073 return -1;
5077 get_param_value(file, sizeof(file), "file", str);
5079 /* compute bus and unit according index */
5081 if (index != -1) {
5082 if (bus_id != 0 || unit_id != -1) {
5083 fprintf(stderr,
5084 "qemu: '%s' index cannot be used with bus and unit\n", str);
5085 return -1;
5087 if (max_devs == 0)
5089 unit_id = index;
5090 bus_id = 0;
5091 } else {
5092 unit_id = index % max_devs;
5093 bus_id = index / max_devs;
5097 /* if user doesn't specify a unit_id,
5098 * try to find the first free
5101 if (unit_id == -1) {
5102 unit_id = 0;
5103 while (drive_get_index(type, bus_id, unit_id) != -1) {
5104 unit_id++;
5105 if (max_devs && unit_id >= max_devs) {
5106 unit_id -= max_devs;
5107 bus_id++;
5112 /* check unit id */
5114 if (max_devs && unit_id >= max_devs) {
5115 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5116 str, unit_id, max_devs - 1);
5117 return -1;
5121 * ignore multiple definitions
5124 if (drive_get_index(type, bus_id, unit_id) != -1)
5125 return 0;
5127 /* init */
5129 if (type == IF_IDE || type == IF_SCSI)
5130 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5131 if (max_devs)
5132 snprintf(buf, sizeof(buf), "%s%i%s%i",
5133 devname, bus_id, mediastr, unit_id);
5134 else
5135 snprintf(buf, sizeof(buf), "%s%s%i",
5136 devname, mediastr, unit_id);
5137 bdrv = bdrv_new(buf);
5138 drives_table[nb_drives].bdrv = bdrv;
5139 drives_table[nb_drives].type = type;
5140 drives_table[nb_drives].bus = bus_id;
5141 drives_table[nb_drives].unit = unit_id;
5142 nb_drives++;
5144 switch(type) {
5145 case IF_IDE:
5146 case IF_SCSI:
5147 switch(media) {
5148 case MEDIA_DISK:
5149 if (cyls != 0) {
5150 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5151 bdrv_set_translation_hint(bdrv, translation);
5153 break;
5154 case MEDIA_CDROM:
5155 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5156 break;
5158 break;
5159 case IF_SD:
5160 /* FIXME: This isn't really a floppy, but it's a reasonable
5161 approximation. */
5162 case IF_FLOPPY:
5163 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5164 break;
5165 case IF_PFLASH:
5166 case IF_MTD:
5167 break;
5169 if (!file[0])
5170 return 0;
5171 bdrv_flags = 0;
5172 if (snapshot)
5173 bdrv_flags |= BDRV_O_SNAPSHOT;
5174 if (!cache)
5175 bdrv_flags |= BDRV_O_DIRECT;
5176 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5177 fprintf(stderr, "qemu: could not open disk image %s\n",
5178 file);
5179 return -1;
5181 return 0;
5184 /***********************************************************/
5185 /* USB devices */
5187 static USBPort *used_usb_ports;
5188 static USBPort *free_usb_ports;
5190 /* ??? Maybe change this to register a hub to keep track of the topology. */
5191 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5192 usb_attachfn attach)
5194 port->opaque = opaque;
5195 port->index = index;
5196 port->attach = attach;
5197 port->next = free_usb_ports;
5198 free_usb_ports = port;
5201 static int usb_device_add(const char *devname)
5203 const char *p;
5204 USBDevice *dev;
5205 USBPort *port;
5207 if (!free_usb_ports)
5208 return -1;
5210 if (strstart(devname, "host:", &p)) {
5211 dev = usb_host_device_open(p);
5212 } else if (!strcmp(devname, "mouse")) {
5213 dev = usb_mouse_init();
5214 } else if (!strcmp(devname, "tablet")) {
5215 dev = usb_tablet_init();
5216 } else if (!strcmp(devname, "keyboard")) {
5217 dev = usb_keyboard_init();
5218 } else if (strstart(devname, "disk:", &p)) {
5219 dev = usb_msd_init(p);
5220 } else if (!strcmp(devname, "wacom-tablet")) {
5221 dev = usb_wacom_init();
5222 } else {
5223 return -1;
5225 if (!dev)
5226 return -1;
5228 /* Find a USB port to add the device to. */
5229 port = free_usb_ports;
5230 if (!port->next) {
5231 USBDevice *hub;
5233 /* Create a new hub and chain it on. */
5234 free_usb_ports = NULL;
5235 port->next = used_usb_ports;
5236 used_usb_ports = port;
5238 hub = usb_hub_init(VM_USB_HUB_SIZE);
5239 usb_attach(port, hub);
5240 port = free_usb_ports;
5243 free_usb_ports = port->next;
5244 port->next = used_usb_ports;
5245 used_usb_ports = port;
5246 usb_attach(port, dev);
5247 return 0;
5250 static int usb_device_del(const char *devname)
5252 USBPort *port;
5253 USBPort **lastp;
5254 USBDevice *dev;
5255 int bus_num, addr;
5256 const char *p;
5258 if (!used_usb_ports)
5259 return -1;
5261 p = strchr(devname, '.');
5262 if (!p)
5263 return -1;
5264 bus_num = strtoul(devname, NULL, 0);
5265 addr = strtoul(p + 1, NULL, 0);
5266 if (bus_num != 0)
5267 return -1;
5269 lastp = &used_usb_ports;
5270 port = used_usb_ports;
5271 while (port && port->dev->addr != addr) {
5272 lastp = &port->next;
5273 port = port->next;
5276 if (!port)
5277 return -1;
5279 dev = port->dev;
5280 *lastp = port->next;
5281 usb_attach(port, NULL);
5282 dev->handle_destroy(dev);
5283 port->next = free_usb_ports;
5284 free_usb_ports = port;
5285 return 0;
5288 void do_usb_add(const char *devname)
5290 int ret;
5291 ret = usb_device_add(devname);
5292 if (ret < 0)
5293 term_printf("Could not add USB device '%s'\n", devname);
5296 void do_usb_del(const char *devname)
5298 int ret;
5299 ret = usb_device_del(devname);
5300 if (ret < 0)
5301 term_printf("Could not remove USB device '%s'\n", devname);
5304 void usb_info(void)
5306 USBDevice *dev;
5307 USBPort *port;
5308 const char *speed_str;
5310 if (!usb_enabled) {
5311 term_printf("USB support not enabled\n");
5312 return;
5315 for (port = used_usb_ports; port; port = port->next) {
5316 dev = port->dev;
5317 if (!dev)
5318 continue;
5319 switch(dev->speed) {
5320 case USB_SPEED_LOW:
5321 speed_str = "1.5";
5322 break;
5323 case USB_SPEED_FULL:
5324 speed_str = "12";
5325 break;
5326 case USB_SPEED_HIGH:
5327 speed_str = "480";
5328 break;
5329 default:
5330 speed_str = "?";
5331 break;
5333 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5334 0, dev->addr, speed_str, dev->devname);
5338 /***********************************************************/
5339 /* PCMCIA/Cardbus */
5341 static struct pcmcia_socket_entry_s {
5342 struct pcmcia_socket_s *socket;
5343 struct pcmcia_socket_entry_s *next;
5344 } *pcmcia_sockets = 0;
5346 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5348 struct pcmcia_socket_entry_s *entry;
5350 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5351 entry->socket = socket;
5352 entry->next = pcmcia_sockets;
5353 pcmcia_sockets = entry;
5356 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5358 struct pcmcia_socket_entry_s *entry, **ptr;
5360 ptr = &pcmcia_sockets;
5361 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5362 if (entry->socket == socket) {
5363 *ptr = entry->next;
5364 qemu_free(entry);
5368 void pcmcia_info(void)
5370 struct pcmcia_socket_entry_s *iter;
5371 if (!pcmcia_sockets)
5372 term_printf("No PCMCIA sockets\n");
5374 for (iter = pcmcia_sockets; iter; iter = iter->next)
5375 term_printf("%s: %s\n", iter->socket->slot_string,
5376 iter->socket->attached ? iter->socket->card_string :
5377 "Empty");
5380 /***********************************************************/
5381 /* dumb display */
5383 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5387 static void dumb_resize(DisplayState *ds, int w, int h)
5391 static void dumb_refresh(DisplayState *ds)
5393 #if defined(CONFIG_SDL)
5394 vga_hw_update();
5395 #endif
5398 static void dumb_display_init(DisplayState *ds)
5400 ds->data = NULL;
5401 ds->linesize = 0;
5402 ds->depth = 0;
5403 ds->dpy_update = dumb_update;
5404 ds->dpy_resize = dumb_resize;
5405 ds->dpy_refresh = dumb_refresh;
5408 /***********************************************************/
5409 /* I/O handling */
5411 #define MAX_IO_HANDLERS 64
5413 typedef struct IOHandlerRecord {
5414 int fd;
5415 IOCanRWHandler *fd_read_poll;
5416 IOHandler *fd_read;
5417 IOHandler *fd_write;
5418 int deleted;
5419 void *opaque;
5420 /* temporary data */
5421 struct pollfd *ufd;
5422 struct IOHandlerRecord *next;
5423 } IOHandlerRecord;
5425 static IOHandlerRecord *first_io_handler;
5427 /* XXX: fd_read_poll should be suppressed, but an API change is
5428 necessary in the character devices to suppress fd_can_read(). */
5429 int qemu_set_fd_handler2(int fd,
5430 IOCanRWHandler *fd_read_poll,
5431 IOHandler *fd_read,
5432 IOHandler *fd_write,
5433 void *opaque)
5435 IOHandlerRecord **pioh, *ioh;
5437 if (!fd_read && !fd_write) {
5438 pioh = &first_io_handler;
5439 for(;;) {
5440 ioh = *pioh;
5441 if (ioh == NULL)
5442 break;
5443 if (ioh->fd == fd) {
5444 ioh->deleted = 1;
5445 break;
5447 pioh = &ioh->next;
5449 } else {
5450 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5451 if (ioh->fd == fd)
5452 goto found;
5454 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5455 if (!ioh)
5456 return -1;
5457 ioh->next = first_io_handler;
5458 first_io_handler = ioh;
5459 found:
5460 ioh->fd = fd;
5461 ioh->fd_read_poll = fd_read_poll;
5462 ioh->fd_read = fd_read;
5463 ioh->fd_write = fd_write;
5464 ioh->opaque = opaque;
5465 ioh->deleted = 0;
5467 return 0;
5470 int qemu_set_fd_handler(int fd,
5471 IOHandler *fd_read,
5472 IOHandler *fd_write,
5473 void *opaque)
5475 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5478 /***********************************************************/
5479 /* Polling handling */
5481 typedef struct PollingEntry {
5482 PollingFunc *func;
5483 void *opaque;
5484 struct PollingEntry *next;
5485 } PollingEntry;
5487 static PollingEntry *first_polling_entry;
5489 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5491 PollingEntry **ppe, *pe;
5492 pe = qemu_mallocz(sizeof(PollingEntry));
5493 if (!pe)
5494 return -1;
5495 pe->func = func;
5496 pe->opaque = opaque;
5497 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5498 *ppe = pe;
5499 return 0;
5502 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5504 PollingEntry **ppe, *pe;
5505 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5506 pe = *ppe;
5507 if (pe->func == func && pe->opaque == opaque) {
5508 *ppe = pe->next;
5509 qemu_free(pe);
5510 break;
5515 #ifdef _WIN32
5516 /***********************************************************/
5517 /* Wait objects support */
5518 typedef struct WaitObjects {
5519 int num;
5520 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5521 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5522 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5523 } WaitObjects;
5525 static WaitObjects wait_objects = {0};
5527 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5529 WaitObjects *w = &wait_objects;
5531 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5532 return -1;
5533 w->events[w->num] = handle;
5534 w->func[w->num] = func;
5535 w->opaque[w->num] = opaque;
5536 w->num++;
5537 return 0;
5540 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5542 int i, found;
5543 WaitObjects *w = &wait_objects;
5545 found = 0;
5546 for (i = 0; i < w->num; i++) {
5547 if (w->events[i] == handle)
5548 found = 1;
5549 if (found) {
5550 w->events[i] = w->events[i + 1];
5551 w->func[i] = w->func[i + 1];
5552 w->opaque[i] = w->opaque[i + 1];
5555 if (found)
5556 w->num--;
5558 #endif
5560 #define SELF_ANNOUNCE_ROUNDS 5
5561 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5562 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5563 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5565 static int announce_self_create(uint8_t *buf,
5566 uint8_t *mac_addr)
5568 uint32_t magic = EXPERIMENTAL_MAGIC;
5569 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5571 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5573 memset(buf, 0xff, 6); /* h_dst */
5574 memcpy(buf + 6, mac_addr, 6); /* h_src */
5575 memcpy(buf + 12, &proto, 2); /* h_proto */
5576 memcpy(buf + 14, &magic, 4); /* magic */
5578 return 18; /* len */
5581 static void qemu_announce_self(void)
5583 int i, j, len;
5584 VLANState *vlan;
5585 VLANClientState *vc;
5586 uint8_t buf[256];
5588 for (i = 0; i < nb_nics; i++) {
5589 len = announce_self_create(buf, nd_table[i].macaddr);
5590 vlan = nd_table[i].vlan;
5591 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5592 if (vc->fd_read == tap_receive) /* send only if tap */
5593 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5594 vc->fd_read(vc->opaque, buf, len);
5599 /***********************************************************/
5600 /* savevm/loadvm support */
5602 #define IO_BUF_SIZE 32768
5604 struct QEMUFile {
5605 QEMUFilePutBufferFunc *put_buffer;
5606 QEMUFileGetBufferFunc *get_buffer;
5607 QEMUFileCloseFunc *close;
5608 void *opaque;
5610 int64_t buf_offset; /* start of buffer when writing, end of buffer
5611 when reading */
5612 int buf_index;
5613 int buf_size; /* 0 when writing */
5614 uint8_t buf[IO_BUF_SIZE];
5617 typedef struct QEMUFileFD
5619 int fd;
5620 } QEMUFileFD;
5622 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5624 QEMUFileFD *s = opaque;
5625 int offset = 0;
5626 ssize_t len;
5628 again:
5629 len = read(s->fd, buf + offset, size - offset);
5630 if (len == -1) {
5631 if (errno == EINTR || errno == EAGAIN)
5632 goto again;
5635 return len;
5638 QEMUFile *qemu_fopen_fd(int fd)
5640 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5641 s->fd = fd;
5642 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5645 typedef struct QEMUFileUnix
5647 FILE *outfile;
5648 } QEMUFileUnix;
5650 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5652 QEMUFileUnix *s = opaque;
5653 fseek(s->outfile, pos, SEEK_SET);
5654 fwrite(buf, 1, size, s->outfile);
5657 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5659 QEMUFileUnix *s = opaque;
5660 fseek(s->outfile, pos, SEEK_SET);
5661 return fread(buf, 1, size, s->outfile);
5664 static void file_close(void *opaque)
5666 QEMUFileUnix *s = opaque;
5667 fclose(s->outfile);
5668 qemu_free(s);
5671 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5673 QEMUFileUnix *s;
5675 s = qemu_mallocz(sizeof(QEMUFileUnix));
5676 if (!s)
5677 return NULL;
5679 s->outfile = fopen(filename, mode);
5680 if (!s->outfile)
5681 goto fail;
5683 if (!strcmp(mode, "wb"))
5684 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5685 else if (!strcmp(mode, "rb"))
5686 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5688 fail:
5689 if (s->outfile)
5690 fclose(s->outfile);
5691 qemu_free(s);
5692 return NULL;
5695 typedef struct QEMUFileBdrv
5697 BlockDriverState *bs;
5698 int64_t base_offset;
5699 } QEMUFileBdrv;
5701 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5703 QEMUFileBdrv *s = opaque;
5704 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5707 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5709 QEMUFileBdrv *s = opaque;
5710 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5713 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5715 QEMUFileBdrv *s;
5717 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5718 if (!s)
5719 return NULL;
5721 s->bs = bs;
5722 s->base_offset = offset;
5724 if (is_writable)
5725 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5727 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5730 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5731 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5733 QEMUFile *f;
5735 f = qemu_mallocz(sizeof(QEMUFile));
5736 if (!f)
5737 return NULL;
5739 f->opaque = opaque;
5740 f->put_buffer = put_buffer;
5741 f->get_buffer = get_buffer;
5742 f->close = close;
5744 return f;
5747 void qemu_fflush(QEMUFile *f)
5749 if (!f->put_buffer)
5750 return;
5752 if (f->buf_index > 0) {
5753 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5754 f->buf_offset += f->buf_index;
5755 f->buf_index = 0;
5759 static void qemu_fill_buffer(QEMUFile *f)
5761 int len;
5763 if (!f->get_buffer)
5764 return;
5766 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5767 if (len < 0)
5768 len = 0;
5770 f->buf_index = 0;
5771 f->buf_size = len;
5772 f->buf_offset += len;
5775 void qemu_fclose(QEMUFile *f)
5777 qemu_fflush(f);
5778 if (f->close)
5779 f->close(f->opaque);
5780 qemu_free(f);
5783 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5785 int l;
5786 while (size > 0) {
5787 l = IO_BUF_SIZE - f->buf_index;
5788 if (l > size)
5789 l = size;
5790 memcpy(f->buf + f->buf_index, buf, l);
5791 f->buf_index += l;
5792 buf += l;
5793 size -= l;
5794 if (f->buf_index >= IO_BUF_SIZE)
5795 qemu_fflush(f);
5799 void qemu_put_byte(QEMUFile *f, int v)
5801 f->buf[f->buf_index++] = v;
5802 if (f->buf_index >= IO_BUF_SIZE)
5803 qemu_fflush(f);
5806 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5808 int size, l;
5810 size = size1;
5811 while (size > 0) {
5812 l = f->buf_size - f->buf_index;
5813 if (l == 0) {
5814 qemu_fill_buffer(f);
5815 l = f->buf_size - f->buf_index;
5816 if (l == 0)
5817 break;
5819 if (l > size)
5820 l = size;
5821 memcpy(buf, f->buf + f->buf_index, l);
5822 f->buf_index += l;
5823 buf += l;
5824 size -= l;
5826 return size1 - size;
5829 int qemu_get_byte(QEMUFile *f)
5831 if (f->buf_index >= f->buf_size) {
5832 qemu_fill_buffer(f);
5833 if (f->buf_index >= f->buf_size)
5834 return 0;
5836 return f->buf[f->buf_index++];
5839 int64_t qemu_ftell(QEMUFile *f)
5841 return f->buf_offset - f->buf_size + f->buf_index;
5844 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5846 if (whence == SEEK_SET) {
5847 /* nothing to do */
5848 } else if (whence == SEEK_CUR) {
5849 pos += qemu_ftell(f);
5850 } else {
5851 /* SEEK_END not supported */
5852 return -1;
5854 if (f->put_buffer) {
5855 qemu_fflush(f);
5856 f->buf_offset = pos;
5857 } else {
5858 f->buf_offset = pos;
5859 f->buf_index = 0;
5860 f->buf_size = 0;
5862 return pos;
5865 void qemu_put_be16(QEMUFile *f, unsigned int v)
5867 qemu_put_byte(f, v >> 8);
5868 qemu_put_byte(f, v);
5871 void qemu_put_be32(QEMUFile *f, unsigned int v)
5873 qemu_put_byte(f, v >> 24);
5874 qemu_put_byte(f, v >> 16);
5875 qemu_put_byte(f, v >> 8);
5876 qemu_put_byte(f, v);
5879 void qemu_put_be64(QEMUFile *f, uint64_t v)
5881 qemu_put_be32(f, v >> 32);
5882 qemu_put_be32(f, v);
5885 unsigned int qemu_get_be16(QEMUFile *f)
5887 unsigned int v;
5888 v = qemu_get_byte(f) << 8;
5889 v |= qemu_get_byte(f);
5890 return v;
5893 unsigned int qemu_get_be32(QEMUFile *f)
5895 unsigned int v;
5896 v = qemu_get_byte(f) << 24;
5897 v |= qemu_get_byte(f) << 16;
5898 v |= qemu_get_byte(f) << 8;
5899 v |= qemu_get_byte(f);
5900 return v;
5903 uint64_t qemu_get_be64(QEMUFile *f)
5905 uint64_t v;
5906 v = (uint64_t)qemu_get_be32(f) << 32;
5907 v |= qemu_get_be32(f);
5908 return v;
5911 typedef struct SaveStateEntry {
5912 char idstr[256];
5913 int instance_id;
5914 int version_id;
5915 SaveStateHandler *save_state;
5916 LoadStateHandler *load_state;
5917 void *opaque;
5918 struct SaveStateEntry *next;
5919 } SaveStateEntry;
5921 static SaveStateEntry *first_se;
5923 int register_savevm(const char *idstr,
5924 int instance_id,
5925 int version_id,
5926 SaveStateHandler *save_state,
5927 LoadStateHandler *load_state,
5928 void *opaque)
5930 SaveStateEntry *se, **pse;
5932 se = qemu_malloc(sizeof(SaveStateEntry));
5933 if (!se)
5934 return -1;
5935 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5936 se->instance_id = instance_id;
5937 se->version_id = version_id;
5938 se->save_state = save_state;
5939 se->load_state = load_state;
5940 se->opaque = opaque;
5941 se->next = NULL;
5943 /* add at the end of list */
5944 pse = &first_se;
5945 while (*pse != NULL)
5946 pse = &(*pse)->next;
5947 *pse = se;
5948 return 0;
5951 #define QEMU_VM_FILE_MAGIC 0x5145564d
5952 #define QEMU_VM_FILE_VERSION 0x00000002
5954 static int qemu_savevm_state(QEMUFile *f)
5956 SaveStateEntry *se;
5957 int len, ret;
5958 int64_t cur_pos, len_pos, total_len_pos;
5960 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5961 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5962 total_len_pos = qemu_ftell(f);
5963 qemu_put_be64(f, 0); /* total size */
5965 for(se = first_se; se != NULL; se = se->next) {
5966 /* ID string */
5967 len = strlen(se->idstr);
5968 qemu_put_byte(f, len);
5969 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5971 qemu_put_be32(f, se->instance_id);
5972 qemu_put_be32(f, se->version_id);
5974 /* record size: filled later */
5975 len_pos = qemu_ftell(f);
5976 qemu_put_be32(f, 0);
5977 se->save_state(f, se->opaque);
5979 /* fill record size */
5980 cur_pos = qemu_ftell(f);
5981 len = cur_pos - len_pos - 4;
5982 qemu_fseek(f, len_pos, SEEK_SET);
5983 qemu_put_be32(f, len);
5984 qemu_fseek(f, cur_pos, SEEK_SET);
5986 cur_pos = qemu_ftell(f);
5987 qemu_fseek(f, total_len_pos, SEEK_SET);
5988 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5989 qemu_fseek(f, cur_pos, SEEK_SET);
5991 ret = 0;
5992 return ret;
5995 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5997 SaveStateEntry *se;
5999 for(se = first_se; se != NULL; se = se->next) {
6000 if (!strcmp(se->idstr, idstr) &&
6001 instance_id == se->instance_id)
6002 return se;
6004 return NULL;
6007 static int qemu_loadvm_state(QEMUFile *f)
6009 SaveStateEntry *se;
6010 int len, ret, instance_id, record_len, version_id;
6011 int64_t total_len, end_pos, cur_pos;
6012 unsigned int v;
6013 char idstr[256];
6015 v = qemu_get_be32(f);
6016 if (v != QEMU_VM_FILE_MAGIC)
6017 goto fail;
6018 v = qemu_get_be32(f);
6019 if (v != QEMU_VM_FILE_VERSION) {
6020 fail:
6021 ret = -1;
6022 goto the_end;
6024 total_len = qemu_get_be64(f);
6025 end_pos = total_len + qemu_ftell(f);
6026 for(;;) {
6027 if (qemu_ftell(f) >= end_pos)
6028 break;
6029 len = qemu_get_byte(f);
6030 qemu_get_buffer(f, (uint8_t *)idstr, len);
6031 idstr[len] = '\0';
6032 instance_id = qemu_get_be32(f);
6033 version_id = qemu_get_be32(f);
6034 record_len = qemu_get_be32(f);
6035 #if 0
6036 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6037 idstr, instance_id, version_id, record_len);
6038 #endif
6039 cur_pos = qemu_ftell(f);
6040 se = find_se(idstr, instance_id);
6041 if (!se) {
6042 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6043 instance_id, idstr);
6044 } else {
6045 ret = se->load_state(f, se->opaque, version_id);
6046 if (ret < 0) {
6047 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6048 instance_id, idstr);
6049 goto the_end;
6052 /* always seek to exact end of record */
6053 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6055 ret = 0;
6056 the_end:
6057 return ret;
6060 int qemu_live_savevm_state(QEMUFile *f)
6062 SaveStateEntry *se;
6063 int len, ret;
6065 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6066 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6068 for(se = first_se; se != NULL; se = se->next) {
6069 len = strlen(se->idstr);
6071 qemu_put_byte(f, len);
6072 qemu_put_buffer(f, se->idstr, len);
6073 qemu_put_be32(f, se->instance_id);
6074 qemu_put_be32(f, se->version_id);
6076 se->save_state(f, se->opaque);
6079 qemu_put_byte(f, 0);
6081 ret = 0;
6082 return ret;
6085 int qemu_live_loadvm_state(QEMUFile *f)
6087 SaveStateEntry *se;
6088 int len, ret, instance_id, version_id;
6089 unsigned int v;
6090 char idstr[256];
6092 v = qemu_get_be32(f);
6093 if (v != QEMU_VM_FILE_MAGIC)
6094 goto fail;
6095 v = qemu_get_be32(f);
6096 if (v != QEMU_VM_FILE_VERSION) {
6097 fail:
6098 ret = -1;
6099 goto the_end;
6102 for(;;) {
6103 len = qemu_get_byte(f);
6104 if (len == 0)
6105 break;
6106 qemu_get_buffer(f, idstr, len);
6107 idstr[len] = '\0';
6108 instance_id = qemu_get_be32(f);
6109 version_id = qemu_get_be32(f);
6110 se = find_se(idstr, instance_id);
6111 if (!se) {
6112 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6113 instance_id, idstr);
6114 } else {
6115 if (version_id > se->version_id) { /* src version > dst version */
6116 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6117 idstr, version_id, se->version_id);
6118 ret = -1;
6119 goto the_end;
6121 ret = se->load_state(f, se->opaque, version_id);
6122 if (ret < 0) {
6123 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6124 instance_id, idstr);
6125 goto the_end;
6129 ret = 0;
6131 qemu_announce_self();
6133 the_end:
6134 return ret;
6137 /* device can contain snapshots */
6138 static int bdrv_can_snapshot(BlockDriverState *bs)
6140 return (bs &&
6141 !bdrv_is_removable(bs) &&
6142 !bdrv_is_read_only(bs));
6145 /* device must be snapshots in order to have a reliable snapshot */
6146 static int bdrv_has_snapshot(BlockDriverState *bs)
6148 return (bs &&
6149 !bdrv_is_removable(bs) &&
6150 !bdrv_is_read_only(bs));
6153 static BlockDriverState *get_bs_snapshots(void)
6155 BlockDriverState *bs;
6156 int i;
6158 if (bs_snapshots)
6159 return bs_snapshots;
6160 for(i = 0; i <= nb_drives; i++) {
6161 bs = drives_table[i].bdrv;
6162 if (bdrv_can_snapshot(bs))
6163 goto ok;
6165 return NULL;
6167 bs_snapshots = bs;
6168 return bs;
6171 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6172 const char *name)
6174 QEMUSnapshotInfo *sn_tab, *sn;
6175 int nb_sns, i, ret;
6177 ret = -ENOENT;
6178 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6179 if (nb_sns < 0)
6180 return ret;
6181 for(i = 0; i < nb_sns; i++) {
6182 sn = &sn_tab[i];
6183 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6184 *sn_info = *sn;
6185 ret = 0;
6186 break;
6189 qemu_free(sn_tab);
6190 return ret;
6193 void do_savevm(const char *name)
6195 BlockDriverState *bs, *bs1;
6196 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6197 int must_delete, ret, i;
6198 BlockDriverInfo bdi1, *bdi = &bdi1;
6199 QEMUFile *f;
6200 int saved_vm_running;
6201 #ifdef _WIN32
6202 struct _timeb tb;
6203 #else
6204 struct timeval tv;
6205 #endif
6207 bs = get_bs_snapshots();
6208 if (!bs) {
6209 term_printf("No block device can accept snapshots\n");
6210 return;
6213 /* ??? Should this occur after vm_stop? */
6214 qemu_aio_flush();
6216 saved_vm_running = vm_running;
6217 vm_stop(0);
6219 must_delete = 0;
6220 if (name) {
6221 ret = bdrv_snapshot_find(bs, old_sn, name);
6222 if (ret >= 0) {
6223 must_delete = 1;
6226 memset(sn, 0, sizeof(*sn));
6227 if (must_delete) {
6228 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6229 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6230 } else {
6231 if (name)
6232 pstrcpy(sn->name, sizeof(sn->name), name);
6235 /* fill auxiliary fields */
6236 #ifdef _WIN32
6237 _ftime(&tb);
6238 sn->date_sec = tb.time;
6239 sn->date_nsec = tb.millitm * 1000000;
6240 #else
6241 gettimeofday(&tv, NULL);
6242 sn->date_sec = tv.tv_sec;
6243 sn->date_nsec = tv.tv_usec * 1000;
6244 #endif
6245 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6247 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6248 term_printf("Device %s does not support VM state snapshots\n",
6249 bdrv_get_device_name(bs));
6250 goto the_end;
6253 /* save the VM state */
6254 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6255 if (!f) {
6256 term_printf("Could not open VM state file\n");
6257 goto the_end;
6259 ret = qemu_savevm_state(f);
6260 sn->vm_state_size = qemu_ftell(f);
6261 qemu_fclose(f);
6262 if (ret < 0) {
6263 term_printf("Error %d while writing VM\n", ret);
6264 goto the_end;
6267 /* create the snapshots */
6269 for(i = 0; i < nb_drives; i++) {
6270 bs1 = drives_table[i].bdrv;
6271 if (bdrv_has_snapshot(bs1)) {
6272 if (must_delete) {
6273 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6274 if (ret < 0) {
6275 term_printf("Error while deleting snapshot on '%s'\n",
6276 bdrv_get_device_name(bs1));
6279 ret = bdrv_snapshot_create(bs1, sn);
6280 if (ret < 0) {
6281 term_printf("Error while creating snapshot on '%s'\n",
6282 bdrv_get_device_name(bs1));
6287 the_end:
6288 if (saved_vm_running)
6289 vm_start();
6292 void do_loadvm(const char *name)
6294 BlockDriverState *bs, *bs1;
6295 BlockDriverInfo bdi1, *bdi = &bdi1;
6296 QEMUFile *f;
6297 int i, ret;
6298 int saved_vm_running;
6300 bs = get_bs_snapshots();
6301 if (!bs) {
6302 term_printf("No block device supports snapshots\n");
6303 return;
6306 /* Flush all IO requests so they don't interfere with the new state. */
6307 qemu_aio_flush();
6309 saved_vm_running = vm_running;
6310 vm_stop(0);
6312 for(i = 0; i <= nb_drives; i++) {
6313 bs1 = drives_table[i].bdrv;
6314 if (bdrv_has_snapshot(bs1)) {
6315 ret = bdrv_snapshot_goto(bs1, name);
6316 if (ret < 0) {
6317 if (bs != bs1)
6318 term_printf("Warning: ");
6319 switch(ret) {
6320 case -ENOTSUP:
6321 term_printf("Snapshots not supported on device '%s'\n",
6322 bdrv_get_device_name(bs1));
6323 break;
6324 case -ENOENT:
6325 term_printf("Could not find snapshot '%s' on device '%s'\n",
6326 name, bdrv_get_device_name(bs1));
6327 break;
6328 default:
6329 term_printf("Error %d while activating snapshot on '%s'\n",
6330 ret, bdrv_get_device_name(bs1));
6331 break;
6333 /* fatal on snapshot block device */
6334 if (bs == bs1)
6335 goto the_end;
6340 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6341 term_printf("Device %s does not support VM state snapshots\n",
6342 bdrv_get_device_name(bs));
6343 return;
6346 /* restore the VM state */
6347 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6348 if (!f) {
6349 term_printf("Could not open VM state file\n");
6350 goto the_end;
6352 ret = qemu_loadvm_state(f);
6353 qemu_fclose(f);
6354 if (ret < 0) {
6355 term_printf("Error %d while loading VM state\n", ret);
6357 the_end:
6358 if (saved_vm_running)
6359 vm_start();
6362 void do_delvm(const char *name)
6364 BlockDriverState *bs, *bs1;
6365 int i, ret;
6367 bs = get_bs_snapshots();
6368 if (!bs) {
6369 term_printf("No block device supports snapshots\n");
6370 return;
6373 for(i = 0; i <= nb_drives; i++) {
6374 bs1 = drives_table[i].bdrv;
6375 if (bdrv_has_snapshot(bs1)) {
6376 ret = bdrv_snapshot_delete(bs1, name);
6377 if (ret < 0) {
6378 if (ret == -ENOTSUP)
6379 term_printf("Snapshots not supported on device '%s'\n",
6380 bdrv_get_device_name(bs1));
6381 else
6382 term_printf("Error %d while deleting snapshot on '%s'\n",
6383 ret, bdrv_get_device_name(bs1));
6389 void do_info_snapshots(void)
6391 BlockDriverState *bs, *bs1;
6392 QEMUSnapshotInfo *sn_tab, *sn;
6393 int nb_sns, i;
6394 char buf[256];
6396 bs = get_bs_snapshots();
6397 if (!bs) {
6398 term_printf("No available block device supports snapshots\n");
6399 return;
6401 term_printf("Snapshot devices:");
6402 for(i = 0; i <= nb_drives; i++) {
6403 bs1 = drives_table[i].bdrv;
6404 if (bdrv_has_snapshot(bs1)) {
6405 if (bs == bs1)
6406 term_printf(" %s", bdrv_get_device_name(bs1));
6409 term_printf("\n");
6411 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6412 if (nb_sns < 0) {
6413 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6414 return;
6416 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6417 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6418 for(i = 0; i < nb_sns; i++) {
6419 sn = &sn_tab[i];
6420 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6422 qemu_free(sn_tab);
6425 /***********************************************************/
6426 /* cpu save/restore */
6428 #if defined(TARGET_I386)
6430 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6432 qemu_put_be32(f, dt->selector);
6433 qemu_put_betl(f, dt->base);
6434 qemu_put_be32(f, dt->limit);
6435 qemu_put_be32(f, dt->flags);
6438 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6440 dt->selector = qemu_get_be32(f);
6441 dt->base = qemu_get_betl(f);
6442 dt->limit = qemu_get_be32(f);
6443 dt->flags = qemu_get_be32(f);
6446 void cpu_save(QEMUFile *f, void *opaque)
6448 CPUState *env = opaque;
6449 uint16_t fptag, fpus, fpuc, fpregs_format;
6450 uint32_t hflags;
6451 int i;
6453 #ifdef USE_KVM
6454 if (kvm_allowed)
6455 kvm_save_registers(env);
6456 #endif
6458 for(i = 0; i < CPU_NB_REGS; i++)
6459 qemu_put_betls(f, &env->regs[i]);
6460 qemu_put_betls(f, &env->eip);
6461 qemu_put_betls(f, &env->eflags);
6462 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6463 qemu_put_be32s(f, &hflags);
6465 /* FPU */
6466 fpuc = env->fpuc;
6467 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6468 fptag = 0;
6469 for(i = 0; i < 8; i++) {
6470 fptag |= ((!env->fptags[i]) << i);
6473 qemu_put_be16s(f, &fpuc);
6474 qemu_put_be16s(f, &fpus);
6475 qemu_put_be16s(f, &fptag);
6477 #ifdef USE_X86LDOUBLE
6478 fpregs_format = 0;
6479 #else
6480 fpregs_format = 1;
6481 #endif
6482 qemu_put_be16s(f, &fpregs_format);
6484 for(i = 0; i < 8; i++) {
6485 #ifdef USE_X86LDOUBLE
6487 uint64_t mant;
6488 uint16_t exp;
6489 /* we save the real CPU data (in case of MMX usage only 'mant'
6490 contains the MMX register */
6491 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6492 qemu_put_be64(f, mant);
6493 qemu_put_be16(f, exp);
6495 #else
6496 /* if we use doubles for float emulation, we save the doubles to
6497 avoid losing information in case of MMX usage. It can give
6498 problems if the image is restored on a CPU where long
6499 doubles are used instead. */
6500 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6501 #endif
6504 for(i = 0; i < 6; i++)
6505 cpu_put_seg(f, &env->segs[i]);
6506 cpu_put_seg(f, &env->ldt);
6507 cpu_put_seg(f, &env->tr);
6508 cpu_put_seg(f, &env->gdt);
6509 cpu_put_seg(f, &env->idt);
6511 qemu_put_be32s(f, &env->sysenter_cs);
6512 qemu_put_be32s(f, &env->sysenter_esp);
6513 qemu_put_be32s(f, &env->sysenter_eip);
6515 qemu_put_betls(f, &env->cr[0]);
6516 qemu_put_betls(f, &env->cr[2]);
6517 qemu_put_betls(f, &env->cr[3]);
6518 qemu_put_betls(f, &env->cr[4]);
6520 for(i = 0; i < 8; i++)
6521 qemu_put_betls(f, &env->dr[i]);
6523 /* MMU */
6524 qemu_put_be32s(f, &env->a20_mask);
6526 /* XMM */
6527 qemu_put_be32s(f, &env->mxcsr);
6528 for(i = 0; i < CPU_NB_REGS; i++) {
6529 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6530 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6533 #ifdef TARGET_X86_64
6534 qemu_put_be64s(f, &env->efer);
6535 qemu_put_be64s(f, &env->star);
6536 qemu_put_be64s(f, &env->lstar);
6537 qemu_put_be64s(f, &env->cstar);
6538 qemu_put_be64s(f, &env->fmask);
6539 qemu_put_be64s(f, &env->kernelgsbase);
6540 #endif
6541 qemu_put_be32s(f, &env->smbase);
6543 #ifdef USE_KVM
6544 if (kvm_allowed) {
6545 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6546 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6548 qemu_put_be64s(f, &env->tsc);
6550 #endif
6554 #ifdef USE_X86LDOUBLE
6555 /* XXX: add that in a FPU generic layer */
6556 union x86_longdouble {
6557 uint64_t mant;
6558 uint16_t exp;
6561 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6562 #define EXPBIAS1 1023
6563 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6564 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6566 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6568 int e;
6569 /* mantissa */
6570 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6571 /* exponent + sign */
6572 e = EXPD1(temp) - EXPBIAS1 + 16383;
6573 e |= SIGND1(temp) >> 16;
6574 p->exp = e;
6576 #endif
6578 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6580 CPUState *env = opaque;
6581 int i, guess_mmx;
6582 uint32_t hflags;
6583 uint16_t fpus, fpuc, fptag, fpregs_format;
6585 if (version_id != 3 && version_id != 4)
6586 return -EINVAL;
6587 for(i = 0; i < CPU_NB_REGS; i++)
6588 qemu_get_betls(f, &env->regs[i]);
6589 qemu_get_betls(f, &env->eip);
6590 qemu_get_betls(f, &env->eflags);
6591 qemu_get_be32s(f, &hflags);
6593 qemu_get_be16s(f, &fpuc);
6594 qemu_get_be16s(f, &fpus);
6595 qemu_get_be16s(f, &fptag);
6596 qemu_get_be16s(f, &fpregs_format);
6598 /* NOTE: we cannot always restore the FPU state if the image come
6599 from a host with a different 'USE_X86LDOUBLE' define. We guess
6600 if we are in an MMX state to restore correctly in that case. */
6601 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6602 for(i = 0; i < 8; i++) {
6603 uint64_t mant;
6604 uint16_t exp;
6606 switch(fpregs_format) {
6607 case 0:
6608 mant = qemu_get_be64(f);
6609 exp = qemu_get_be16(f);
6610 #ifdef USE_X86LDOUBLE
6611 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6612 #else
6613 /* difficult case */
6614 if (guess_mmx)
6615 env->fpregs[i].mmx.MMX_Q(0) = mant;
6616 else
6617 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6618 #endif
6619 break;
6620 case 1:
6621 mant = qemu_get_be64(f);
6622 #ifdef USE_X86LDOUBLE
6624 union x86_longdouble *p;
6625 /* difficult case */
6626 p = (void *)&env->fpregs[i];
6627 if (guess_mmx) {
6628 p->mant = mant;
6629 p->exp = 0xffff;
6630 } else {
6631 fp64_to_fp80(p, mant);
6634 #else
6635 env->fpregs[i].mmx.MMX_Q(0) = mant;
6636 #endif
6637 break;
6638 default:
6639 return -EINVAL;
6643 env->fpuc = fpuc;
6644 /* XXX: restore FPU round state */
6645 env->fpstt = (fpus >> 11) & 7;
6646 env->fpus = fpus & ~0x3800;
6647 fptag ^= 0xff;
6648 for(i = 0; i < 8; i++) {
6649 env->fptags[i] = (fptag >> i) & 1;
6652 for(i = 0; i < 6; i++)
6653 cpu_get_seg(f, &env->segs[i]);
6654 cpu_get_seg(f, &env->ldt);
6655 cpu_get_seg(f, &env->tr);
6656 cpu_get_seg(f, &env->gdt);
6657 cpu_get_seg(f, &env->idt);
6659 qemu_get_be32s(f, &env->sysenter_cs);
6660 qemu_get_be32s(f, &env->sysenter_esp);
6661 qemu_get_be32s(f, &env->sysenter_eip);
6663 qemu_get_betls(f, &env->cr[0]);
6664 qemu_get_betls(f, &env->cr[2]);
6665 qemu_get_betls(f, &env->cr[3]);
6666 qemu_get_betls(f, &env->cr[4]);
6668 for(i = 0; i < 8; i++)
6669 qemu_get_betls(f, &env->dr[i]);
6671 /* MMU */
6672 qemu_get_be32s(f, &env->a20_mask);
6674 qemu_get_be32s(f, &env->mxcsr);
6675 for(i = 0; i < CPU_NB_REGS; i++) {
6676 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6677 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6680 #ifdef TARGET_X86_64
6681 qemu_get_be64s(f, &env->efer);
6682 qemu_get_be64s(f, &env->star);
6683 qemu_get_be64s(f, &env->lstar);
6684 qemu_get_be64s(f, &env->cstar);
6685 qemu_get_be64s(f, &env->fmask);
6686 qemu_get_be64s(f, &env->kernelgsbase);
6687 #endif
6688 if (version_id >= 4)
6689 qemu_get_be32s(f, &env->smbase);
6691 /* XXX: compute hflags from scratch, except for CPL and IIF */
6692 env->hflags = hflags;
6693 tlb_flush(env, 1);
6694 #ifdef USE_KVM
6695 if (kvm_allowed) {
6696 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6697 because no userspace IRQs will ever clear this flag */
6698 env->hflags &= ~HF_HALTED_MASK;
6699 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6700 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6702 qemu_get_be64s(f, &env->tsc);
6703 kvm_load_registers(env);
6705 #endif
6706 return 0;
6709 #elif defined(TARGET_PPC)
6710 void cpu_save(QEMUFile *f, void *opaque)
6714 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6716 return 0;
6719 #elif defined(TARGET_MIPS)
6720 void cpu_save(QEMUFile *f, void *opaque)
6724 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6726 return 0;
6729 #elif defined(TARGET_SPARC)
6730 void cpu_save(QEMUFile *f, void *opaque)
6732 CPUState *env = opaque;
6733 int i;
6734 uint32_t tmp;
6736 for(i = 0; i < 8; i++)
6737 qemu_put_betls(f, &env->gregs[i]);
6738 for(i = 0; i < NWINDOWS * 16; i++)
6739 qemu_put_betls(f, &env->regbase[i]);
6741 /* FPU */
6742 for(i = 0; i < TARGET_FPREGS; i++) {
6743 union {
6744 float32 f;
6745 uint32_t i;
6746 } u;
6747 u.f = env->fpr[i];
6748 qemu_put_be32(f, u.i);
6751 qemu_put_betls(f, &env->pc);
6752 qemu_put_betls(f, &env->npc);
6753 qemu_put_betls(f, &env->y);
6754 tmp = GET_PSR(env);
6755 qemu_put_be32(f, tmp);
6756 qemu_put_betls(f, &env->fsr);
6757 qemu_put_betls(f, &env->tbr);
6758 #ifndef TARGET_SPARC64
6759 qemu_put_be32s(f, &env->wim);
6760 /* MMU */
6761 for(i = 0; i < 16; i++)
6762 qemu_put_be32s(f, &env->mmuregs[i]);
6763 #endif
6766 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6768 CPUState *env = opaque;
6769 int i;
6770 uint32_t tmp;
6772 for(i = 0; i < 8; i++)
6773 qemu_get_betls(f, &env->gregs[i]);
6774 for(i = 0; i < NWINDOWS * 16; i++)
6775 qemu_get_betls(f, &env->regbase[i]);
6777 /* FPU */
6778 for(i = 0; i < TARGET_FPREGS; i++) {
6779 union {
6780 float32 f;
6781 uint32_t i;
6782 } u;
6783 u.i = qemu_get_be32(f);
6784 env->fpr[i] = u.f;
6787 qemu_get_betls(f, &env->pc);
6788 qemu_get_betls(f, &env->npc);
6789 qemu_get_betls(f, &env->y);
6790 tmp = qemu_get_be32(f);
6791 env->cwp = 0; /* needed to ensure that the wrapping registers are
6792 correctly updated */
6793 PUT_PSR(env, tmp);
6794 qemu_get_betls(f, &env->fsr);
6795 qemu_get_betls(f, &env->tbr);
6796 #ifndef TARGET_SPARC64
6797 qemu_get_be32s(f, &env->wim);
6798 /* MMU */
6799 for(i = 0; i < 16; i++)
6800 qemu_get_be32s(f, &env->mmuregs[i]);
6801 #endif
6802 tlb_flush(env, 1);
6803 return 0;
6806 #elif defined(TARGET_ARM)
6808 void cpu_save(QEMUFile *f, void *opaque)
6810 int i;
6811 CPUARMState *env = (CPUARMState *)opaque;
6813 for (i = 0; i < 16; i++) {
6814 qemu_put_be32(f, env->regs[i]);
6816 qemu_put_be32(f, cpsr_read(env));
6817 qemu_put_be32(f, env->spsr);
6818 for (i = 0; i < 6; i++) {
6819 qemu_put_be32(f, env->banked_spsr[i]);
6820 qemu_put_be32(f, env->banked_r13[i]);
6821 qemu_put_be32(f, env->banked_r14[i]);
6823 for (i = 0; i < 5; i++) {
6824 qemu_put_be32(f, env->usr_regs[i]);
6825 qemu_put_be32(f, env->fiq_regs[i]);
6827 qemu_put_be32(f, env->cp15.c0_cpuid);
6828 qemu_put_be32(f, env->cp15.c0_cachetype);
6829 qemu_put_be32(f, env->cp15.c1_sys);
6830 qemu_put_be32(f, env->cp15.c1_coproc);
6831 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6832 qemu_put_be32(f, env->cp15.c2_base0);
6833 qemu_put_be32(f, env->cp15.c2_base1);
6834 qemu_put_be32(f, env->cp15.c2_mask);
6835 qemu_put_be32(f, env->cp15.c2_data);
6836 qemu_put_be32(f, env->cp15.c2_insn);
6837 qemu_put_be32(f, env->cp15.c3);
6838 qemu_put_be32(f, env->cp15.c5_insn);
6839 qemu_put_be32(f, env->cp15.c5_data);
6840 for (i = 0; i < 8; i++) {
6841 qemu_put_be32(f, env->cp15.c6_region[i]);
6843 qemu_put_be32(f, env->cp15.c6_insn);
6844 qemu_put_be32(f, env->cp15.c6_data);
6845 qemu_put_be32(f, env->cp15.c9_insn);
6846 qemu_put_be32(f, env->cp15.c9_data);
6847 qemu_put_be32(f, env->cp15.c13_fcse);
6848 qemu_put_be32(f, env->cp15.c13_context);
6849 qemu_put_be32(f, env->cp15.c13_tls1);
6850 qemu_put_be32(f, env->cp15.c13_tls2);
6851 qemu_put_be32(f, env->cp15.c13_tls3);
6852 qemu_put_be32(f, env->cp15.c15_cpar);
6854 qemu_put_be32(f, env->features);
6856 if (arm_feature(env, ARM_FEATURE_VFP)) {
6857 for (i = 0; i < 16; i++) {
6858 CPU_DoubleU u;
6859 u.d = env->vfp.regs[i];
6860 qemu_put_be32(f, u.l.upper);
6861 qemu_put_be32(f, u.l.lower);
6863 for (i = 0; i < 16; i++) {
6864 qemu_put_be32(f, env->vfp.xregs[i]);
6867 /* TODO: Should use proper FPSCR access functions. */
6868 qemu_put_be32(f, env->vfp.vec_len);
6869 qemu_put_be32(f, env->vfp.vec_stride);
6871 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6872 for (i = 16; i < 32; i++) {
6873 CPU_DoubleU u;
6874 u.d = env->vfp.regs[i];
6875 qemu_put_be32(f, u.l.upper);
6876 qemu_put_be32(f, u.l.lower);
6881 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6882 for (i = 0; i < 16; i++) {
6883 qemu_put_be64(f, env->iwmmxt.regs[i]);
6885 for (i = 0; i < 16; i++) {
6886 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6890 if (arm_feature(env, ARM_FEATURE_M)) {
6891 qemu_put_be32(f, env->v7m.other_sp);
6892 qemu_put_be32(f, env->v7m.vecbase);
6893 qemu_put_be32(f, env->v7m.basepri);
6894 qemu_put_be32(f, env->v7m.control);
6895 qemu_put_be32(f, env->v7m.current_sp);
6896 qemu_put_be32(f, env->v7m.exception);
6900 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6902 CPUARMState *env = (CPUARMState *)opaque;
6903 int i;
6905 if (version_id != ARM_CPU_SAVE_VERSION)
6906 return -EINVAL;
6908 for (i = 0; i < 16; i++) {
6909 env->regs[i] = qemu_get_be32(f);
6911 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6912 env->spsr = qemu_get_be32(f);
6913 for (i = 0; i < 6; i++) {
6914 env->banked_spsr[i] = qemu_get_be32(f);
6915 env->banked_r13[i] = qemu_get_be32(f);
6916 env->banked_r14[i] = qemu_get_be32(f);
6918 for (i = 0; i < 5; i++) {
6919 env->usr_regs[i] = qemu_get_be32(f);
6920 env->fiq_regs[i] = qemu_get_be32(f);
6922 env->cp15.c0_cpuid = qemu_get_be32(f);
6923 env->cp15.c0_cachetype = qemu_get_be32(f);
6924 env->cp15.c1_sys = qemu_get_be32(f);
6925 env->cp15.c1_coproc = qemu_get_be32(f);
6926 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6927 env->cp15.c2_base0 = qemu_get_be32(f);
6928 env->cp15.c2_base1 = qemu_get_be32(f);
6929 env->cp15.c2_mask = qemu_get_be32(f);
6930 env->cp15.c2_data = qemu_get_be32(f);
6931 env->cp15.c2_insn = qemu_get_be32(f);
6932 env->cp15.c3 = qemu_get_be32(f);
6933 env->cp15.c5_insn = qemu_get_be32(f);
6934 env->cp15.c5_data = qemu_get_be32(f);
6935 for (i = 0; i < 8; i++) {
6936 env->cp15.c6_region[i] = qemu_get_be32(f);
6938 env->cp15.c6_insn = qemu_get_be32(f);
6939 env->cp15.c6_data = qemu_get_be32(f);
6940 env->cp15.c9_insn = qemu_get_be32(f);
6941 env->cp15.c9_data = qemu_get_be32(f);
6942 env->cp15.c13_fcse = qemu_get_be32(f);
6943 env->cp15.c13_context = qemu_get_be32(f);
6944 env->cp15.c13_tls1 = qemu_get_be32(f);
6945 env->cp15.c13_tls2 = qemu_get_be32(f);
6946 env->cp15.c13_tls3 = qemu_get_be32(f);
6947 env->cp15.c15_cpar = qemu_get_be32(f);
6949 env->features = qemu_get_be32(f);
6951 if (arm_feature(env, ARM_FEATURE_VFP)) {
6952 for (i = 0; i < 16; i++) {
6953 CPU_DoubleU u;
6954 u.l.upper = qemu_get_be32(f);
6955 u.l.lower = qemu_get_be32(f);
6956 env->vfp.regs[i] = u.d;
6958 for (i = 0; i < 16; i++) {
6959 env->vfp.xregs[i] = qemu_get_be32(f);
6962 /* TODO: Should use proper FPSCR access functions. */
6963 env->vfp.vec_len = qemu_get_be32(f);
6964 env->vfp.vec_stride = qemu_get_be32(f);
6966 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6967 for (i = 0; i < 16; i++) {
6968 CPU_DoubleU u;
6969 u.l.upper = qemu_get_be32(f);
6970 u.l.lower = qemu_get_be32(f);
6971 env->vfp.regs[i] = u.d;
6976 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6977 for (i = 0; i < 16; i++) {
6978 env->iwmmxt.regs[i] = qemu_get_be64(f);
6980 for (i = 0; i < 16; i++) {
6981 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6985 if (arm_feature(env, ARM_FEATURE_M)) {
6986 env->v7m.other_sp = qemu_get_be32(f);
6987 env->v7m.vecbase = qemu_get_be32(f);
6988 env->v7m.basepri = qemu_get_be32(f);
6989 env->v7m.control = qemu_get_be32(f);
6990 env->v7m.current_sp = qemu_get_be32(f);
6991 env->v7m.exception = qemu_get_be32(f);
6994 return 0;
6997 #elif defined(TARGET_IA64)
6998 void cpu_save(QEMUFile *f, void *opaque)
7002 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7004 return 0;
7006 #else
7008 //#warning No CPU save/restore functions
7010 #endif
7012 /***********************************************************/
7013 /* ram save/restore */
7015 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7017 int v;
7019 v = qemu_get_byte(f);
7020 switch(v) {
7021 case 0:
7022 if (qemu_get_buffer(f, buf, len) != len)
7023 return -EIO;
7024 break;
7025 case 1:
7026 v = qemu_get_byte(f);
7027 memset(buf, v, len);
7028 break;
7029 default:
7030 return -EINVAL;
7032 return 0;
7035 static int ram_load_v1(QEMUFile *f, void *opaque)
7037 int i, ret;
7039 if (qemu_get_be32(f) != phys_ram_size)
7040 return -EINVAL;
7041 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7042 #ifdef USE_KVM
7043 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7044 continue;
7045 #endif
7046 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7047 if (ret)
7048 return ret;
7050 return 0;
7053 #define BDRV_HASH_BLOCK_SIZE 1024
7054 #define IOBUF_SIZE 4096
7055 #define RAM_CBLOCK_MAGIC 0xfabe
7057 typedef struct RamCompressState {
7058 z_stream zstream;
7059 QEMUFile *f;
7060 uint8_t buf[IOBUF_SIZE];
7061 } RamCompressState;
7063 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7065 int ret;
7066 memset(s, 0, sizeof(*s));
7067 s->f = f;
7068 ret = deflateInit2(&s->zstream, 1,
7069 Z_DEFLATED, 15,
7070 9, Z_DEFAULT_STRATEGY);
7071 if (ret != Z_OK)
7072 return -1;
7073 s->zstream.avail_out = IOBUF_SIZE;
7074 s->zstream.next_out = s->buf;
7075 return 0;
7078 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7080 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7081 qemu_put_be16(s->f, len);
7082 qemu_put_buffer(s->f, buf, len);
7085 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7087 int ret;
7089 s->zstream.avail_in = len;
7090 s->zstream.next_in = (uint8_t *)buf;
7091 while (s->zstream.avail_in > 0) {
7092 ret = deflate(&s->zstream, Z_NO_FLUSH);
7093 if (ret != Z_OK)
7094 return -1;
7095 if (s->zstream.avail_out == 0) {
7096 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7097 s->zstream.avail_out = IOBUF_SIZE;
7098 s->zstream.next_out = s->buf;
7101 return 0;
7104 static void ram_compress_close(RamCompressState *s)
7106 int len, ret;
7108 /* compress last bytes */
7109 for(;;) {
7110 ret = deflate(&s->zstream, Z_FINISH);
7111 if (ret == Z_OK || ret == Z_STREAM_END) {
7112 len = IOBUF_SIZE - s->zstream.avail_out;
7113 if (len > 0) {
7114 ram_put_cblock(s, s->buf, len);
7116 s->zstream.avail_out = IOBUF_SIZE;
7117 s->zstream.next_out = s->buf;
7118 if (ret == Z_STREAM_END)
7119 break;
7120 } else {
7121 goto fail;
7124 fail:
7125 deflateEnd(&s->zstream);
7128 typedef struct RamDecompressState {
7129 z_stream zstream;
7130 QEMUFile *f;
7131 uint8_t buf[IOBUF_SIZE];
7132 } RamDecompressState;
7134 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7136 int ret;
7137 memset(s, 0, sizeof(*s));
7138 s->f = f;
7139 ret = inflateInit(&s->zstream);
7140 if (ret != Z_OK)
7141 return -1;
7142 return 0;
7145 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7147 int ret, clen;
7149 s->zstream.avail_out = len;
7150 s->zstream.next_out = buf;
7151 while (s->zstream.avail_out > 0) {
7152 if (s->zstream.avail_in == 0) {
7153 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7154 return -1;
7155 clen = qemu_get_be16(s->f);
7156 if (clen > IOBUF_SIZE)
7157 return -1;
7158 qemu_get_buffer(s->f, s->buf, clen);
7159 s->zstream.avail_in = clen;
7160 s->zstream.next_in = s->buf;
7162 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7163 if (ret != Z_OK && ret != Z_STREAM_END) {
7164 return -1;
7167 return 0;
7170 static void ram_decompress_close(RamDecompressState *s)
7172 inflateEnd(&s->zstream);
7175 static void ram_save_live(QEMUFile *f, void *opaque)
7177 target_ulong addr;
7179 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7180 #ifdef USE_KVM
7181 if (kvm_allowed && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7182 continue;
7183 #endif
7184 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7185 qemu_put_be32(f, addr);
7186 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7189 qemu_put_be32(f, 1);
7192 static void ram_save_static(QEMUFile *f, void *opaque)
7194 int i;
7195 RamCompressState s1, *s = &s1;
7196 uint8_t buf[10];
7198 qemu_put_be32(f, phys_ram_size);
7199 if (ram_compress_open(s, f) < 0)
7200 return;
7201 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7202 #ifdef USE_KVM
7203 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7204 continue;
7205 #endif
7206 #if 0
7207 if (tight_savevm_enabled) {
7208 int64_t sector_num;
7209 int j;
7211 /* find if the memory block is available on a virtual
7212 block device */
7213 sector_num = -1;
7214 for(j = 0; j < nb_drives; j++) {
7215 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7216 phys_ram_base + i,
7217 BDRV_HASH_BLOCK_SIZE);
7218 if (sector_num >= 0)
7219 break;
7221 if (j == nb_drives)
7222 goto normal_compress;
7223 buf[0] = 1;
7224 buf[1] = j;
7225 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7226 ram_compress_buf(s, buf, 10);
7227 } else
7228 #endif
7230 // normal_compress:
7231 buf[0] = 0;
7232 ram_compress_buf(s, buf, 1);
7233 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7236 ram_compress_close(s);
7239 static void ram_save(QEMUFile *f, void *opaque)
7241 int in_migration = cpu_physical_memory_get_dirty_tracking();
7243 qemu_put_byte(f, in_migration);
7245 if (in_migration)
7246 ram_save_live(f, opaque);
7247 else
7248 ram_save_static(f, opaque);
7251 static int ram_load_live(QEMUFile *f, void *opaque)
7253 target_ulong addr;
7255 do {
7256 addr = qemu_get_be32(f);
7257 if (addr == 1)
7258 break;
7260 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7261 } while (1);
7263 return 0;
7266 static int ram_load_static(QEMUFile *f, void *opaque)
7268 RamDecompressState s1, *s = &s1;
7269 uint8_t buf[10];
7270 int i;
7272 if (qemu_get_be32(f) != phys_ram_size)
7273 return -EINVAL;
7274 if (ram_decompress_open(s, f) < 0)
7275 return -EINVAL;
7276 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7277 #ifdef USE_KVM
7278 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7279 continue;
7280 #endif
7281 if (ram_decompress_buf(s, buf, 1) < 0) {
7282 fprintf(stderr, "Error while reading ram block header\n");
7283 goto error;
7285 if (buf[0] == 0) {
7286 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7287 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7288 goto error;
7290 } else
7291 #if 0
7292 if (buf[0] == 1) {
7293 int bs_index;
7294 int64_t sector_num;
7296 ram_decompress_buf(s, buf + 1, 9);
7297 bs_index = buf[1];
7298 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7299 if (bs_index >= nb_drives) {
7300 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7301 goto error;
7303 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7304 phys_ram_base + i,
7305 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7306 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7307 bs_index, sector_num);
7308 goto error;
7310 } else
7311 #endif
7313 error:
7314 printf("Error block header\n");
7315 return -EINVAL;
7318 ram_decompress_close(s);
7319 return 0;
7322 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7324 int ret;
7326 switch (version_id) {
7327 case 1:
7328 ret = ram_load_v1(f, opaque);
7329 break;
7330 case 3:
7331 if (qemu_get_byte(f)) {
7332 ret = ram_load_live(f, opaque);
7333 break;
7335 case 2:
7336 ret = ram_load_static(f, opaque);
7337 break;
7338 default:
7339 ret = -EINVAL;
7340 break;
7343 return ret;
7346 /***********************************************************/
7347 /* bottom halves (can be seen as timers which expire ASAP) */
7349 struct QEMUBH {
7350 QEMUBHFunc *cb;
7351 void *opaque;
7352 int scheduled;
7353 QEMUBH *next;
7356 static QEMUBH *first_bh = NULL;
7358 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7360 QEMUBH *bh;
7361 bh = qemu_mallocz(sizeof(QEMUBH));
7362 if (!bh)
7363 return NULL;
7364 bh->cb = cb;
7365 bh->opaque = opaque;
7366 return bh;
7369 int qemu_bh_poll(void)
7371 QEMUBH *bh, **pbh;
7372 int ret;
7374 ret = 0;
7375 for(;;) {
7376 pbh = &first_bh;
7377 bh = *pbh;
7378 if (!bh)
7379 break;
7380 ret = 1;
7381 *pbh = bh->next;
7382 bh->scheduled = 0;
7383 bh->cb(bh->opaque);
7385 return ret;
7388 void qemu_bh_schedule(QEMUBH *bh)
7390 CPUState *env = cpu_single_env;
7391 if (bh->scheduled)
7392 return;
7393 bh->scheduled = 1;
7394 bh->next = first_bh;
7395 first_bh = bh;
7397 /* stop the currently executing CPU to execute the BH ASAP */
7398 if (env) {
7399 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7403 void qemu_bh_cancel(QEMUBH *bh)
7405 QEMUBH **pbh;
7406 if (bh->scheduled) {
7407 pbh = &first_bh;
7408 while (*pbh != bh)
7409 pbh = &(*pbh)->next;
7410 *pbh = bh->next;
7411 bh->scheduled = 0;
7415 void qemu_bh_delete(QEMUBH *bh)
7417 qemu_bh_cancel(bh);
7418 qemu_free(bh);
7421 /***********************************************************/
7422 /* machine registration */
7424 QEMUMachine *first_machine = NULL;
7426 int qemu_register_machine(QEMUMachine *m)
7428 QEMUMachine **pm;
7429 pm = &first_machine;
7430 while (*pm != NULL)
7431 pm = &(*pm)->next;
7432 m->next = NULL;
7433 *pm = m;
7434 return 0;
7437 static QEMUMachine *find_machine(const char *name)
7439 QEMUMachine *m;
7441 for(m = first_machine; m != NULL; m = m->next) {
7442 if (!strcmp(m->name, name))
7443 return m;
7445 return NULL;
7448 /***********************************************************/
7449 /* main execution loop */
7451 static void gui_update(void *opaque)
7453 DisplayState *ds = opaque;
7454 ds->dpy_refresh(ds);
7455 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7458 struct vm_change_state_entry {
7459 VMChangeStateHandler *cb;
7460 void *opaque;
7461 LIST_ENTRY (vm_change_state_entry) entries;
7464 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7466 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7467 void *opaque)
7469 VMChangeStateEntry *e;
7471 e = qemu_mallocz(sizeof (*e));
7472 if (!e)
7473 return NULL;
7475 e->cb = cb;
7476 e->opaque = opaque;
7477 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7478 return e;
7481 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7483 LIST_REMOVE (e, entries);
7484 qemu_free (e);
7487 static void vm_state_notify(int running)
7489 VMChangeStateEntry *e;
7491 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7492 e->cb(e->opaque, running);
7496 /* XXX: support several handlers */
7497 static VMStopHandler *vm_stop_cb;
7498 static void *vm_stop_opaque;
7500 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7502 vm_stop_cb = cb;
7503 vm_stop_opaque = opaque;
7504 return 0;
7507 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7509 vm_stop_cb = NULL;
7512 void vm_start(void)
7514 if (!vm_running) {
7515 cpu_enable_ticks();
7516 vm_running = 1;
7517 vm_state_notify(1);
7518 qemu_rearm_alarm_timer(alarm_timer);
7522 void vm_stop(int reason)
7524 if (vm_running) {
7525 cpu_disable_ticks();
7526 vm_running = 0;
7527 if (reason != 0) {
7528 if (vm_stop_cb) {
7529 vm_stop_cb(vm_stop_opaque, reason);
7532 vm_state_notify(0);
7536 /* reset/shutdown handler */
7538 typedef struct QEMUResetEntry {
7539 QEMUResetHandler *func;
7540 void *opaque;
7541 struct QEMUResetEntry *next;
7542 } QEMUResetEntry;
7544 static QEMUResetEntry *first_reset_entry;
7545 static int reset_requested;
7546 static int shutdown_requested;
7547 static int powerdown_requested;
7549 int qemu_shutdown_requested(void)
7551 int r = shutdown_requested;
7552 shutdown_requested = 0;
7553 return r;
7556 int qemu_reset_requested(void)
7558 int r = reset_requested;
7559 reset_requested = 0;
7560 return r;
7563 int qemu_powerdown_requested(void)
7565 int r = powerdown_requested;
7566 powerdown_requested = 0;
7567 return r;
7570 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7572 QEMUResetEntry **pre, *re;
7574 pre = &first_reset_entry;
7575 while (*pre != NULL)
7576 pre = &(*pre)->next;
7577 re = qemu_mallocz(sizeof(QEMUResetEntry));
7578 re->func = func;
7579 re->opaque = opaque;
7580 re->next = NULL;
7581 *pre = re;
7584 void qemu_system_reset(void)
7586 QEMUResetEntry *re;
7588 /* reset all devices */
7589 for(re = first_reset_entry; re != NULL; re = re->next) {
7590 re->func(re->opaque);
7594 void qemu_system_reset_request(void)
7596 if (no_reboot) {
7597 shutdown_requested = 1;
7598 } else {
7599 reset_requested = 1;
7601 if (cpu_single_env)
7602 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7605 void qemu_system_shutdown_request(void)
7607 shutdown_requested = 1;
7608 if (cpu_single_env)
7609 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7612 void qemu_system_powerdown_request(void)
7614 powerdown_requested = 1;
7615 if (cpu_single_env)
7616 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7619 void main_loop_wait(int timeout)
7621 IOHandlerRecord *ioh;
7622 fd_set rfds, wfds, xfds;
7623 int ret, nfds;
7624 #ifdef _WIN32
7625 int ret2, i;
7626 #endif
7627 struct timeval tv;
7628 PollingEntry *pe;
7631 /* XXX: need to suppress polling by better using win32 events */
7632 ret = 0;
7633 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7634 ret |= pe->func(pe->opaque);
7636 #ifdef _WIN32
7637 if (ret == 0) {
7638 int err;
7639 WaitObjects *w = &wait_objects;
7641 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7642 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7643 if (w->func[ret - WAIT_OBJECT_0])
7644 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7646 /* Check for additional signaled events */
7647 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7649 /* Check if event is signaled */
7650 ret2 = WaitForSingleObject(w->events[i], 0);
7651 if(ret2 == WAIT_OBJECT_0) {
7652 if (w->func[i])
7653 w->func[i](w->opaque[i]);
7654 } else if (ret2 == WAIT_TIMEOUT) {
7655 } else {
7656 err = GetLastError();
7657 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7660 } else if (ret == WAIT_TIMEOUT) {
7661 } else {
7662 err = GetLastError();
7663 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7666 #endif
7667 /* poll any events */
7668 /* XXX: separate device handlers from system ones */
7669 nfds = -1;
7670 FD_ZERO(&rfds);
7671 FD_ZERO(&wfds);
7672 FD_ZERO(&xfds);
7673 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7674 if (ioh->deleted)
7675 continue;
7676 if (ioh->fd_read &&
7677 (!ioh->fd_read_poll ||
7678 ioh->fd_read_poll(ioh->opaque) != 0)) {
7679 FD_SET(ioh->fd, &rfds);
7680 if (ioh->fd > nfds)
7681 nfds = ioh->fd;
7683 if (ioh->fd_write) {
7684 FD_SET(ioh->fd, &wfds);
7685 if (ioh->fd > nfds)
7686 nfds = ioh->fd;
7690 tv.tv_sec = 0;
7691 #ifdef _WIN32
7692 tv.tv_usec = 0;
7693 #else
7694 tv.tv_usec = timeout * 1000;
7695 #endif
7696 #if defined(CONFIG_SLIRP)
7697 if (slirp_inited) {
7698 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7700 #endif
7701 moreio:
7702 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7703 if (ret > 0) {
7704 IOHandlerRecord **pioh;
7705 int more = 0;
7707 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7708 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7709 ioh->fd_read(ioh->opaque);
7710 more = 1;
7712 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7713 ioh->fd_write(ioh->opaque);
7714 more = 1;
7718 /* remove deleted IO handlers */
7719 pioh = &first_io_handler;
7720 while (*pioh) {
7721 ioh = *pioh;
7722 if (ioh->deleted) {
7723 *pioh = ioh->next;
7724 qemu_free(ioh);
7725 } else
7726 pioh = &ioh->next;
7728 if (more)
7729 goto moreio;
7731 #if defined(CONFIG_SLIRP)
7732 if (slirp_inited) {
7733 if (ret < 0) {
7734 FD_ZERO(&rfds);
7735 FD_ZERO(&wfds);
7736 FD_ZERO(&xfds);
7738 slirp_select_poll(&rfds, &wfds, &xfds);
7740 #endif
7741 qemu_aio_poll();
7743 if (vm_running) {
7744 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7745 qemu_get_clock(vm_clock));
7746 /* run dma transfers, if any */
7747 DMA_run();
7750 /* real time timers */
7751 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7752 qemu_get_clock(rt_clock));
7754 /* Check bottom-halves last in case any of the earlier events triggered
7755 them. */
7756 qemu_bh_poll();
7760 static int main_loop(void)
7762 int ret, timeout;
7763 #ifdef CONFIG_PROFILER
7764 int64_t ti;
7765 #endif
7766 CPUState *env;
7769 #ifdef USE_KVM
7770 if (kvm_allowed) {
7771 kvm_main_loop();
7772 cpu_disable_ticks();
7773 return 0;
7775 #endif
7776 cur_cpu = first_cpu;
7777 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7778 for(;;) {
7779 if (vm_running) {
7781 for(;;) {
7782 /* get next cpu */
7783 env = next_cpu;
7784 #ifdef CONFIG_PROFILER
7785 ti = profile_getclock();
7786 #endif
7787 ret = cpu_exec(env);
7788 #ifdef CONFIG_PROFILER
7789 qemu_time += profile_getclock() - ti;
7790 #endif
7791 next_cpu = env->next_cpu ?: first_cpu;
7792 if (event_pending) {
7793 ret = EXCP_INTERRUPT;
7794 event_pending = 0;
7795 break;
7797 if (ret == EXCP_HLT) {
7798 /* Give the next CPU a chance to run. */
7799 cur_cpu = env;
7800 continue;
7802 if (ret != EXCP_HALTED)
7803 break;
7804 /* all CPUs are halted ? */
7805 if (env == cur_cpu)
7806 break;
7808 cur_cpu = env;
7810 if (shutdown_requested) {
7811 ret = EXCP_INTERRUPT;
7812 break;
7814 if (reset_requested) {
7815 reset_requested = 0;
7816 qemu_system_reset();
7817 #ifdef USE_KVM
7818 if (kvm_allowed)
7819 kvm_load_registers(env);
7820 #endif
7821 ret = EXCP_INTERRUPT;
7823 if (powerdown_requested) {
7824 powerdown_requested = 0;
7825 qemu_system_powerdown();
7826 ret = EXCP_INTERRUPT;
7828 if (ret == EXCP_DEBUG) {
7829 vm_stop(EXCP_DEBUG);
7831 /* If all cpus are halted then wait until the next IRQ */
7832 /* XXX: use timeout computed from timers */
7833 if (ret == EXCP_HALTED)
7834 timeout = 10;
7835 else
7836 timeout = 0;
7837 } else {
7838 timeout = 10;
7840 #ifdef CONFIG_PROFILER
7841 ti = profile_getclock();
7842 #endif
7843 main_loop_wait(timeout);
7844 #ifdef CONFIG_PROFILER
7845 dev_time += profile_getclock() - ti;
7846 #endif
7848 cpu_disable_ticks();
7849 return ret;
7852 static void help(int exitcode)
7854 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
7855 ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7856 "usage: %s [options] [disk_image]\n"
7857 "\n"
7858 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7859 "\n"
7860 "Standard options:\n"
7861 "-M machine select emulated machine (-M ? for list)\n"
7862 "-cpu cpu select CPU (-cpu ? for list)\n"
7863 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7864 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7865 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7866 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7867 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7868 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7869 " [,cache=on|off]\n"
7870 " use 'file' as a drive image\n"
7871 "-mtdblock file use 'file' as on-board Flash memory image\n"
7872 "-sd file use 'file' as SecureDigital card image\n"
7873 "-pflash file use 'file' as a parallel flash image\n"
7874 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7875 "-snapshot write to temporary files instead of disk image files\n"
7876 #ifdef CONFIG_SDL
7877 "-no-frame open SDL window without a frame and window decorations\n"
7878 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7879 "-no-quit disable SDL window close capability\n"
7880 #endif
7881 #ifdef TARGET_I386
7882 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7883 #endif
7884 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7885 "-smp n set the number of CPUs to 'n' [default=1]\n"
7886 "-nographic disable graphical output and redirect serial I/Os to console\n"
7887 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7888 #ifndef _WIN32
7889 "-k language use keyboard layout (for example \"fr\" for French)\n"
7890 #endif
7891 #ifdef HAS_AUDIO
7892 "-audio-help print list of audio drivers and their options\n"
7893 "-soundhw c1,... enable audio support\n"
7894 " and only specified sound cards (comma separated list)\n"
7895 " use -soundhw ? to get the list of supported cards\n"
7896 " use -soundhw all to enable all of them\n"
7897 #endif
7898 "-localtime set the real time clock to local time [default=utc]\n"
7899 "-full-screen start in full screen\n"
7900 #ifdef TARGET_I386
7901 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7902 #endif
7903 "-usb enable the USB driver (will be the default soon)\n"
7904 "-usbdevice name add the host or guest USB device 'name'\n"
7905 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7906 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7907 #endif
7908 "-name string set the name of the guest\n"
7909 "\n"
7910 "Network options:\n"
7911 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7912 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7913 #ifdef CONFIG_SLIRP
7914 "-net user[,vlan=n][,hostname=host]\n"
7915 " connect the user mode network stack to VLAN 'n' and send\n"
7916 " hostname 'host' to DHCP clients\n"
7917 #endif
7918 #ifdef _WIN32
7919 "-net tap[,vlan=n],ifname=name\n"
7920 " connect the host TAP network interface to VLAN 'n'\n"
7921 #else
7922 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7923 " connect the host TAP network interface to VLAN 'n' and use the\n"
7924 " network scripts 'file' (default=%s)\n"
7925 " and 'dfile' (default=%s);\n"
7926 " use '[down]script=no' to disable script execution;\n"
7927 " use 'fd=h' to connect to an already opened TAP interface\n"
7928 #endif
7929 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7930 " connect the vlan 'n' to another VLAN using a socket connection\n"
7931 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7932 " connect the vlan 'n' to multicast maddr and port\n"
7933 "-net none use it alone to have zero network devices; if no -net option\n"
7934 " is provided, the default is '-net nic -net user'\n"
7935 "\n"
7936 #ifdef CONFIG_SLIRP
7937 "-tftp dir allow tftp access to files in dir [-net user]\n"
7938 "-bootp file advertise file in BOOTP replies\n"
7939 #ifndef _WIN32
7940 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7941 #endif
7942 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7943 " redirect TCP or UDP connections from host to guest [-net user]\n"
7944 #endif
7945 "\n"
7946 "Linux boot specific:\n"
7947 "-kernel bzImage use 'bzImage' as kernel image\n"
7948 "-append cmdline use 'cmdline' as kernel command line\n"
7949 "-initrd file use 'file' as initial ram disk\n"
7950 "\n"
7951 "Debug/Expert options:\n"
7952 "-monitor dev redirect the monitor to char device 'dev'\n"
7953 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
7954 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
7955 "-serial dev redirect the serial port to char device 'dev'\n"
7956 "-parallel dev redirect the parallel port to char device 'dev'\n"
7957 "-pidfile file Write PID to 'file'\n"
7958 "-S freeze CPU at startup (use 'c' to start execution)\n"
7959 "-s wait gdb connection to port\n"
7960 "-p port set gdb connection port [default=%s]\n"
7961 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7962 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7963 " translation (t=none or lba) (usually qemu can guess them)\n"
7964 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7965 #ifdef USE_KQEMU
7966 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7967 "-no-kqemu disable KQEMU kernel module usage\n"
7968 #endif
7969 #ifdef USE_KVM
7970 "-no-kvm disable KVM hardware virtualization\n"
7971 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
7972 #endif
7973 #ifdef TARGET_I386
7974 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7975 " (default is CL-GD5446 PCI VGA)\n"
7976 "-no-acpi disable ACPI\n"
7977 #endif
7978 "-no-reboot exit instead of rebooting\n"
7979 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7980 "-vnc display start a VNC server on display\n"
7981 #ifndef _WIN32
7982 "-daemonize daemonize QEMU after initializing\n"
7983 #endif
7984 "-tdf inject timer interrupts that got lost\n"
7985 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
7986 "-option-rom rom load a file, rom, into the option ROM space\n"
7987 #ifdef TARGET_SPARC
7988 "-prom-env variable=value set OpenBIOS nvram variables\n"
7989 #endif
7990 "-clock force the use of the given methods for timer alarm.\n"
7991 " To see what timers are available use -clock help\n"
7992 "\n"
7993 "During emulation, the following keys are useful:\n"
7994 "ctrl-alt-f toggle full screen\n"
7995 "ctrl-alt-n switch to virtual console 'n'\n"
7996 "ctrl-alt toggle mouse and keyboard grab\n"
7997 "\n"
7998 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8000 "qemu",
8001 DEFAULT_RAM_SIZE,
8002 #ifndef _WIN32
8003 DEFAULT_NETWORK_SCRIPT,
8004 DEFAULT_NETWORK_DOWN_SCRIPT,
8005 #endif
8006 DEFAULT_GDBSTUB_PORT,
8007 "/tmp/qemu.log");
8008 exit(exitcode);
8011 #define HAS_ARG 0x0001
8013 enum {
8014 QEMU_OPTION_h,
8016 QEMU_OPTION_M,
8017 QEMU_OPTION_cpu,
8018 QEMU_OPTION_fda,
8019 QEMU_OPTION_fdb,
8020 QEMU_OPTION_hda,
8021 QEMU_OPTION_hdb,
8022 QEMU_OPTION_hdc,
8023 QEMU_OPTION_hdd,
8024 QEMU_OPTION_drive,
8025 QEMU_OPTION_cdrom,
8026 QEMU_OPTION_mtdblock,
8027 QEMU_OPTION_sd,
8028 QEMU_OPTION_pflash,
8029 QEMU_OPTION_boot,
8030 QEMU_OPTION_snapshot,
8031 #ifdef TARGET_I386
8032 QEMU_OPTION_no_fd_bootchk,
8033 #endif
8034 QEMU_OPTION_m,
8035 QEMU_OPTION_nographic,
8036 QEMU_OPTION_portrait,
8037 #ifdef HAS_AUDIO
8038 QEMU_OPTION_audio_help,
8039 QEMU_OPTION_soundhw,
8040 #endif
8042 QEMU_OPTION_net,
8043 QEMU_OPTION_tftp,
8044 QEMU_OPTION_bootp,
8045 QEMU_OPTION_smb,
8046 QEMU_OPTION_redir,
8048 QEMU_OPTION_kernel,
8049 QEMU_OPTION_append,
8050 QEMU_OPTION_initrd,
8052 QEMU_OPTION_S,
8053 QEMU_OPTION_s,
8054 QEMU_OPTION_p,
8055 QEMU_OPTION_d,
8056 QEMU_OPTION_hdachs,
8057 QEMU_OPTION_L,
8058 QEMU_OPTION_bios,
8059 QEMU_OPTION_no_code_copy,
8060 QEMU_OPTION_k,
8061 QEMU_OPTION_localtime,
8062 QEMU_OPTION_cirrusvga,
8063 QEMU_OPTION_vmsvga,
8064 QEMU_OPTION_g,
8065 QEMU_OPTION_std_vga,
8066 QEMU_OPTION_echr,
8067 QEMU_OPTION_monitor,
8068 QEMU_OPTION_balloon,
8069 QEMU_OPTION_vmchannel,
8070 QEMU_OPTION_serial,
8071 QEMU_OPTION_parallel,
8072 QEMU_OPTION_loadvm,
8073 QEMU_OPTION_full_screen,
8074 QEMU_OPTION_no_frame,
8075 QEMU_OPTION_alt_grab,
8076 QEMU_OPTION_no_quit,
8077 QEMU_OPTION_pidfile,
8078 QEMU_OPTION_no_kqemu,
8079 QEMU_OPTION_kernel_kqemu,
8080 QEMU_OPTION_win2k_hack,
8081 QEMU_OPTION_usb,
8082 QEMU_OPTION_usbdevice,
8083 QEMU_OPTION_smp,
8084 QEMU_OPTION_vnc,
8085 QEMU_OPTION_no_acpi,
8086 QEMU_OPTION_no_kvm,
8087 QEMU_OPTION_no_kvm_irqchip,
8088 QEMU_OPTION_no_reboot,
8089 QEMU_OPTION_show_cursor,
8090 QEMU_OPTION_daemonize,
8091 QEMU_OPTION_option_rom,
8092 QEMU_OPTION_semihosting,
8093 QEMU_OPTION_cpu_vendor,
8094 QEMU_OPTION_name,
8095 QEMU_OPTION_prom_env,
8096 QEMU_OPTION_old_param,
8097 QEMU_OPTION_clock,
8098 QEMU_OPTION_startdate,
8099 QEMU_OPTION_incoming,
8100 QEMU_OPTION_tdf,
8101 QEMU_OPTION_kvm_shadow_memory,
8104 typedef struct QEMUOption {
8105 const char *name;
8106 int flags;
8107 int index;
8108 } QEMUOption;
8110 const QEMUOption qemu_options[] = {
8111 { "h", 0, QEMU_OPTION_h },
8112 { "help", 0, QEMU_OPTION_h },
8114 { "M", HAS_ARG, QEMU_OPTION_M },
8115 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8116 { "fda", HAS_ARG, QEMU_OPTION_fda },
8117 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8118 { "hda", HAS_ARG, QEMU_OPTION_hda },
8119 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8120 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8121 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8122 { "drive", HAS_ARG, QEMU_OPTION_drive },
8123 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8124 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8125 { "sd", HAS_ARG, QEMU_OPTION_sd },
8126 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8127 { "boot", HAS_ARG, QEMU_OPTION_boot },
8128 { "snapshot", 0, QEMU_OPTION_snapshot },
8129 #ifdef TARGET_I386
8130 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8131 #endif
8132 { "m", HAS_ARG, QEMU_OPTION_m },
8133 { "nographic", 0, QEMU_OPTION_nographic },
8134 { "portrait", 0, QEMU_OPTION_portrait },
8135 { "k", HAS_ARG, QEMU_OPTION_k },
8136 #ifdef HAS_AUDIO
8137 { "audio-help", 0, QEMU_OPTION_audio_help },
8138 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8139 #endif
8141 { "net", HAS_ARG, QEMU_OPTION_net},
8142 #ifdef CONFIG_SLIRP
8143 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8144 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8145 #ifndef _WIN32
8146 { "smb", HAS_ARG, QEMU_OPTION_smb },
8147 #endif
8148 { "redir", HAS_ARG, QEMU_OPTION_redir },
8149 #endif
8151 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8152 { "append", HAS_ARG, QEMU_OPTION_append },
8153 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8155 { "S", 0, QEMU_OPTION_S },
8156 { "s", 0, QEMU_OPTION_s },
8157 { "p", HAS_ARG, QEMU_OPTION_p },
8158 { "d", HAS_ARG, QEMU_OPTION_d },
8159 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8160 { "L", HAS_ARG, QEMU_OPTION_L },
8161 { "bios", HAS_ARG, QEMU_OPTION_bios },
8162 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8163 #ifdef USE_KQEMU
8164 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8165 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8166 #endif
8167 #ifdef USE_KVM
8168 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8169 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8170 #endif
8171 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8172 { "g", 1, QEMU_OPTION_g },
8173 #endif
8174 { "localtime", 0, QEMU_OPTION_localtime },
8175 { "std-vga", 0, QEMU_OPTION_std_vga },
8176 { "monitor", 1, QEMU_OPTION_monitor },
8177 { "balloon", 1, QEMU_OPTION_balloon },
8178 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8179 { "echr", HAS_ARG, QEMU_OPTION_echr },
8180 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8181 { "serial", HAS_ARG, QEMU_OPTION_serial },
8182 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8183 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8184 { "incoming", 1, QEMU_OPTION_incoming },
8185 { "full-screen", 0, QEMU_OPTION_full_screen },
8186 #ifdef CONFIG_SDL
8187 { "no-frame", 0, QEMU_OPTION_no_frame },
8188 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8189 { "no-quit", 0, QEMU_OPTION_no_quit },
8190 #endif
8191 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8192 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8193 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8194 { "smp", HAS_ARG, QEMU_OPTION_smp },
8195 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8197 /* temporary options */
8198 { "usb", 0, QEMU_OPTION_usb },
8199 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8200 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8201 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8202 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8203 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8204 { "daemonize", 0, QEMU_OPTION_daemonize },
8205 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8206 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8207 { "semihosting", 0, QEMU_OPTION_semihosting },
8208 #endif
8209 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8210 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8211 { "name", HAS_ARG, QEMU_OPTION_name },
8212 #if defined(TARGET_SPARC)
8213 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8214 #endif
8215 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8216 #if defined(TARGET_ARM)
8217 { "old-param", 0, QEMU_OPTION_old_param },
8218 #endif
8219 { "clock", HAS_ARG, QEMU_OPTION_clock },
8220 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8221 { NULL },
8224 /* password input */
8226 int qemu_key_check(BlockDriverState *bs, const char *name)
8228 char password[256];
8229 int i;
8231 if (!bdrv_is_encrypted(bs))
8232 return 0;
8234 term_printf("%s is encrypted.\n", name);
8235 for(i = 0; i < 3; i++) {
8236 monitor_readline("Password: ", 1, password, sizeof(password));
8237 if (bdrv_set_key(bs, password) == 0)
8238 return 0;
8239 term_printf("invalid password\n");
8241 return -EPERM;
8244 static BlockDriverState *get_bdrv(int index)
8246 if (index > nb_drives)
8247 return NULL;
8248 return drives_table[index].bdrv;
8251 static void read_passwords(void)
8253 BlockDriverState *bs;
8254 int i;
8256 for(i = 0; i < 6; i++) {
8257 bs = get_bdrv(i);
8258 if (bs)
8259 qemu_key_check(bs, bdrv_get_device_name(bs));
8263 /* XXX: currently we cannot use simultaneously different CPUs */
8264 static void register_machines(void)
8266 #if defined(TARGET_I386)
8267 qemu_register_machine(&pc_machine);
8268 qemu_register_machine(&isapc_machine);
8269 #elif defined(TARGET_PPC)
8270 qemu_register_machine(&heathrow_machine);
8271 qemu_register_machine(&core99_machine);
8272 qemu_register_machine(&prep_machine);
8273 qemu_register_machine(&ref405ep_machine);
8274 qemu_register_machine(&taihu_machine);
8275 #elif defined(TARGET_MIPS)
8276 qemu_register_machine(&mips_machine);
8277 qemu_register_machine(&mips_malta_machine);
8278 qemu_register_machine(&mips_pica61_machine);
8279 qemu_register_machine(&mips_mipssim_machine);
8280 #elif defined(TARGET_SPARC)
8281 #ifdef TARGET_SPARC64
8282 qemu_register_machine(&sun4u_machine);
8283 #else
8284 qemu_register_machine(&ss5_machine);
8285 qemu_register_machine(&ss10_machine);
8286 qemu_register_machine(&ss600mp_machine);
8287 qemu_register_machine(&ss20_machine);
8288 #endif
8289 #elif defined(TARGET_ARM)
8290 qemu_register_machine(&integratorcp_machine);
8291 qemu_register_machine(&versatilepb_machine);
8292 qemu_register_machine(&versatileab_machine);
8293 qemu_register_machine(&realview_machine);
8294 qemu_register_machine(&akitapda_machine);
8295 qemu_register_machine(&spitzpda_machine);
8296 qemu_register_machine(&borzoipda_machine);
8297 qemu_register_machine(&terrierpda_machine);
8298 qemu_register_machine(&palmte_machine);
8299 qemu_register_machine(&lm3s811evb_machine);
8300 qemu_register_machine(&lm3s6965evb_machine);
8301 qemu_register_machine(&connex_machine);
8302 qemu_register_machine(&verdex_machine);
8303 qemu_register_machine(&mainstone2_machine);
8304 #elif defined(TARGET_SH4)
8305 qemu_register_machine(&shix_machine);
8306 qemu_register_machine(&r2d_machine);
8307 #elif defined(TARGET_ALPHA)
8308 /* XXX: TODO */
8309 #elif defined(TARGET_M68K)
8310 qemu_register_machine(&mcf5208evb_machine);
8311 qemu_register_machine(&an5206_machine);
8312 qemu_register_machine(&dummy_m68k_machine);
8313 #elif defined(TARGET_CRIS)
8314 qemu_register_machine(&bareetraxfs_machine);
8315 #elif defined(TARGET_IA64)
8316 qemu_register_machine(&ipf_machine);
8317 #else
8318 #error unsupported CPU
8319 #endif
8322 #ifdef HAS_AUDIO
8323 struct soundhw soundhw[] = {
8324 #ifdef HAS_AUDIO_CHOICE
8325 #ifdef TARGET_I386
8327 "pcspk",
8328 "PC speaker",
8331 { .init_isa = pcspk_audio_init }
8333 #endif
8335 "sb16",
8336 "Creative Sound Blaster 16",
8339 { .init_isa = SB16_init }
8342 #ifdef CONFIG_ADLIB
8344 "adlib",
8345 #ifdef HAS_YMF262
8346 "Yamaha YMF262 (OPL3)",
8347 #else
8348 "Yamaha YM3812 (OPL2)",
8349 #endif
8352 { .init_isa = Adlib_init }
8354 #endif
8356 #ifdef CONFIG_GUS
8358 "gus",
8359 "Gravis Ultrasound GF1",
8362 { .init_isa = GUS_init }
8364 #endif
8367 "es1370",
8368 "ENSONIQ AudioPCI ES1370",
8371 { .init_pci = es1370_init }
8373 #endif
8375 { NULL, NULL, 0, 0, { NULL } }
8378 static void select_soundhw (const char *optarg)
8380 struct soundhw *c;
8382 if (*optarg == '?') {
8383 show_valid_cards:
8385 printf ("Valid sound card names (comma separated):\n");
8386 for (c = soundhw; c->name; ++c) {
8387 printf ("%-11s %s\n", c->name, c->descr);
8389 printf ("\n-soundhw all will enable all of the above\n");
8390 exit (*optarg != '?');
8392 else {
8393 size_t l;
8394 const char *p;
8395 char *e;
8396 int bad_card = 0;
8398 if (!strcmp (optarg, "all")) {
8399 for (c = soundhw; c->name; ++c) {
8400 c->enabled = 1;
8402 return;
8405 p = optarg;
8406 while (*p) {
8407 e = strchr (p, ',');
8408 l = !e ? strlen (p) : (size_t) (e - p);
8410 for (c = soundhw; c->name; ++c) {
8411 if (!strncmp (c->name, p, l)) {
8412 c->enabled = 1;
8413 break;
8417 if (!c->name) {
8418 if (l > 80) {
8419 fprintf (stderr,
8420 "Unknown sound card name (too big to show)\n");
8422 else {
8423 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8424 (int) l, p);
8426 bad_card = 1;
8428 p += l + (e != NULL);
8431 if (bad_card)
8432 goto show_valid_cards;
8435 #endif
8437 #ifdef _WIN32
8438 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8440 exit(STATUS_CONTROL_C_EXIT);
8441 return TRUE;
8443 #endif
8445 #define MAX_NET_CLIENTS 32
8447 static int saved_argc;
8448 static char **saved_argv;
8450 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8452 *argc = saved_argc;
8453 *argv = saved_argv;
8454 *opt_daemonize = daemonize;
8455 *opt_incoming = incoming;
8458 int main(int argc, char **argv)
8460 #ifdef CONFIG_GDBSTUB
8461 int use_gdbstub;
8462 const char *gdbstub_port;
8463 #endif
8464 uint32_t boot_devices_bitmap = 0;
8465 int i;
8466 int snapshot, linux_boot, net_boot;
8467 const char *initrd_filename;
8468 const char *kernel_filename, *kernel_cmdline;
8469 const char *boot_devices = "";
8470 DisplayState *ds = &display_state;
8471 int cyls, heads, secs, translation;
8472 char net_clients[MAX_NET_CLIENTS][256];
8473 int nb_net_clients;
8474 int hda_index;
8475 int optind;
8476 const char *r, *optarg;
8477 CharDriverState *monitor_hd;
8478 char monitor_device[128];
8479 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8480 int vmchannel_device_index;
8481 char serial_devices[MAX_SERIAL_PORTS][128];
8482 int serial_device_index;
8483 char parallel_devices[MAX_PARALLEL_PORTS][128];
8484 int parallel_device_index;
8485 const char *loadvm = NULL;
8486 QEMUMachine *machine;
8487 const char *cpu_model;
8488 char usb_devices[MAX_USB_CMDLINE][128];
8489 int usb_devices_index;
8490 int fds[2];
8491 const char *pid_file = NULL;
8492 VLANState *vlan;
8494 saved_argc = argc;
8495 saved_argv = argv;
8497 LIST_INIT (&vm_change_state_head);
8498 #ifndef _WIN32
8500 struct sigaction act;
8501 sigfillset(&act.sa_mask);
8502 act.sa_flags = 0;
8503 act.sa_handler = SIG_IGN;
8504 sigaction(SIGPIPE, &act, NULL);
8506 #else
8507 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8508 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8509 QEMU to run on a single CPU */
8511 HANDLE h;
8512 DWORD mask, smask;
8513 int i;
8514 h = GetCurrentProcess();
8515 if (GetProcessAffinityMask(h, &mask, &smask)) {
8516 for(i = 0; i < 32; i++) {
8517 if (mask & (1 << i))
8518 break;
8520 if (i != 32) {
8521 mask = 1 << i;
8522 SetProcessAffinityMask(h, mask);
8526 #endif
8528 register_machines();
8529 machine = first_machine;
8530 cpu_model = NULL;
8531 initrd_filename = NULL;
8532 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8533 vga_ram_size = VGA_RAM_SIZE;
8534 #ifdef CONFIG_GDBSTUB
8535 use_gdbstub = 0;
8536 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8537 #endif
8538 snapshot = 0;
8539 nographic = 0;
8540 kernel_filename = NULL;
8541 kernel_cmdline = "";
8542 cyls = heads = secs = 0;
8543 translation = BIOS_ATA_TRANSLATION_AUTO;
8544 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8546 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8547 vmchannel_devices[i][0] = '\0';
8548 vmchannel_device_index = 0;
8550 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8551 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8552 serial_devices[i][0] = '\0';
8553 serial_device_index = 0;
8555 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8556 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8557 parallel_devices[i][0] = '\0';
8558 parallel_device_index = 0;
8560 usb_devices_index = 0;
8562 nb_net_clients = 0;
8563 nb_drives = 0;
8564 nb_drives_opt = 0;
8565 hda_index = -1;
8567 nb_nics = 0;
8568 /* default mac address of the first network interface */
8570 optind = 1;
8571 for(;;) {
8572 if (optind >= argc)
8573 break;
8574 r = argv[optind];
8575 if (r[0] != '-') {
8576 hda_index = drive_add(HD_ALIAS, argv[optind++], 0);
8577 } else {
8578 const QEMUOption *popt;
8580 optind++;
8581 /* Treat --foo the same as -foo. */
8582 if (r[1] == '-')
8583 r++;
8584 popt = qemu_options;
8585 for(;;) {
8586 if (!popt->name) {
8587 fprintf(stderr, "%s: invalid option -- '%s'\n",
8588 argv[0], r);
8589 exit(1);
8591 if (!strcmp(popt->name, r + 1))
8592 break;
8593 popt++;
8595 if (popt->flags & HAS_ARG) {
8596 if (optind >= argc) {
8597 fprintf(stderr, "%s: option '%s' requires an argument\n",
8598 argv[0], r);
8599 exit(1);
8601 optarg = argv[optind++];
8602 } else {
8603 optarg = NULL;
8606 switch(popt->index) {
8607 case QEMU_OPTION_M:
8608 machine = find_machine(optarg);
8609 if (!machine) {
8610 QEMUMachine *m;
8611 printf("Supported machines are:\n");
8612 for(m = first_machine; m != NULL; m = m->next) {
8613 printf("%-10s %s%s\n",
8614 m->name, m->desc,
8615 m == first_machine ? " (default)" : "");
8617 exit(*optarg != '?');
8619 break;
8620 case QEMU_OPTION_cpu:
8621 /* hw initialization will check this */
8622 if (*optarg == '?') {
8623 /* XXX: implement xxx_cpu_list for targets that still miss it */
8624 #if defined(cpu_list)
8625 cpu_list(stdout, &fprintf);
8626 #endif
8627 exit(0);
8628 } else {
8629 cpu_model = optarg;
8631 break;
8632 case QEMU_OPTION_initrd:
8633 initrd_filename = optarg;
8634 break;
8635 case QEMU_OPTION_hda:
8636 if (cyls == 0)
8637 hda_index = drive_add(HD_ALIAS, optarg, 0);
8638 else
8639 hda_index = drive_add(HD_ALIAS
8640 ",cyls=%d,heads=%d,secs=%d%s",
8641 optarg, 0, cyls, heads, secs,
8642 translation == BIOS_ATA_TRANSLATION_LBA ?
8643 ",trans=lba" :
8644 translation == BIOS_ATA_TRANSLATION_NONE ?
8645 ",trans=none" : "");
8646 break;
8647 case QEMU_OPTION_hdb:
8648 case QEMU_OPTION_hdc:
8649 case QEMU_OPTION_hdd:
8650 drive_add(HD_ALIAS, optarg, popt->index - QEMU_OPTION_hda);
8651 break;
8652 case QEMU_OPTION_drive:
8653 drive_add("%s", optarg);
8654 break;
8655 case QEMU_OPTION_mtdblock:
8656 drive_add(MTD_ALIAS, optarg);
8657 break;
8658 case QEMU_OPTION_sd:
8659 drive_add("file=\"%s\"," SD_ALIAS, optarg);
8660 break;
8661 case QEMU_OPTION_pflash:
8662 drive_add(PFLASH_ALIAS, optarg);
8663 break;
8664 case QEMU_OPTION_snapshot:
8665 snapshot = 1;
8666 break;
8667 case QEMU_OPTION_hdachs:
8669 const char *p;
8670 p = optarg;
8671 cyls = strtol(p, (char **)&p, 0);
8672 if (cyls < 1 || cyls > 16383)
8673 goto chs_fail;
8674 if (*p != ',')
8675 goto chs_fail;
8676 p++;
8677 heads = strtol(p, (char **)&p, 0);
8678 if (heads < 1 || heads > 16)
8679 goto chs_fail;
8680 if (*p != ',')
8681 goto chs_fail;
8682 p++;
8683 secs = strtol(p, (char **)&p, 0);
8684 if (secs < 1 || secs > 63)
8685 goto chs_fail;
8686 if (*p == ',') {
8687 p++;
8688 if (!strcmp(p, "none"))
8689 translation = BIOS_ATA_TRANSLATION_NONE;
8690 else if (!strcmp(p, "lba"))
8691 translation = BIOS_ATA_TRANSLATION_LBA;
8692 else if (!strcmp(p, "auto"))
8693 translation = BIOS_ATA_TRANSLATION_AUTO;
8694 else
8695 goto chs_fail;
8696 } else if (*p != '\0') {
8697 chs_fail:
8698 fprintf(stderr, "qemu: invalid physical CHS format\n");
8699 exit(1);
8701 if (hda_index != -1)
8702 snprintf(drives_opt[hda_index] +
8703 strlen(drives_opt[hda_index]),
8704 sizeof(drives_opt[0]) -
8705 strlen(drives_opt[hda_index]),
8706 ",cyls=%d,heads=%d,secs=%d%s",
8707 cyls, heads, secs,
8708 translation == BIOS_ATA_TRANSLATION_LBA ?
8709 ",trans=lba" :
8710 translation == BIOS_ATA_TRANSLATION_NONE ?
8711 ",trans=none" : "");
8713 break;
8714 case QEMU_OPTION_nographic:
8715 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8716 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8717 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8718 nographic = 1;
8719 break;
8720 case QEMU_OPTION_portrait:
8721 graphic_rotate = 1;
8722 break;
8723 case QEMU_OPTION_kernel:
8724 kernel_filename = optarg;
8725 break;
8726 case QEMU_OPTION_append:
8727 kernel_cmdline = optarg;
8728 break;
8729 case QEMU_OPTION_cdrom:
8730 drive_add("file=\"%s\"," CDROM_ALIAS, optarg);
8731 break;
8732 case QEMU_OPTION_boot:
8733 boot_devices = optarg;
8734 /* We just do some generic consistency checks */
8736 /* Could easily be extended to 64 devices if needed */
8737 const char *p;
8739 boot_devices_bitmap = 0;
8740 for (p = boot_devices; *p != '\0'; p++) {
8741 /* Allowed boot devices are:
8742 * a b : floppy disk drives
8743 * c ... f : IDE disk drives
8744 * g ... m : machine implementation dependant drives
8745 * n ... p : network devices
8746 * It's up to each machine implementation to check
8747 * if the given boot devices match the actual hardware
8748 * implementation and firmware features.
8750 if (*p < 'a' || *p > 'q') {
8751 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8752 exit(1);
8754 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8755 fprintf(stderr,
8756 "Boot device '%c' was given twice\n",*p);
8757 exit(1);
8759 boot_devices_bitmap |= 1 << (*p - 'a');
8762 break;
8763 case QEMU_OPTION_fda:
8764 case QEMU_OPTION_fdb:
8765 drive_add("file=\"%s\"," FD_ALIAS, optarg,
8766 popt->index - QEMU_OPTION_fda);
8767 break;
8768 #ifdef TARGET_I386
8769 case QEMU_OPTION_no_fd_bootchk:
8770 fd_bootchk = 0;
8771 break;
8772 #endif
8773 case QEMU_OPTION_no_code_copy:
8774 code_copy_enabled = 0;
8775 break;
8776 case QEMU_OPTION_net:
8777 if (nb_net_clients >= MAX_NET_CLIENTS) {
8778 fprintf(stderr, "qemu: too many network clients\n");
8779 exit(1);
8781 pstrcpy(net_clients[nb_net_clients],
8782 sizeof(net_clients[0]),
8783 optarg);
8784 nb_net_clients++;
8785 break;
8786 #ifdef CONFIG_SLIRP
8787 case QEMU_OPTION_tftp:
8788 tftp_prefix = optarg;
8789 break;
8790 case QEMU_OPTION_bootp:
8791 bootp_filename = optarg;
8792 break;
8793 #ifndef _WIN32
8794 case QEMU_OPTION_smb:
8795 net_slirp_smb(optarg);
8796 break;
8797 #endif
8798 case QEMU_OPTION_redir:
8799 net_slirp_redir(optarg);
8800 break;
8801 #endif
8802 #ifdef HAS_AUDIO
8803 case QEMU_OPTION_audio_help:
8804 AUD_help ();
8805 exit (0);
8806 break;
8807 case QEMU_OPTION_soundhw:
8808 select_soundhw (optarg);
8809 break;
8810 #endif
8811 case QEMU_OPTION_h:
8812 help(0);
8813 break;
8814 case QEMU_OPTION_m:
8815 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
8816 if (ram_size <= 0)
8817 help(1);
8818 if (ram_size > PHYS_RAM_MAX_SIZE) {
8819 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8820 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8821 exit(1);
8823 break;
8824 case QEMU_OPTION_d:
8826 int mask;
8827 CPULogItem *item;
8829 mask = cpu_str_to_log_mask(optarg);
8830 if (!mask) {
8831 printf("Log items (comma separated):\n");
8832 for(item = cpu_log_items; item->mask != 0; item++) {
8833 printf("%-10s %s\n", item->name, item->help);
8835 exit(1);
8837 cpu_set_log(mask);
8839 break;
8840 #ifdef CONFIG_GDBSTUB
8841 case QEMU_OPTION_s:
8842 use_gdbstub = 1;
8843 break;
8844 case QEMU_OPTION_p:
8845 gdbstub_port = optarg;
8846 break;
8847 #endif
8848 case QEMU_OPTION_L:
8849 bios_dir = optarg;
8850 break;
8851 case QEMU_OPTION_bios:
8852 bios_name = optarg;
8853 break;
8854 case QEMU_OPTION_S:
8855 autostart = 0;
8856 break;
8857 case QEMU_OPTION_k:
8858 keyboard_layout = optarg;
8859 break;
8860 case QEMU_OPTION_localtime:
8861 rtc_utc = 0;
8862 break;
8863 case QEMU_OPTION_cirrusvga:
8864 cirrus_vga_enabled = 1;
8865 vmsvga_enabled = 0;
8866 break;
8867 case QEMU_OPTION_vmsvga:
8868 cirrus_vga_enabled = 0;
8869 vmsvga_enabled = 1;
8870 break;
8871 case QEMU_OPTION_std_vga:
8872 cirrus_vga_enabled = 0;
8873 vmsvga_enabled = 0;
8874 break;
8875 case QEMU_OPTION_g:
8877 const char *p;
8878 int w, h, depth;
8879 p = optarg;
8880 w = strtol(p, (char **)&p, 10);
8881 if (w <= 0) {
8882 graphic_error:
8883 fprintf(stderr, "qemu: invalid resolution or depth\n");
8884 exit(1);
8886 if (*p != 'x')
8887 goto graphic_error;
8888 p++;
8889 h = strtol(p, (char **)&p, 10);
8890 if (h <= 0)
8891 goto graphic_error;
8892 if (*p == 'x') {
8893 p++;
8894 depth = strtol(p, (char **)&p, 10);
8895 if (depth != 8 && depth != 15 && depth != 16 &&
8896 depth != 24 && depth != 32)
8897 goto graphic_error;
8898 } else if (*p == '\0') {
8899 depth = graphic_depth;
8900 } else {
8901 goto graphic_error;
8904 graphic_width = w;
8905 graphic_height = h;
8906 graphic_depth = depth;
8908 break;
8909 case QEMU_OPTION_echr:
8911 char *r;
8912 term_escape_char = strtol(optarg, &r, 0);
8913 if (r == optarg)
8914 printf("Bad argument to echr\n");
8915 break;
8917 case QEMU_OPTION_monitor:
8918 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8919 break;
8920 case QEMU_OPTION_balloon:
8921 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8922 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8923 exit(1);
8925 if (balloon_used) {
8926 fprintf(stderr, "qemu: only one balloon device can be used\n");
8927 exit(1);
8929 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
8930 vmchannel_device_index++;
8931 balloon_used = 1;
8932 break;
8933 case QEMU_OPTION_vmchannel:
8934 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8935 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8936 exit(1);
8938 pstrcpy(vmchannel_devices[vmchannel_device_index],
8939 sizeof(vmchannel_devices[0]), optarg);
8940 vmchannel_device_index++;
8941 break;
8942 case QEMU_OPTION_serial:
8943 if (serial_device_index >= MAX_SERIAL_PORTS) {
8944 fprintf(stderr, "qemu: too many serial ports\n");
8945 exit(1);
8947 pstrcpy(serial_devices[serial_device_index],
8948 sizeof(serial_devices[0]), optarg);
8949 serial_device_index++;
8950 break;
8951 case QEMU_OPTION_parallel:
8952 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8953 fprintf(stderr, "qemu: too many parallel ports\n");
8954 exit(1);
8956 pstrcpy(parallel_devices[parallel_device_index],
8957 sizeof(parallel_devices[0]), optarg);
8958 parallel_device_index++;
8959 break;
8960 case QEMU_OPTION_loadvm:
8961 loadvm = optarg;
8962 break;
8963 case QEMU_OPTION_incoming:
8964 incoming = optarg;
8965 break;
8966 case QEMU_OPTION_full_screen:
8967 full_screen = 1;
8968 break;
8969 #ifdef CONFIG_SDL
8970 case QEMU_OPTION_no_frame:
8971 no_frame = 1;
8972 break;
8973 case QEMU_OPTION_alt_grab:
8974 alt_grab = 1;
8975 break;
8976 case QEMU_OPTION_no_quit:
8977 no_quit = 1;
8978 break;
8979 #endif
8980 case QEMU_OPTION_pidfile:
8981 pid_file = optarg;
8982 break;
8983 #ifdef TARGET_I386
8984 case QEMU_OPTION_win2k_hack:
8985 win2k_install_hack = 1;
8986 break;
8987 #endif
8988 #ifdef USE_KQEMU
8989 case QEMU_OPTION_no_kqemu:
8990 kqemu_allowed = 0;
8991 break;
8992 case QEMU_OPTION_kernel_kqemu:
8993 kqemu_allowed = 2;
8994 break;
8995 #endif
8996 #ifdef USE_KVM
8997 case QEMU_OPTION_no_kvm:
8998 kvm_allowed = 0;
8999 break;
9000 case QEMU_OPTION_no_kvm_irqchip:
9001 kvm_irqchip = 0;
9002 break;
9003 #endif
9004 case QEMU_OPTION_usb:
9005 usb_enabled = 1;
9006 break;
9007 case QEMU_OPTION_usbdevice:
9008 usb_enabled = 1;
9009 if (usb_devices_index >= MAX_USB_CMDLINE) {
9010 fprintf(stderr, "Too many USB devices\n");
9011 exit(1);
9013 pstrcpy(usb_devices[usb_devices_index],
9014 sizeof(usb_devices[usb_devices_index]),
9015 optarg);
9016 usb_devices_index++;
9017 break;
9018 case QEMU_OPTION_smp:
9019 smp_cpus = atoi(optarg);
9020 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9021 fprintf(stderr, "Invalid number of CPUs\n");
9022 exit(1);
9024 break;
9025 case QEMU_OPTION_vnc:
9026 vnc_display = optarg;
9027 break;
9028 case QEMU_OPTION_no_acpi:
9029 acpi_enabled = 0;
9030 break;
9031 case QEMU_OPTION_no_reboot:
9032 no_reboot = 1;
9033 break;
9034 case QEMU_OPTION_show_cursor:
9035 cursor_hide = 0;
9036 break;
9037 case QEMU_OPTION_daemonize:
9038 daemonize = 1;
9039 break;
9040 case QEMU_OPTION_option_rom:
9041 if (nb_option_roms >= MAX_OPTION_ROMS) {
9042 fprintf(stderr, "Too many option ROMs\n");
9043 exit(1);
9045 option_rom[nb_option_roms] = optarg;
9046 nb_option_roms++;
9047 break;
9048 case QEMU_OPTION_semihosting:
9049 semihosting_enabled = 1;
9050 break;
9051 case QEMU_OPTION_tdf:
9052 time_drift_fix = 1;
9053 break;
9054 case QEMU_OPTION_kvm_shadow_memory:
9055 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9056 break;
9057 case QEMU_OPTION_name:
9058 qemu_name = optarg;
9059 break;
9060 #ifdef TARGET_SPARC
9061 case QEMU_OPTION_prom_env:
9062 if (nb_prom_envs >= MAX_PROM_ENVS) {
9063 fprintf(stderr, "Too many prom variables\n");
9064 exit(1);
9066 prom_envs[nb_prom_envs] = optarg;
9067 nb_prom_envs++;
9068 break;
9069 #endif
9070 case QEMU_OPTION_cpu_vendor:
9071 cpu_vendor_string = optarg;
9072 break;
9073 #ifdef TARGET_ARM
9074 case QEMU_OPTION_old_param:
9075 old_param = 1;
9076 #endif
9077 case QEMU_OPTION_clock:
9078 configure_alarms(optarg);
9079 break;
9080 case QEMU_OPTION_startdate:
9082 struct tm tm;
9083 if (!strcmp(optarg, "now")) {
9084 rtc_start_date = -1;
9085 } else {
9086 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9087 &tm.tm_year,
9088 &tm.tm_mon,
9089 &tm.tm_mday,
9090 &tm.tm_hour,
9091 &tm.tm_min,
9092 &tm.tm_sec) == 6) {
9093 /* OK */
9094 } else if (sscanf(optarg, "%d-%d-%d",
9095 &tm.tm_year,
9096 &tm.tm_mon,
9097 &tm.tm_mday) == 3) {
9098 tm.tm_hour = 0;
9099 tm.tm_min = 0;
9100 tm.tm_sec = 0;
9101 } else {
9102 goto date_fail;
9104 tm.tm_year -= 1900;
9105 tm.tm_mon--;
9106 rtc_start_date = mktimegm(&tm);
9107 if (rtc_start_date == -1) {
9108 date_fail:
9109 fprintf(stderr, "Invalid date format. Valid format are:\n"
9110 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9111 exit(1);
9115 break;
9120 #ifndef _WIN32
9121 if (daemonize) {
9122 pid_t pid;
9124 if (pipe(fds) == -1)
9125 exit(1);
9127 pid = fork();
9128 if (pid > 0) {
9129 uint8_t status;
9130 ssize_t len;
9132 close(fds[1]);
9134 again:
9135 len = read(fds[0], &status, 1);
9136 if (len == -1 && (errno == EINTR))
9137 goto again;
9139 if (len != 1)
9140 exit(1);
9141 else if (status == 1) {
9142 fprintf(stderr, "Could not acquire pidfile\n");
9143 exit(1);
9144 } else
9145 exit(0);
9146 } else if (pid < 0)
9147 exit(1);
9149 setsid();
9151 pid = fork();
9152 if (pid > 0)
9153 exit(0);
9154 else if (pid < 0)
9155 exit(1);
9157 umask(027);
9159 signal(SIGTSTP, SIG_IGN);
9160 signal(SIGTTOU, SIG_IGN);
9161 signal(SIGTTIN, SIG_IGN);
9163 #endif
9165 #if USE_KVM
9166 if (kvm_allowed) {
9167 if (kvm_qemu_init() < 0) {
9168 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9169 kvm_allowed = 0;
9172 #endif
9174 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9175 if (daemonize) {
9176 uint8_t status = 1;
9177 write(fds[1], &status, 1);
9178 } else
9179 fprintf(stderr, "Could not acquire pid file\n");
9180 exit(1);
9183 #ifdef USE_KQEMU
9184 if (smp_cpus > 1)
9185 kqemu_allowed = 0;
9186 #endif
9187 linux_boot = (kernel_filename != NULL);
9188 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9190 /* XXX: this should not be: some embedded targets just have flash */
9191 if (!linux_boot && net_boot == 0 &&
9192 nb_drives_opt == 0)
9193 help(1);
9195 /* boot to floppy or the default cd if no hard disk defined yet */
9196 if (!boot_devices[0]) {
9197 boot_devices = "cad";
9199 setvbuf(stdout, NULL, _IOLBF, 0);
9201 init_timers();
9202 init_timer_alarm();
9203 qemu_aio_init();
9205 #ifdef _WIN32
9206 socket_init();
9207 #endif
9209 /* init network clients */
9210 if (nb_net_clients == 0) {
9211 /* if no clients, we use a default config */
9212 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9213 "nic");
9214 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9215 "user");
9216 nb_net_clients = 2;
9219 for(i = 0;i < nb_net_clients; i++) {
9220 if (net_client_init(net_clients[i]) < 0)
9221 exit(1);
9223 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9224 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9225 continue;
9226 if (vlan->nb_guest_devs == 0) {
9227 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9228 exit(1);
9230 if (vlan->nb_host_devs == 0)
9231 fprintf(stderr,
9232 "Warning: vlan %d is not connected to host network\n",
9233 vlan->id);
9236 #ifdef TARGET_I386
9237 /* XXX: this should be moved in the PC machine instantiation code */
9238 if (net_boot != 0) {
9239 int netroms = 0;
9240 for (i = 0; i < nb_nics && i < 4; i++) {
9241 const char *model = nd_table[i].model;
9242 char buf[1024];
9243 if (net_boot & (1 << i)) {
9244 if (model == NULL)
9245 model = "ne2k_pci";
9246 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9247 if (get_image_size(buf) > 0) {
9248 if (nb_option_roms >= MAX_OPTION_ROMS) {
9249 fprintf(stderr, "Too many option ROMs\n");
9250 exit(1);
9252 option_rom[nb_option_roms] = strdup(buf);
9253 nb_option_roms++;
9254 netroms++;
9258 if (netroms == 0) {
9259 fprintf(stderr, "No valid PXE rom found for network device\n");
9260 exit(1);
9263 #endif
9265 /* init the memory */
9266 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9268 #if USE_KVM
9269 /* Initialize kvm */
9270 #ifdef TARGET_IA64
9271 #define KVM_EXTRA_PAGES 0
9272 #else
9273 #define KVM_EXTRA_PAGES 3
9274 #endif
9275 if (kvm_allowed) {
9276 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9277 if (kvm_qemu_create_context() < 0) {
9278 fprintf(stderr, "Could not create KVM context\n");
9279 exit(1);
9281 #ifdef KVM_CAP_USER_MEMORY
9283 int ret;
9285 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9286 if (ret) {
9287 phys_ram_base = qemu_vmalloc(phys_ram_size);
9288 if (!phys_ram_base) {
9289 fprintf(stderr, "Could not allocate physical memory\n");
9290 exit(1);
9294 #endif
9295 } else {
9296 phys_ram_base = qemu_vmalloc(phys_ram_size);
9297 if (!phys_ram_base) {
9298 fprintf(stderr, "Could not allocate physical memory\n");
9299 exit(1);
9302 #else
9303 phys_ram_base = qemu_vmalloc(phys_ram_size);
9304 if (!phys_ram_base) {
9305 fprintf(stderr, "Could not allocate physical memory\n");
9306 exit(1);
9308 #endif
9310 bdrv_init();
9312 /* we always create the cdrom drive, even if no disk is there */
9314 if (nb_drives_opt < MAX_DRIVES)
9315 drive_add(CDROM_ALIAS);
9317 /* we always create at least one floppy */
9319 if (nb_drives_opt < MAX_DRIVES)
9320 drive_add(FD_ALIAS, 0);
9322 /* we always create one sd slot, even if no card is in it */
9324 if (nb_drives_opt < MAX_DRIVES)
9325 drive_add(SD_ALIAS);
9327 /* open the virtual block devices */
9329 for(i = 0; i < nb_drives_opt; i++)
9330 if (drive_init(drives_opt[i], snapshot, machine) == -1)
9331 exit(1);
9333 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9334 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9336 init_ioports();
9338 /* terminal init */
9339 memset(&display_state, 0, sizeof(display_state));
9340 if (nographic) {
9341 /* nearly nothing to do */
9342 dumb_display_init(ds);
9343 } else if (vnc_display != NULL) {
9344 vnc_display_init(ds);
9345 if (vnc_display_open(ds, vnc_display) < 0)
9346 exit(1);
9347 } else {
9348 #if defined(CONFIG_SDL)
9349 sdl_display_init(ds, full_screen, no_frame);
9350 #elif defined(CONFIG_COCOA)
9351 cocoa_display_init(ds, full_screen);
9352 #else
9353 dumb_display_init(ds);
9354 #endif
9357 /* Maintain compatibility with multiple stdio monitors */
9358 if (!strcmp(monitor_device,"stdio")) {
9359 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9360 if (!strcmp(serial_devices[i],"mon:stdio")) {
9361 monitor_device[0] = '\0';
9362 break;
9363 } else if (!strcmp(serial_devices[i],"stdio")) {
9364 monitor_device[0] = '\0';
9365 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9366 break;
9370 if (monitor_device[0] != '\0') {
9371 monitor_hd = qemu_chr_open(monitor_device);
9372 if (!monitor_hd) {
9373 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9374 exit(1);
9376 monitor_init(monitor_hd, !nographic);
9379 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9380 const char *devname = vmchannel_devices[i];
9381 if (devname[0] != '\0' && strcmp(devname, "none")) {
9382 int devid;
9383 char *termn;
9385 if (strstart(devname, "di:", &devname)) {
9386 devid = strtol(devname, &termn, 16);
9387 devname = termn + 1;
9389 else {
9390 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9391 devname);
9392 exit(1);
9394 vmchannel_hds[i] = qemu_chr_open(devname);
9395 if (!vmchannel_hds[i]) {
9396 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9397 devname);
9398 exit(1);
9400 vmchannel_init(vmchannel_hds[i], devid, i);
9404 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9405 const char *devname = serial_devices[i];
9406 if (devname[0] != '\0' && strcmp(devname, "none")) {
9407 serial_hds[i] = qemu_chr_open(devname);
9408 if (!serial_hds[i]) {
9409 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9410 devname);
9411 exit(1);
9413 if (strstart(devname, "vc", 0))
9414 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9418 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9419 const char *devname = parallel_devices[i];
9420 if (devname[0] != '\0' && strcmp(devname, "none")) {
9421 parallel_hds[i] = qemu_chr_open(devname);
9422 if (!parallel_hds[i]) {
9423 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9424 devname);
9425 exit(1);
9427 if (strstart(devname, "vc", 0))
9428 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9432 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9433 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9435 /* init USB devices */
9436 if (usb_enabled) {
9437 for(i = 0; i < usb_devices_index; i++) {
9438 if (usb_device_add(usb_devices[i]) < 0) {
9439 fprintf(stderr, "Warning: could not add USB device %s\n",
9440 usb_devices[i]);
9445 if (display_state.dpy_refresh) {
9446 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9447 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9450 #ifdef USE_KVM
9451 if (kvm_allowed)
9452 kvm_init_ap();
9453 #endif
9455 #ifdef CONFIG_GDBSTUB
9456 if (use_gdbstub) {
9457 /* XXX: use standard host:port notation and modify options
9458 accordingly. */
9459 if (gdbserver_start(gdbstub_port) < 0) {
9460 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9461 gdbstub_port);
9462 exit(1);
9465 #endif
9466 if (loadvm)
9467 do_loadvm(loadvm);
9469 if (incoming) {
9470 int rc;
9472 rc = migrate_incoming(incoming);
9473 if (rc != 0) {
9474 fprintf(stderr, "Migration failed rc=%d\n", rc);
9475 exit(rc);
9480 /* XXX: simplify init */
9481 read_passwords();
9482 if (autostart) {
9483 vm_start();
9487 if (daemonize) {
9488 uint8_t status = 0;
9489 ssize_t len;
9490 int fd;
9492 again1:
9493 len = write(fds[1], &status, 1);
9494 if (len == -1 && (errno == EINTR))
9495 goto again1;
9497 if (len != 1)
9498 exit(1);
9500 chdir("/");
9501 TFR(fd = open("/dev/null", O_RDWR));
9502 if (fd == -1)
9503 exit(1);
9505 dup2(fd, 0);
9506 dup2(fd, 1);
9507 dup2(fd, 2);
9509 close(fd);
9512 main_loop();
9513 quit_timers();
9515 #if !defined(_WIN32)
9516 /* close network clients */
9517 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9518 VLANClientState *vc;
9520 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9521 if (vc->fd_read == tap_receive) {
9522 char ifname[64];
9523 TAPState *s = vc->opaque;
9525 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9526 s->down_script[0])
9527 launch_script(s->down_script, ifname, s->fd);
9531 #endif
9532 return 0;