Add acpi powerbutton support
[qemu-kvm/fedora.git] / vl.c
blob0f023ac28882a0f2fe4fd3d09cd13e831018ef15
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 int extboot_drive = -1;
181 /* point to the block driver where the snapshots are managed */
182 BlockDriverState *bs_snapshots;
183 int vga_ram_size;
184 static DisplayState display_state;
185 int nographic;
186 const char* keyboard_layout = NULL;
187 int64_t ticks_per_sec;
188 int64_t ram_size;
189 int pit_min_timer_count = 0;
190 int nb_nics;
191 NICInfo nd_table[MAX_NICS];
192 int vm_running;
193 int rtc_utc = 1;
194 int rtc_start_date = -1; /* -1 means now */
195 int cirrus_vga_enabled = 1;
196 int vmsvga_enabled = 0;
197 #ifdef TARGET_SPARC
198 int graphic_width = 1024;
199 int graphic_height = 768;
200 int graphic_depth = 8;
201 #else
202 int graphic_width = 800;
203 int graphic_height = 600;
204 int graphic_depth = 15;
205 #endif
206 int full_screen = 0;
207 int no_frame = 0;
208 int no_quit = 0;
209 int balloon_used = 0;
210 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
211 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
212 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
213 #ifdef TARGET_I386
214 int win2k_install_hack = 0;
215 #endif
216 int usb_enabled = 0;
217 static VLANState *first_vlan;
218 int smp_cpus = 1;
219 const char *vnc_display;
220 #if defined(TARGET_SPARC)
221 #define MAX_CPUS 16
222 #elif defined(TARGET_I386)
223 #define MAX_CPUS 255
224 #elif defined(TARGET_IA64)
225 #define MAX_CPUS 4
226 #else
227 #define MAX_CPUS 1
228 #endif
229 int acpi_enabled = 1;
230 int fd_bootchk = 1;
231 int no_reboot = 0;
232 int cursor_hide = 1;
233 int graphic_rotate = 0;
234 int daemonize = 0;
235 const char *incoming;
236 const char *option_rom[MAX_OPTION_ROMS];
237 int nb_option_roms;
238 int semihosting_enabled = 0;
239 int autostart = 1;
240 int time_drift_fix = 0;
241 unsigned int kvm_shadow_memory = 0;
242 const char *cpu_vendor_string;
243 #ifdef TARGET_ARM
244 int old_param = 0;
245 #endif
246 const char *qemu_name;
247 int alt_grab = 0;
248 #ifdef TARGET_SPARC
249 unsigned int nb_prom_envs = 0;
250 const char *prom_envs[MAX_PROM_ENVS];
251 #endif
252 int nb_drives_opt;
253 char drives_opt[MAX_DRIVES][1024];
255 static CPUState *cur_cpu;
256 static CPUState *next_cpu;
257 static int event_pending = 1;
259 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
261 void decorate_application_name(char *appname, int max_len)
263 #if USE_KVM
264 if (kvm_allowed)
266 int remain = max_len - strlen(appname) - 1;
268 if (remain > 0)
269 strncat(appname, "/KVM", remain);
271 #endif
274 /***********************************************************/
275 /* x86 ISA bus support */
277 target_phys_addr_t isa_mem_base = 0;
278 PicState2 *isa_pic;
280 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
282 #ifdef DEBUG_UNUSED_IOPORT
283 fprintf(stderr, "unused inb: port=0x%04x\n", address);
284 #endif
285 return 0xff;
288 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
290 #ifdef DEBUG_UNUSED_IOPORT
291 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
292 #endif
295 /* default is to make two byte accesses */
296 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
298 uint32_t data;
299 data = ioport_read_table[0][address](ioport_opaque[address], address);
300 address = (address + 1) & (MAX_IOPORTS - 1);
301 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
302 return data;
305 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
307 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
308 address = (address + 1) & (MAX_IOPORTS - 1);
309 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
312 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
314 #ifdef DEBUG_UNUSED_IOPORT
315 fprintf(stderr, "unused inl: port=0x%04x\n", address);
316 #endif
317 return 0xffffffff;
320 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
322 #ifdef DEBUG_UNUSED_IOPORT
323 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
324 #endif
327 static void init_ioports(void)
329 int i;
331 for(i = 0; i < MAX_IOPORTS; i++) {
332 ioport_read_table[0][i] = default_ioport_readb;
333 ioport_write_table[0][i] = default_ioport_writeb;
334 ioport_read_table[1][i] = default_ioport_readw;
335 ioport_write_table[1][i] = default_ioport_writew;
336 ioport_read_table[2][i] = default_ioport_readl;
337 ioport_write_table[2][i] = default_ioport_writel;
341 /* size is the word size in byte */
342 int register_ioport_read(int start, int length, int size,
343 IOPortReadFunc *func, void *opaque)
345 int i, bsize;
347 if (size == 1) {
348 bsize = 0;
349 } else if (size == 2) {
350 bsize = 1;
351 } else if (size == 4) {
352 bsize = 2;
353 } else {
354 hw_error("register_ioport_read: invalid size");
355 return -1;
357 for(i = start; i < start + length; i += size) {
358 ioport_read_table[bsize][i] = func;
359 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
360 hw_error("register_ioport_read: invalid opaque");
361 ioport_opaque[i] = opaque;
363 return 0;
366 /* size is the word size in byte */
367 int register_ioport_write(int start, int length, int size,
368 IOPortWriteFunc *func, void *opaque)
370 int i, bsize;
372 if (size == 1) {
373 bsize = 0;
374 } else if (size == 2) {
375 bsize = 1;
376 } else if (size == 4) {
377 bsize = 2;
378 } else {
379 hw_error("register_ioport_write: invalid size");
380 return -1;
382 for(i = start; i < start + length; i += size) {
383 ioport_write_table[bsize][i] = func;
384 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
385 hw_error("register_ioport_write: invalid opaque");
386 ioport_opaque[i] = opaque;
388 return 0;
391 void isa_unassign_ioport(int start, int length)
393 int i;
395 for(i = start; i < start + length; i++) {
396 ioport_read_table[0][i] = default_ioport_readb;
397 ioport_read_table[1][i] = default_ioport_readw;
398 ioport_read_table[2][i] = default_ioport_readl;
400 ioport_write_table[0][i] = default_ioport_writeb;
401 ioport_write_table[1][i] = default_ioport_writew;
402 ioport_write_table[2][i] = default_ioport_writel;
406 /***********************************************************/
408 void cpu_outb(CPUState *env, int addr, int val)
410 #ifdef DEBUG_IOPORT
411 if (loglevel & CPU_LOG_IOPORT)
412 fprintf(logfile, "outb: %04x %02x\n", addr, val);
413 #endif
414 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
415 #ifdef USE_KQEMU
416 if (env)
417 env->last_io_time = cpu_get_time_fast();
418 #endif
421 void cpu_outw(CPUState *env, int addr, int val)
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "outw: %04x %04x\n", addr, val);
426 #endif
427 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
428 #ifdef USE_KQEMU
429 if (env)
430 env->last_io_time = cpu_get_time_fast();
431 #endif
434 void cpu_outl(CPUState *env, int addr, int val)
436 #ifdef DEBUG_IOPORT
437 if (loglevel & CPU_LOG_IOPORT)
438 fprintf(logfile, "outl: %04x %08x\n", addr, val);
439 #endif
440 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
441 #ifdef USE_KQEMU
442 if (env)
443 env->last_io_time = cpu_get_time_fast();
444 #endif
447 int cpu_inb(CPUState *env, int addr)
449 int val;
450 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
451 #ifdef DEBUG_IOPORT
452 if (loglevel & CPU_LOG_IOPORT)
453 fprintf(logfile, "inb : %04x %02x\n", addr, val);
454 #endif
455 #ifdef USE_KQEMU
456 if (env)
457 env->last_io_time = cpu_get_time_fast();
458 #endif
459 return val;
462 int cpu_inw(CPUState *env, int addr)
464 int val;
465 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
466 #ifdef DEBUG_IOPORT
467 if (loglevel & CPU_LOG_IOPORT)
468 fprintf(logfile, "inw : %04x %04x\n", addr, val);
469 #endif
470 #ifdef USE_KQEMU
471 if (env)
472 env->last_io_time = cpu_get_time_fast();
473 #endif
474 return val;
477 int cpu_inl(CPUState *env, int addr)
479 int val;
480 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
481 #ifdef DEBUG_IOPORT
482 if (loglevel & CPU_LOG_IOPORT)
483 fprintf(logfile, "inl : %04x %08x\n", addr, val);
484 #endif
485 #ifdef USE_KQEMU
486 if (env)
487 env->last_io_time = cpu_get_time_fast();
488 #endif
489 return val;
492 /***********************************************************/
493 void hw_error(const char *fmt, ...)
495 va_list ap;
496 CPUState *env;
498 va_start(ap, fmt);
499 fprintf(stderr, "qemu: hardware error: ");
500 vfprintf(stderr, fmt, ap);
501 fprintf(stderr, "\n");
502 for(env = first_cpu; env != NULL; env = env->next_cpu) {
503 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
504 #ifdef TARGET_I386
505 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
506 #else
507 cpu_dump_state(env, stderr, fprintf, 0);
508 #endif
510 va_end(ap);
511 abort();
514 /***********************************************************/
515 /* keyboard/mouse */
517 static QEMUPutKBDEvent *qemu_put_kbd_event;
518 static void *qemu_put_kbd_event_opaque;
519 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
520 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
522 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
524 qemu_put_kbd_event_opaque = opaque;
525 qemu_put_kbd_event = func;
528 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
529 void *opaque, int absolute,
530 const char *name)
532 QEMUPutMouseEntry *s, *cursor;
534 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
535 if (!s)
536 return NULL;
538 s->qemu_put_mouse_event = func;
539 s->qemu_put_mouse_event_opaque = opaque;
540 s->qemu_put_mouse_event_absolute = absolute;
541 s->qemu_put_mouse_event_name = qemu_strdup(name);
542 s->next = NULL;
544 if (!qemu_put_mouse_event_head) {
545 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
546 return s;
549 cursor = qemu_put_mouse_event_head;
550 while (cursor->next != NULL)
551 cursor = cursor->next;
553 cursor->next = s;
554 qemu_put_mouse_event_current = s;
556 return s;
559 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
561 QEMUPutMouseEntry *prev = NULL, *cursor;
563 if (!qemu_put_mouse_event_head || entry == NULL)
564 return;
566 cursor = qemu_put_mouse_event_head;
567 while (cursor != NULL && cursor != entry) {
568 prev = cursor;
569 cursor = cursor->next;
572 if (cursor == NULL) // does not exist or list empty
573 return;
574 else if (prev == NULL) { // entry is head
575 qemu_put_mouse_event_head = cursor->next;
576 if (qemu_put_mouse_event_current == entry)
577 qemu_put_mouse_event_current = cursor->next;
578 qemu_free(entry->qemu_put_mouse_event_name);
579 qemu_free(entry);
580 return;
583 prev->next = entry->next;
585 if (qemu_put_mouse_event_current == entry)
586 qemu_put_mouse_event_current = prev;
588 qemu_free(entry->qemu_put_mouse_event_name);
589 qemu_free(entry);
592 void kbd_put_keycode(int keycode)
594 if (qemu_put_kbd_event) {
595 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
599 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
601 QEMUPutMouseEvent *mouse_event;
602 void *mouse_event_opaque;
603 int width;
605 if (!qemu_put_mouse_event_current) {
606 return;
609 mouse_event =
610 qemu_put_mouse_event_current->qemu_put_mouse_event;
611 mouse_event_opaque =
612 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
614 if (mouse_event) {
615 if (graphic_rotate) {
616 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
617 width = 0x7fff;
618 else
619 width = graphic_width;
620 mouse_event(mouse_event_opaque,
621 width - dy, dx, dz, buttons_state);
622 } else
623 mouse_event(mouse_event_opaque,
624 dx, dy, dz, buttons_state);
628 int kbd_mouse_is_absolute(void)
630 if (!qemu_put_mouse_event_current)
631 return 0;
633 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
636 void do_info_mice(void)
638 QEMUPutMouseEntry *cursor;
639 int index = 0;
641 if (!qemu_put_mouse_event_head) {
642 term_printf("No mouse devices connected\n");
643 return;
646 term_printf("Mouse devices available:\n");
647 cursor = qemu_put_mouse_event_head;
648 while (cursor != NULL) {
649 term_printf("%c Mouse #%d: %s\n",
650 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
651 index, cursor->qemu_put_mouse_event_name);
652 index++;
653 cursor = cursor->next;
657 void do_mouse_set(int index)
659 QEMUPutMouseEntry *cursor;
660 int i = 0;
662 if (!qemu_put_mouse_event_head) {
663 term_printf("No mouse devices connected\n");
664 return;
667 cursor = qemu_put_mouse_event_head;
668 while (cursor != NULL && index != i) {
669 i++;
670 cursor = cursor->next;
673 if (cursor != NULL)
674 qemu_put_mouse_event_current = cursor;
675 else
676 term_printf("Mouse at given index not found\n");
679 /* compute with 96 bit intermediate result: (a*b)/c */
680 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
682 union {
683 uint64_t ll;
684 struct {
685 #ifdef WORDS_BIGENDIAN
686 uint32_t high, low;
687 #else
688 uint32_t low, high;
689 #endif
690 } l;
691 } u, res;
692 uint64_t rl, rh;
694 u.ll = a;
695 rl = (uint64_t)u.l.low * (uint64_t)b;
696 rh = (uint64_t)u.l.high * (uint64_t)b;
697 rh += (rl >> 32);
698 res.l.high = rh / c;
699 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
700 return res.ll;
703 /***********************************************************/
704 /* real time host monotonic timer */
706 #define QEMU_TIMER_BASE 1000000000LL
708 #ifdef WIN32
710 static int64_t clock_freq;
712 static void init_get_clock(void)
714 LARGE_INTEGER freq;
715 int ret;
716 ret = QueryPerformanceFrequency(&freq);
717 if (ret == 0) {
718 fprintf(stderr, "Could not calibrate ticks\n");
719 exit(1);
721 clock_freq = freq.QuadPart;
724 static int64_t get_clock(void)
726 LARGE_INTEGER ti;
727 QueryPerformanceCounter(&ti);
728 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
731 #else
733 static int use_rt_clock;
735 static void init_get_clock(void)
737 use_rt_clock = 0;
738 #if defined(__linux__)
740 struct timespec ts;
741 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
742 use_rt_clock = 1;
745 #endif
748 static int64_t get_clock(void)
750 #if defined(__linux__)
751 if (use_rt_clock) {
752 struct timespec ts;
753 clock_gettime(CLOCK_MONOTONIC, &ts);
754 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
755 } else
756 #endif
758 /* XXX: using gettimeofday leads to problems if the date
759 changes, so it should be avoided. */
760 struct timeval tv;
761 gettimeofday(&tv, NULL);
762 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
766 #endif
768 /***********************************************************/
769 /* guest cycle counter */
771 static int64_t cpu_ticks_prev;
772 static int64_t cpu_ticks_offset;
773 static int64_t cpu_clock_offset;
774 static int cpu_ticks_enabled;
776 /* return the host CPU cycle counter and handle stop/restart */
777 int64_t cpu_get_ticks(void)
779 if (!cpu_ticks_enabled) {
780 return cpu_ticks_offset;
781 } else {
782 int64_t ticks;
783 ticks = cpu_get_real_ticks();
784 if (cpu_ticks_prev > ticks) {
785 /* Note: non increasing ticks may happen if the host uses
786 software suspend */
787 cpu_ticks_offset += cpu_ticks_prev - ticks;
789 cpu_ticks_prev = ticks;
790 return ticks + cpu_ticks_offset;
794 /* return the host CPU monotonic timer and handle stop/restart */
795 static int64_t cpu_get_clock(void)
797 int64_t ti;
798 if (!cpu_ticks_enabled) {
799 return cpu_clock_offset;
800 } else {
801 ti = get_clock();
802 return ti + cpu_clock_offset;
806 /* enable cpu_get_ticks() */
807 void cpu_enable_ticks(void)
809 if (!cpu_ticks_enabled) {
810 cpu_ticks_offset -= cpu_get_real_ticks();
811 cpu_clock_offset -= get_clock();
812 cpu_ticks_enabled = 1;
816 /* disable cpu_get_ticks() : the clock is stopped. You must not call
817 cpu_get_ticks() after that. */
818 void cpu_disable_ticks(void)
820 if (cpu_ticks_enabled) {
821 cpu_ticks_offset = cpu_get_ticks();
822 cpu_clock_offset = cpu_get_clock();
823 cpu_ticks_enabled = 0;
827 /***********************************************************/
828 /* timers */
830 #define QEMU_TIMER_REALTIME 0
831 #define QEMU_TIMER_VIRTUAL 1
833 struct QEMUClock {
834 int type;
835 /* XXX: add frequency */
838 struct QEMUTimer {
839 QEMUClock *clock;
840 int64_t expire_time;
841 QEMUTimerCB *cb;
842 void *opaque;
843 struct QEMUTimer *next;
846 struct qemu_alarm_timer {
847 char const *name;
848 unsigned int flags;
850 int (*start)(struct qemu_alarm_timer *t);
851 void (*stop)(struct qemu_alarm_timer *t);
852 void (*rearm)(struct qemu_alarm_timer *t);
853 void *priv;
856 #define ALARM_FLAG_DYNTICKS 0x1
858 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
860 return t->flags & ALARM_FLAG_DYNTICKS;
863 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
865 if (!alarm_has_dynticks(t))
866 return;
868 t->rearm(t);
871 /* TODO: MIN_TIMER_REARM_US should be optimized */
872 #define MIN_TIMER_REARM_US 250
874 static struct qemu_alarm_timer *alarm_timer;
876 #ifdef _WIN32
878 struct qemu_alarm_win32 {
879 MMRESULT timerId;
880 HANDLE host_alarm;
881 unsigned int period;
882 } alarm_win32_data = {0, NULL, -1};
884 static int win32_start_timer(struct qemu_alarm_timer *t);
885 static void win32_stop_timer(struct qemu_alarm_timer *t);
886 static void win32_rearm_timer(struct qemu_alarm_timer *t);
888 #else
890 static int unix_start_timer(struct qemu_alarm_timer *t);
891 static void unix_stop_timer(struct qemu_alarm_timer *t);
893 #ifdef __linux__
895 static int dynticks_start_timer(struct qemu_alarm_timer *t);
896 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
897 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
899 static int hpet_start_timer(struct qemu_alarm_timer *t);
900 static void hpet_stop_timer(struct qemu_alarm_timer *t);
902 static int rtc_start_timer(struct qemu_alarm_timer *t);
903 static void rtc_stop_timer(struct qemu_alarm_timer *t);
905 #endif /* __linux__ */
907 #endif /* _WIN32 */
909 static struct qemu_alarm_timer alarm_timers[] = {
910 #ifndef _WIN32
911 #ifdef __linux__
912 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
913 dynticks_stop_timer, dynticks_rearm_timer, NULL},
914 /* HPET - if available - is preferred */
915 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
916 /* ...otherwise try RTC */
917 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
918 #endif
919 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
920 #else
921 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
922 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
923 {"win32", 0, win32_start_timer,
924 win32_stop_timer, NULL, &alarm_win32_data},
925 #endif
926 {NULL, }
929 static void show_available_alarms()
931 int i;
933 printf("Available alarm timers, in order of precedence:\n");
934 for (i = 0; alarm_timers[i].name; i++)
935 printf("%s\n", alarm_timers[i].name);
938 static void configure_alarms(char const *opt)
940 int i;
941 int cur = 0;
942 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
943 char *arg;
944 char *name;
946 if (!strcmp(opt, "help")) {
947 show_available_alarms();
948 exit(0);
951 arg = strdup(opt);
953 /* Reorder the array */
954 name = strtok(arg, ",");
955 while (name) {
956 struct qemu_alarm_timer tmp;
958 for (i = 0; i < count && alarm_timers[i].name; i++) {
959 if (!strcmp(alarm_timers[i].name, name))
960 break;
963 if (i == count) {
964 fprintf(stderr, "Unknown clock %s\n", name);
965 goto next;
968 if (i < cur)
969 /* Ignore */
970 goto next;
972 /* Swap */
973 tmp = alarm_timers[i];
974 alarm_timers[i] = alarm_timers[cur];
975 alarm_timers[cur] = tmp;
977 cur++;
978 next:
979 name = strtok(NULL, ",");
982 free(arg);
984 if (cur) {
985 /* Disable remaining timers */
986 for (i = cur; i < count; i++)
987 alarm_timers[i].name = NULL;
990 /* debug */
991 show_available_alarms();
994 QEMUClock *rt_clock;
995 QEMUClock *vm_clock;
997 static QEMUTimer *active_timers[2];
999 static QEMUClock *qemu_new_clock(int type)
1001 QEMUClock *clock;
1002 clock = qemu_mallocz(sizeof(QEMUClock));
1003 if (!clock)
1004 return NULL;
1005 clock->type = type;
1006 return clock;
1009 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1011 QEMUTimer *ts;
1013 ts = qemu_mallocz(sizeof(QEMUTimer));
1014 ts->clock = clock;
1015 ts->cb = cb;
1016 ts->opaque = opaque;
1017 return ts;
1020 void qemu_free_timer(QEMUTimer *ts)
1022 qemu_free(ts);
1025 /* stop a timer, but do not dealloc it */
1026 void qemu_del_timer(QEMUTimer *ts)
1028 QEMUTimer **pt, *t;
1030 /* NOTE: this code must be signal safe because
1031 qemu_timer_expired() can be called from a signal. */
1032 pt = &active_timers[ts->clock->type];
1033 for(;;) {
1034 t = *pt;
1035 if (!t)
1036 break;
1037 if (t == ts) {
1038 *pt = t->next;
1039 break;
1041 pt = &t->next;
1045 /* modify the current timer so that it will be fired when current_time
1046 >= expire_time. The corresponding callback will be called. */
1047 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1049 QEMUTimer **pt, *t;
1051 qemu_del_timer(ts);
1053 /* add the timer in the sorted list */
1054 /* NOTE: this code must be signal safe because
1055 qemu_timer_expired() can be called from a signal. */
1056 pt = &active_timers[ts->clock->type];
1057 for(;;) {
1058 t = *pt;
1059 if (!t)
1060 break;
1061 if (t->expire_time > expire_time)
1062 break;
1063 pt = &t->next;
1065 ts->expire_time = expire_time;
1066 ts->next = *pt;
1067 *pt = ts;
1070 int qemu_timer_pending(QEMUTimer *ts)
1072 QEMUTimer *t;
1073 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1074 if (t == ts)
1075 return 1;
1077 return 0;
1080 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1082 if (!timer_head)
1083 return 0;
1084 return (timer_head->expire_time <= current_time);
1087 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1089 QEMUTimer *ts;
1091 for(;;) {
1092 ts = *ptimer_head;
1093 if (!ts || ts->expire_time > current_time)
1094 break;
1095 /* remove timer from the list before calling the callback */
1096 *ptimer_head = ts->next;
1097 ts->next = NULL;
1099 /* run the callback (the timer list can be modified) */
1100 ts->cb(ts->opaque);
1102 qemu_rearm_alarm_timer(alarm_timer);
1105 int64_t qemu_get_clock(QEMUClock *clock)
1107 switch(clock->type) {
1108 case QEMU_TIMER_REALTIME:
1109 return get_clock() / 1000000;
1110 default:
1111 case QEMU_TIMER_VIRTUAL:
1112 return cpu_get_clock();
1116 static void init_timers(void)
1118 init_get_clock();
1119 ticks_per_sec = QEMU_TIMER_BASE;
1120 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1121 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1124 /* save a timer */
1125 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1127 uint64_t expire_time;
1129 if (qemu_timer_pending(ts)) {
1130 expire_time = ts->expire_time;
1131 } else {
1132 expire_time = -1;
1134 qemu_put_be64(f, expire_time);
1137 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1139 uint64_t expire_time;
1141 expire_time = qemu_get_be64(f);
1142 if (expire_time != -1) {
1143 qemu_mod_timer(ts, expire_time);
1144 } else {
1145 qemu_del_timer(ts);
1149 static void timer_save(QEMUFile *f, void *opaque)
1151 if (cpu_ticks_enabled) {
1152 hw_error("cannot save state if virtual timers are running");
1154 qemu_put_be64(f, cpu_ticks_offset);
1155 qemu_put_be64(f, ticks_per_sec);
1156 qemu_put_be64(f, cpu_clock_offset);
1159 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1161 if (version_id != 1 && version_id != 2)
1162 return -EINVAL;
1163 if (cpu_ticks_enabled) {
1164 return -EINVAL;
1166 cpu_ticks_offset=qemu_get_be64(f);
1167 ticks_per_sec=qemu_get_be64(f);
1168 if (version_id == 2) {
1169 cpu_clock_offset=qemu_get_be64(f);
1171 return 0;
1174 #ifdef _WIN32
1175 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1176 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1177 #else
1178 static void host_alarm_handler(int host_signum)
1179 #endif
1181 #if 0
1182 #define DISP_FREQ 1000
1184 static int64_t delta_min = INT64_MAX;
1185 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1186 static int count;
1187 ti = qemu_get_clock(vm_clock);
1188 if (last_clock != 0) {
1189 delta = ti - last_clock;
1190 if (delta < delta_min)
1191 delta_min = delta;
1192 if (delta > delta_max)
1193 delta_max = delta;
1194 delta_cum += delta;
1195 if (++count == DISP_FREQ) {
1196 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1197 muldiv64(delta_min, 1000000, ticks_per_sec),
1198 muldiv64(delta_max, 1000000, ticks_per_sec),
1199 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1200 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1201 count = 0;
1202 delta_min = INT64_MAX;
1203 delta_max = 0;
1204 delta_cum = 0;
1207 last_clock = ti;
1209 #endif
1210 if (1 ||
1211 alarm_has_dynticks(alarm_timer) ||
1212 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1213 qemu_get_clock(vm_clock)) ||
1214 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1215 qemu_get_clock(rt_clock))) {
1216 #ifdef _WIN32
1217 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1218 SetEvent(data->host_alarm);
1219 #endif
1220 CPUState *env = next_cpu;
1222 if (env) {
1223 /* stop the currently executing cpu because a timer occured */
1224 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1225 #ifdef USE_KQEMU
1226 if (env->kqemu_enabled) {
1227 kqemu_cpu_interrupt(env);
1229 #endif
1231 event_pending = 1;
1235 static uint64_t qemu_next_deadline(void)
1237 int64_t nearest_delta_us = INT64_MAX;
1238 int64_t vmdelta_us;
1240 if (active_timers[QEMU_TIMER_REALTIME])
1241 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1242 qemu_get_clock(rt_clock))*1000;
1244 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1245 /* round up */
1246 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1247 qemu_get_clock(vm_clock)+999)/1000;
1248 if (vmdelta_us < nearest_delta_us)
1249 nearest_delta_us = vmdelta_us;
1252 /* Avoid arming the timer to negative, zero, or too low values */
1253 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1254 nearest_delta_us = MIN_TIMER_REARM_US;
1256 return nearest_delta_us;
1259 #ifndef _WIN32
1261 #if defined(__linux__)
1263 #define RTC_FREQ 1024
1265 static void enable_sigio_timer(int fd)
1267 struct sigaction act;
1269 /* timer signal */
1270 sigfillset(&act.sa_mask);
1271 act.sa_flags = 0;
1272 act.sa_handler = host_alarm_handler;
1274 sigaction(SIGIO, &act, NULL);
1275 fcntl(fd, F_SETFL, O_ASYNC);
1276 fcntl(fd, F_SETOWN, getpid());
1279 static int hpet_start_timer(struct qemu_alarm_timer *t)
1281 struct hpet_info info;
1282 int r, fd;
1284 fd = open("/dev/hpet", O_RDONLY);
1285 if (fd < 0)
1286 return -1;
1288 /* Set frequency */
1289 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1290 if (r < 0) {
1291 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1292 "error, but for better emulation accuracy type:\n"
1293 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1294 goto fail;
1297 /* Check capabilities */
1298 r = ioctl(fd, HPET_INFO, &info);
1299 if (r < 0)
1300 goto fail;
1302 /* Enable periodic mode */
1303 r = ioctl(fd, HPET_EPI, 0);
1304 if (info.hi_flags && (r < 0))
1305 goto fail;
1307 /* Enable interrupt */
1308 r = ioctl(fd, HPET_IE_ON, 0);
1309 if (r < 0)
1310 goto fail;
1312 enable_sigio_timer(fd);
1313 t->priv = (void *)(long)fd;
1315 return 0;
1316 fail:
1317 close(fd);
1318 return -1;
1321 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1323 int fd = (long)t->priv;
1325 close(fd);
1328 static int rtc_start_timer(struct qemu_alarm_timer *t)
1330 int rtc_fd;
1332 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1333 if (rtc_fd < 0)
1334 return -1;
1335 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1336 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1337 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1338 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1339 goto fail;
1341 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1342 fail:
1343 close(rtc_fd);
1344 return -1;
1347 enable_sigio_timer(rtc_fd);
1349 t->priv = (void *)(long)rtc_fd;
1351 return 0;
1354 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1356 int rtc_fd = (long)t->priv;
1358 close(rtc_fd);
1361 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1363 struct sigevent ev;
1364 timer_t host_timer;
1365 struct sigaction act;
1367 sigfillset(&act.sa_mask);
1368 act.sa_flags = 0;
1369 act.sa_handler = host_alarm_handler;
1371 sigaction(SIGALRM, &act, NULL);
1373 ev.sigev_value.sival_int = 0;
1374 ev.sigev_notify = SIGEV_SIGNAL;
1375 ev.sigev_signo = SIGALRM;
1377 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1378 perror("timer_create");
1380 /* disable dynticks */
1381 fprintf(stderr, "Dynamic Ticks disabled\n");
1383 return -1;
1386 t->priv = (void *)host_timer;
1388 return 0;
1391 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1393 timer_t host_timer = (timer_t)t->priv;
1395 timer_delete(host_timer);
1398 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1400 timer_t host_timer = (timer_t)t->priv;
1401 struct itimerspec timeout;
1402 int64_t nearest_delta_us = INT64_MAX;
1403 int64_t current_us;
1405 if (!active_timers[QEMU_TIMER_REALTIME] &&
1406 !active_timers[QEMU_TIMER_VIRTUAL])
1407 return;
1409 nearest_delta_us = qemu_next_deadline();
1411 /* check whether a timer is already running */
1412 if (timer_gettime(host_timer, &timeout)) {
1413 perror("gettime");
1414 fprintf(stderr, "Internal timer error: aborting\n");
1415 exit(1);
1417 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1418 if (current_us && current_us <= nearest_delta_us)
1419 return;
1421 timeout.it_interval.tv_sec = 0;
1422 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1423 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1424 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1425 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1426 perror("settime");
1427 fprintf(stderr, "Internal timer error: aborting\n");
1428 exit(1);
1432 #endif /* defined(__linux__) */
1434 static int unix_start_timer(struct qemu_alarm_timer *t)
1436 struct sigaction act;
1437 struct itimerval itv;
1438 int err;
1440 /* timer signal */
1441 sigfillset(&act.sa_mask);
1442 act.sa_flags = 0;
1443 act.sa_handler = host_alarm_handler;
1445 sigaction(SIGALRM, &act, NULL);
1447 itv.it_interval.tv_sec = 0;
1448 /* for i386 kernel 2.6 to get 1 ms */
1449 itv.it_interval.tv_usec = 999;
1450 itv.it_value.tv_sec = 0;
1451 itv.it_value.tv_usec = 10 * 1000;
1453 err = setitimer(ITIMER_REAL, &itv, NULL);
1454 if (err)
1455 return -1;
1457 return 0;
1460 static void unix_stop_timer(struct qemu_alarm_timer *t)
1462 struct itimerval itv;
1464 memset(&itv, 0, sizeof(itv));
1465 setitimer(ITIMER_REAL, &itv, NULL);
1468 #endif /* !defined(_WIN32) */
1470 #ifdef _WIN32
1472 static int win32_start_timer(struct qemu_alarm_timer *t)
1474 TIMECAPS tc;
1475 struct qemu_alarm_win32 *data = t->priv;
1476 UINT flags;
1478 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1479 if (!data->host_alarm) {
1480 perror("Failed CreateEvent");
1481 return -1;
1484 memset(&tc, 0, sizeof(tc));
1485 timeGetDevCaps(&tc, sizeof(tc));
1487 if (data->period < tc.wPeriodMin)
1488 data->period = tc.wPeriodMin;
1490 timeBeginPeriod(data->period);
1492 flags = TIME_CALLBACK_FUNCTION;
1493 if (alarm_has_dynticks(t))
1494 flags |= TIME_ONESHOT;
1495 else
1496 flags |= TIME_PERIODIC;
1498 data->timerId = timeSetEvent(1, // interval (ms)
1499 data->period, // resolution
1500 host_alarm_handler, // function
1501 (DWORD)t, // parameter
1502 flags);
1504 if (!data->timerId) {
1505 perror("Failed to initialize win32 alarm timer");
1507 timeEndPeriod(data->period);
1508 CloseHandle(data->host_alarm);
1509 return -1;
1512 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1514 return 0;
1517 static void win32_stop_timer(struct qemu_alarm_timer *t)
1519 struct qemu_alarm_win32 *data = t->priv;
1521 timeKillEvent(data->timerId);
1522 timeEndPeriod(data->period);
1524 CloseHandle(data->host_alarm);
1527 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1529 struct qemu_alarm_win32 *data = t->priv;
1530 uint64_t nearest_delta_us;
1532 if (!active_timers[QEMU_TIMER_REALTIME] &&
1533 !active_timers[QEMU_TIMER_VIRTUAL])
1534 return;
1536 nearest_delta_us = qemu_next_deadline();
1537 nearest_delta_us /= 1000;
1539 timeKillEvent(data->timerId);
1541 data->timerId = timeSetEvent(1,
1542 data->period,
1543 host_alarm_handler,
1544 (DWORD)t,
1545 TIME_ONESHOT | TIME_PERIODIC);
1547 if (!data->timerId) {
1548 perror("Failed to re-arm win32 alarm timer");
1550 timeEndPeriod(data->period);
1551 CloseHandle(data->host_alarm);
1552 exit(1);
1556 #endif /* _WIN32 */
1558 static void init_timer_alarm(void)
1560 struct qemu_alarm_timer *t;
1561 int i, err = -1;
1563 for (i = 0; alarm_timers[i].name; i++) {
1564 t = &alarm_timers[i];
1566 err = t->start(t);
1567 if (!err)
1568 break;
1571 if (err) {
1572 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1573 fprintf(stderr, "Terminating\n");
1574 exit(1);
1577 alarm_timer = t;
1580 static void quit_timers(void)
1582 alarm_timer->stop(alarm_timer);
1583 alarm_timer = NULL;
1586 /***********************************************************/
1587 /* character device */
1589 static void qemu_chr_event(CharDriverState *s, int event)
1591 if (!s->chr_event)
1592 return;
1593 s->chr_event(s->handler_opaque, event);
1596 static void qemu_chr_reset_bh(void *opaque)
1598 CharDriverState *s = opaque;
1599 qemu_chr_event(s, CHR_EVENT_RESET);
1600 qemu_bh_delete(s->bh);
1601 s->bh = NULL;
1604 void qemu_chr_reset(CharDriverState *s)
1606 if (s->bh == NULL) {
1607 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1608 qemu_bh_schedule(s->bh);
1612 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1614 return s->chr_write(s, buf, len);
1617 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1619 if (!s->chr_ioctl)
1620 return -ENOTSUP;
1621 return s->chr_ioctl(s, cmd, arg);
1624 int qemu_chr_can_read(CharDriverState *s)
1626 if (!s->chr_can_read)
1627 return 0;
1628 return s->chr_can_read(s->handler_opaque);
1631 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1633 s->chr_read(s->handler_opaque, buf, len);
1636 void qemu_chr_accept_input(CharDriverState *s)
1638 if (s->chr_accept_input)
1639 s->chr_accept_input(s);
1642 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1644 char buf[4096];
1645 va_list ap;
1646 va_start(ap, fmt);
1647 vsnprintf(buf, sizeof(buf), fmt, ap);
1648 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1649 va_end(ap);
1652 void qemu_chr_send_event(CharDriverState *s, int event)
1654 if (s->chr_send_event)
1655 s->chr_send_event(s, event);
1658 void qemu_chr_add_handlers(CharDriverState *s,
1659 IOCanRWHandler *fd_can_read,
1660 IOReadHandler *fd_read,
1661 IOEventHandler *fd_event,
1662 void *opaque)
1664 s->chr_can_read = fd_can_read;
1665 s->chr_read = fd_read;
1666 s->chr_event = fd_event;
1667 s->handler_opaque = opaque;
1668 if (s->chr_update_read_handler)
1669 s->chr_update_read_handler(s);
1672 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1674 return len;
1677 static CharDriverState *qemu_chr_open_null(void)
1679 CharDriverState *chr;
1681 chr = qemu_mallocz(sizeof(CharDriverState));
1682 if (!chr)
1683 return NULL;
1684 chr->chr_write = null_chr_write;
1685 return chr;
1688 /* MUX driver for serial I/O splitting */
1689 static int term_timestamps;
1690 static int64_t term_timestamps_start;
1691 #define MAX_MUX 4
1692 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1693 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1694 typedef struct {
1695 IOCanRWHandler *chr_can_read[MAX_MUX];
1696 IOReadHandler *chr_read[MAX_MUX];
1697 IOEventHandler *chr_event[MAX_MUX];
1698 void *ext_opaque[MAX_MUX];
1699 CharDriverState *drv;
1700 unsigned char buffer[MUX_BUFFER_SIZE];
1701 int prod;
1702 int cons;
1703 int mux_cnt;
1704 int term_got_escape;
1705 int max_size;
1706 } MuxDriver;
1709 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1711 MuxDriver *d = chr->opaque;
1712 int ret;
1713 if (!term_timestamps) {
1714 ret = d->drv->chr_write(d->drv, buf, len);
1715 } else {
1716 int i;
1718 ret = 0;
1719 for(i = 0; i < len; i++) {
1720 ret += d->drv->chr_write(d->drv, buf+i, 1);
1721 if (buf[i] == '\n') {
1722 char buf1[64];
1723 int64_t ti;
1724 int secs;
1726 ti = get_clock();
1727 if (term_timestamps_start == -1)
1728 term_timestamps_start = ti;
1729 ti -= term_timestamps_start;
1730 secs = ti / 1000000000;
1731 snprintf(buf1, sizeof(buf1),
1732 "[%02d:%02d:%02d.%03d] ",
1733 secs / 3600,
1734 (secs / 60) % 60,
1735 secs % 60,
1736 (int)((ti / 1000000) % 1000));
1737 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1741 return ret;
1744 static char *mux_help[] = {
1745 "% h print this help\n\r",
1746 "% x exit emulator\n\r",
1747 "% s save disk data back to file (if -snapshot)\n\r",
1748 "% t toggle console timestamps\n\r"
1749 "% b send break (magic sysrq)\n\r",
1750 "% c switch between console and monitor\n\r",
1751 "% % sends %\n\r",
1752 NULL
1755 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1756 static void mux_print_help(CharDriverState *chr)
1758 int i, j;
1759 char ebuf[15] = "Escape-Char";
1760 char cbuf[50] = "\n\r";
1762 if (term_escape_char > 0 && term_escape_char < 26) {
1763 sprintf(cbuf,"\n\r");
1764 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1765 } else {
1766 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1767 term_escape_char);
1769 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1770 for (i = 0; mux_help[i] != NULL; i++) {
1771 for (j=0; mux_help[i][j] != '\0'; j++) {
1772 if (mux_help[i][j] == '%')
1773 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1774 else
1775 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1780 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1782 if (d->term_got_escape) {
1783 d->term_got_escape = 0;
1784 if (ch == term_escape_char)
1785 goto send_char;
1786 switch(ch) {
1787 case '?':
1788 case 'h':
1789 mux_print_help(chr);
1790 break;
1791 case 'x':
1793 char *term = "QEMU: Terminated\n\r";
1794 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1795 exit(0);
1796 break;
1798 case 's':
1800 int i;
1801 for (i = 0; i < nb_drives; i++) {
1802 bdrv_commit(drives_table[i].bdrv);
1805 break;
1806 case 'b':
1807 qemu_chr_event(chr, CHR_EVENT_BREAK);
1808 break;
1809 case 'c':
1810 /* Switch to the next registered device */
1811 chr->focus++;
1812 if (chr->focus >= d->mux_cnt)
1813 chr->focus = 0;
1814 break;
1815 case 't':
1816 term_timestamps = !term_timestamps;
1817 term_timestamps_start = -1;
1818 break;
1820 } else if (ch == term_escape_char) {
1821 d->term_got_escape = 1;
1822 } else {
1823 send_char:
1824 return 1;
1826 return 0;
1829 static void mux_chr_accept_input(CharDriverState *chr)
1831 int m = chr->focus;
1832 MuxDriver *d = chr->opaque;
1834 while (d->prod != d->cons &&
1835 d->chr_can_read[m] &&
1836 d->chr_can_read[m](d->ext_opaque[m])) {
1837 d->chr_read[m](d->ext_opaque[m],
1838 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1842 static int mux_chr_can_read(void *opaque)
1844 CharDriverState *chr = opaque;
1845 MuxDriver *d = chr->opaque;
1847 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1848 return 1;
1849 if (d->chr_can_read[chr->focus])
1850 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1851 return 0;
1854 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1856 CharDriverState *chr = opaque;
1857 MuxDriver *d = chr->opaque;
1858 int m = chr->focus;
1859 int i;
1861 mux_chr_accept_input (opaque);
1863 for(i = 0; i < size; i++)
1864 if (mux_proc_byte(chr, d, buf[i])) {
1865 if (d->prod == d->cons &&
1866 d->chr_can_read[m] &&
1867 d->chr_can_read[m](d->ext_opaque[m]))
1868 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1869 else
1870 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1874 static void mux_chr_event(void *opaque, int event)
1876 CharDriverState *chr = opaque;
1877 MuxDriver *d = chr->opaque;
1878 int i;
1880 /* Send the event to all registered listeners */
1881 for (i = 0; i < d->mux_cnt; i++)
1882 if (d->chr_event[i])
1883 d->chr_event[i](d->ext_opaque[i], event);
1886 static void mux_chr_update_read_handler(CharDriverState *chr)
1888 MuxDriver *d = chr->opaque;
1890 if (d->mux_cnt >= MAX_MUX) {
1891 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1892 return;
1894 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1895 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1896 d->chr_read[d->mux_cnt] = chr->chr_read;
1897 d->chr_event[d->mux_cnt] = chr->chr_event;
1898 /* Fix up the real driver with mux routines */
1899 if (d->mux_cnt == 0) {
1900 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1901 mux_chr_event, chr);
1903 chr->focus = d->mux_cnt;
1904 d->mux_cnt++;
1907 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1909 CharDriverState *chr;
1910 MuxDriver *d;
1912 chr = qemu_mallocz(sizeof(CharDriverState));
1913 if (!chr)
1914 return NULL;
1915 d = qemu_mallocz(sizeof(MuxDriver));
1916 if (!d) {
1917 free(chr);
1918 return NULL;
1921 chr->opaque = d;
1922 d->drv = drv;
1923 chr->focus = -1;
1924 chr->chr_write = mux_chr_write;
1925 chr->chr_update_read_handler = mux_chr_update_read_handler;
1926 chr->chr_accept_input = mux_chr_accept_input;
1927 return chr;
1931 #ifdef _WIN32
1933 static void socket_cleanup(void)
1935 WSACleanup();
1938 static int socket_init(void)
1940 WSADATA Data;
1941 int ret, err;
1943 ret = WSAStartup(MAKEWORD(2,2), &Data);
1944 if (ret != 0) {
1945 err = WSAGetLastError();
1946 fprintf(stderr, "WSAStartup: %d\n", err);
1947 return -1;
1949 atexit(socket_cleanup);
1950 return 0;
1953 static int send_all(int fd, const uint8_t *buf, int len1)
1955 int ret, len;
1957 len = len1;
1958 while (len > 0) {
1959 ret = send(fd, buf, len, 0);
1960 if (ret < 0) {
1961 int errno;
1962 errno = WSAGetLastError();
1963 if (errno != WSAEWOULDBLOCK) {
1964 return -1;
1966 } else if (ret == 0) {
1967 break;
1968 } else {
1969 buf += ret;
1970 len -= ret;
1973 return len1 - len;
1976 void socket_set_nonblock(int fd)
1978 unsigned long opt = 1;
1979 ioctlsocket(fd, FIONBIO, &opt);
1982 #else
1984 static int unix_write(int fd, const uint8_t *buf, int len1)
1986 int ret, len;
1988 len = len1;
1989 while (len > 0) {
1990 ret = write(fd, buf, len);
1991 if (ret < 0) {
1992 if (errno != EINTR && errno != EAGAIN)
1993 return -1;
1994 } else if (ret == 0) {
1995 break;
1996 } else {
1997 buf += ret;
1998 len -= ret;
2001 return len1 - len;
2004 static inline int send_all(int fd, const uint8_t *buf, int len1)
2006 return unix_write(fd, buf, len1);
2009 void socket_set_nonblock(int fd)
2011 fcntl(fd, F_SETFL, O_NONBLOCK);
2013 #endif /* !_WIN32 */
2015 #ifndef _WIN32
2017 typedef struct {
2018 int fd_in, fd_out;
2019 int max_size;
2020 } FDCharDriver;
2022 #define STDIO_MAX_CLIENTS 1
2023 static int stdio_nb_clients = 0;
2025 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2027 FDCharDriver *s = chr->opaque;
2028 return unix_write(s->fd_out, buf, len);
2031 static int fd_chr_read_poll(void *opaque)
2033 CharDriverState *chr = opaque;
2034 FDCharDriver *s = chr->opaque;
2036 s->max_size = qemu_chr_can_read(chr);
2037 return s->max_size;
2040 static void fd_chr_read(void *opaque)
2042 CharDriverState *chr = opaque;
2043 FDCharDriver *s = chr->opaque;
2044 int size, len;
2045 uint8_t buf[1024];
2047 len = sizeof(buf);
2048 if (len > s->max_size)
2049 len = s->max_size;
2050 if (len == 0)
2051 return;
2052 size = read(s->fd_in, buf, len);
2053 if (size == 0) {
2054 /* FD has been closed. Remove it from the active list. */
2055 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2056 return;
2058 if (size > 0) {
2059 qemu_chr_read(chr, buf, size);
2063 static void fd_chr_update_read_handler(CharDriverState *chr)
2065 FDCharDriver *s = chr->opaque;
2067 if (s->fd_in >= 0) {
2068 if (nographic && s->fd_in == 0) {
2069 } else {
2070 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2071 fd_chr_read, NULL, chr);
2076 /* open a character device to a unix fd */
2077 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2079 CharDriverState *chr;
2080 FDCharDriver *s;
2082 chr = qemu_mallocz(sizeof(CharDriverState));
2083 if (!chr)
2084 return NULL;
2085 s = qemu_mallocz(sizeof(FDCharDriver));
2086 if (!s) {
2087 free(chr);
2088 return NULL;
2090 s->fd_in = fd_in;
2091 s->fd_out = fd_out;
2092 chr->opaque = s;
2093 chr->chr_write = fd_chr_write;
2094 chr->chr_update_read_handler = fd_chr_update_read_handler;
2096 qemu_chr_reset(chr);
2098 return chr;
2101 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2103 int fd_out;
2105 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2106 if (fd_out < 0)
2107 return NULL;
2108 return qemu_chr_open_fd(-1, fd_out);
2111 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2113 int fd_in, fd_out;
2114 char filename_in[256], filename_out[256];
2116 snprintf(filename_in, 256, "%s.in", filename);
2117 snprintf(filename_out, 256, "%s.out", filename);
2118 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2119 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2120 if (fd_in < 0 || fd_out < 0) {
2121 if (fd_in >= 0)
2122 close(fd_in);
2123 if (fd_out >= 0)
2124 close(fd_out);
2125 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2126 if (fd_in < 0)
2127 return NULL;
2129 return qemu_chr_open_fd(fd_in, fd_out);
2133 /* for STDIO, we handle the case where several clients use it
2134 (nographic mode) */
2136 #define TERM_FIFO_MAX_SIZE 1
2138 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2139 static int term_fifo_size;
2141 static int stdio_read_poll(void *opaque)
2143 CharDriverState *chr = opaque;
2145 /* try to flush the queue if needed */
2146 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2147 qemu_chr_read(chr, term_fifo, 1);
2148 term_fifo_size = 0;
2150 /* see if we can absorb more chars */
2151 if (term_fifo_size == 0)
2152 return 1;
2153 else
2154 return 0;
2157 static void stdio_read(void *opaque)
2159 int size;
2160 uint8_t buf[1];
2161 CharDriverState *chr = opaque;
2163 size = read(0, buf, 1);
2164 if (size == 0) {
2165 /* stdin has been closed. Remove it from the active list. */
2166 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2167 return;
2169 if (size > 0) {
2170 if (qemu_chr_can_read(chr) > 0) {
2171 qemu_chr_read(chr, buf, 1);
2172 } else if (term_fifo_size == 0) {
2173 term_fifo[term_fifo_size++] = buf[0];
2178 /* init terminal so that we can grab keys */
2179 static struct termios oldtty;
2180 static int old_fd0_flags;
2182 static void term_exit(void)
2184 tcsetattr (0, TCSANOW, &oldtty);
2185 fcntl(0, F_SETFL, old_fd0_flags);
2188 static void term_init(void)
2190 struct termios tty;
2192 tcgetattr (0, &tty);
2193 oldtty = tty;
2194 old_fd0_flags = fcntl(0, F_GETFL);
2196 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2197 |INLCR|IGNCR|ICRNL|IXON);
2198 tty.c_oflag |= OPOST;
2199 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2200 /* if graphical mode, we allow Ctrl-C handling */
2201 if (nographic)
2202 tty.c_lflag &= ~ISIG;
2203 tty.c_cflag &= ~(CSIZE|PARENB);
2204 tty.c_cflag |= CS8;
2205 tty.c_cc[VMIN] = 1;
2206 tty.c_cc[VTIME] = 0;
2208 tcsetattr (0, TCSANOW, &tty);
2210 atexit(term_exit);
2212 fcntl(0, F_SETFL, O_NONBLOCK);
2215 static CharDriverState *qemu_chr_open_stdio(void)
2217 CharDriverState *chr;
2219 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2220 return NULL;
2221 chr = qemu_chr_open_fd(0, 1);
2222 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2223 stdio_nb_clients++;
2224 term_init();
2226 return chr;
2229 #if defined(__linux__) || defined(__sun__)
2230 static CharDriverState *qemu_chr_open_pty(void)
2232 struct termios tty;
2233 char slave_name[1024];
2234 int master_fd, slave_fd;
2236 #if defined(__linux__)
2237 /* Not satisfying */
2238 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2239 return NULL;
2241 #endif
2243 /* Disabling local echo and line-buffered output */
2244 tcgetattr (master_fd, &tty);
2245 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2246 tty.c_cc[VMIN] = 1;
2247 tty.c_cc[VTIME] = 0;
2248 tcsetattr (master_fd, TCSAFLUSH, &tty);
2250 fprintf(stderr, "char device redirected to %s\n", slave_name);
2251 return qemu_chr_open_fd(master_fd, master_fd);
2254 static void tty_serial_init(int fd, int speed,
2255 int parity, int data_bits, int stop_bits)
2257 struct termios tty;
2258 speed_t spd;
2260 #if 0
2261 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2262 speed, parity, data_bits, stop_bits);
2263 #endif
2264 tcgetattr (fd, &tty);
2266 switch(speed) {
2267 case 50:
2268 spd = B50;
2269 break;
2270 case 75:
2271 spd = B75;
2272 break;
2273 case 300:
2274 spd = B300;
2275 break;
2276 case 600:
2277 spd = B600;
2278 break;
2279 case 1200:
2280 spd = B1200;
2281 break;
2282 case 2400:
2283 spd = B2400;
2284 break;
2285 case 4800:
2286 spd = B4800;
2287 break;
2288 case 9600:
2289 spd = B9600;
2290 break;
2291 case 19200:
2292 spd = B19200;
2293 break;
2294 case 38400:
2295 spd = B38400;
2296 break;
2297 case 57600:
2298 spd = B57600;
2299 break;
2300 default:
2301 case 115200:
2302 spd = B115200;
2303 break;
2306 cfsetispeed(&tty, spd);
2307 cfsetospeed(&tty, spd);
2309 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2310 |INLCR|IGNCR|ICRNL|IXON);
2311 tty.c_oflag |= OPOST;
2312 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2313 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2314 switch(data_bits) {
2315 default:
2316 case 8:
2317 tty.c_cflag |= CS8;
2318 break;
2319 case 7:
2320 tty.c_cflag |= CS7;
2321 break;
2322 case 6:
2323 tty.c_cflag |= CS6;
2324 break;
2325 case 5:
2326 tty.c_cflag |= CS5;
2327 break;
2329 switch(parity) {
2330 default:
2331 case 'N':
2332 break;
2333 case 'E':
2334 tty.c_cflag |= PARENB;
2335 break;
2336 case 'O':
2337 tty.c_cflag |= PARENB | PARODD;
2338 break;
2340 if (stop_bits == 2)
2341 tty.c_cflag |= CSTOPB;
2343 tcsetattr (fd, TCSANOW, &tty);
2346 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2348 FDCharDriver *s = chr->opaque;
2350 switch(cmd) {
2351 case CHR_IOCTL_SERIAL_SET_PARAMS:
2353 QEMUSerialSetParams *ssp = arg;
2354 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2355 ssp->data_bits, ssp->stop_bits);
2357 break;
2358 case CHR_IOCTL_SERIAL_SET_BREAK:
2360 int enable = *(int *)arg;
2361 if (enable)
2362 tcsendbreak(s->fd_in, 1);
2364 break;
2365 default:
2366 return -ENOTSUP;
2368 return 0;
2371 static CharDriverState *qemu_chr_open_tty(const char *filename)
2373 CharDriverState *chr;
2374 int fd;
2376 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2377 fcntl(fd, F_SETFL, O_NONBLOCK);
2378 tty_serial_init(fd, 115200, 'N', 8, 1);
2379 chr = qemu_chr_open_fd(fd, fd);
2380 if (!chr) {
2381 close(fd);
2382 return NULL;
2384 chr->chr_ioctl = tty_serial_ioctl;
2385 qemu_chr_reset(chr);
2386 return chr;
2388 #else /* ! __linux__ && ! __sun__ */
2389 static CharDriverState *qemu_chr_open_pty(void)
2391 return NULL;
2393 #endif /* __linux__ || __sun__ */
2395 #if defined(__linux__)
2396 typedef struct {
2397 int fd;
2398 int mode;
2399 } ParallelCharDriver;
2401 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2403 if (s->mode != mode) {
2404 int m = mode;
2405 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2406 return 0;
2407 s->mode = mode;
2409 return 1;
2412 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2414 ParallelCharDriver *drv = chr->opaque;
2415 int fd = drv->fd;
2416 uint8_t b;
2418 switch(cmd) {
2419 case CHR_IOCTL_PP_READ_DATA:
2420 if (ioctl(fd, PPRDATA, &b) < 0)
2421 return -ENOTSUP;
2422 *(uint8_t *)arg = b;
2423 break;
2424 case CHR_IOCTL_PP_WRITE_DATA:
2425 b = *(uint8_t *)arg;
2426 if (ioctl(fd, PPWDATA, &b) < 0)
2427 return -ENOTSUP;
2428 break;
2429 case CHR_IOCTL_PP_READ_CONTROL:
2430 if (ioctl(fd, PPRCONTROL, &b) < 0)
2431 return -ENOTSUP;
2432 /* Linux gives only the lowest bits, and no way to know data
2433 direction! For better compatibility set the fixed upper
2434 bits. */
2435 *(uint8_t *)arg = b | 0xc0;
2436 break;
2437 case CHR_IOCTL_PP_WRITE_CONTROL:
2438 b = *(uint8_t *)arg;
2439 if (ioctl(fd, PPWCONTROL, &b) < 0)
2440 return -ENOTSUP;
2441 break;
2442 case CHR_IOCTL_PP_READ_STATUS:
2443 if (ioctl(fd, PPRSTATUS, &b) < 0)
2444 return -ENOTSUP;
2445 *(uint8_t *)arg = b;
2446 break;
2447 case CHR_IOCTL_PP_EPP_READ_ADDR:
2448 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2449 struct ParallelIOArg *parg = arg;
2450 int n = read(fd, parg->buffer, parg->count);
2451 if (n != parg->count) {
2452 return -EIO;
2455 break;
2456 case CHR_IOCTL_PP_EPP_READ:
2457 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2458 struct ParallelIOArg *parg = arg;
2459 int n = read(fd, parg->buffer, parg->count);
2460 if (n != parg->count) {
2461 return -EIO;
2464 break;
2465 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2466 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2467 struct ParallelIOArg *parg = arg;
2468 int n = write(fd, parg->buffer, parg->count);
2469 if (n != parg->count) {
2470 return -EIO;
2473 break;
2474 case CHR_IOCTL_PP_EPP_WRITE:
2475 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2476 struct ParallelIOArg *parg = arg;
2477 int n = write(fd, parg->buffer, parg->count);
2478 if (n != parg->count) {
2479 return -EIO;
2482 break;
2483 default:
2484 return -ENOTSUP;
2486 return 0;
2489 static void pp_close(CharDriverState *chr)
2491 ParallelCharDriver *drv = chr->opaque;
2492 int fd = drv->fd;
2494 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2495 ioctl(fd, PPRELEASE);
2496 close(fd);
2497 qemu_free(drv);
2500 static CharDriverState *qemu_chr_open_pp(const char *filename)
2502 CharDriverState *chr;
2503 ParallelCharDriver *drv;
2504 int fd;
2506 TFR(fd = open(filename, O_RDWR));
2507 if (fd < 0)
2508 return NULL;
2510 if (ioctl(fd, PPCLAIM) < 0) {
2511 close(fd);
2512 return NULL;
2515 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2516 if (!drv) {
2517 close(fd);
2518 return NULL;
2520 drv->fd = fd;
2521 drv->mode = IEEE1284_MODE_COMPAT;
2523 chr = qemu_mallocz(sizeof(CharDriverState));
2524 if (!chr) {
2525 qemu_free(drv);
2526 close(fd);
2527 return NULL;
2529 chr->chr_write = null_chr_write;
2530 chr->chr_ioctl = pp_ioctl;
2531 chr->chr_close = pp_close;
2532 chr->opaque = drv;
2534 qemu_chr_reset(chr);
2536 return chr;
2538 #endif /* __linux__ */
2540 #else /* _WIN32 */
2542 typedef struct {
2543 int max_size;
2544 HANDLE hcom, hrecv, hsend;
2545 OVERLAPPED orecv, osend;
2546 BOOL fpipe;
2547 DWORD len;
2548 } WinCharState;
2550 #define NSENDBUF 2048
2551 #define NRECVBUF 2048
2552 #define MAXCONNECT 1
2553 #define NTIMEOUT 5000
2555 static int win_chr_poll(void *opaque);
2556 static int win_chr_pipe_poll(void *opaque);
2558 static void win_chr_close(CharDriverState *chr)
2560 WinCharState *s = chr->opaque;
2562 if (s->hsend) {
2563 CloseHandle(s->hsend);
2564 s->hsend = NULL;
2566 if (s->hrecv) {
2567 CloseHandle(s->hrecv);
2568 s->hrecv = NULL;
2570 if (s->hcom) {
2571 CloseHandle(s->hcom);
2572 s->hcom = NULL;
2574 if (s->fpipe)
2575 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2576 else
2577 qemu_del_polling_cb(win_chr_poll, chr);
2580 static int win_chr_init(CharDriverState *chr, const char *filename)
2582 WinCharState *s = chr->opaque;
2583 COMMCONFIG comcfg;
2584 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2585 COMSTAT comstat;
2586 DWORD size;
2587 DWORD err;
2589 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2590 if (!s->hsend) {
2591 fprintf(stderr, "Failed CreateEvent\n");
2592 goto fail;
2594 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2595 if (!s->hrecv) {
2596 fprintf(stderr, "Failed CreateEvent\n");
2597 goto fail;
2600 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2601 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2602 if (s->hcom == INVALID_HANDLE_VALUE) {
2603 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2604 s->hcom = NULL;
2605 goto fail;
2608 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2609 fprintf(stderr, "Failed SetupComm\n");
2610 goto fail;
2613 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2614 size = sizeof(COMMCONFIG);
2615 GetDefaultCommConfig(filename, &comcfg, &size);
2616 comcfg.dcb.DCBlength = sizeof(DCB);
2617 CommConfigDialog(filename, NULL, &comcfg);
2619 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2620 fprintf(stderr, "Failed SetCommState\n");
2621 goto fail;
2624 if (!SetCommMask(s->hcom, EV_ERR)) {
2625 fprintf(stderr, "Failed SetCommMask\n");
2626 goto fail;
2629 cto.ReadIntervalTimeout = MAXDWORD;
2630 if (!SetCommTimeouts(s->hcom, &cto)) {
2631 fprintf(stderr, "Failed SetCommTimeouts\n");
2632 goto fail;
2635 if (!ClearCommError(s->hcom, &err, &comstat)) {
2636 fprintf(stderr, "Failed ClearCommError\n");
2637 goto fail;
2639 qemu_add_polling_cb(win_chr_poll, chr);
2640 return 0;
2642 fail:
2643 win_chr_close(chr);
2644 return -1;
2647 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2649 WinCharState *s = chr->opaque;
2650 DWORD len, ret, size, err;
2652 len = len1;
2653 ZeroMemory(&s->osend, sizeof(s->osend));
2654 s->osend.hEvent = s->hsend;
2655 while (len > 0) {
2656 if (s->hsend)
2657 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2658 else
2659 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2660 if (!ret) {
2661 err = GetLastError();
2662 if (err == ERROR_IO_PENDING) {
2663 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2664 if (ret) {
2665 buf += size;
2666 len -= size;
2667 } else {
2668 break;
2670 } else {
2671 break;
2673 } else {
2674 buf += size;
2675 len -= size;
2678 return len1 - len;
2681 static int win_chr_read_poll(CharDriverState *chr)
2683 WinCharState *s = chr->opaque;
2685 s->max_size = qemu_chr_can_read(chr);
2686 return s->max_size;
2689 static void win_chr_readfile(CharDriverState *chr)
2691 WinCharState *s = chr->opaque;
2692 int ret, err;
2693 uint8_t buf[1024];
2694 DWORD size;
2696 ZeroMemory(&s->orecv, sizeof(s->orecv));
2697 s->orecv.hEvent = s->hrecv;
2698 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2699 if (!ret) {
2700 err = GetLastError();
2701 if (err == ERROR_IO_PENDING) {
2702 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2706 if (size > 0) {
2707 qemu_chr_read(chr, buf, size);
2711 static void win_chr_read(CharDriverState *chr)
2713 WinCharState *s = chr->opaque;
2715 if (s->len > s->max_size)
2716 s->len = s->max_size;
2717 if (s->len == 0)
2718 return;
2720 win_chr_readfile(chr);
2723 static int win_chr_poll(void *opaque)
2725 CharDriverState *chr = opaque;
2726 WinCharState *s = chr->opaque;
2727 COMSTAT status;
2728 DWORD comerr;
2730 ClearCommError(s->hcom, &comerr, &status);
2731 if (status.cbInQue > 0) {
2732 s->len = status.cbInQue;
2733 win_chr_read_poll(chr);
2734 win_chr_read(chr);
2735 return 1;
2737 return 0;
2740 static CharDriverState *qemu_chr_open_win(const char *filename)
2742 CharDriverState *chr;
2743 WinCharState *s;
2745 chr = qemu_mallocz(sizeof(CharDriverState));
2746 if (!chr)
2747 return NULL;
2748 s = qemu_mallocz(sizeof(WinCharState));
2749 if (!s) {
2750 free(chr);
2751 return NULL;
2753 chr->opaque = s;
2754 chr->chr_write = win_chr_write;
2755 chr->chr_close = win_chr_close;
2757 if (win_chr_init(chr, filename) < 0) {
2758 free(s);
2759 free(chr);
2760 return NULL;
2762 qemu_chr_reset(chr);
2763 return chr;
2766 static int win_chr_pipe_poll(void *opaque)
2768 CharDriverState *chr = opaque;
2769 WinCharState *s = chr->opaque;
2770 DWORD size;
2772 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2773 if (size > 0) {
2774 s->len = size;
2775 win_chr_read_poll(chr);
2776 win_chr_read(chr);
2777 return 1;
2779 return 0;
2782 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2784 WinCharState *s = chr->opaque;
2785 OVERLAPPED ov;
2786 int ret;
2787 DWORD size;
2788 char openname[256];
2790 s->fpipe = TRUE;
2792 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2793 if (!s->hsend) {
2794 fprintf(stderr, "Failed CreateEvent\n");
2795 goto fail;
2797 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2798 if (!s->hrecv) {
2799 fprintf(stderr, "Failed CreateEvent\n");
2800 goto fail;
2803 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2804 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2805 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2806 PIPE_WAIT,
2807 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2808 if (s->hcom == INVALID_HANDLE_VALUE) {
2809 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2810 s->hcom = NULL;
2811 goto fail;
2814 ZeroMemory(&ov, sizeof(ov));
2815 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2816 ret = ConnectNamedPipe(s->hcom, &ov);
2817 if (ret) {
2818 fprintf(stderr, "Failed ConnectNamedPipe\n");
2819 goto fail;
2822 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2823 if (!ret) {
2824 fprintf(stderr, "Failed GetOverlappedResult\n");
2825 if (ov.hEvent) {
2826 CloseHandle(ov.hEvent);
2827 ov.hEvent = NULL;
2829 goto fail;
2832 if (ov.hEvent) {
2833 CloseHandle(ov.hEvent);
2834 ov.hEvent = NULL;
2836 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2837 return 0;
2839 fail:
2840 win_chr_close(chr);
2841 return -1;
2845 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2847 CharDriverState *chr;
2848 WinCharState *s;
2850 chr = qemu_mallocz(sizeof(CharDriverState));
2851 if (!chr)
2852 return NULL;
2853 s = qemu_mallocz(sizeof(WinCharState));
2854 if (!s) {
2855 free(chr);
2856 return NULL;
2858 chr->opaque = s;
2859 chr->chr_write = win_chr_write;
2860 chr->chr_close = win_chr_close;
2862 if (win_chr_pipe_init(chr, filename) < 0) {
2863 free(s);
2864 free(chr);
2865 return NULL;
2867 qemu_chr_reset(chr);
2868 return chr;
2871 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2873 CharDriverState *chr;
2874 WinCharState *s;
2876 chr = qemu_mallocz(sizeof(CharDriverState));
2877 if (!chr)
2878 return NULL;
2879 s = qemu_mallocz(sizeof(WinCharState));
2880 if (!s) {
2881 free(chr);
2882 return NULL;
2884 s->hcom = fd_out;
2885 chr->opaque = s;
2886 chr->chr_write = win_chr_write;
2887 qemu_chr_reset(chr);
2888 return chr;
2891 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2893 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2896 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2898 HANDLE fd_out;
2900 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2901 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2902 if (fd_out == INVALID_HANDLE_VALUE)
2903 return NULL;
2905 return qemu_chr_open_win_file(fd_out);
2907 #endif /* !_WIN32 */
2909 /***********************************************************/
2910 /* UDP Net console */
2912 typedef struct {
2913 int fd;
2914 struct sockaddr_in daddr;
2915 uint8_t buf[1024];
2916 int bufcnt;
2917 int bufptr;
2918 int max_size;
2919 } NetCharDriver;
2921 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2923 NetCharDriver *s = chr->opaque;
2925 return sendto(s->fd, buf, len, 0,
2926 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2929 static int udp_chr_read_poll(void *opaque)
2931 CharDriverState *chr = opaque;
2932 NetCharDriver *s = chr->opaque;
2934 s->max_size = qemu_chr_can_read(chr);
2936 /* If there were any stray characters in the queue process them
2937 * first
2939 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2940 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2941 s->bufptr++;
2942 s->max_size = qemu_chr_can_read(chr);
2944 return s->max_size;
2947 static void udp_chr_read(void *opaque)
2949 CharDriverState *chr = opaque;
2950 NetCharDriver *s = chr->opaque;
2952 if (s->max_size == 0)
2953 return;
2954 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2955 s->bufptr = s->bufcnt;
2956 if (s->bufcnt <= 0)
2957 return;
2959 s->bufptr = 0;
2960 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2961 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2962 s->bufptr++;
2963 s->max_size = qemu_chr_can_read(chr);
2967 static void udp_chr_update_read_handler(CharDriverState *chr)
2969 NetCharDriver *s = chr->opaque;
2971 if (s->fd >= 0) {
2972 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2973 udp_chr_read, NULL, chr);
2977 #ifndef _WIN32
2978 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2979 #endif
2980 int parse_host_src_port(struct sockaddr_in *haddr,
2981 struct sockaddr_in *saddr,
2982 const char *str);
2984 static CharDriverState *qemu_chr_open_udp(const char *def)
2986 CharDriverState *chr = NULL;
2987 NetCharDriver *s = NULL;
2988 int fd = -1;
2989 struct sockaddr_in saddr;
2991 chr = qemu_mallocz(sizeof(CharDriverState));
2992 if (!chr)
2993 goto return_err;
2994 s = qemu_mallocz(sizeof(NetCharDriver));
2995 if (!s)
2996 goto return_err;
2998 fd = socket(PF_INET, SOCK_DGRAM, 0);
2999 if (fd < 0) {
3000 perror("socket(PF_INET, SOCK_DGRAM)");
3001 goto return_err;
3004 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3005 printf("Could not parse: %s\n", def);
3006 goto return_err;
3009 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3011 perror("bind");
3012 goto return_err;
3015 s->fd = fd;
3016 s->bufcnt = 0;
3017 s->bufptr = 0;
3018 chr->opaque = s;
3019 chr->chr_write = udp_chr_write;
3020 chr->chr_update_read_handler = udp_chr_update_read_handler;
3021 return chr;
3023 return_err:
3024 if (chr)
3025 free(chr);
3026 if (s)
3027 free(s);
3028 if (fd >= 0)
3029 closesocket(fd);
3030 return NULL;
3033 /***********************************************************/
3034 /* TCP Net console */
3036 typedef struct {
3037 int fd, listen_fd;
3038 int connected;
3039 int max_size;
3040 int do_telnetopt;
3041 int do_nodelay;
3042 int is_unix;
3043 } TCPCharDriver;
3045 static void tcp_chr_accept(void *opaque);
3047 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3049 TCPCharDriver *s = chr->opaque;
3050 if (s->connected) {
3051 return send_all(s->fd, buf, len);
3052 } else {
3053 /* XXX: indicate an error ? */
3054 return len;
3058 static int tcp_chr_read_poll(void *opaque)
3060 CharDriverState *chr = opaque;
3061 TCPCharDriver *s = chr->opaque;
3062 if (!s->connected)
3063 return 0;
3064 s->max_size = qemu_chr_can_read(chr);
3065 return s->max_size;
3068 #define IAC 255
3069 #define IAC_BREAK 243
3070 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3071 TCPCharDriver *s,
3072 uint8_t *buf, int *size)
3074 /* Handle any telnet client's basic IAC options to satisfy char by
3075 * char mode with no echo. All IAC options will be removed from
3076 * the buf and the do_telnetopt variable will be used to track the
3077 * state of the width of the IAC information.
3079 * IAC commands come in sets of 3 bytes with the exception of the
3080 * "IAC BREAK" command and the double IAC.
3083 int i;
3084 int j = 0;
3086 for (i = 0; i < *size; i++) {
3087 if (s->do_telnetopt > 1) {
3088 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3089 /* Double IAC means send an IAC */
3090 if (j != i)
3091 buf[j] = buf[i];
3092 j++;
3093 s->do_telnetopt = 1;
3094 } else {
3095 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3096 /* Handle IAC break commands by sending a serial break */
3097 qemu_chr_event(chr, CHR_EVENT_BREAK);
3098 s->do_telnetopt++;
3100 s->do_telnetopt++;
3102 if (s->do_telnetopt >= 4) {
3103 s->do_telnetopt = 1;
3105 } else {
3106 if ((unsigned char)buf[i] == IAC) {
3107 s->do_telnetopt = 2;
3108 } else {
3109 if (j != i)
3110 buf[j] = buf[i];
3111 j++;
3115 *size = j;
3118 static void tcp_chr_read(void *opaque)
3120 CharDriverState *chr = opaque;
3121 TCPCharDriver *s = chr->opaque;
3122 uint8_t buf[1024];
3123 int len, size;
3125 if (!s->connected || s->max_size <= 0)
3126 return;
3127 len = sizeof(buf);
3128 if (len > s->max_size)
3129 len = s->max_size;
3130 size = recv(s->fd, buf, len, 0);
3131 if (size == 0) {
3132 /* connection closed */
3133 s->connected = 0;
3134 if (s->listen_fd >= 0) {
3135 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3137 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3138 closesocket(s->fd);
3139 s->fd = -1;
3140 } else if (size > 0) {
3141 if (s->do_telnetopt)
3142 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3143 if (size > 0)
3144 qemu_chr_read(chr, buf, size);
3148 static void tcp_chr_connect(void *opaque)
3150 CharDriverState *chr = opaque;
3151 TCPCharDriver *s = chr->opaque;
3153 s->connected = 1;
3154 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3155 tcp_chr_read, NULL, chr);
3156 qemu_chr_reset(chr);
3159 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3160 static void tcp_chr_telnet_init(int fd)
3162 char buf[3];
3163 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3164 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3165 send(fd, (char *)buf, 3, 0);
3166 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3167 send(fd, (char *)buf, 3, 0);
3168 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3169 send(fd, (char *)buf, 3, 0);
3170 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3171 send(fd, (char *)buf, 3, 0);
3174 static void socket_set_nodelay(int fd)
3176 int val = 1;
3177 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3180 static void tcp_chr_accept(void *opaque)
3182 CharDriverState *chr = opaque;
3183 TCPCharDriver *s = chr->opaque;
3184 struct sockaddr_in saddr;
3185 #ifndef _WIN32
3186 struct sockaddr_un uaddr;
3187 #endif
3188 struct sockaddr *addr;
3189 socklen_t len;
3190 int fd;
3192 for(;;) {
3193 #ifndef _WIN32
3194 if (s->is_unix) {
3195 len = sizeof(uaddr);
3196 addr = (struct sockaddr *)&uaddr;
3197 } else
3198 #endif
3200 len = sizeof(saddr);
3201 addr = (struct sockaddr *)&saddr;
3203 fd = accept(s->listen_fd, addr, &len);
3204 if (fd < 0 && errno != EINTR) {
3205 return;
3206 } else if (fd >= 0) {
3207 if (s->do_telnetopt)
3208 tcp_chr_telnet_init(fd);
3209 break;
3212 socket_set_nonblock(fd);
3213 if (s->do_nodelay)
3214 socket_set_nodelay(fd);
3215 s->fd = fd;
3216 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3217 tcp_chr_connect(chr);
3220 static void tcp_chr_close(CharDriverState *chr)
3222 TCPCharDriver *s = chr->opaque;
3223 if (s->fd >= 0)
3224 closesocket(s->fd);
3225 if (s->listen_fd >= 0)
3226 closesocket(s->listen_fd);
3227 qemu_free(s);
3230 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3231 int is_telnet,
3232 int is_unix)
3234 CharDriverState *chr = NULL;
3235 TCPCharDriver *s = NULL;
3236 int fd = -1, ret, err, val;
3237 int is_listen = 0;
3238 int is_waitconnect = 1;
3239 int do_nodelay = 0;
3240 const char *ptr;
3241 struct sockaddr_in saddr;
3242 #ifndef _WIN32
3243 struct sockaddr_un uaddr;
3244 #endif
3245 struct sockaddr *addr;
3246 socklen_t addrlen;
3248 #ifndef _WIN32
3249 if (is_unix) {
3250 addr = (struct sockaddr *)&uaddr;
3251 addrlen = sizeof(uaddr);
3252 if (parse_unix_path(&uaddr, host_str) < 0)
3253 goto fail;
3254 } else
3255 #endif
3257 addr = (struct sockaddr *)&saddr;
3258 addrlen = sizeof(saddr);
3259 if (parse_host_port(&saddr, host_str) < 0)
3260 goto fail;
3263 ptr = host_str;
3264 while((ptr = strchr(ptr,','))) {
3265 ptr++;
3266 if (!strncmp(ptr,"server",6)) {
3267 is_listen = 1;
3268 } else if (!strncmp(ptr,"nowait",6)) {
3269 is_waitconnect = 0;
3270 } else if (!strncmp(ptr,"nodelay",6)) {
3271 do_nodelay = 1;
3272 } else {
3273 printf("Unknown option: %s\n", ptr);
3274 goto fail;
3277 if (!is_listen)
3278 is_waitconnect = 0;
3280 chr = qemu_mallocz(sizeof(CharDriverState));
3281 if (!chr)
3282 goto fail;
3283 s = qemu_mallocz(sizeof(TCPCharDriver));
3284 if (!s)
3285 goto fail;
3287 #ifndef _WIN32
3288 if (is_unix)
3289 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3290 else
3291 #endif
3292 fd = socket(PF_INET, SOCK_STREAM, 0);
3294 if (fd < 0)
3295 goto fail;
3297 if (!is_waitconnect)
3298 socket_set_nonblock(fd);
3300 s->connected = 0;
3301 s->fd = -1;
3302 s->listen_fd = -1;
3303 s->is_unix = is_unix;
3304 s->do_nodelay = do_nodelay && !is_unix;
3306 chr->opaque = s;
3307 chr->chr_write = tcp_chr_write;
3308 chr->chr_close = tcp_chr_close;
3310 if (is_listen) {
3311 /* allow fast reuse */
3312 #ifndef _WIN32
3313 if (is_unix) {
3314 char path[109];
3315 strncpy(path, uaddr.sun_path, 108);
3316 path[108] = 0;
3317 unlink(path);
3318 } else
3319 #endif
3321 val = 1;
3322 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3325 ret = bind(fd, addr, addrlen);
3326 if (ret < 0)
3327 goto fail;
3329 ret = listen(fd, 0);
3330 if (ret < 0)
3331 goto fail;
3333 s->listen_fd = fd;
3334 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3335 if (is_telnet)
3336 s->do_telnetopt = 1;
3337 } else {
3338 for(;;) {
3339 ret = connect(fd, addr, addrlen);
3340 if (ret < 0) {
3341 err = socket_error();
3342 if (err == EINTR || err == EWOULDBLOCK) {
3343 } else if (err == EINPROGRESS) {
3344 break;
3345 #ifdef _WIN32
3346 } else if (err == WSAEALREADY) {
3347 break;
3348 #endif
3349 } else {
3350 goto fail;
3352 } else {
3353 s->connected = 1;
3354 break;
3357 s->fd = fd;
3358 socket_set_nodelay(fd);
3359 if (s->connected)
3360 tcp_chr_connect(chr);
3361 else
3362 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3365 if (is_listen && is_waitconnect) {
3366 printf("QEMU waiting for connection on: %s\n", host_str);
3367 tcp_chr_accept(chr);
3368 socket_set_nonblock(s->listen_fd);
3371 return chr;
3372 fail:
3373 if (fd >= 0)
3374 closesocket(fd);
3375 qemu_free(s);
3376 qemu_free(chr);
3377 return NULL;
3380 CharDriverState *qemu_chr_open(const char *filename)
3382 const char *p;
3384 if (!strcmp(filename, "vc")) {
3385 return text_console_init(&display_state, 0);
3386 } else if (strstart(filename, "vc:", &p)) {
3387 return text_console_init(&display_state, p);
3388 } else if (!strcmp(filename, "null")) {
3389 return qemu_chr_open_null();
3390 } else
3391 if (strstart(filename, "tcp:", &p)) {
3392 return qemu_chr_open_tcp(p, 0, 0);
3393 } else
3394 if (strstart(filename, "telnet:", &p)) {
3395 return qemu_chr_open_tcp(p, 1, 0);
3396 } else
3397 if (strstart(filename, "udp:", &p)) {
3398 return qemu_chr_open_udp(p);
3399 } else
3400 if (strstart(filename, "mon:", &p)) {
3401 CharDriverState *drv = qemu_chr_open(p);
3402 if (drv) {
3403 drv = qemu_chr_open_mux(drv);
3404 monitor_init(drv, !nographic);
3405 return drv;
3407 printf("Unable to open driver: %s\n", p);
3408 return 0;
3409 } else
3410 #ifndef _WIN32
3411 if (strstart(filename, "unix:", &p)) {
3412 return qemu_chr_open_tcp(p, 0, 1);
3413 } else if (strstart(filename, "file:", &p)) {
3414 return qemu_chr_open_file_out(p);
3415 } else if (strstart(filename, "pipe:", &p)) {
3416 return qemu_chr_open_pipe(p);
3417 } else if (!strcmp(filename, "pty")) {
3418 return qemu_chr_open_pty();
3419 } else if (!strcmp(filename, "stdio")) {
3420 return qemu_chr_open_stdio();
3421 } else
3422 #if defined(__linux__)
3423 if (strstart(filename, "/dev/parport", NULL)) {
3424 return qemu_chr_open_pp(filename);
3425 } else
3426 #endif
3427 #if defined(__linux__) || defined(__sun__)
3428 if (strstart(filename, "/dev/", NULL)) {
3429 return qemu_chr_open_tty(filename);
3430 } else
3431 #endif
3432 #else /* !_WIN32 */
3433 if (strstart(filename, "COM", NULL)) {
3434 return qemu_chr_open_win(filename);
3435 } else
3436 if (strstart(filename, "pipe:", &p)) {
3437 return qemu_chr_open_win_pipe(p);
3438 } else
3439 if (strstart(filename, "con:", NULL)) {
3440 return qemu_chr_open_win_con(filename);
3441 } else
3442 if (strstart(filename, "file:", &p)) {
3443 return qemu_chr_open_win_file_out(p);
3445 #endif
3447 return NULL;
3451 void qemu_chr_close(CharDriverState *chr)
3453 if (chr->chr_close)
3454 chr->chr_close(chr);
3457 /***********************************************************/
3458 /* network device redirectors */
3460 __attribute__ (( unused ))
3461 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3463 int len, i, j, c;
3465 for(i=0;i<size;i+=16) {
3466 len = size - i;
3467 if (len > 16)
3468 len = 16;
3469 fprintf(f, "%08x ", i);
3470 for(j=0;j<16;j++) {
3471 if (j < len)
3472 fprintf(f, " %02x", buf[i+j]);
3473 else
3474 fprintf(f, " ");
3476 fprintf(f, " ");
3477 for(j=0;j<len;j++) {
3478 c = buf[i+j];
3479 if (c < ' ' || c > '~')
3480 c = '.';
3481 fprintf(f, "%c", c);
3483 fprintf(f, "\n");
3487 static int parse_macaddr(uint8_t *macaddr, const char *p)
3489 int i;
3490 char *last_char;
3491 long int offset;
3493 errno = 0;
3494 offset = strtol(p, &last_char, 0);
3495 if (0 == errno && '\0' == *last_char &&
3496 offset >= 0 && offset <= 0xFFFFFF) {
3497 macaddr[3] = (offset & 0xFF0000) >> 16;
3498 macaddr[4] = (offset & 0xFF00) >> 8;
3499 macaddr[5] = offset & 0xFF;
3500 return 0;
3501 } else {
3502 for(i = 0; i < 6; i++) {
3503 macaddr[i] = strtol(p, (char **)&p, 16);
3504 if (i == 5) {
3505 if (*p != '\0')
3506 return -1;
3507 } else {
3508 if (*p != ':' && *p != '-')
3509 return -1;
3510 p++;
3513 return 0;
3516 return -1;
3519 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3521 const char *p, *p1;
3522 int len;
3523 p = *pp;
3524 p1 = strchr(p, sep);
3525 if (!p1)
3526 return -1;
3527 len = p1 - p;
3528 p1++;
3529 if (buf_size > 0) {
3530 if (len > buf_size - 1)
3531 len = buf_size - 1;
3532 memcpy(buf, p, len);
3533 buf[len] = '\0';
3535 *pp = p1;
3536 return 0;
3539 int parse_host_src_port(struct sockaddr_in *haddr,
3540 struct sockaddr_in *saddr,
3541 const char *input_str)
3543 char *str = strdup(input_str);
3544 char *host_str = str;
3545 char *src_str;
3546 char *ptr;
3549 * Chop off any extra arguments at the end of the string which
3550 * would start with a comma, then fill in the src port information
3551 * if it was provided else use the "any address" and "any port".
3553 if ((ptr = strchr(str,',')))
3554 *ptr = '\0';
3556 if ((src_str = strchr(input_str,'@'))) {
3557 *src_str = '\0';
3558 src_str++;
3561 if (parse_host_port(haddr, host_str) < 0)
3562 goto fail;
3564 if (!src_str || *src_str == '\0')
3565 src_str = ":0";
3567 if (parse_host_port(saddr, src_str) < 0)
3568 goto fail;
3570 free(str);
3571 return(0);
3573 fail:
3574 free(str);
3575 return -1;
3578 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3580 char buf[512];
3581 struct hostent *he;
3582 const char *p, *r;
3583 int port;
3585 p = str;
3586 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3587 return -1;
3588 saddr->sin_family = AF_INET;
3589 if (buf[0] == '\0') {
3590 saddr->sin_addr.s_addr = 0;
3591 } else {
3592 if (isdigit(buf[0])) {
3593 if (!inet_aton(buf, &saddr->sin_addr))
3594 return -1;
3595 } else {
3596 if ((he = gethostbyname(buf)) == NULL)
3597 return - 1;
3598 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3601 port = strtol(p, (char **)&r, 0);
3602 if (r == p)
3603 return -1;
3604 saddr->sin_port = htons(port);
3605 return 0;
3608 #ifndef _WIN32
3609 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3611 const char *p;
3612 int len;
3614 len = MIN(108, strlen(str));
3615 p = strchr(str, ',');
3616 if (p)
3617 len = MIN(len, p - str);
3619 memset(uaddr, 0, sizeof(*uaddr));
3621 uaddr->sun_family = AF_UNIX;
3622 memcpy(uaddr->sun_path, str, len);
3624 return 0;
3626 #endif
3628 /* find or alloc a new VLAN */
3629 VLANState *qemu_find_vlan(int id)
3631 VLANState **pvlan, *vlan;
3632 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3633 if (vlan->id == id)
3634 return vlan;
3636 vlan = qemu_mallocz(sizeof(VLANState));
3637 if (!vlan)
3638 return NULL;
3639 vlan->id = id;
3640 vlan->next = NULL;
3641 pvlan = &first_vlan;
3642 while (*pvlan != NULL)
3643 pvlan = &(*pvlan)->next;
3644 *pvlan = vlan;
3645 return vlan;
3648 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3649 IOReadHandler *fd_read,
3650 IOCanRWHandler *fd_can_read,
3651 void *opaque)
3653 VLANClientState *vc, **pvc;
3654 vc = qemu_mallocz(sizeof(VLANClientState));
3655 if (!vc)
3656 return NULL;
3657 vc->fd_read = fd_read;
3658 vc->fd_can_read = fd_can_read;
3659 vc->opaque = opaque;
3660 vc->vlan = vlan;
3662 vc->next = NULL;
3663 pvc = &vlan->first_client;
3664 while (*pvc != NULL)
3665 pvc = &(*pvc)->next;
3666 *pvc = vc;
3667 return vc;
3670 int qemu_can_send_packet(VLANClientState *vc1)
3672 VLANState *vlan = vc1->vlan;
3673 VLANClientState *vc;
3675 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3676 if (vc != vc1) {
3677 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3678 return 1;
3681 return 0;
3684 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3686 VLANState *vlan = vc1->vlan;
3687 VLANClientState *vc;
3689 #if 0
3690 printf("vlan %d send:\n", vlan->id);
3691 hex_dump(stdout, buf, size);
3692 #endif
3693 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3694 if (vc != vc1) {
3695 vc->fd_read(vc->opaque, buf, size);
3700 #if defined(CONFIG_SLIRP)
3702 /* slirp network adapter */
3704 static int slirp_inited;
3705 static VLANClientState *slirp_vc;
3707 int slirp_can_output(void)
3709 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3712 void slirp_output(const uint8_t *pkt, int pkt_len)
3714 #if 0
3715 printf("slirp output:\n");
3716 hex_dump(stdout, pkt, pkt_len);
3717 #endif
3718 if (!slirp_vc)
3719 return;
3720 qemu_send_packet(slirp_vc, pkt, pkt_len);
3723 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3725 #if 0
3726 printf("slirp input:\n");
3727 hex_dump(stdout, buf, size);
3728 #endif
3729 slirp_input(buf, size);
3732 static int net_slirp_init(VLANState *vlan)
3734 if (!slirp_inited) {
3735 slirp_inited = 1;
3736 slirp_init();
3738 slirp_vc = qemu_new_vlan_client(vlan,
3739 slirp_receive, NULL, NULL);
3740 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3741 return 0;
3744 static void net_slirp_redir(const char *redir_str)
3746 int is_udp;
3747 char buf[256], *r;
3748 const char *p;
3749 struct in_addr guest_addr;
3750 int host_port, guest_port;
3752 if (!slirp_inited) {
3753 slirp_inited = 1;
3754 slirp_init();
3757 p = redir_str;
3758 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3759 goto fail;
3760 if (!strcmp(buf, "tcp")) {
3761 is_udp = 0;
3762 } else if (!strcmp(buf, "udp")) {
3763 is_udp = 1;
3764 } else {
3765 goto fail;
3768 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3769 goto fail;
3770 host_port = strtol(buf, &r, 0);
3771 if (r == buf)
3772 goto fail;
3774 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3775 goto fail;
3776 if (buf[0] == '\0') {
3777 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3779 if (!inet_aton(buf, &guest_addr))
3780 goto fail;
3782 guest_port = strtol(p, &r, 0);
3783 if (r == p)
3784 goto fail;
3786 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3787 fprintf(stderr, "qemu: could not set up redirection\n");
3788 exit(1);
3790 return;
3791 fail:
3792 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3793 exit(1);
3796 #ifndef _WIN32
3798 char smb_dir[1024];
3800 static void smb_exit(void)
3802 DIR *d;
3803 struct dirent *de;
3804 char filename[1024];
3806 /* erase all the files in the directory */
3807 d = opendir(smb_dir);
3808 for(;;) {
3809 de = readdir(d);
3810 if (!de)
3811 break;
3812 if (strcmp(de->d_name, ".") != 0 &&
3813 strcmp(de->d_name, "..") != 0) {
3814 snprintf(filename, sizeof(filename), "%s/%s",
3815 smb_dir, de->d_name);
3816 unlink(filename);
3819 closedir(d);
3820 rmdir(smb_dir);
3823 /* automatic user mode samba server configuration */
3824 static void net_slirp_smb(const char *exported_dir)
3826 char smb_conf[1024];
3827 char smb_cmdline[1024];
3828 FILE *f;
3830 if (!slirp_inited) {
3831 slirp_inited = 1;
3832 slirp_init();
3835 /* XXX: better tmp dir construction */
3836 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3837 if (mkdir(smb_dir, 0700) < 0) {
3838 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3839 exit(1);
3841 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3843 f = fopen(smb_conf, "w");
3844 if (!f) {
3845 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3846 exit(1);
3848 fprintf(f,
3849 "[global]\n"
3850 "private dir=%s\n"
3851 "smb ports=0\n"
3852 "socket address=127.0.0.1\n"
3853 "pid directory=%s\n"
3854 "lock directory=%s\n"
3855 "log file=%s/log.smbd\n"
3856 "smb passwd file=%s/smbpasswd\n"
3857 "security = share\n"
3858 "[qemu]\n"
3859 "path=%s\n"
3860 "read only=no\n"
3861 "guest ok=yes\n",
3862 smb_dir,
3863 smb_dir,
3864 smb_dir,
3865 smb_dir,
3866 smb_dir,
3867 exported_dir
3869 fclose(f);
3870 atexit(smb_exit);
3872 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3873 SMBD_COMMAND, smb_conf);
3875 slirp_add_exec(0, smb_cmdline, 4, 139);
3878 #endif /* !defined(_WIN32) */
3879 void do_info_slirp(void)
3881 slirp_stats();
3884 #endif /* CONFIG_SLIRP */
3886 #if !defined(_WIN32)
3888 typedef struct TAPState {
3889 VLANClientState *vc;
3890 int fd;
3891 char down_script[1024];
3892 int no_poll;
3893 } TAPState;
3895 static int tap_read_poll(void *opaque)
3897 TAPState *s = opaque;
3898 return (!s->no_poll);
3901 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3903 TAPState *s = opaque;
3904 int ret;
3905 for(;;) {
3906 ret = write(s->fd, buf, size);
3907 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3908 } else {
3909 break;
3914 static void tap_send(void *opaque)
3916 TAPState *s = opaque;
3917 uint8_t buf[4096];
3918 int size;
3920 #ifdef __sun__
3921 struct strbuf sbuf;
3922 int f = 0;
3923 sbuf.maxlen = sizeof(buf);
3924 sbuf.buf = buf;
3925 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3926 #else
3927 size = read(s->fd, buf, sizeof(buf));
3928 #endif
3929 if (size > 0) {
3930 qemu_send_packet(s->vc, buf, size);
3934 int hack_around_tap(void *opaque)
3936 VLANClientState *vc = opaque;
3937 TAPState *ts = vc->opaque;
3939 if (vc->fd_read != tap_receive)
3940 return -1;
3942 if (ts) {
3943 ts->no_poll = 1;
3944 return ts->fd;
3947 return -1;
3950 /* fd support */
3952 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3954 TAPState *s;
3956 s = qemu_mallocz(sizeof(TAPState));
3957 if (!s)
3958 return NULL;
3959 s->fd = fd;
3960 s->no_poll = 0;
3961 enable_sigio_timer(fd);
3962 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3963 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
3964 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3965 return s;
3968 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3969 static int tap_open(char *ifname, int ifname_size)
3971 int fd;
3972 char *dev;
3973 struct stat s;
3975 TFR(fd = open("/dev/tap", O_RDWR));
3976 if (fd < 0) {
3977 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3978 return -1;
3981 fstat(fd, &s);
3982 dev = devname(s.st_rdev, S_IFCHR);
3983 pstrcpy(ifname, ifname_size, dev);
3985 fcntl(fd, F_SETFL, O_NONBLOCK);
3986 return fd;
3988 #elif defined(__sun__)
3989 #define TUNNEWPPA (('T'<<16) | 0x0001)
3991 * Allocate TAP device, returns opened fd.
3992 * Stores dev name in the first arg(must be large enough).
3994 int tap_alloc(char *dev)
3996 int tap_fd, if_fd, ppa = -1;
3997 static int ip_fd = 0;
3998 char *ptr;
4000 static int arp_fd = 0;
4001 int ip_muxid, arp_muxid;
4002 struct strioctl strioc_if, strioc_ppa;
4003 int link_type = I_PLINK;;
4004 struct lifreq ifr;
4005 char actual_name[32] = "";
4007 memset(&ifr, 0x0, sizeof(ifr));
4009 if( *dev ){
4010 ptr = dev;
4011 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4012 ppa = atoi(ptr);
4015 /* Check if IP device was opened */
4016 if( ip_fd )
4017 close(ip_fd);
4019 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4020 if (ip_fd < 0) {
4021 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4022 return -1;
4025 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4026 if (tap_fd < 0) {
4027 syslog(LOG_ERR, "Can't open /dev/tap");
4028 return -1;
4031 /* Assign a new PPA and get its unit number. */
4032 strioc_ppa.ic_cmd = TUNNEWPPA;
4033 strioc_ppa.ic_timout = 0;
4034 strioc_ppa.ic_len = sizeof(ppa);
4035 strioc_ppa.ic_dp = (char *)&ppa;
4036 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4037 syslog (LOG_ERR, "Can't assign new interface");
4039 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4040 if (if_fd < 0) {
4041 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4042 return -1;
4044 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4045 syslog(LOG_ERR, "Can't push IP module");
4046 return -1;
4049 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4050 syslog(LOG_ERR, "Can't get flags\n");
4052 snprintf (actual_name, 32, "tap%d", ppa);
4053 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4055 ifr.lifr_ppa = ppa;
4056 /* Assign ppa according to the unit number returned by tun device */
4058 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4059 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4060 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4061 syslog (LOG_ERR, "Can't get flags\n");
4062 /* Push arp module to if_fd */
4063 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4064 syslog (LOG_ERR, "Can't push ARP module (2)");
4066 /* Push arp module to ip_fd */
4067 if (ioctl (ip_fd, I_POP, NULL) < 0)
4068 syslog (LOG_ERR, "I_POP failed\n");
4069 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4070 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4071 /* Open arp_fd */
4072 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4073 if (arp_fd < 0)
4074 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4076 /* Set ifname to arp */
4077 strioc_if.ic_cmd = SIOCSLIFNAME;
4078 strioc_if.ic_timout = 0;
4079 strioc_if.ic_len = sizeof(ifr);
4080 strioc_if.ic_dp = (char *)&ifr;
4081 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4082 syslog (LOG_ERR, "Can't set ifname to arp\n");
4085 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4086 syslog(LOG_ERR, "Can't link TAP device to IP");
4087 return -1;
4090 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4091 syslog (LOG_ERR, "Can't link TAP device to ARP");
4093 close (if_fd);
4095 memset(&ifr, 0x0, sizeof(ifr));
4096 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4097 ifr.lifr_ip_muxid = ip_muxid;
4098 ifr.lifr_arp_muxid = arp_muxid;
4100 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4102 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4103 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4104 syslog (LOG_ERR, "Can't set multiplexor id");
4107 sprintf(dev, "tap%d", ppa);
4108 return tap_fd;
4111 static int tap_open(char *ifname, int ifname_size)
4113 char dev[10]="";
4114 int fd;
4115 if( (fd = tap_alloc(dev)) < 0 ){
4116 fprintf(stderr, "Cannot allocate TAP device\n");
4117 return -1;
4119 pstrcpy(ifname, ifname_size, dev);
4120 fcntl(fd, F_SETFL, O_NONBLOCK);
4121 return fd;
4123 #else
4124 static int tap_open(char *ifname, int ifname_size)
4126 struct ifreq ifr;
4127 int fd, ret;
4129 TFR(fd = open("/dev/net/tun", O_RDWR));
4130 if (fd < 0) {
4131 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4132 return -1;
4134 memset(&ifr, 0, sizeof(ifr));
4135 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4136 if (ifname[0] != '\0')
4137 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4138 else
4139 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4140 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4141 if (ret != 0) {
4142 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4143 close(fd);
4144 return -1;
4146 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4147 fcntl(fd, F_SETFL, O_NONBLOCK);
4148 return fd;
4150 #endif
4152 static int launch_script(const char *setup_script, const char *ifname, int fd)
4154 int pid, status;
4155 char *args[3];
4156 char **parg;
4158 /* try to launch network script */
4159 pid = fork();
4160 if (pid >= 0) {
4161 if (pid == 0) {
4162 int open_max = sysconf (_SC_OPEN_MAX), i;
4163 for (i = 0; i < open_max; i++)
4164 if (i != STDIN_FILENO &&
4165 i != STDOUT_FILENO &&
4166 i != STDERR_FILENO &&
4167 i != fd)
4168 close(i);
4170 parg = args;
4171 *parg++ = (char *)setup_script;
4172 *parg++ = (char *)ifname;
4173 *parg++ = NULL;
4174 execv(setup_script, args);
4175 _exit(1);
4177 while (waitpid(pid, &status, 0) != pid);
4178 if (!WIFEXITED(status) ||
4179 WEXITSTATUS(status) != 0) {
4180 fprintf(stderr, "%s: could not launch network script\n",
4181 setup_script);
4182 return -1;
4185 return 0;
4188 static int net_tap_init(VLANState *vlan, const char *ifname1,
4189 const char *setup_script, const char *down_script)
4191 TAPState *s;
4192 int fd;
4193 char ifname[128];
4195 if (ifname1 != NULL)
4196 pstrcpy(ifname, sizeof(ifname), ifname1);
4197 else
4198 ifname[0] = '\0';
4199 TFR(fd = tap_open(ifname, sizeof(ifname)));
4200 if (fd < 0)
4201 return -1;
4203 if (!setup_script || !strcmp(setup_script, "no"))
4204 setup_script = "";
4205 if (setup_script[0] != '\0') {
4206 if (launch_script(setup_script, ifname, fd))
4207 return -1;
4209 s = net_tap_fd_init(vlan, fd);
4210 if (!s)
4211 return -1;
4212 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4213 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4214 if (down_script && strcmp(down_script, "no"))
4215 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4216 return 0;
4219 #endif /* !_WIN32 */
4221 /* network connection */
4222 typedef struct NetSocketState {
4223 VLANClientState *vc;
4224 int fd;
4225 int state; /* 0 = getting length, 1 = getting data */
4226 int index;
4227 int packet_len;
4228 uint8_t buf[4096];
4229 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4230 } NetSocketState;
4232 typedef struct NetSocketListenState {
4233 VLANState *vlan;
4234 int fd;
4235 } NetSocketListenState;
4237 /* XXX: we consider we can send the whole packet without blocking */
4238 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4240 NetSocketState *s = opaque;
4241 uint32_t len;
4242 len = htonl(size);
4244 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4245 send_all(s->fd, buf, size);
4248 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4250 NetSocketState *s = opaque;
4251 sendto(s->fd, buf, size, 0,
4252 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4255 static void net_socket_send(void *opaque)
4257 NetSocketState *s = opaque;
4258 int l, size, err;
4259 uint8_t buf1[4096];
4260 const uint8_t *buf;
4262 size = recv(s->fd, buf1, sizeof(buf1), 0);
4263 if (size < 0) {
4264 err = socket_error();
4265 if (err != EWOULDBLOCK)
4266 goto eoc;
4267 } else if (size == 0) {
4268 /* end of connection */
4269 eoc:
4270 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4271 closesocket(s->fd);
4272 return;
4274 buf = buf1;
4275 while (size > 0) {
4276 /* reassemble a packet from the network */
4277 switch(s->state) {
4278 case 0:
4279 l = 4 - s->index;
4280 if (l > size)
4281 l = size;
4282 memcpy(s->buf + s->index, buf, l);
4283 buf += l;
4284 size -= l;
4285 s->index += l;
4286 if (s->index == 4) {
4287 /* got length */
4288 s->packet_len = ntohl(*(uint32_t *)s->buf);
4289 s->index = 0;
4290 s->state = 1;
4292 break;
4293 case 1:
4294 l = s->packet_len - s->index;
4295 if (l > size)
4296 l = size;
4297 memcpy(s->buf + s->index, buf, l);
4298 s->index += l;
4299 buf += l;
4300 size -= l;
4301 if (s->index >= s->packet_len) {
4302 qemu_send_packet(s->vc, s->buf, s->packet_len);
4303 s->index = 0;
4304 s->state = 0;
4306 break;
4311 static void net_socket_send_dgram(void *opaque)
4313 NetSocketState *s = opaque;
4314 int size;
4316 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4317 if (size < 0)
4318 return;
4319 if (size == 0) {
4320 /* end of connection */
4321 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4322 return;
4324 qemu_send_packet(s->vc, s->buf, size);
4327 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4329 struct ip_mreq imr;
4330 int fd;
4331 int val, ret;
4332 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4333 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4334 inet_ntoa(mcastaddr->sin_addr),
4335 (int)ntohl(mcastaddr->sin_addr.s_addr));
4336 return -1;
4339 fd = socket(PF_INET, SOCK_DGRAM, 0);
4340 if (fd < 0) {
4341 perror("socket(PF_INET, SOCK_DGRAM)");
4342 return -1;
4345 val = 1;
4346 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4347 (const char *)&val, sizeof(val));
4348 if (ret < 0) {
4349 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4350 goto fail;
4353 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4354 if (ret < 0) {
4355 perror("bind");
4356 goto fail;
4359 /* Add host to multicast group */
4360 imr.imr_multiaddr = mcastaddr->sin_addr;
4361 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4363 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4364 (const char *)&imr, sizeof(struct ip_mreq));
4365 if (ret < 0) {
4366 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4367 goto fail;
4370 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4371 val = 1;
4372 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4373 (const char *)&val, sizeof(val));
4374 if (ret < 0) {
4375 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4376 goto fail;
4379 socket_set_nonblock(fd);
4380 return fd;
4381 fail:
4382 if (fd >= 0)
4383 closesocket(fd);
4384 return -1;
4387 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4388 int is_connected)
4390 struct sockaddr_in saddr;
4391 int newfd;
4392 socklen_t saddr_len;
4393 NetSocketState *s;
4395 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4396 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4397 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4400 if (is_connected) {
4401 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4402 /* must be bound */
4403 if (saddr.sin_addr.s_addr==0) {
4404 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4405 fd);
4406 return NULL;
4408 /* clone dgram socket */
4409 newfd = net_socket_mcast_create(&saddr);
4410 if (newfd < 0) {
4411 /* error already reported by net_socket_mcast_create() */
4412 close(fd);
4413 return NULL;
4415 /* clone newfd to fd, close newfd */
4416 dup2(newfd, fd);
4417 close(newfd);
4419 } else {
4420 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4421 fd, strerror(errno));
4422 return NULL;
4426 s = qemu_mallocz(sizeof(NetSocketState));
4427 if (!s)
4428 return NULL;
4429 s->fd = fd;
4431 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4432 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4434 /* mcast: save bound address as dst */
4435 if (is_connected) s->dgram_dst=saddr;
4437 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4438 "socket: fd=%d (%s mcast=%s:%d)",
4439 fd, is_connected? "cloned" : "",
4440 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4441 return s;
4444 static void net_socket_connect(void *opaque)
4446 NetSocketState *s = opaque;
4447 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4450 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4451 int is_connected)
4453 NetSocketState *s;
4454 s = qemu_mallocz(sizeof(NetSocketState));
4455 if (!s)
4456 return NULL;
4457 s->fd = fd;
4458 s->vc = qemu_new_vlan_client(vlan,
4459 net_socket_receive, NULL, s);
4460 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4461 "socket: fd=%d", fd);
4462 if (is_connected) {
4463 net_socket_connect(s);
4464 } else {
4465 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4467 return s;
4470 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4471 int is_connected)
4473 int so_type=-1, optlen=sizeof(so_type);
4475 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4476 (socklen_t *)&optlen)< 0) {
4477 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4478 return NULL;
4480 switch(so_type) {
4481 case SOCK_DGRAM:
4482 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4483 case SOCK_STREAM:
4484 return net_socket_fd_init_stream(vlan, fd, is_connected);
4485 default:
4486 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4487 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4488 return net_socket_fd_init_stream(vlan, fd, is_connected);
4490 return NULL;
4493 static void net_socket_accept(void *opaque)
4495 NetSocketListenState *s = opaque;
4496 NetSocketState *s1;
4497 struct sockaddr_in saddr;
4498 socklen_t len;
4499 int fd;
4501 for(;;) {
4502 len = sizeof(saddr);
4503 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4504 if (fd < 0 && errno != EINTR) {
4505 return;
4506 } else if (fd >= 0) {
4507 break;
4510 s1 = net_socket_fd_init(s->vlan, fd, 1);
4511 if (!s1) {
4512 closesocket(fd);
4513 } else {
4514 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4515 "socket: connection from %s:%d",
4516 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4520 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4522 NetSocketListenState *s;
4523 int fd, val, ret;
4524 struct sockaddr_in saddr;
4526 if (parse_host_port(&saddr, host_str) < 0)
4527 return -1;
4529 s = qemu_mallocz(sizeof(NetSocketListenState));
4530 if (!s)
4531 return -1;
4533 fd = socket(PF_INET, SOCK_STREAM, 0);
4534 if (fd < 0) {
4535 perror("socket");
4536 return -1;
4538 socket_set_nonblock(fd);
4540 /* allow fast reuse */
4541 val = 1;
4542 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4544 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4545 if (ret < 0) {
4546 perror("bind");
4547 return -1;
4549 ret = listen(fd, 0);
4550 if (ret < 0) {
4551 perror("listen");
4552 return -1;
4554 s->vlan = vlan;
4555 s->fd = fd;
4556 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4557 return 0;
4560 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4562 NetSocketState *s;
4563 int fd, connected, ret, err;
4564 struct sockaddr_in saddr;
4566 if (parse_host_port(&saddr, host_str) < 0)
4567 return -1;
4569 fd = socket(PF_INET, SOCK_STREAM, 0);
4570 if (fd < 0) {
4571 perror("socket");
4572 return -1;
4574 socket_set_nonblock(fd);
4576 connected = 0;
4577 for(;;) {
4578 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4579 if (ret < 0) {
4580 err = socket_error();
4581 if (err == EINTR || err == EWOULDBLOCK) {
4582 } else if (err == EINPROGRESS) {
4583 break;
4584 #ifdef _WIN32
4585 } else if (err == WSAEALREADY) {
4586 break;
4587 #endif
4588 } else {
4589 perror("connect");
4590 closesocket(fd);
4591 return -1;
4593 } else {
4594 connected = 1;
4595 break;
4598 s = net_socket_fd_init(vlan, fd, connected);
4599 if (!s)
4600 return -1;
4601 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4602 "socket: connect to %s:%d",
4603 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4604 return 0;
4607 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4609 NetSocketState *s;
4610 int fd;
4611 struct sockaddr_in saddr;
4613 if (parse_host_port(&saddr, host_str) < 0)
4614 return -1;
4617 fd = net_socket_mcast_create(&saddr);
4618 if (fd < 0)
4619 return -1;
4621 s = net_socket_fd_init(vlan, fd, 0);
4622 if (!s)
4623 return -1;
4625 s->dgram_dst = saddr;
4627 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4628 "socket: mcast=%s:%d",
4629 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4630 return 0;
4634 static const char *get_word(char *buf, int buf_size, const char *p)
4636 char *q;
4637 int substring;
4639 substring = 0;
4640 q = buf;
4641 while (*p != '\0') {
4642 if (*p == '\\') {
4643 p++;
4644 if (*p == '\0')
4645 break;
4646 } else if (*p == '\"') {
4647 substring = !substring;
4648 p++;
4649 continue;
4650 } else if (!substring && (*p == ',' || *p == '='))
4651 break;
4652 if (q && (q - buf) < buf_size - 1)
4653 *q++ = *p;
4654 p++;
4656 if (q)
4657 *q = '\0';
4659 return p;
4662 static int get_param_value(char *buf, int buf_size,
4663 const char *tag, const char *str)
4665 const char *p;
4666 char option[128];
4668 p = str;
4669 for(;;) {
4670 p = get_word(option, sizeof(option), p);
4671 if (*p != '=')
4672 break;
4673 p++;
4674 if (!strcmp(tag, option)) {
4675 (void)get_word(buf, buf_size, p);
4676 return strlen(buf);
4677 } else {
4678 p = get_word(NULL, 0, p);
4680 if (*p != ',')
4681 break;
4682 p++;
4684 return 0;
4687 static int check_params(char *buf, int buf_size,
4688 char **params, const char *str)
4690 const char *p;
4691 int i;
4693 p = str;
4694 for(;;) {
4695 p = get_word(buf, buf_size, p);
4696 if (*p != '=')
4697 return -1;
4698 p++;
4699 for(i = 0; params[i] != NULL; i++)
4700 if (!strcmp(params[i], buf))
4701 break;
4702 if (params[i] == NULL)
4703 return -1;
4704 p = get_word(NULL, 0, p);
4705 if (*p != ',')
4706 break;
4707 p++;
4709 return 0;
4713 static int net_client_init(const char *str)
4715 const char *p;
4716 char *q;
4717 char device[64];
4718 char buf[1024];
4719 int vlan_id, ret;
4720 VLANState *vlan;
4722 p = str;
4723 q = device;
4724 while (*p != '\0' && *p != ',') {
4725 if ((q - device) < sizeof(device) - 1)
4726 *q++ = *p;
4727 p++;
4729 *q = '\0';
4730 if (*p == ',')
4731 p++;
4732 vlan_id = 0;
4733 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4734 vlan_id = strtol(buf, NULL, 0);
4736 vlan = qemu_find_vlan(vlan_id);
4737 if (!vlan) {
4738 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4739 return -1;
4741 if (!strcmp(device, "nic")) {
4742 NICInfo *nd;
4743 uint8_t *macaddr;
4745 if (nb_nics >= MAX_NICS) {
4746 fprintf(stderr, "Too Many NICs\n");
4747 return -1;
4749 nd = &nd_table[nb_nics];
4750 macaddr = nd->macaddr;
4751 macaddr[0] = 0x52;
4752 macaddr[1] = 0x54;
4753 macaddr[2] = 0x00;
4754 macaddr[3] = 0x12;
4755 macaddr[4] = 0x34;
4756 macaddr[5] = 0x56 + nb_nics;
4758 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4759 if (parse_macaddr(macaddr, buf) < 0) {
4760 fprintf(stderr, "invalid syntax for ethernet address\n");
4761 return -1;
4764 if (get_param_value(buf, sizeof(buf), "model", p)) {
4765 nd->model = strdup(buf);
4767 nd->vlan = vlan;
4768 nb_nics++;
4769 vlan->nb_guest_devs++;
4770 ret = 0;
4771 } else
4772 if (!strcmp(device, "none")) {
4773 /* does nothing. It is needed to signal that no network cards
4774 are wanted */
4775 ret = 0;
4776 } else
4777 #ifdef CONFIG_SLIRP
4778 if (!strcmp(device, "user")) {
4779 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4780 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4782 vlan->nb_host_devs++;
4783 ret = net_slirp_init(vlan);
4784 } else
4785 #endif
4786 #ifdef _WIN32
4787 if (!strcmp(device, "tap")) {
4788 char ifname[64];
4789 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4790 fprintf(stderr, "tap: no interface name\n");
4791 return -1;
4793 vlan->nb_host_devs++;
4794 ret = tap_win32_init(vlan, ifname);
4795 } else
4796 #else
4797 if (!strcmp(device, "tap")) {
4798 char ifname[64];
4799 char setup_script[1024], down_script[1024];
4800 int fd;
4801 vlan->nb_host_devs++;
4802 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4803 fd = strtol(buf, NULL, 0);
4804 ret = -1;
4805 if (net_tap_fd_init(vlan, fd))
4806 ret = 0;
4807 } else {
4808 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4809 ifname[0] = '\0';
4811 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4812 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4814 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4815 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4817 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4819 } else
4820 #endif
4821 if (!strcmp(device, "socket")) {
4822 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4823 int fd;
4824 fd = strtol(buf, NULL, 0);
4825 ret = -1;
4826 if (net_socket_fd_init(vlan, fd, 1))
4827 ret = 0;
4828 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4829 ret = net_socket_listen_init(vlan, buf);
4830 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4831 ret = net_socket_connect_init(vlan, buf);
4832 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4833 ret = net_socket_mcast_init(vlan, buf);
4834 } else {
4835 fprintf(stderr, "Unknown socket options: %s\n", p);
4836 return -1;
4838 vlan->nb_host_devs++;
4839 } else
4841 fprintf(stderr, "Unknown network device: %s\n", device);
4842 return -1;
4844 if (ret < 0) {
4845 fprintf(stderr, "Could not initialize device '%s'\n", device);
4848 return ret;
4851 void do_info_network(void)
4853 VLANState *vlan;
4854 VLANClientState *vc;
4856 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4857 term_printf("VLAN %d devices:\n", vlan->id);
4858 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4859 term_printf(" %s\n", vc->info_str);
4863 #define HD_ALIAS "file=\"%s\",index=%d,media=disk"
4864 #ifdef TARGET_PPC
4865 #define CDROM_ALIAS "index=1,media=cdrom"
4866 #else
4867 #define CDROM_ALIAS "index=2,media=cdrom"
4868 #endif
4869 #define FD_ALIAS "index=%d,if=floppy"
4870 #define PFLASH_ALIAS "file=\"%s\",if=pflash"
4871 #define MTD_ALIAS "file=\"%s\",if=mtd"
4872 #define SD_ALIAS "index=0,if=sd"
4874 static int drive_add(const char *fmt, ...)
4876 va_list ap;
4878 if (nb_drives_opt >= MAX_DRIVES) {
4879 fprintf(stderr, "qemu: too many drives\n");
4880 exit(1);
4883 va_start(ap, fmt);
4884 vsnprintf(drives_opt[nb_drives_opt], sizeof(drives_opt[0]), fmt, ap);
4885 va_end(ap);
4887 return nb_drives_opt++;
4890 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4892 int index;
4894 /* seek interface, bus and unit */
4896 for (index = 0; index < nb_drives; index++)
4897 if (drives_table[index].type == type &&
4898 drives_table[index].bus == bus &&
4899 drives_table[index].unit == unit)
4900 return index;
4902 return -1;
4905 int drive_get_max_bus(BlockInterfaceType type)
4907 int max_bus;
4908 int index;
4910 max_bus = -1;
4911 for (index = 0; index < nb_drives; index++) {
4912 if(drives_table[index].type == type &&
4913 drives_table[index].bus > max_bus)
4914 max_bus = drives_table[index].bus;
4916 return max_bus;
4919 static int drive_init(const char *str, int snapshot, QEMUMachine *machine)
4921 char buf[128];
4922 char file[1024];
4923 char devname[128];
4924 const char *mediastr = "";
4925 BlockInterfaceType type;
4926 enum { MEDIA_DISK, MEDIA_CDROM } media;
4927 int bus_id, unit_id;
4928 int cyls, heads, secs, translation;
4929 BlockDriverState *bdrv;
4930 int max_devs;
4931 int index;
4932 int cache;
4933 int bdrv_flags;
4934 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4935 "secs", "trans", "media", "snapshot", "file",
4936 "cache", "boot", NULL };
4938 if (check_params(buf, sizeof(buf), params, str) < 0) {
4939 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4940 buf, str);
4941 return -1;
4944 file[0] = 0;
4945 cyls = heads = secs = 0;
4946 bus_id = 0;
4947 unit_id = -1;
4948 translation = BIOS_ATA_TRANSLATION_AUTO;
4949 index = -1;
4950 cache = 1;
4952 if (!strcmp(machine->name, "realview") ||
4953 !strcmp(machine->name, "SS-5") ||
4954 !strcmp(machine->name, "SS-10") ||
4955 !strcmp(machine->name, "SS-600MP") ||
4956 !strcmp(machine->name, "versatilepb") ||
4957 !strcmp(machine->name, "versatileab")) {
4958 type = IF_SCSI;
4959 max_devs = MAX_SCSI_DEVS;
4960 strcpy(devname, "scsi");
4961 } else {
4962 type = IF_IDE;
4963 max_devs = MAX_IDE_DEVS;
4964 strcpy(devname, "ide");
4966 media = MEDIA_DISK;
4968 /* extract parameters */
4970 if (get_param_value(buf, sizeof(buf), "bus", str)) {
4971 bus_id = strtol(buf, NULL, 0);
4972 if (bus_id < 0) {
4973 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4974 return -1;
4978 if (get_param_value(buf, sizeof(buf), "unit", str)) {
4979 unit_id = strtol(buf, NULL, 0);
4980 if (unit_id < 0) {
4981 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4982 return -1;
4986 if (get_param_value(buf, sizeof(buf), "if", str)) {
4987 strncpy(devname, buf, sizeof(devname));
4988 if (!strcmp(buf, "ide")) {
4989 type = IF_IDE;
4990 max_devs = MAX_IDE_DEVS;
4991 } else if (!strcmp(buf, "scsi")) {
4992 type = IF_SCSI;
4993 max_devs = MAX_SCSI_DEVS;
4994 } else if (!strcmp(buf, "floppy")) {
4995 type = IF_FLOPPY;
4996 max_devs = 0;
4997 } else if (!strcmp(buf, "pflash")) {
4998 type = IF_PFLASH;
4999 max_devs = 0;
5000 } else if (!strcmp(buf, "mtd")) {
5001 type = IF_MTD;
5002 max_devs = 0;
5003 } else if (!strcmp(buf, "sd")) {
5004 type = IF_SD;
5005 max_devs = 0;
5006 } else if (!strcmp(buf, "virtio")) {
5007 type = IF_VIRTIO;
5008 max_devs = 0;
5009 } else {
5010 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5011 return -1;
5015 if (get_param_value(buf, sizeof(buf), "index", str)) {
5016 index = strtol(buf, NULL, 0);
5017 if (index < 0) {
5018 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5019 return -1;
5023 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5024 cyls = strtol(buf, NULL, 0);
5027 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5028 heads = strtol(buf, NULL, 0);
5031 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5032 secs = strtol(buf, NULL, 0);
5035 if (cyls || heads || secs) {
5036 if (cyls < 1 || cyls > 16383) {
5037 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5038 return -1;
5040 if (heads < 1 || heads > 16) {
5041 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5042 return -1;
5044 if (secs < 1 || secs > 63) {
5045 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5046 return -1;
5050 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5051 if (!cyls) {
5052 fprintf(stderr,
5053 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5054 str);
5055 return -1;
5057 if (!strcmp(buf, "none"))
5058 translation = BIOS_ATA_TRANSLATION_NONE;
5059 else if (!strcmp(buf, "lba"))
5060 translation = BIOS_ATA_TRANSLATION_LBA;
5061 else if (!strcmp(buf, "auto"))
5062 translation = BIOS_ATA_TRANSLATION_AUTO;
5063 else {
5064 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5065 return -1;
5069 if (get_param_value(buf, sizeof(buf), "media", str)) {
5070 if (!strcmp(buf, "disk")) {
5071 media = MEDIA_DISK;
5072 } else if (!strcmp(buf, "cdrom")) {
5073 if (cyls || secs || heads) {
5074 fprintf(stderr,
5075 "qemu: '%s' invalid physical CHS format\n", str);
5076 return -1;
5078 media = MEDIA_CDROM;
5079 } else {
5080 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5081 return -1;
5085 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5086 if (!strcmp(buf, "on"))
5087 snapshot = 1;
5088 else if (!strcmp(buf, "off"))
5089 snapshot = 0;
5090 else {
5091 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5092 return -1;
5096 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5097 if (!strcmp(buf, "off"))
5098 cache = 0;
5099 else if (!strcmp(buf, "on"))
5100 cache = 1;
5101 else {
5102 fprintf(stderr, "qemu: invalid cache option\n");
5103 return -1;
5107 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5108 if (!strcmp(buf, "on")) {
5109 if (extboot_drive != -1) {
5110 fprintf(stderr, "qemu: two bootable drives specified\n");
5111 return -1;
5113 extboot_drive = nb_drives;
5114 } else if (strcmp(buf, "off")) {
5115 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5116 return -1;
5120 get_param_value(file, sizeof(file), "file", str);
5122 /* compute bus and unit according index */
5124 if (index != -1) {
5125 if (bus_id != 0 || unit_id != -1) {
5126 fprintf(stderr,
5127 "qemu: '%s' index cannot be used with bus and unit\n", str);
5128 return -1;
5130 if (max_devs == 0)
5132 unit_id = index;
5133 bus_id = 0;
5134 } else {
5135 unit_id = index % max_devs;
5136 bus_id = index / max_devs;
5140 /* if user doesn't specify a unit_id,
5141 * try to find the first free
5144 if (unit_id == -1) {
5145 unit_id = 0;
5146 while (drive_get_index(type, bus_id, unit_id) != -1) {
5147 unit_id++;
5148 if (max_devs && unit_id >= max_devs) {
5149 unit_id -= max_devs;
5150 bus_id++;
5155 /* check unit id */
5157 if (max_devs && unit_id >= max_devs) {
5158 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5159 str, unit_id, max_devs - 1);
5160 return -1;
5164 * ignore multiple definitions
5167 if (drive_get_index(type, bus_id, unit_id) != -1)
5168 return 0;
5170 /* init */
5172 if (type == IF_IDE || type == IF_SCSI)
5173 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5174 if (max_devs)
5175 snprintf(buf, sizeof(buf), "%s%i%s%i",
5176 devname, bus_id, mediastr, unit_id);
5177 else
5178 snprintf(buf, sizeof(buf), "%s%s%i",
5179 devname, mediastr, unit_id);
5180 bdrv = bdrv_new(buf);
5181 drives_table[nb_drives].bdrv = bdrv;
5182 drives_table[nb_drives].type = type;
5183 drives_table[nb_drives].bus = bus_id;
5184 drives_table[nb_drives].unit = unit_id;
5185 nb_drives++;
5187 switch(type) {
5188 case IF_IDE:
5189 case IF_SCSI:
5190 switch(media) {
5191 case MEDIA_DISK:
5192 if (cyls != 0) {
5193 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5194 bdrv_set_translation_hint(bdrv, translation);
5196 break;
5197 case MEDIA_CDROM:
5198 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5199 break;
5201 break;
5202 case IF_SD:
5203 /* FIXME: This isn't really a floppy, but it's a reasonable
5204 approximation. */
5205 case IF_FLOPPY:
5206 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5207 break;
5208 case IF_PFLASH:
5209 case IF_MTD:
5210 case IF_VIRTIO:
5211 break;
5213 if (!file[0])
5214 return 0;
5215 bdrv_flags = 0;
5216 if (snapshot)
5217 bdrv_flags |= BDRV_O_SNAPSHOT;
5218 if (!cache)
5219 bdrv_flags |= BDRV_O_DIRECT;
5220 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5221 fprintf(stderr, "qemu: could not open disk image %s\n",
5222 file);
5223 return -1;
5225 return 0;
5228 /***********************************************************/
5229 /* USB devices */
5231 static USBPort *used_usb_ports;
5232 static USBPort *free_usb_ports;
5234 /* ??? Maybe change this to register a hub to keep track of the topology. */
5235 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5236 usb_attachfn attach)
5238 port->opaque = opaque;
5239 port->index = index;
5240 port->attach = attach;
5241 port->next = free_usb_ports;
5242 free_usb_ports = port;
5245 static int usb_device_add(const char *devname)
5247 const char *p;
5248 USBDevice *dev;
5249 USBPort *port;
5251 if (!free_usb_ports)
5252 return -1;
5254 if (strstart(devname, "host:", &p)) {
5255 dev = usb_host_device_open(p);
5256 } else if (!strcmp(devname, "mouse")) {
5257 dev = usb_mouse_init();
5258 } else if (!strcmp(devname, "tablet")) {
5259 dev = usb_tablet_init();
5260 } else if (!strcmp(devname, "keyboard")) {
5261 dev = usb_keyboard_init();
5262 } else if (strstart(devname, "disk:", &p)) {
5263 dev = usb_msd_init(p);
5264 } else if (!strcmp(devname, "wacom-tablet")) {
5265 dev = usb_wacom_init();
5266 } else {
5267 return -1;
5269 if (!dev)
5270 return -1;
5272 /* Find a USB port to add the device to. */
5273 port = free_usb_ports;
5274 if (!port->next) {
5275 USBDevice *hub;
5277 /* Create a new hub and chain it on. */
5278 free_usb_ports = NULL;
5279 port->next = used_usb_ports;
5280 used_usb_ports = port;
5282 hub = usb_hub_init(VM_USB_HUB_SIZE);
5283 usb_attach(port, hub);
5284 port = free_usb_ports;
5287 free_usb_ports = port->next;
5288 port->next = used_usb_ports;
5289 used_usb_ports = port;
5290 usb_attach(port, dev);
5291 return 0;
5294 static int usb_device_del(const char *devname)
5296 USBPort *port;
5297 USBPort **lastp;
5298 USBDevice *dev;
5299 int bus_num, addr;
5300 const char *p;
5302 if (!used_usb_ports)
5303 return -1;
5305 p = strchr(devname, '.');
5306 if (!p)
5307 return -1;
5308 bus_num = strtoul(devname, NULL, 0);
5309 addr = strtoul(p + 1, NULL, 0);
5310 if (bus_num != 0)
5311 return -1;
5313 lastp = &used_usb_ports;
5314 port = used_usb_ports;
5315 while (port && port->dev->addr != addr) {
5316 lastp = &port->next;
5317 port = port->next;
5320 if (!port)
5321 return -1;
5323 dev = port->dev;
5324 *lastp = port->next;
5325 usb_attach(port, NULL);
5326 dev->handle_destroy(dev);
5327 port->next = free_usb_ports;
5328 free_usb_ports = port;
5329 return 0;
5332 void do_usb_add(const char *devname)
5334 int ret;
5335 ret = usb_device_add(devname);
5336 if (ret < 0)
5337 term_printf("Could not add USB device '%s'\n", devname);
5340 void do_usb_del(const char *devname)
5342 int ret;
5343 ret = usb_device_del(devname);
5344 if (ret < 0)
5345 term_printf("Could not remove USB device '%s'\n", devname);
5348 void usb_info(void)
5350 USBDevice *dev;
5351 USBPort *port;
5352 const char *speed_str;
5354 if (!usb_enabled) {
5355 term_printf("USB support not enabled\n");
5356 return;
5359 for (port = used_usb_ports; port; port = port->next) {
5360 dev = port->dev;
5361 if (!dev)
5362 continue;
5363 switch(dev->speed) {
5364 case USB_SPEED_LOW:
5365 speed_str = "1.5";
5366 break;
5367 case USB_SPEED_FULL:
5368 speed_str = "12";
5369 break;
5370 case USB_SPEED_HIGH:
5371 speed_str = "480";
5372 break;
5373 default:
5374 speed_str = "?";
5375 break;
5377 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5378 0, dev->addr, speed_str, dev->devname);
5382 /***********************************************************/
5383 /* PCMCIA/Cardbus */
5385 static struct pcmcia_socket_entry_s {
5386 struct pcmcia_socket_s *socket;
5387 struct pcmcia_socket_entry_s *next;
5388 } *pcmcia_sockets = 0;
5390 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5392 struct pcmcia_socket_entry_s *entry;
5394 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5395 entry->socket = socket;
5396 entry->next = pcmcia_sockets;
5397 pcmcia_sockets = entry;
5400 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5402 struct pcmcia_socket_entry_s *entry, **ptr;
5404 ptr = &pcmcia_sockets;
5405 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5406 if (entry->socket == socket) {
5407 *ptr = entry->next;
5408 qemu_free(entry);
5412 void pcmcia_info(void)
5414 struct pcmcia_socket_entry_s *iter;
5415 if (!pcmcia_sockets)
5416 term_printf("No PCMCIA sockets\n");
5418 for (iter = pcmcia_sockets; iter; iter = iter->next)
5419 term_printf("%s: %s\n", iter->socket->slot_string,
5420 iter->socket->attached ? iter->socket->card_string :
5421 "Empty");
5424 /***********************************************************/
5425 /* dumb display */
5427 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5431 static void dumb_resize(DisplayState *ds, int w, int h)
5435 static void dumb_refresh(DisplayState *ds)
5437 #if defined(CONFIG_SDL)
5438 vga_hw_update();
5439 #endif
5442 static void dumb_display_init(DisplayState *ds)
5444 ds->data = NULL;
5445 ds->linesize = 0;
5446 ds->depth = 0;
5447 ds->dpy_update = dumb_update;
5448 ds->dpy_resize = dumb_resize;
5449 ds->dpy_refresh = dumb_refresh;
5452 /***********************************************************/
5453 /* I/O handling */
5455 #define MAX_IO_HANDLERS 64
5457 typedef struct IOHandlerRecord {
5458 int fd;
5459 IOCanRWHandler *fd_read_poll;
5460 IOHandler *fd_read;
5461 IOHandler *fd_write;
5462 int deleted;
5463 void *opaque;
5464 /* temporary data */
5465 struct pollfd *ufd;
5466 struct IOHandlerRecord *next;
5467 } IOHandlerRecord;
5469 static IOHandlerRecord *first_io_handler;
5471 /* XXX: fd_read_poll should be suppressed, but an API change is
5472 necessary in the character devices to suppress fd_can_read(). */
5473 int qemu_set_fd_handler2(int fd,
5474 IOCanRWHandler *fd_read_poll,
5475 IOHandler *fd_read,
5476 IOHandler *fd_write,
5477 void *opaque)
5479 IOHandlerRecord **pioh, *ioh;
5481 if (!fd_read && !fd_write) {
5482 pioh = &first_io_handler;
5483 for(;;) {
5484 ioh = *pioh;
5485 if (ioh == NULL)
5486 break;
5487 if (ioh->fd == fd) {
5488 ioh->deleted = 1;
5489 break;
5491 pioh = &ioh->next;
5493 } else {
5494 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5495 if (ioh->fd == fd)
5496 goto found;
5498 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5499 if (!ioh)
5500 return -1;
5501 ioh->next = first_io_handler;
5502 first_io_handler = ioh;
5503 found:
5504 ioh->fd = fd;
5505 ioh->fd_read_poll = fd_read_poll;
5506 ioh->fd_read = fd_read;
5507 ioh->fd_write = fd_write;
5508 ioh->opaque = opaque;
5509 ioh->deleted = 0;
5511 return 0;
5514 int qemu_set_fd_handler(int fd,
5515 IOHandler *fd_read,
5516 IOHandler *fd_write,
5517 void *opaque)
5519 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5522 /***********************************************************/
5523 /* Polling handling */
5525 typedef struct PollingEntry {
5526 PollingFunc *func;
5527 void *opaque;
5528 struct PollingEntry *next;
5529 } PollingEntry;
5531 static PollingEntry *first_polling_entry;
5533 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5535 PollingEntry **ppe, *pe;
5536 pe = qemu_mallocz(sizeof(PollingEntry));
5537 if (!pe)
5538 return -1;
5539 pe->func = func;
5540 pe->opaque = opaque;
5541 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5542 *ppe = pe;
5543 return 0;
5546 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5548 PollingEntry **ppe, *pe;
5549 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5550 pe = *ppe;
5551 if (pe->func == func && pe->opaque == opaque) {
5552 *ppe = pe->next;
5553 qemu_free(pe);
5554 break;
5559 #ifdef _WIN32
5560 /***********************************************************/
5561 /* Wait objects support */
5562 typedef struct WaitObjects {
5563 int num;
5564 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5565 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5566 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5567 } WaitObjects;
5569 static WaitObjects wait_objects = {0};
5571 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5573 WaitObjects *w = &wait_objects;
5575 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5576 return -1;
5577 w->events[w->num] = handle;
5578 w->func[w->num] = func;
5579 w->opaque[w->num] = opaque;
5580 w->num++;
5581 return 0;
5584 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5586 int i, found;
5587 WaitObjects *w = &wait_objects;
5589 found = 0;
5590 for (i = 0; i < w->num; i++) {
5591 if (w->events[i] == handle)
5592 found = 1;
5593 if (found) {
5594 w->events[i] = w->events[i + 1];
5595 w->func[i] = w->func[i + 1];
5596 w->opaque[i] = w->opaque[i + 1];
5599 if (found)
5600 w->num--;
5602 #endif
5604 #define SELF_ANNOUNCE_ROUNDS 5
5605 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5606 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5607 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5609 static int announce_self_create(uint8_t *buf,
5610 uint8_t *mac_addr)
5612 uint32_t magic = EXPERIMENTAL_MAGIC;
5613 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5615 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5617 memset(buf, 0xff, 6); /* h_dst */
5618 memcpy(buf + 6, mac_addr, 6); /* h_src */
5619 memcpy(buf + 12, &proto, 2); /* h_proto */
5620 memcpy(buf + 14, &magic, 4); /* magic */
5622 return 18; /* len */
5625 static void qemu_announce_self(void)
5627 int i, j, len;
5628 VLANState *vlan;
5629 VLANClientState *vc;
5630 uint8_t buf[256];
5632 for (i = 0; i < nb_nics; i++) {
5633 len = announce_self_create(buf, nd_table[i].macaddr);
5634 vlan = nd_table[i].vlan;
5635 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5636 if (vc->fd_read == tap_receive) /* send only if tap */
5637 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5638 vc->fd_read(vc->opaque, buf, len);
5643 /***********************************************************/
5644 /* savevm/loadvm support */
5646 #define IO_BUF_SIZE 32768
5648 struct QEMUFile {
5649 QEMUFilePutBufferFunc *put_buffer;
5650 QEMUFileGetBufferFunc *get_buffer;
5651 QEMUFileCloseFunc *close;
5652 void *opaque;
5654 int64_t buf_offset; /* start of buffer when writing, end of buffer
5655 when reading */
5656 int buf_index;
5657 int buf_size; /* 0 when writing */
5658 uint8_t buf[IO_BUF_SIZE];
5661 typedef struct QEMUFileFD
5663 int fd;
5664 } QEMUFileFD;
5666 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5668 QEMUFileFD *s = opaque;
5669 int offset = 0;
5670 ssize_t len;
5672 again:
5673 len = read(s->fd, buf + offset, size - offset);
5674 if (len == -1) {
5675 if (errno == EINTR || errno == EAGAIN)
5676 goto again;
5679 return len;
5682 QEMUFile *qemu_fopen_fd(int fd)
5684 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5685 s->fd = fd;
5686 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5689 typedef struct QEMUFileUnix
5691 FILE *outfile;
5692 } QEMUFileUnix;
5694 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5696 QEMUFileUnix *s = opaque;
5697 fseek(s->outfile, pos, SEEK_SET);
5698 fwrite(buf, 1, size, s->outfile);
5701 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5703 QEMUFileUnix *s = opaque;
5704 fseek(s->outfile, pos, SEEK_SET);
5705 return fread(buf, 1, size, s->outfile);
5708 static void file_close(void *opaque)
5710 QEMUFileUnix *s = opaque;
5711 fclose(s->outfile);
5712 qemu_free(s);
5715 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5717 QEMUFileUnix *s;
5719 s = qemu_mallocz(sizeof(QEMUFileUnix));
5720 if (!s)
5721 return NULL;
5723 s->outfile = fopen(filename, mode);
5724 if (!s->outfile)
5725 goto fail;
5727 if (!strcmp(mode, "wb"))
5728 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5729 else if (!strcmp(mode, "rb"))
5730 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5732 fail:
5733 if (s->outfile)
5734 fclose(s->outfile);
5735 qemu_free(s);
5736 return NULL;
5739 typedef struct QEMUFileBdrv
5741 BlockDriverState *bs;
5742 int64_t base_offset;
5743 } QEMUFileBdrv;
5745 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5747 QEMUFileBdrv *s = opaque;
5748 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5751 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5753 QEMUFileBdrv *s = opaque;
5754 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5757 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5759 QEMUFileBdrv *s;
5761 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5762 if (!s)
5763 return NULL;
5765 s->bs = bs;
5766 s->base_offset = offset;
5768 if (is_writable)
5769 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5771 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5774 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5775 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5777 QEMUFile *f;
5779 f = qemu_mallocz(sizeof(QEMUFile));
5780 if (!f)
5781 return NULL;
5783 f->opaque = opaque;
5784 f->put_buffer = put_buffer;
5785 f->get_buffer = get_buffer;
5786 f->close = close;
5788 return f;
5791 void qemu_fflush(QEMUFile *f)
5793 if (!f->put_buffer)
5794 return;
5796 if (f->buf_index > 0) {
5797 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5798 f->buf_offset += f->buf_index;
5799 f->buf_index = 0;
5803 static void qemu_fill_buffer(QEMUFile *f)
5805 int len;
5807 if (!f->get_buffer)
5808 return;
5810 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5811 if (len < 0)
5812 len = 0;
5814 f->buf_index = 0;
5815 f->buf_size = len;
5816 f->buf_offset += len;
5819 void qemu_fclose(QEMUFile *f)
5821 qemu_fflush(f);
5822 if (f->close)
5823 f->close(f->opaque);
5824 qemu_free(f);
5827 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5829 int l;
5830 while (size > 0) {
5831 l = IO_BUF_SIZE - f->buf_index;
5832 if (l > size)
5833 l = size;
5834 memcpy(f->buf + f->buf_index, buf, l);
5835 f->buf_index += l;
5836 buf += l;
5837 size -= l;
5838 if (f->buf_index >= IO_BUF_SIZE)
5839 qemu_fflush(f);
5843 void qemu_put_byte(QEMUFile *f, int v)
5845 f->buf[f->buf_index++] = v;
5846 if (f->buf_index >= IO_BUF_SIZE)
5847 qemu_fflush(f);
5850 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5852 int size, l;
5854 size = size1;
5855 while (size > 0) {
5856 l = f->buf_size - f->buf_index;
5857 if (l == 0) {
5858 qemu_fill_buffer(f);
5859 l = f->buf_size - f->buf_index;
5860 if (l == 0)
5861 break;
5863 if (l > size)
5864 l = size;
5865 memcpy(buf, f->buf + f->buf_index, l);
5866 f->buf_index += l;
5867 buf += l;
5868 size -= l;
5870 return size1 - size;
5873 int qemu_get_byte(QEMUFile *f)
5875 if (f->buf_index >= f->buf_size) {
5876 qemu_fill_buffer(f);
5877 if (f->buf_index >= f->buf_size)
5878 return 0;
5880 return f->buf[f->buf_index++];
5883 int64_t qemu_ftell(QEMUFile *f)
5885 return f->buf_offset - f->buf_size + f->buf_index;
5888 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5890 if (whence == SEEK_SET) {
5891 /* nothing to do */
5892 } else if (whence == SEEK_CUR) {
5893 pos += qemu_ftell(f);
5894 } else {
5895 /* SEEK_END not supported */
5896 return -1;
5898 if (f->put_buffer) {
5899 qemu_fflush(f);
5900 f->buf_offset = pos;
5901 } else {
5902 f->buf_offset = pos;
5903 f->buf_index = 0;
5904 f->buf_size = 0;
5906 return pos;
5909 void qemu_put_be16(QEMUFile *f, unsigned int v)
5911 qemu_put_byte(f, v >> 8);
5912 qemu_put_byte(f, v);
5915 void qemu_put_be32(QEMUFile *f, unsigned int v)
5917 qemu_put_byte(f, v >> 24);
5918 qemu_put_byte(f, v >> 16);
5919 qemu_put_byte(f, v >> 8);
5920 qemu_put_byte(f, v);
5923 void qemu_put_be64(QEMUFile *f, uint64_t v)
5925 qemu_put_be32(f, v >> 32);
5926 qemu_put_be32(f, v);
5929 unsigned int qemu_get_be16(QEMUFile *f)
5931 unsigned int v;
5932 v = qemu_get_byte(f) << 8;
5933 v |= qemu_get_byte(f);
5934 return v;
5937 unsigned int qemu_get_be32(QEMUFile *f)
5939 unsigned int v;
5940 v = qemu_get_byte(f) << 24;
5941 v |= qemu_get_byte(f) << 16;
5942 v |= qemu_get_byte(f) << 8;
5943 v |= qemu_get_byte(f);
5944 return v;
5947 uint64_t qemu_get_be64(QEMUFile *f)
5949 uint64_t v;
5950 v = (uint64_t)qemu_get_be32(f) << 32;
5951 v |= qemu_get_be32(f);
5952 return v;
5955 typedef struct SaveStateEntry {
5956 char idstr[256];
5957 int instance_id;
5958 int version_id;
5959 SaveStateHandler *save_state;
5960 LoadStateHandler *load_state;
5961 void *opaque;
5962 struct SaveStateEntry *next;
5963 } SaveStateEntry;
5965 static SaveStateEntry *first_se;
5967 int register_savevm(const char *idstr,
5968 int instance_id,
5969 int version_id,
5970 SaveStateHandler *save_state,
5971 LoadStateHandler *load_state,
5972 void *opaque)
5974 SaveStateEntry *se, **pse;
5976 se = qemu_malloc(sizeof(SaveStateEntry));
5977 if (!se)
5978 return -1;
5979 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5980 se->instance_id = instance_id;
5981 se->version_id = version_id;
5982 se->save_state = save_state;
5983 se->load_state = load_state;
5984 se->opaque = opaque;
5985 se->next = NULL;
5987 /* add at the end of list */
5988 pse = &first_se;
5989 while (*pse != NULL)
5990 pse = &(*pse)->next;
5991 *pse = se;
5992 return 0;
5995 #define QEMU_VM_FILE_MAGIC 0x5145564d
5996 #define QEMU_VM_FILE_VERSION 0x00000002
5998 static int qemu_savevm_state(QEMUFile *f)
6000 SaveStateEntry *se;
6001 int len, ret;
6002 int64_t cur_pos, len_pos, total_len_pos;
6004 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6005 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6006 total_len_pos = qemu_ftell(f);
6007 qemu_put_be64(f, 0); /* total size */
6009 for(se = first_se; se != NULL; se = se->next) {
6010 /* ID string */
6011 len = strlen(se->idstr);
6012 qemu_put_byte(f, len);
6013 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6015 qemu_put_be32(f, se->instance_id);
6016 qemu_put_be32(f, se->version_id);
6018 /* record size: filled later */
6019 len_pos = qemu_ftell(f);
6020 qemu_put_be32(f, 0);
6021 se->save_state(f, se->opaque);
6023 /* fill record size */
6024 cur_pos = qemu_ftell(f);
6025 len = cur_pos - len_pos - 4;
6026 qemu_fseek(f, len_pos, SEEK_SET);
6027 qemu_put_be32(f, len);
6028 qemu_fseek(f, cur_pos, SEEK_SET);
6030 cur_pos = qemu_ftell(f);
6031 qemu_fseek(f, total_len_pos, SEEK_SET);
6032 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6033 qemu_fseek(f, cur_pos, SEEK_SET);
6035 ret = 0;
6036 return ret;
6039 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6041 SaveStateEntry *se;
6043 for(se = first_se; se != NULL; se = se->next) {
6044 if (!strcmp(se->idstr, idstr) &&
6045 instance_id == se->instance_id)
6046 return se;
6048 return NULL;
6051 static int qemu_loadvm_state(QEMUFile *f)
6053 SaveStateEntry *se;
6054 int len, ret, instance_id, record_len, version_id;
6055 int64_t total_len, end_pos, cur_pos;
6056 unsigned int v;
6057 char idstr[256];
6059 v = qemu_get_be32(f);
6060 if (v != QEMU_VM_FILE_MAGIC)
6061 goto fail;
6062 v = qemu_get_be32(f);
6063 if (v != QEMU_VM_FILE_VERSION) {
6064 fail:
6065 ret = -1;
6066 goto the_end;
6068 total_len = qemu_get_be64(f);
6069 end_pos = total_len + qemu_ftell(f);
6070 for(;;) {
6071 if (qemu_ftell(f) >= end_pos)
6072 break;
6073 len = qemu_get_byte(f);
6074 qemu_get_buffer(f, (uint8_t *)idstr, len);
6075 idstr[len] = '\0';
6076 instance_id = qemu_get_be32(f);
6077 version_id = qemu_get_be32(f);
6078 record_len = qemu_get_be32(f);
6079 #if 0
6080 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6081 idstr, instance_id, version_id, record_len);
6082 #endif
6083 cur_pos = qemu_ftell(f);
6084 se = find_se(idstr, instance_id);
6085 if (!se) {
6086 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6087 instance_id, idstr);
6088 } else {
6089 ret = se->load_state(f, se->opaque, version_id);
6090 if (ret < 0) {
6091 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6092 instance_id, idstr);
6093 goto the_end;
6096 /* always seek to exact end of record */
6097 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6099 ret = 0;
6100 the_end:
6101 return ret;
6104 int qemu_live_savevm_state(QEMUFile *f)
6106 SaveStateEntry *se;
6107 int len, ret;
6109 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6110 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6112 for(se = first_se; se != NULL; se = se->next) {
6113 len = strlen(se->idstr);
6115 qemu_put_byte(f, len);
6116 qemu_put_buffer(f, se->idstr, len);
6117 qemu_put_be32(f, se->instance_id);
6118 qemu_put_be32(f, se->version_id);
6120 se->save_state(f, se->opaque);
6123 qemu_put_byte(f, 0);
6125 ret = 0;
6126 return ret;
6129 int qemu_live_loadvm_state(QEMUFile *f)
6131 SaveStateEntry *se;
6132 int len, ret, instance_id, version_id;
6133 unsigned int v;
6134 char idstr[256];
6136 v = qemu_get_be32(f);
6137 if (v != QEMU_VM_FILE_MAGIC)
6138 goto fail;
6139 v = qemu_get_be32(f);
6140 if (v != QEMU_VM_FILE_VERSION) {
6141 fail:
6142 ret = -1;
6143 goto the_end;
6146 for(;;) {
6147 len = qemu_get_byte(f);
6148 if (len == 0)
6149 break;
6150 qemu_get_buffer(f, idstr, len);
6151 idstr[len] = '\0';
6152 instance_id = qemu_get_be32(f);
6153 version_id = qemu_get_be32(f);
6154 se = find_se(idstr, instance_id);
6155 if (!se) {
6156 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6157 instance_id, idstr);
6158 } else {
6159 if (version_id > se->version_id) { /* src version > dst version */
6160 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6161 idstr, version_id, se->version_id);
6162 ret = -1;
6163 goto the_end;
6165 ret = se->load_state(f, se->opaque, version_id);
6166 if (ret < 0) {
6167 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6168 instance_id, idstr);
6169 goto the_end;
6173 ret = 0;
6175 qemu_announce_self();
6177 the_end:
6178 return ret;
6181 /* device can contain snapshots */
6182 static int bdrv_can_snapshot(BlockDriverState *bs)
6184 return (bs &&
6185 !bdrv_is_removable(bs) &&
6186 !bdrv_is_read_only(bs));
6189 /* device must be snapshots in order to have a reliable snapshot */
6190 static int bdrv_has_snapshot(BlockDriverState *bs)
6192 return (bs &&
6193 !bdrv_is_removable(bs) &&
6194 !bdrv_is_read_only(bs));
6197 static BlockDriverState *get_bs_snapshots(void)
6199 BlockDriverState *bs;
6200 int i;
6202 if (bs_snapshots)
6203 return bs_snapshots;
6204 for(i = 0; i <= nb_drives; i++) {
6205 bs = drives_table[i].bdrv;
6206 if (bdrv_can_snapshot(bs))
6207 goto ok;
6209 return NULL;
6211 bs_snapshots = bs;
6212 return bs;
6215 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6216 const char *name)
6218 QEMUSnapshotInfo *sn_tab, *sn;
6219 int nb_sns, i, ret;
6221 ret = -ENOENT;
6222 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6223 if (nb_sns < 0)
6224 return ret;
6225 for(i = 0; i < nb_sns; i++) {
6226 sn = &sn_tab[i];
6227 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6228 *sn_info = *sn;
6229 ret = 0;
6230 break;
6233 qemu_free(sn_tab);
6234 return ret;
6237 void do_savevm(const char *name)
6239 BlockDriverState *bs, *bs1;
6240 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6241 int must_delete, ret, i;
6242 BlockDriverInfo bdi1, *bdi = &bdi1;
6243 QEMUFile *f;
6244 int saved_vm_running;
6245 #ifdef _WIN32
6246 struct _timeb tb;
6247 #else
6248 struct timeval tv;
6249 #endif
6251 bs = get_bs_snapshots();
6252 if (!bs) {
6253 term_printf("No block device can accept snapshots\n");
6254 return;
6257 /* ??? Should this occur after vm_stop? */
6258 qemu_aio_flush();
6260 saved_vm_running = vm_running;
6261 vm_stop(0);
6263 must_delete = 0;
6264 if (name) {
6265 ret = bdrv_snapshot_find(bs, old_sn, name);
6266 if (ret >= 0) {
6267 must_delete = 1;
6270 memset(sn, 0, sizeof(*sn));
6271 if (must_delete) {
6272 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6273 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6274 } else {
6275 if (name)
6276 pstrcpy(sn->name, sizeof(sn->name), name);
6279 /* fill auxiliary fields */
6280 #ifdef _WIN32
6281 _ftime(&tb);
6282 sn->date_sec = tb.time;
6283 sn->date_nsec = tb.millitm * 1000000;
6284 #else
6285 gettimeofday(&tv, NULL);
6286 sn->date_sec = tv.tv_sec;
6287 sn->date_nsec = tv.tv_usec * 1000;
6288 #endif
6289 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6291 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6292 term_printf("Device %s does not support VM state snapshots\n",
6293 bdrv_get_device_name(bs));
6294 goto the_end;
6297 /* save the VM state */
6298 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6299 if (!f) {
6300 term_printf("Could not open VM state file\n");
6301 goto the_end;
6303 ret = qemu_savevm_state(f);
6304 sn->vm_state_size = qemu_ftell(f);
6305 qemu_fclose(f);
6306 if (ret < 0) {
6307 term_printf("Error %d while writing VM\n", ret);
6308 goto the_end;
6311 /* create the snapshots */
6313 for(i = 0; i < nb_drives; i++) {
6314 bs1 = drives_table[i].bdrv;
6315 if (bdrv_has_snapshot(bs1)) {
6316 if (must_delete) {
6317 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6318 if (ret < 0) {
6319 term_printf("Error while deleting snapshot on '%s'\n",
6320 bdrv_get_device_name(bs1));
6323 ret = bdrv_snapshot_create(bs1, sn);
6324 if (ret < 0) {
6325 term_printf("Error while creating snapshot on '%s'\n",
6326 bdrv_get_device_name(bs1));
6331 the_end:
6332 if (saved_vm_running)
6333 vm_start();
6336 void do_loadvm(const char *name)
6338 BlockDriverState *bs, *bs1;
6339 BlockDriverInfo bdi1, *bdi = &bdi1;
6340 QEMUFile *f;
6341 int i, ret;
6342 int saved_vm_running;
6344 bs = get_bs_snapshots();
6345 if (!bs) {
6346 term_printf("No block device supports snapshots\n");
6347 return;
6350 /* Flush all IO requests so they don't interfere with the new state. */
6351 qemu_aio_flush();
6353 saved_vm_running = vm_running;
6354 vm_stop(0);
6356 for(i = 0; i <= nb_drives; i++) {
6357 bs1 = drives_table[i].bdrv;
6358 if (bdrv_has_snapshot(bs1)) {
6359 ret = bdrv_snapshot_goto(bs1, name);
6360 if (ret < 0) {
6361 if (bs != bs1)
6362 term_printf("Warning: ");
6363 switch(ret) {
6364 case -ENOTSUP:
6365 term_printf("Snapshots not supported on device '%s'\n",
6366 bdrv_get_device_name(bs1));
6367 break;
6368 case -ENOENT:
6369 term_printf("Could not find snapshot '%s' on device '%s'\n",
6370 name, bdrv_get_device_name(bs1));
6371 break;
6372 default:
6373 term_printf("Error %d while activating snapshot on '%s'\n",
6374 ret, bdrv_get_device_name(bs1));
6375 break;
6377 /* fatal on snapshot block device */
6378 if (bs == bs1)
6379 goto the_end;
6384 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6385 term_printf("Device %s does not support VM state snapshots\n",
6386 bdrv_get_device_name(bs));
6387 return;
6390 /* restore the VM state */
6391 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6392 if (!f) {
6393 term_printf("Could not open VM state file\n");
6394 goto the_end;
6396 ret = qemu_loadvm_state(f);
6397 qemu_fclose(f);
6398 if (ret < 0) {
6399 term_printf("Error %d while loading VM state\n", ret);
6401 the_end:
6402 if (saved_vm_running)
6403 vm_start();
6406 void do_delvm(const char *name)
6408 BlockDriverState *bs, *bs1;
6409 int i, ret;
6411 bs = get_bs_snapshots();
6412 if (!bs) {
6413 term_printf("No block device supports snapshots\n");
6414 return;
6417 for(i = 0; i <= nb_drives; i++) {
6418 bs1 = drives_table[i].bdrv;
6419 if (bdrv_has_snapshot(bs1)) {
6420 ret = bdrv_snapshot_delete(bs1, name);
6421 if (ret < 0) {
6422 if (ret == -ENOTSUP)
6423 term_printf("Snapshots not supported on device '%s'\n",
6424 bdrv_get_device_name(bs1));
6425 else
6426 term_printf("Error %d while deleting snapshot on '%s'\n",
6427 ret, bdrv_get_device_name(bs1));
6433 void do_info_snapshots(void)
6435 BlockDriverState *bs, *bs1;
6436 QEMUSnapshotInfo *sn_tab, *sn;
6437 int nb_sns, i;
6438 char buf[256];
6440 bs = get_bs_snapshots();
6441 if (!bs) {
6442 term_printf("No available block device supports snapshots\n");
6443 return;
6445 term_printf("Snapshot devices:");
6446 for(i = 0; i <= nb_drives; i++) {
6447 bs1 = drives_table[i].bdrv;
6448 if (bdrv_has_snapshot(bs1)) {
6449 if (bs == bs1)
6450 term_printf(" %s", bdrv_get_device_name(bs1));
6453 term_printf("\n");
6455 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6456 if (nb_sns < 0) {
6457 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6458 return;
6460 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6461 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6462 for(i = 0; i < nb_sns; i++) {
6463 sn = &sn_tab[i];
6464 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6466 qemu_free(sn_tab);
6469 /***********************************************************/
6470 /* cpu save/restore */
6472 #if defined(TARGET_I386)
6474 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6476 qemu_put_be32(f, dt->selector);
6477 qemu_put_betl(f, dt->base);
6478 qemu_put_be32(f, dt->limit);
6479 qemu_put_be32(f, dt->flags);
6482 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6484 dt->selector = qemu_get_be32(f);
6485 dt->base = qemu_get_betl(f);
6486 dt->limit = qemu_get_be32(f);
6487 dt->flags = qemu_get_be32(f);
6490 void cpu_save(QEMUFile *f, void *opaque)
6492 CPUState *env = opaque;
6493 uint16_t fptag, fpus, fpuc, fpregs_format;
6494 uint32_t hflags;
6495 int i;
6497 #ifdef USE_KVM
6498 if (kvm_allowed)
6499 kvm_save_registers(env);
6500 #endif
6502 for(i = 0; i < CPU_NB_REGS; i++)
6503 qemu_put_betls(f, &env->regs[i]);
6504 qemu_put_betls(f, &env->eip);
6505 qemu_put_betls(f, &env->eflags);
6506 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6507 qemu_put_be32s(f, &hflags);
6509 /* FPU */
6510 fpuc = env->fpuc;
6511 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6512 fptag = 0;
6513 for(i = 0; i < 8; i++) {
6514 fptag |= ((!env->fptags[i]) << i);
6517 qemu_put_be16s(f, &fpuc);
6518 qemu_put_be16s(f, &fpus);
6519 qemu_put_be16s(f, &fptag);
6521 #ifdef USE_X86LDOUBLE
6522 fpregs_format = 0;
6523 #else
6524 fpregs_format = 1;
6525 #endif
6526 qemu_put_be16s(f, &fpregs_format);
6528 for(i = 0; i < 8; i++) {
6529 #ifdef USE_X86LDOUBLE
6531 uint64_t mant;
6532 uint16_t exp;
6533 /* we save the real CPU data (in case of MMX usage only 'mant'
6534 contains the MMX register */
6535 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6536 qemu_put_be64(f, mant);
6537 qemu_put_be16(f, exp);
6539 #else
6540 /* if we use doubles for float emulation, we save the doubles to
6541 avoid losing information in case of MMX usage. It can give
6542 problems if the image is restored on a CPU where long
6543 doubles are used instead. */
6544 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6545 #endif
6548 for(i = 0; i < 6; i++)
6549 cpu_put_seg(f, &env->segs[i]);
6550 cpu_put_seg(f, &env->ldt);
6551 cpu_put_seg(f, &env->tr);
6552 cpu_put_seg(f, &env->gdt);
6553 cpu_put_seg(f, &env->idt);
6555 qemu_put_be32s(f, &env->sysenter_cs);
6556 qemu_put_be32s(f, &env->sysenter_esp);
6557 qemu_put_be32s(f, &env->sysenter_eip);
6559 qemu_put_betls(f, &env->cr[0]);
6560 qemu_put_betls(f, &env->cr[2]);
6561 qemu_put_betls(f, &env->cr[3]);
6562 qemu_put_betls(f, &env->cr[4]);
6564 for(i = 0; i < 8; i++)
6565 qemu_put_betls(f, &env->dr[i]);
6567 /* MMU */
6568 qemu_put_be32s(f, &env->a20_mask);
6570 /* XMM */
6571 qemu_put_be32s(f, &env->mxcsr);
6572 for(i = 0; i < CPU_NB_REGS; i++) {
6573 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6574 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6577 #ifdef TARGET_X86_64
6578 qemu_put_be64s(f, &env->efer);
6579 qemu_put_be64s(f, &env->star);
6580 qemu_put_be64s(f, &env->lstar);
6581 qemu_put_be64s(f, &env->cstar);
6582 qemu_put_be64s(f, &env->fmask);
6583 qemu_put_be64s(f, &env->kernelgsbase);
6584 #endif
6585 qemu_put_be32s(f, &env->smbase);
6587 #ifdef USE_KVM
6588 if (kvm_allowed) {
6589 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6590 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6592 qemu_put_be64s(f, &env->tsc);
6594 #endif
6598 #ifdef USE_X86LDOUBLE
6599 /* XXX: add that in a FPU generic layer */
6600 union x86_longdouble {
6601 uint64_t mant;
6602 uint16_t exp;
6605 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6606 #define EXPBIAS1 1023
6607 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6608 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6610 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6612 int e;
6613 /* mantissa */
6614 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6615 /* exponent + sign */
6616 e = EXPD1(temp) - EXPBIAS1 + 16383;
6617 e |= SIGND1(temp) >> 16;
6618 p->exp = e;
6620 #endif
6622 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6624 CPUState *env = opaque;
6625 int i, guess_mmx;
6626 uint32_t hflags;
6627 uint16_t fpus, fpuc, fptag, fpregs_format;
6629 if (version_id != 3 && version_id != 4)
6630 return -EINVAL;
6631 for(i = 0; i < CPU_NB_REGS; i++)
6632 qemu_get_betls(f, &env->regs[i]);
6633 qemu_get_betls(f, &env->eip);
6634 qemu_get_betls(f, &env->eflags);
6635 qemu_get_be32s(f, &hflags);
6637 qemu_get_be16s(f, &fpuc);
6638 qemu_get_be16s(f, &fpus);
6639 qemu_get_be16s(f, &fptag);
6640 qemu_get_be16s(f, &fpregs_format);
6642 /* NOTE: we cannot always restore the FPU state if the image come
6643 from a host with a different 'USE_X86LDOUBLE' define. We guess
6644 if we are in an MMX state to restore correctly in that case. */
6645 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6646 for(i = 0; i < 8; i++) {
6647 uint64_t mant;
6648 uint16_t exp;
6650 switch(fpregs_format) {
6651 case 0:
6652 mant = qemu_get_be64(f);
6653 exp = qemu_get_be16(f);
6654 #ifdef USE_X86LDOUBLE
6655 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6656 #else
6657 /* difficult case */
6658 if (guess_mmx)
6659 env->fpregs[i].mmx.MMX_Q(0) = mant;
6660 else
6661 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6662 #endif
6663 break;
6664 case 1:
6665 mant = qemu_get_be64(f);
6666 #ifdef USE_X86LDOUBLE
6668 union x86_longdouble *p;
6669 /* difficult case */
6670 p = (void *)&env->fpregs[i];
6671 if (guess_mmx) {
6672 p->mant = mant;
6673 p->exp = 0xffff;
6674 } else {
6675 fp64_to_fp80(p, mant);
6678 #else
6679 env->fpregs[i].mmx.MMX_Q(0) = mant;
6680 #endif
6681 break;
6682 default:
6683 return -EINVAL;
6687 env->fpuc = fpuc;
6688 /* XXX: restore FPU round state */
6689 env->fpstt = (fpus >> 11) & 7;
6690 env->fpus = fpus & ~0x3800;
6691 fptag ^= 0xff;
6692 for(i = 0; i < 8; i++) {
6693 env->fptags[i] = (fptag >> i) & 1;
6696 for(i = 0; i < 6; i++)
6697 cpu_get_seg(f, &env->segs[i]);
6698 cpu_get_seg(f, &env->ldt);
6699 cpu_get_seg(f, &env->tr);
6700 cpu_get_seg(f, &env->gdt);
6701 cpu_get_seg(f, &env->idt);
6703 qemu_get_be32s(f, &env->sysenter_cs);
6704 qemu_get_be32s(f, &env->sysenter_esp);
6705 qemu_get_be32s(f, &env->sysenter_eip);
6707 qemu_get_betls(f, &env->cr[0]);
6708 qemu_get_betls(f, &env->cr[2]);
6709 qemu_get_betls(f, &env->cr[3]);
6710 qemu_get_betls(f, &env->cr[4]);
6712 for(i = 0; i < 8; i++)
6713 qemu_get_betls(f, &env->dr[i]);
6715 /* MMU */
6716 qemu_get_be32s(f, &env->a20_mask);
6718 qemu_get_be32s(f, &env->mxcsr);
6719 for(i = 0; i < CPU_NB_REGS; i++) {
6720 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6721 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6724 #ifdef TARGET_X86_64
6725 qemu_get_be64s(f, &env->efer);
6726 qemu_get_be64s(f, &env->star);
6727 qemu_get_be64s(f, &env->lstar);
6728 qemu_get_be64s(f, &env->cstar);
6729 qemu_get_be64s(f, &env->fmask);
6730 qemu_get_be64s(f, &env->kernelgsbase);
6731 #endif
6732 if (version_id >= 4)
6733 qemu_get_be32s(f, &env->smbase);
6735 /* XXX: compute hflags from scratch, except for CPL and IIF */
6736 env->hflags = hflags;
6737 tlb_flush(env, 1);
6738 #ifdef USE_KVM
6739 if (kvm_allowed) {
6740 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6741 because no userspace IRQs will ever clear this flag */
6742 env->hflags &= ~HF_HALTED_MASK;
6743 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6744 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6746 qemu_get_be64s(f, &env->tsc);
6747 kvm_load_registers(env);
6749 #endif
6750 return 0;
6753 #elif defined(TARGET_PPC)
6754 void cpu_save(QEMUFile *f, void *opaque)
6758 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6760 return 0;
6763 #elif defined(TARGET_MIPS)
6764 void cpu_save(QEMUFile *f, void *opaque)
6768 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6770 return 0;
6773 #elif defined(TARGET_SPARC)
6774 void cpu_save(QEMUFile *f, void *opaque)
6776 CPUState *env = opaque;
6777 int i;
6778 uint32_t tmp;
6780 for(i = 0; i < 8; i++)
6781 qemu_put_betls(f, &env->gregs[i]);
6782 for(i = 0; i < NWINDOWS * 16; i++)
6783 qemu_put_betls(f, &env->regbase[i]);
6785 /* FPU */
6786 for(i = 0; i < TARGET_FPREGS; i++) {
6787 union {
6788 float32 f;
6789 uint32_t i;
6790 } u;
6791 u.f = env->fpr[i];
6792 qemu_put_be32(f, u.i);
6795 qemu_put_betls(f, &env->pc);
6796 qemu_put_betls(f, &env->npc);
6797 qemu_put_betls(f, &env->y);
6798 tmp = GET_PSR(env);
6799 qemu_put_be32(f, tmp);
6800 qemu_put_betls(f, &env->fsr);
6801 qemu_put_betls(f, &env->tbr);
6802 #ifndef TARGET_SPARC64
6803 qemu_put_be32s(f, &env->wim);
6804 /* MMU */
6805 for(i = 0; i < 16; i++)
6806 qemu_put_be32s(f, &env->mmuregs[i]);
6807 #endif
6810 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6812 CPUState *env = opaque;
6813 int i;
6814 uint32_t tmp;
6816 for(i = 0; i < 8; i++)
6817 qemu_get_betls(f, &env->gregs[i]);
6818 for(i = 0; i < NWINDOWS * 16; i++)
6819 qemu_get_betls(f, &env->regbase[i]);
6821 /* FPU */
6822 for(i = 0; i < TARGET_FPREGS; i++) {
6823 union {
6824 float32 f;
6825 uint32_t i;
6826 } u;
6827 u.i = qemu_get_be32(f);
6828 env->fpr[i] = u.f;
6831 qemu_get_betls(f, &env->pc);
6832 qemu_get_betls(f, &env->npc);
6833 qemu_get_betls(f, &env->y);
6834 tmp = qemu_get_be32(f);
6835 env->cwp = 0; /* needed to ensure that the wrapping registers are
6836 correctly updated */
6837 PUT_PSR(env, tmp);
6838 qemu_get_betls(f, &env->fsr);
6839 qemu_get_betls(f, &env->tbr);
6840 #ifndef TARGET_SPARC64
6841 qemu_get_be32s(f, &env->wim);
6842 /* MMU */
6843 for(i = 0; i < 16; i++)
6844 qemu_get_be32s(f, &env->mmuregs[i]);
6845 #endif
6846 tlb_flush(env, 1);
6847 return 0;
6850 #elif defined(TARGET_ARM)
6852 void cpu_save(QEMUFile *f, void *opaque)
6854 int i;
6855 CPUARMState *env = (CPUARMState *)opaque;
6857 for (i = 0; i < 16; i++) {
6858 qemu_put_be32(f, env->regs[i]);
6860 qemu_put_be32(f, cpsr_read(env));
6861 qemu_put_be32(f, env->spsr);
6862 for (i = 0; i < 6; i++) {
6863 qemu_put_be32(f, env->banked_spsr[i]);
6864 qemu_put_be32(f, env->banked_r13[i]);
6865 qemu_put_be32(f, env->banked_r14[i]);
6867 for (i = 0; i < 5; i++) {
6868 qemu_put_be32(f, env->usr_regs[i]);
6869 qemu_put_be32(f, env->fiq_regs[i]);
6871 qemu_put_be32(f, env->cp15.c0_cpuid);
6872 qemu_put_be32(f, env->cp15.c0_cachetype);
6873 qemu_put_be32(f, env->cp15.c1_sys);
6874 qemu_put_be32(f, env->cp15.c1_coproc);
6875 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6876 qemu_put_be32(f, env->cp15.c2_base0);
6877 qemu_put_be32(f, env->cp15.c2_base1);
6878 qemu_put_be32(f, env->cp15.c2_mask);
6879 qemu_put_be32(f, env->cp15.c2_data);
6880 qemu_put_be32(f, env->cp15.c2_insn);
6881 qemu_put_be32(f, env->cp15.c3);
6882 qemu_put_be32(f, env->cp15.c5_insn);
6883 qemu_put_be32(f, env->cp15.c5_data);
6884 for (i = 0; i < 8; i++) {
6885 qemu_put_be32(f, env->cp15.c6_region[i]);
6887 qemu_put_be32(f, env->cp15.c6_insn);
6888 qemu_put_be32(f, env->cp15.c6_data);
6889 qemu_put_be32(f, env->cp15.c9_insn);
6890 qemu_put_be32(f, env->cp15.c9_data);
6891 qemu_put_be32(f, env->cp15.c13_fcse);
6892 qemu_put_be32(f, env->cp15.c13_context);
6893 qemu_put_be32(f, env->cp15.c13_tls1);
6894 qemu_put_be32(f, env->cp15.c13_tls2);
6895 qemu_put_be32(f, env->cp15.c13_tls3);
6896 qemu_put_be32(f, env->cp15.c15_cpar);
6898 qemu_put_be32(f, env->features);
6900 if (arm_feature(env, ARM_FEATURE_VFP)) {
6901 for (i = 0; i < 16; i++) {
6902 CPU_DoubleU u;
6903 u.d = env->vfp.regs[i];
6904 qemu_put_be32(f, u.l.upper);
6905 qemu_put_be32(f, u.l.lower);
6907 for (i = 0; i < 16; i++) {
6908 qemu_put_be32(f, env->vfp.xregs[i]);
6911 /* TODO: Should use proper FPSCR access functions. */
6912 qemu_put_be32(f, env->vfp.vec_len);
6913 qemu_put_be32(f, env->vfp.vec_stride);
6915 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6916 for (i = 16; i < 32; i++) {
6917 CPU_DoubleU u;
6918 u.d = env->vfp.regs[i];
6919 qemu_put_be32(f, u.l.upper);
6920 qemu_put_be32(f, u.l.lower);
6925 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6926 for (i = 0; i < 16; i++) {
6927 qemu_put_be64(f, env->iwmmxt.regs[i]);
6929 for (i = 0; i < 16; i++) {
6930 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6934 if (arm_feature(env, ARM_FEATURE_M)) {
6935 qemu_put_be32(f, env->v7m.other_sp);
6936 qemu_put_be32(f, env->v7m.vecbase);
6937 qemu_put_be32(f, env->v7m.basepri);
6938 qemu_put_be32(f, env->v7m.control);
6939 qemu_put_be32(f, env->v7m.current_sp);
6940 qemu_put_be32(f, env->v7m.exception);
6944 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6946 CPUARMState *env = (CPUARMState *)opaque;
6947 int i;
6949 if (version_id != ARM_CPU_SAVE_VERSION)
6950 return -EINVAL;
6952 for (i = 0; i < 16; i++) {
6953 env->regs[i] = qemu_get_be32(f);
6955 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6956 env->spsr = qemu_get_be32(f);
6957 for (i = 0; i < 6; i++) {
6958 env->banked_spsr[i] = qemu_get_be32(f);
6959 env->banked_r13[i] = qemu_get_be32(f);
6960 env->banked_r14[i] = qemu_get_be32(f);
6962 for (i = 0; i < 5; i++) {
6963 env->usr_regs[i] = qemu_get_be32(f);
6964 env->fiq_regs[i] = qemu_get_be32(f);
6966 env->cp15.c0_cpuid = qemu_get_be32(f);
6967 env->cp15.c0_cachetype = qemu_get_be32(f);
6968 env->cp15.c1_sys = qemu_get_be32(f);
6969 env->cp15.c1_coproc = qemu_get_be32(f);
6970 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6971 env->cp15.c2_base0 = qemu_get_be32(f);
6972 env->cp15.c2_base1 = qemu_get_be32(f);
6973 env->cp15.c2_mask = qemu_get_be32(f);
6974 env->cp15.c2_data = qemu_get_be32(f);
6975 env->cp15.c2_insn = qemu_get_be32(f);
6976 env->cp15.c3 = qemu_get_be32(f);
6977 env->cp15.c5_insn = qemu_get_be32(f);
6978 env->cp15.c5_data = qemu_get_be32(f);
6979 for (i = 0; i < 8; i++) {
6980 env->cp15.c6_region[i] = qemu_get_be32(f);
6982 env->cp15.c6_insn = qemu_get_be32(f);
6983 env->cp15.c6_data = qemu_get_be32(f);
6984 env->cp15.c9_insn = qemu_get_be32(f);
6985 env->cp15.c9_data = qemu_get_be32(f);
6986 env->cp15.c13_fcse = qemu_get_be32(f);
6987 env->cp15.c13_context = qemu_get_be32(f);
6988 env->cp15.c13_tls1 = qemu_get_be32(f);
6989 env->cp15.c13_tls2 = qemu_get_be32(f);
6990 env->cp15.c13_tls3 = qemu_get_be32(f);
6991 env->cp15.c15_cpar = qemu_get_be32(f);
6993 env->features = qemu_get_be32(f);
6995 if (arm_feature(env, ARM_FEATURE_VFP)) {
6996 for (i = 0; i < 16; i++) {
6997 CPU_DoubleU u;
6998 u.l.upper = qemu_get_be32(f);
6999 u.l.lower = qemu_get_be32(f);
7000 env->vfp.regs[i] = u.d;
7002 for (i = 0; i < 16; i++) {
7003 env->vfp.xregs[i] = qemu_get_be32(f);
7006 /* TODO: Should use proper FPSCR access functions. */
7007 env->vfp.vec_len = qemu_get_be32(f);
7008 env->vfp.vec_stride = qemu_get_be32(f);
7010 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7011 for (i = 0; i < 16; i++) {
7012 CPU_DoubleU u;
7013 u.l.upper = qemu_get_be32(f);
7014 u.l.lower = qemu_get_be32(f);
7015 env->vfp.regs[i] = u.d;
7020 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7021 for (i = 0; i < 16; i++) {
7022 env->iwmmxt.regs[i] = qemu_get_be64(f);
7024 for (i = 0; i < 16; i++) {
7025 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7029 if (arm_feature(env, ARM_FEATURE_M)) {
7030 env->v7m.other_sp = qemu_get_be32(f);
7031 env->v7m.vecbase = qemu_get_be32(f);
7032 env->v7m.basepri = qemu_get_be32(f);
7033 env->v7m.control = qemu_get_be32(f);
7034 env->v7m.current_sp = qemu_get_be32(f);
7035 env->v7m.exception = qemu_get_be32(f);
7038 return 0;
7041 #elif defined(TARGET_IA64)
7042 void cpu_save(QEMUFile *f, void *opaque)
7046 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7048 return 0;
7050 #else
7052 //#warning No CPU save/restore functions
7054 #endif
7056 /***********************************************************/
7057 /* ram save/restore */
7059 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7061 int v;
7063 v = qemu_get_byte(f);
7064 switch(v) {
7065 case 0:
7066 if (qemu_get_buffer(f, buf, len) != len)
7067 return -EIO;
7068 break;
7069 case 1:
7070 v = qemu_get_byte(f);
7071 memset(buf, v, len);
7072 break;
7073 default:
7074 return -EINVAL;
7076 return 0;
7079 static int ram_load_v1(QEMUFile *f, void *opaque)
7081 int i, ret;
7083 if (qemu_get_be32(f) != phys_ram_size)
7084 return -EINVAL;
7085 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7086 #ifdef USE_KVM
7087 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7088 continue;
7089 #endif
7090 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7091 if (ret)
7092 return ret;
7094 return 0;
7097 #define BDRV_HASH_BLOCK_SIZE 1024
7098 #define IOBUF_SIZE 4096
7099 #define RAM_CBLOCK_MAGIC 0xfabe
7101 typedef struct RamCompressState {
7102 z_stream zstream;
7103 QEMUFile *f;
7104 uint8_t buf[IOBUF_SIZE];
7105 } RamCompressState;
7107 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7109 int ret;
7110 memset(s, 0, sizeof(*s));
7111 s->f = f;
7112 ret = deflateInit2(&s->zstream, 1,
7113 Z_DEFLATED, 15,
7114 9, Z_DEFAULT_STRATEGY);
7115 if (ret != Z_OK)
7116 return -1;
7117 s->zstream.avail_out = IOBUF_SIZE;
7118 s->zstream.next_out = s->buf;
7119 return 0;
7122 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7124 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7125 qemu_put_be16(s->f, len);
7126 qemu_put_buffer(s->f, buf, len);
7129 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7131 int ret;
7133 s->zstream.avail_in = len;
7134 s->zstream.next_in = (uint8_t *)buf;
7135 while (s->zstream.avail_in > 0) {
7136 ret = deflate(&s->zstream, Z_NO_FLUSH);
7137 if (ret != Z_OK)
7138 return -1;
7139 if (s->zstream.avail_out == 0) {
7140 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7141 s->zstream.avail_out = IOBUF_SIZE;
7142 s->zstream.next_out = s->buf;
7145 return 0;
7148 static void ram_compress_close(RamCompressState *s)
7150 int len, ret;
7152 /* compress last bytes */
7153 for(;;) {
7154 ret = deflate(&s->zstream, Z_FINISH);
7155 if (ret == Z_OK || ret == Z_STREAM_END) {
7156 len = IOBUF_SIZE - s->zstream.avail_out;
7157 if (len > 0) {
7158 ram_put_cblock(s, s->buf, len);
7160 s->zstream.avail_out = IOBUF_SIZE;
7161 s->zstream.next_out = s->buf;
7162 if (ret == Z_STREAM_END)
7163 break;
7164 } else {
7165 goto fail;
7168 fail:
7169 deflateEnd(&s->zstream);
7172 typedef struct RamDecompressState {
7173 z_stream zstream;
7174 QEMUFile *f;
7175 uint8_t buf[IOBUF_SIZE];
7176 } RamDecompressState;
7178 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7180 int ret;
7181 memset(s, 0, sizeof(*s));
7182 s->f = f;
7183 ret = inflateInit(&s->zstream);
7184 if (ret != Z_OK)
7185 return -1;
7186 return 0;
7189 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7191 int ret, clen;
7193 s->zstream.avail_out = len;
7194 s->zstream.next_out = buf;
7195 while (s->zstream.avail_out > 0) {
7196 if (s->zstream.avail_in == 0) {
7197 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7198 return -1;
7199 clen = qemu_get_be16(s->f);
7200 if (clen > IOBUF_SIZE)
7201 return -1;
7202 qemu_get_buffer(s->f, s->buf, clen);
7203 s->zstream.avail_in = clen;
7204 s->zstream.next_in = s->buf;
7206 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7207 if (ret != Z_OK && ret != Z_STREAM_END) {
7208 return -1;
7211 return 0;
7214 static void ram_decompress_close(RamDecompressState *s)
7216 inflateEnd(&s->zstream);
7219 static void ram_save_live(QEMUFile *f, void *opaque)
7221 target_ulong addr;
7223 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7224 #ifdef USE_KVM
7225 if (kvm_allowed && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7226 continue;
7227 #endif
7228 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7229 qemu_put_be32(f, addr);
7230 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7233 qemu_put_be32(f, 1);
7236 static void ram_save_static(QEMUFile *f, void *opaque)
7238 int i;
7239 RamCompressState s1, *s = &s1;
7240 uint8_t buf[10];
7242 qemu_put_be32(f, phys_ram_size);
7243 if (ram_compress_open(s, f) < 0)
7244 return;
7245 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7246 #ifdef USE_KVM
7247 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7248 continue;
7249 #endif
7250 #if 0
7251 if (tight_savevm_enabled) {
7252 int64_t sector_num;
7253 int j;
7255 /* find if the memory block is available on a virtual
7256 block device */
7257 sector_num = -1;
7258 for(j = 0; j < nb_drives; j++) {
7259 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7260 phys_ram_base + i,
7261 BDRV_HASH_BLOCK_SIZE);
7262 if (sector_num >= 0)
7263 break;
7265 if (j == nb_drives)
7266 goto normal_compress;
7267 buf[0] = 1;
7268 buf[1] = j;
7269 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7270 ram_compress_buf(s, buf, 10);
7271 } else
7272 #endif
7274 // normal_compress:
7275 buf[0] = 0;
7276 ram_compress_buf(s, buf, 1);
7277 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7280 ram_compress_close(s);
7283 static void ram_save(QEMUFile *f, void *opaque)
7285 int in_migration = cpu_physical_memory_get_dirty_tracking();
7287 qemu_put_byte(f, in_migration);
7289 if (in_migration)
7290 ram_save_live(f, opaque);
7291 else
7292 ram_save_static(f, opaque);
7295 static int ram_load_live(QEMUFile *f, void *opaque)
7297 target_ulong addr;
7299 do {
7300 addr = qemu_get_be32(f);
7301 if (addr == 1)
7302 break;
7304 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7305 } while (1);
7307 return 0;
7310 static int ram_load_static(QEMUFile *f, void *opaque)
7312 RamDecompressState s1, *s = &s1;
7313 uint8_t buf[10];
7314 int i;
7316 if (qemu_get_be32(f) != phys_ram_size)
7317 return -EINVAL;
7318 if (ram_decompress_open(s, f) < 0)
7319 return -EINVAL;
7320 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7321 #ifdef USE_KVM
7322 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7323 continue;
7324 #endif
7325 if (ram_decompress_buf(s, buf, 1) < 0) {
7326 fprintf(stderr, "Error while reading ram block header\n");
7327 goto error;
7329 if (buf[0] == 0) {
7330 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7331 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7332 goto error;
7334 } else
7335 #if 0
7336 if (buf[0] == 1) {
7337 int bs_index;
7338 int64_t sector_num;
7340 ram_decompress_buf(s, buf + 1, 9);
7341 bs_index = buf[1];
7342 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7343 if (bs_index >= nb_drives) {
7344 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7345 goto error;
7347 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7348 phys_ram_base + i,
7349 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7350 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7351 bs_index, sector_num);
7352 goto error;
7354 } else
7355 #endif
7357 error:
7358 printf("Error block header\n");
7359 return -EINVAL;
7362 ram_decompress_close(s);
7363 return 0;
7366 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7368 int ret;
7370 switch (version_id) {
7371 case 1:
7372 ret = ram_load_v1(f, opaque);
7373 break;
7374 case 3:
7375 if (qemu_get_byte(f)) {
7376 ret = ram_load_live(f, opaque);
7377 break;
7379 case 2:
7380 ret = ram_load_static(f, opaque);
7381 break;
7382 default:
7383 ret = -EINVAL;
7384 break;
7387 return ret;
7390 /***********************************************************/
7391 /* bottom halves (can be seen as timers which expire ASAP) */
7393 struct QEMUBH {
7394 QEMUBHFunc *cb;
7395 void *opaque;
7396 int scheduled;
7397 QEMUBH *next;
7400 static QEMUBH *first_bh = NULL;
7402 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7404 QEMUBH *bh;
7405 bh = qemu_mallocz(sizeof(QEMUBH));
7406 if (!bh)
7407 return NULL;
7408 bh->cb = cb;
7409 bh->opaque = opaque;
7410 return bh;
7413 int qemu_bh_poll(void)
7415 QEMUBH *bh, **pbh;
7416 int ret;
7418 ret = 0;
7419 for(;;) {
7420 pbh = &first_bh;
7421 bh = *pbh;
7422 if (!bh)
7423 break;
7424 ret = 1;
7425 *pbh = bh->next;
7426 bh->scheduled = 0;
7427 bh->cb(bh->opaque);
7429 return ret;
7432 void qemu_bh_schedule(QEMUBH *bh)
7434 CPUState *env = cpu_single_env;
7435 if (bh->scheduled)
7436 return;
7437 bh->scheduled = 1;
7438 bh->next = first_bh;
7439 first_bh = bh;
7441 /* stop the currently executing CPU to execute the BH ASAP */
7442 if (env) {
7443 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7447 void qemu_bh_cancel(QEMUBH *bh)
7449 QEMUBH **pbh;
7450 if (bh->scheduled) {
7451 pbh = &first_bh;
7452 while (*pbh != bh)
7453 pbh = &(*pbh)->next;
7454 *pbh = bh->next;
7455 bh->scheduled = 0;
7459 void qemu_bh_delete(QEMUBH *bh)
7461 qemu_bh_cancel(bh);
7462 qemu_free(bh);
7465 /***********************************************************/
7466 /* machine registration */
7468 QEMUMachine *first_machine = NULL;
7470 int qemu_register_machine(QEMUMachine *m)
7472 QEMUMachine **pm;
7473 pm = &first_machine;
7474 while (*pm != NULL)
7475 pm = &(*pm)->next;
7476 m->next = NULL;
7477 *pm = m;
7478 return 0;
7481 static QEMUMachine *find_machine(const char *name)
7483 QEMUMachine *m;
7485 for(m = first_machine; m != NULL; m = m->next) {
7486 if (!strcmp(m->name, name))
7487 return m;
7489 return NULL;
7492 /***********************************************************/
7493 /* main execution loop */
7495 static void gui_update(void *opaque)
7497 DisplayState *ds = opaque;
7498 ds->dpy_refresh(ds);
7499 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7502 struct vm_change_state_entry {
7503 VMChangeStateHandler *cb;
7504 void *opaque;
7505 LIST_ENTRY (vm_change_state_entry) entries;
7508 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7510 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7511 void *opaque)
7513 VMChangeStateEntry *e;
7515 e = qemu_mallocz(sizeof (*e));
7516 if (!e)
7517 return NULL;
7519 e->cb = cb;
7520 e->opaque = opaque;
7521 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7522 return e;
7525 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7527 LIST_REMOVE (e, entries);
7528 qemu_free (e);
7531 static void vm_state_notify(int running)
7533 VMChangeStateEntry *e;
7535 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7536 e->cb(e->opaque, running);
7540 /* XXX: support several handlers */
7541 static VMStopHandler *vm_stop_cb;
7542 static void *vm_stop_opaque;
7544 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7546 vm_stop_cb = cb;
7547 vm_stop_opaque = opaque;
7548 return 0;
7551 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7553 vm_stop_cb = NULL;
7556 void vm_start(void)
7558 if (!vm_running) {
7559 cpu_enable_ticks();
7560 vm_running = 1;
7561 vm_state_notify(1);
7562 qemu_rearm_alarm_timer(alarm_timer);
7566 void vm_stop(int reason)
7568 if (vm_running) {
7569 cpu_disable_ticks();
7570 vm_running = 0;
7571 if (reason != 0) {
7572 if (vm_stop_cb) {
7573 vm_stop_cb(vm_stop_opaque, reason);
7576 vm_state_notify(0);
7580 /* reset/shutdown handler */
7582 typedef struct QEMUResetEntry {
7583 QEMUResetHandler *func;
7584 void *opaque;
7585 struct QEMUResetEntry *next;
7586 } QEMUResetEntry;
7588 static QEMUResetEntry *first_reset_entry;
7589 static int reset_requested;
7590 static int shutdown_requested;
7591 static int powerdown_requested;
7593 int qemu_shutdown_requested(void)
7595 int r = shutdown_requested;
7596 shutdown_requested = 0;
7597 return r;
7600 int qemu_reset_requested(void)
7602 int r = reset_requested;
7603 reset_requested = 0;
7604 return r;
7607 int qemu_powerdown_requested(void)
7609 int r = powerdown_requested;
7610 powerdown_requested = 0;
7611 return r;
7614 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7616 QEMUResetEntry **pre, *re;
7618 pre = &first_reset_entry;
7619 while (*pre != NULL)
7620 pre = &(*pre)->next;
7621 re = qemu_mallocz(sizeof(QEMUResetEntry));
7622 re->func = func;
7623 re->opaque = opaque;
7624 re->next = NULL;
7625 *pre = re;
7628 void qemu_system_reset(void)
7630 QEMUResetEntry *re;
7632 /* reset all devices */
7633 for(re = first_reset_entry; re != NULL; re = re->next) {
7634 re->func(re->opaque);
7638 void qemu_system_reset_request(void)
7640 if (no_reboot) {
7641 shutdown_requested = 1;
7642 } else {
7643 reset_requested = 1;
7645 if (cpu_single_env)
7646 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7649 void qemu_system_shutdown_request(void)
7651 shutdown_requested = 1;
7652 if (cpu_single_env)
7653 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7656 void qemu_system_powerdown_request(void)
7658 powerdown_requested = 1;
7659 if (cpu_single_env)
7660 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7663 void main_loop_wait(int timeout)
7665 IOHandlerRecord *ioh;
7666 fd_set rfds, wfds, xfds;
7667 int ret, nfds;
7668 #ifdef _WIN32
7669 int ret2, i;
7670 #endif
7671 struct timeval tv;
7672 PollingEntry *pe;
7675 /* XXX: need to suppress polling by better using win32 events */
7676 ret = 0;
7677 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7678 ret |= pe->func(pe->opaque);
7680 #ifdef _WIN32
7681 if (ret == 0) {
7682 int err;
7683 WaitObjects *w = &wait_objects;
7685 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7686 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7687 if (w->func[ret - WAIT_OBJECT_0])
7688 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7690 /* Check for additional signaled events */
7691 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7693 /* Check if event is signaled */
7694 ret2 = WaitForSingleObject(w->events[i], 0);
7695 if(ret2 == WAIT_OBJECT_0) {
7696 if (w->func[i])
7697 w->func[i](w->opaque[i]);
7698 } else if (ret2 == WAIT_TIMEOUT) {
7699 } else {
7700 err = GetLastError();
7701 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7704 } else if (ret == WAIT_TIMEOUT) {
7705 } else {
7706 err = GetLastError();
7707 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7710 #endif
7711 /* poll any events */
7712 /* XXX: separate device handlers from system ones */
7713 nfds = -1;
7714 FD_ZERO(&rfds);
7715 FD_ZERO(&wfds);
7716 FD_ZERO(&xfds);
7717 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7718 if (ioh->deleted)
7719 continue;
7720 if (ioh->fd_read &&
7721 (!ioh->fd_read_poll ||
7722 ioh->fd_read_poll(ioh->opaque) != 0)) {
7723 FD_SET(ioh->fd, &rfds);
7724 if (ioh->fd > nfds)
7725 nfds = ioh->fd;
7727 if (ioh->fd_write) {
7728 FD_SET(ioh->fd, &wfds);
7729 if (ioh->fd > nfds)
7730 nfds = ioh->fd;
7734 tv.tv_sec = 0;
7735 #ifdef _WIN32
7736 tv.tv_usec = 0;
7737 #else
7738 tv.tv_usec = timeout * 1000;
7739 #endif
7740 #if defined(CONFIG_SLIRP)
7741 if (slirp_inited) {
7742 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7744 #endif
7745 moreio:
7746 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7747 if (ret > 0) {
7748 IOHandlerRecord **pioh;
7749 int more = 0;
7751 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7752 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7753 ioh->fd_read(ioh->opaque);
7754 more = 1;
7756 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7757 ioh->fd_write(ioh->opaque);
7758 more = 1;
7762 /* remove deleted IO handlers */
7763 pioh = &first_io_handler;
7764 while (*pioh) {
7765 ioh = *pioh;
7766 if (ioh->deleted) {
7767 *pioh = ioh->next;
7768 qemu_free(ioh);
7769 } else
7770 pioh = &ioh->next;
7772 if (more)
7773 goto moreio;
7775 #if defined(CONFIG_SLIRP)
7776 if (slirp_inited) {
7777 if (ret < 0) {
7778 FD_ZERO(&rfds);
7779 FD_ZERO(&wfds);
7780 FD_ZERO(&xfds);
7782 slirp_select_poll(&rfds, &wfds, &xfds);
7784 #endif
7785 virtio_net_poll();
7787 qemu_aio_poll();
7789 if (vm_running) {
7790 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7791 qemu_get_clock(vm_clock));
7792 /* run dma transfers, if any */
7793 DMA_run();
7796 /* real time timers */
7797 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7798 qemu_get_clock(rt_clock));
7800 /* Check bottom-halves last in case any of the earlier events triggered
7801 them. */
7802 qemu_bh_poll();
7806 static int main_loop(void)
7808 int ret, timeout;
7809 #ifdef CONFIG_PROFILER
7810 int64_t ti;
7811 #endif
7812 CPUState *env;
7815 #ifdef USE_KVM
7816 if (kvm_allowed) {
7817 kvm_main_loop();
7818 cpu_disable_ticks();
7819 return 0;
7821 #endif
7822 cur_cpu = first_cpu;
7823 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7824 for(;;) {
7825 if (vm_running) {
7827 for(;;) {
7828 /* get next cpu */
7829 env = next_cpu;
7830 #ifdef CONFIG_PROFILER
7831 ti = profile_getclock();
7832 #endif
7833 ret = cpu_exec(env);
7834 #ifdef CONFIG_PROFILER
7835 qemu_time += profile_getclock() - ti;
7836 #endif
7837 next_cpu = env->next_cpu ?: first_cpu;
7838 if (event_pending) {
7839 ret = EXCP_INTERRUPT;
7840 event_pending = 0;
7841 break;
7843 if (ret == EXCP_HLT) {
7844 /* Give the next CPU a chance to run. */
7845 cur_cpu = env;
7846 continue;
7848 if (ret != EXCP_HALTED)
7849 break;
7850 /* all CPUs are halted ? */
7851 if (env == cur_cpu)
7852 break;
7854 cur_cpu = env;
7856 if (shutdown_requested) {
7857 ret = EXCP_INTERRUPT;
7858 break;
7860 if (reset_requested) {
7861 reset_requested = 0;
7862 qemu_system_reset();
7863 #ifdef USE_KVM
7864 if (kvm_allowed)
7865 kvm_load_registers(env);
7866 #endif
7867 ret = EXCP_INTERRUPT;
7869 if (powerdown_requested) {
7870 powerdown_requested = 0;
7871 qemu_system_powerdown();
7872 ret = EXCP_INTERRUPT;
7874 if (ret == EXCP_DEBUG) {
7875 vm_stop(EXCP_DEBUG);
7877 /* If all cpus are halted then wait until the next IRQ */
7878 /* XXX: use timeout computed from timers */
7879 if (ret == EXCP_HALTED)
7880 timeout = 10;
7881 else
7882 timeout = 0;
7883 } else {
7884 timeout = 10;
7886 #ifdef CONFIG_PROFILER
7887 ti = profile_getclock();
7888 #endif
7889 main_loop_wait(timeout);
7890 #ifdef CONFIG_PROFILER
7891 dev_time += profile_getclock() - ti;
7892 #endif
7894 cpu_disable_ticks();
7895 return ret;
7898 static void help(int exitcode)
7900 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
7901 ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7902 "usage: %s [options] [disk_image]\n"
7903 "\n"
7904 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7905 "\n"
7906 "Standard options:\n"
7907 "-M machine select emulated machine (-M ? for list)\n"
7908 "-cpu cpu select CPU (-cpu ? for list)\n"
7909 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7910 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7911 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7912 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7913 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7914 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7915 " [,cache=on|off][,boot=on|off]\n"
7916 " use 'file' as a drive image\n"
7917 "-mtdblock file use 'file' as on-board Flash memory image\n"
7918 "-sd file use 'file' as SecureDigital card image\n"
7919 "-pflash file use 'file' as a parallel flash image\n"
7920 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7921 "-snapshot write to temporary files instead of disk image files\n"
7922 #ifdef CONFIG_SDL
7923 "-no-frame open SDL window without a frame and window decorations\n"
7924 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7925 "-no-quit disable SDL window close capability\n"
7926 #endif
7927 #ifdef TARGET_I386
7928 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7929 #endif
7930 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7931 "-smp n set the number of CPUs to 'n' [default=1]\n"
7932 "-nographic disable graphical output and redirect serial I/Os to console\n"
7933 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7934 #ifndef _WIN32
7935 "-k language use keyboard layout (for example \"fr\" for French)\n"
7936 #endif
7937 #ifdef HAS_AUDIO
7938 "-audio-help print list of audio drivers and their options\n"
7939 "-soundhw c1,... enable audio support\n"
7940 " and only specified sound cards (comma separated list)\n"
7941 " use -soundhw ? to get the list of supported cards\n"
7942 " use -soundhw all to enable all of them\n"
7943 #endif
7944 "-localtime set the real time clock to local time [default=utc]\n"
7945 "-full-screen start in full screen\n"
7946 #ifdef TARGET_I386
7947 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7948 #endif
7949 "-usb enable the USB driver (will be the default soon)\n"
7950 "-usbdevice name add the host or guest USB device 'name'\n"
7951 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7952 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7953 #endif
7954 "-name string set the name of the guest\n"
7955 "\n"
7956 "Network options:\n"
7957 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7958 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7959 #ifdef CONFIG_SLIRP
7960 "-net user[,vlan=n][,hostname=host]\n"
7961 " connect the user mode network stack to VLAN 'n' and send\n"
7962 " hostname 'host' to DHCP clients\n"
7963 #endif
7964 #ifdef _WIN32
7965 "-net tap[,vlan=n],ifname=name\n"
7966 " connect the host TAP network interface to VLAN 'n'\n"
7967 #else
7968 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7969 " connect the host TAP network interface to VLAN 'n' and use the\n"
7970 " network scripts 'file' (default=%s)\n"
7971 " and 'dfile' (default=%s);\n"
7972 " use '[down]script=no' to disable script execution;\n"
7973 " use 'fd=h' to connect to an already opened TAP interface\n"
7974 #endif
7975 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7976 " connect the vlan 'n' to another VLAN using a socket connection\n"
7977 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7978 " connect the vlan 'n' to multicast maddr and port\n"
7979 "-net none use it alone to have zero network devices; if no -net option\n"
7980 " is provided, the default is '-net nic -net user'\n"
7981 "\n"
7982 #ifdef CONFIG_SLIRP
7983 "-tftp dir allow tftp access to files in dir [-net user]\n"
7984 "-bootp file advertise file in BOOTP replies\n"
7985 #ifndef _WIN32
7986 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7987 #endif
7988 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7989 " redirect TCP or UDP connections from host to guest [-net user]\n"
7990 #endif
7991 "\n"
7992 "Linux boot specific:\n"
7993 "-kernel bzImage use 'bzImage' as kernel image\n"
7994 "-append cmdline use 'cmdline' as kernel command line\n"
7995 "-initrd file use 'file' as initial ram disk\n"
7996 "\n"
7997 "Debug/Expert options:\n"
7998 "-monitor dev redirect the monitor to char device 'dev'\n"
7999 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8000 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8001 "-serial dev redirect the serial port to char device 'dev'\n"
8002 "-parallel dev redirect the parallel port to char device 'dev'\n"
8003 "-pidfile file Write PID to 'file'\n"
8004 "-S freeze CPU at startup (use 'c' to start execution)\n"
8005 "-s wait gdb connection to port\n"
8006 "-p port set gdb connection port [default=%s]\n"
8007 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8008 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8009 " translation (t=none or lba) (usually qemu can guess them)\n"
8010 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8011 #ifdef USE_KQEMU
8012 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8013 "-no-kqemu disable KQEMU kernel module usage\n"
8014 #endif
8015 #ifdef USE_KVM
8016 "-no-kvm disable KVM hardware virtualization\n"
8017 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8018 #endif
8019 #ifdef TARGET_I386
8020 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8021 " (default is CL-GD5446 PCI VGA)\n"
8022 "-no-acpi disable ACPI\n"
8023 #endif
8024 "-no-reboot exit instead of rebooting\n"
8025 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8026 "-vnc display start a VNC server on display\n"
8027 #ifndef _WIN32
8028 "-daemonize daemonize QEMU after initializing\n"
8029 #endif
8030 "-tdf inject timer interrupts that got lost\n"
8031 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8032 "-option-rom rom load a file, rom, into the option ROM space\n"
8033 #ifdef TARGET_SPARC
8034 "-prom-env variable=value set OpenBIOS nvram variables\n"
8035 #endif
8036 "-clock force the use of the given methods for timer alarm.\n"
8037 " To see what timers are available use -clock help\n"
8038 "\n"
8039 "During emulation, the following keys are useful:\n"
8040 "ctrl-alt-f toggle full screen\n"
8041 "ctrl-alt-n switch to virtual console 'n'\n"
8042 "ctrl-alt toggle mouse and keyboard grab\n"
8043 "\n"
8044 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8046 "qemu",
8047 DEFAULT_RAM_SIZE,
8048 #ifndef _WIN32
8049 DEFAULT_NETWORK_SCRIPT,
8050 DEFAULT_NETWORK_DOWN_SCRIPT,
8051 #endif
8052 DEFAULT_GDBSTUB_PORT,
8053 "/tmp/qemu.log");
8054 exit(exitcode);
8057 #define HAS_ARG 0x0001
8059 enum {
8060 QEMU_OPTION_h,
8062 QEMU_OPTION_M,
8063 QEMU_OPTION_cpu,
8064 QEMU_OPTION_fda,
8065 QEMU_OPTION_fdb,
8066 QEMU_OPTION_hda,
8067 QEMU_OPTION_hdb,
8068 QEMU_OPTION_hdc,
8069 QEMU_OPTION_hdd,
8070 QEMU_OPTION_drive,
8071 QEMU_OPTION_cdrom,
8072 QEMU_OPTION_mtdblock,
8073 QEMU_OPTION_sd,
8074 QEMU_OPTION_pflash,
8075 QEMU_OPTION_boot,
8076 QEMU_OPTION_snapshot,
8077 #ifdef TARGET_I386
8078 QEMU_OPTION_no_fd_bootchk,
8079 #endif
8080 QEMU_OPTION_m,
8081 QEMU_OPTION_nographic,
8082 QEMU_OPTION_portrait,
8083 #ifdef HAS_AUDIO
8084 QEMU_OPTION_audio_help,
8085 QEMU_OPTION_soundhw,
8086 #endif
8088 QEMU_OPTION_net,
8089 QEMU_OPTION_tftp,
8090 QEMU_OPTION_bootp,
8091 QEMU_OPTION_smb,
8092 QEMU_OPTION_redir,
8094 QEMU_OPTION_kernel,
8095 QEMU_OPTION_append,
8096 QEMU_OPTION_initrd,
8098 QEMU_OPTION_S,
8099 QEMU_OPTION_s,
8100 QEMU_OPTION_p,
8101 QEMU_OPTION_d,
8102 QEMU_OPTION_hdachs,
8103 QEMU_OPTION_L,
8104 QEMU_OPTION_bios,
8105 QEMU_OPTION_no_code_copy,
8106 QEMU_OPTION_k,
8107 QEMU_OPTION_localtime,
8108 QEMU_OPTION_cirrusvga,
8109 QEMU_OPTION_vmsvga,
8110 QEMU_OPTION_g,
8111 QEMU_OPTION_std_vga,
8112 QEMU_OPTION_echr,
8113 QEMU_OPTION_monitor,
8114 QEMU_OPTION_balloon,
8115 QEMU_OPTION_vmchannel,
8116 QEMU_OPTION_serial,
8117 QEMU_OPTION_parallel,
8118 QEMU_OPTION_loadvm,
8119 QEMU_OPTION_full_screen,
8120 QEMU_OPTION_no_frame,
8121 QEMU_OPTION_alt_grab,
8122 QEMU_OPTION_no_quit,
8123 QEMU_OPTION_pidfile,
8124 QEMU_OPTION_no_kqemu,
8125 QEMU_OPTION_kernel_kqemu,
8126 QEMU_OPTION_win2k_hack,
8127 QEMU_OPTION_usb,
8128 QEMU_OPTION_usbdevice,
8129 QEMU_OPTION_smp,
8130 QEMU_OPTION_vnc,
8131 QEMU_OPTION_no_acpi,
8132 QEMU_OPTION_no_kvm,
8133 QEMU_OPTION_no_kvm_irqchip,
8134 QEMU_OPTION_no_reboot,
8135 QEMU_OPTION_show_cursor,
8136 QEMU_OPTION_daemonize,
8137 QEMU_OPTION_option_rom,
8138 QEMU_OPTION_semihosting,
8139 QEMU_OPTION_cpu_vendor,
8140 QEMU_OPTION_name,
8141 QEMU_OPTION_prom_env,
8142 QEMU_OPTION_old_param,
8143 QEMU_OPTION_clock,
8144 QEMU_OPTION_startdate,
8145 QEMU_OPTION_incoming,
8146 QEMU_OPTION_tdf,
8147 QEMU_OPTION_kvm_shadow_memory,
8150 typedef struct QEMUOption {
8151 const char *name;
8152 int flags;
8153 int index;
8154 } QEMUOption;
8156 const QEMUOption qemu_options[] = {
8157 { "h", 0, QEMU_OPTION_h },
8158 { "help", 0, QEMU_OPTION_h },
8160 { "M", HAS_ARG, QEMU_OPTION_M },
8161 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8162 { "fda", HAS_ARG, QEMU_OPTION_fda },
8163 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8164 { "hda", HAS_ARG, QEMU_OPTION_hda },
8165 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8166 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8167 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8168 { "drive", HAS_ARG, QEMU_OPTION_drive },
8169 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8170 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8171 { "sd", HAS_ARG, QEMU_OPTION_sd },
8172 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8173 { "boot", HAS_ARG, QEMU_OPTION_boot },
8174 { "snapshot", 0, QEMU_OPTION_snapshot },
8175 #ifdef TARGET_I386
8176 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8177 #endif
8178 { "m", HAS_ARG, QEMU_OPTION_m },
8179 { "nographic", 0, QEMU_OPTION_nographic },
8180 { "portrait", 0, QEMU_OPTION_portrait },
8181 { "k", HAS_ARG, QEMU_OPTION_k },
8182 #ifdef HAS_AUDIO
8183 { "audio-help", 0, QEMU_OPTION_audio_help },
8184 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8185 #endif
8187 { "net", HAS_ARG, QEMU_OPTION_net},
8188 #ifdef CONFIG_SLIRP
8189 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8190 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8191 #ifndef _WIN32
8192 { "smb", HAS_ARG, QEMU_OPTION_smb },
8193 #endif
8194 { "redir", HAS_ARG, QEMU_OPTION_redir },
8195 #endif
8197 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8198 { "append", HAS_ARG, QEMU_OPTION_append },
8199 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8201 { "S", 0, QEMU_OPTION_S },
8202 { "s", 0, QEMU_OPTION_s },
8203 { "p", HAS_ARG, QEMU_OPTION_p },
8204 { "d", HAS_ARG, QEMU_OPTION_d },
8205 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8206 { "L", HAS_ARG, QEMU_OPTION_L },
8207 { "bios", HAS_ARG, QEMU_OPTION_bios },
8208 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8209 #ifdef USE_KQEMU
8210 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8211 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8212 #endif
8213 #ifdef USE_KVM
8214 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8215 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8216 #endif
8217 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8218 { "g", 1, QEMU_OPTION_g },
8219 #endif
8220 { "localtime", 0, QEMU_OPTION_localtime },
8221 { "std-vga", 0, QEMU_OPTION_std_vga },
8222 { "monitor", 1, QEMU_OPTION_monitor },
8223 { "balloon", 1, QEMU_OPTION_balloon },
8224 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8225 { "echr", HAS_ARG, QEMU_OPTION_echr },
8226 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8227 { "serial", HAS_ARG, QEMU_OPTION_serial },
8228 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8229 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8230 { "incoming", 1, QEMU_OPTION_incoming },
8231 { "full-screen", 0, QEMU_OPTION_full_screen },
8232 #ifdef CONFIG_SDL
8233 { "no-frame", 0, QEMU_OPTION_no_frame },
8234 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8235 { "no-quit", 0, QEMU_OPTION_no_quit },
8236 #endif
8237 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8238 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8239 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8240 { "smp", HAS_ARG, QEMU_OPTION_smp },
8241 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8243 /* temporary options */
8244 { "usb", 0, QEMU_OPTION_usb },
8245 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8246 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8247 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8248 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8249 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8250 { "daemonize", 0, QEMU_OPTION_daemonize },
8251 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8252 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8253 { "semihosting", 0, QEMU_OPTION_semihosting },
8254 #endif
8255 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8256 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8257 { "name", HAS_ARG, QEMU_OPTION_name },
8258 #if defined(TARGET_SPARC)
8259 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8260 #endif
8261 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8262 #if defined(TARGET_ARM)
8263 { "old-param", 0, QEMU_OPTION_old_param },
8264 #endif
8265 { "clock", HAS_ARG, QEMU_OPTION_clock },
8266 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8267 { NULL },
8270 /* password input */
8272 int qemu_key_check(BlockDriverState *bs, const char *name)
8274 char password[256];
8275 int i;
8277 if (!bdrv_is_encrypted(bs))
8278 return 0;
8280 term_printf("%s is encrypted.\n", name);
8281 for(i = 0; i < 3; i++) {
8282 monitor_readline("Password: ", 1, password, sizeof(password));
8283 if (bdrv_set_key(bs, password) == 0)
8284 return 0;
8285 term_printf("invalid password\n");
8287 return -EPERM;
8290 static BlockDriverState *get_bdrv(int index)
8292 if (index > nb_drives)
8293 return NULL;
8294 return drives_table[index].bdrv;
8297 static void read_passwords(void)
8299 BlockDriverState *bs;
8300 int i;
8302 for(i = 0; i < 6; i++) {
8303 bs = get_bdrv(i);
8304 if (bs)
8305 qemu_key_check(bs, bdrv_get_device_name(bs));
8309 /* XXX: currently we cannot use simultaneously different CPUs */
8310 static void register_machines(void)
8312 #if defined(TARGET_I386)
8313 qemu_register_machine(&pc_machine);
8314 qemu_register_machine(&isapc_machine);
8315 #elif defined(TARGET_PPC)
8316 qemu_register_machine(&heathrow_machine);
8317 qemu_register_machine(&core99_machine);
8318 qemu_register_machine(&prep_machine);
8319 qemu_register_machine(&ref405ep_machine);
8320 qemu_register_machine(&taihu_machine);
8321 #elif defined(TARGET_MIPS)
8322 qemu_register_machine(&mips_machine);
8323 qemu_register_machine(&mips_malta_machine);
8324 qemu_register_machine(&mips_pica61_machine);
8325 qemu_register_machine(&mips_mipssim_machine);
8326 #elif defined(TARGET_SPARC)
8327 #ifdef TARGET_SPARC64
8328 qemu_register_machine(&sun4u_machine);
8329 #else
8330 qemu_register_machine(&ss5_machine);
8331 qemu_register_machine(&ss10_machine);
8332 qemu_register_machine(&ss600mp_machine);
8333 qemu_register_machine(&ss20_machine);
8334 #endif
8335 #elif defined(TARGET_ARM)
8336 qemu_register_machine(&integratorcp_machine);
8337 qemu_register_machine(&versatilepb_machine);
8338 qemu_register_machine(&versatileab_machine);
8339 qemu_register_machine(&realview_machine);
8340 qemu_register_machine(&akitapda_machine);
8341 qemu_register_machine(&spitzpda_machine);
8342 qemu_register_machine(&borzoipda_machine);
8343 qemu_register_machine(&terrierpda_machine);
8344 qemu_register_machine(&palmte_machine);
8345 qemu_register_machine(&lm3s811evb_machine);
8346 qemu_register_machine(&lm3s6965evb_machine);
8347 qemu_register_machine(&connex_machine);
8348 qemu_register_machine(&verdex_machine);
8349 qemu_register_machine(&mainstone2_machine);
8350 #elif defined(TARGET_SH4)
8351 qemu_register_machine(&shix_machine);
8352 qemu_register_machine(&r2d_machine);
8353 #elif defined(TARGET_ALPHA)
8354 /* XXX: TODO */
8355 #elif defined(TARGET_M68K)
8356 qemu_register_machine(&mcf5208evb_machine);
8357 qemu_register_machine(&an5206_machine);
8358 qemu_register_machine(&dummy_m68k_machine);
8359 #elif defined(TARGET_CRIS)
8360 qemu_register_machine(&bareetraxfs_machine);
8361 #elif defined(TARGET_IA64)
8362 qemu_register_machine(&ipf_machine);
8363 #else
8364 #error unsupported CPU
8365 #endif
8368 #ifdef HAS_AUDIO
8369 struct soundhw soundhw[] = {
8370 #ifdef HAS_AUDIO_CHOICE
8371 #ifdef TARGET_I386
8373 "pcspk",
8374 "PC speaker",
8377 { .init_isa = pcspk_audio_init }
8379 #endif
8381 "sb16",
8382 "Creative Sound Blaster 16",
8385 { .init_isa = SB16_init }
8388 #ifdef CONFIG_ADLIB
8390 "adlib",
8391 #ifdef HAS_YMF262
8392 "Yamaha YMF262 (OPL3)",
8393 #else
8394 "Yamaha YM3812 (OPL2)",
8395 #endif
8398 { .init_isa = Adlib_init }
8400 #endif
8402 #ifdef CONFIG_GUS
8404 "gus",
8405 "Gravis Ultrasound GF1",
8408 { .init_isa = GUS_init }
8410 #endif
8413 "es1370",
8414 "ENSONIQ AudioPCI ES1370",
8417 { .init_pci = es1370_init }
8419 #endif
8421 { NULL, NULL, 0, 0, { NULL } }
8424 static void select_soundhw (const char *optarg)
8426 struct soundhw *c;
8428 if (*optarg == '?') {
8429 show_valid_cards:
8431 printf ("Valid sound card names (comma separated):\n");
8432 for (c = soundhw; c->name; ++c) {
8433 printf ("%-11s %s\n", c->name, c->descr);
8435 printf ("\n-soundhw all will enable all of the above\n");
8436 exit (*optarg != '?');
8438 else {
8439 size_t l;
8440 const char *p;
8441 char *e;
8442 int bad_card = 0;
8444 if (!strcmp (optarg, "all")) {
8445 for (c = soundhw; c->name; ++c) {
8446 c->enabled = 1;
8448 return;
8451 p = optarg;
8452 while (*p) {
8453 e = strchr (p, ',');
8454 l = !e ? strlen (p) : (size_t) (e - p);
8456 for (c = soundhw; c->name; ++c) {
8457 if (!strncmp (c->name, p, l)) {
8458 c->enabled = 1;
8459 break;
8463 if (!c->name) {
8464 if (l > 80) {
8465 fprintf (stderr,
8466 "Unknown sound card name (too big to show)\n");
8468 else {
8469 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8470 (int) l, p);
8472 bad_card = 1;
8474 p += l + (e != NULL);
8477 if (bad_card)
8478 goto show_valid_cards;
8481 #endif
8483 #ifdef _WIN32
8484 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8486 exit(STATUS_CONTROL_C_EXIT);
8487 return TRUE;
8489 #endif
8491 #define MAX_NET_CLIENTS 32
8493 static int saved_argc;
8494 static char **saved_argv;
8496 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8498 *argc = saved_argc;
8499 *argv = saved_argv;
8500 *opt_daemonize = daemonize;
8501 *opt_incoming = incoming;
8504 int main(int argc, char **argv)
8506 #ifdef CONFIG_GDBSTUB
8507 int use_gdbstub;
8508 const char *gdbstub_port;
8509 #endif
8510 uint32_t boot_devices_bitmap = 0;
8511 int i;
8512 int snapshot, linux_boot, net_boot;
8513 const char *initrd_filename;
8514 const char *kernel_filename, *kernel_cmdline;
8515 const char *boot_devices = "";
8516 DisplayState *ds = &display_state;
8517 int cyls, heads, secs, translation;
8518 char net_clients[MAX_NET_CLIENTS][256];
8519 int nb_net_clients;
8520 int hda_index;
8521 int optind;
8522 const char *r, *optarg;
8523 CharDriverState *monitor_hd;
8524 char monitor_device[128];
8525 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8526 int vmchannel_device_index;
8527 char serial_devices[MAX_SERIAL_PORTS][128];
8528 int serial_device_index;
8529 char parallel_devices[MAX_PARALLEL_PORTS][128];
8530 int parallel_device_index;
8531 const char *loadvm = NULL;
8532 QEMUMachine *machine;
8533 const char *cpu_model;
8534 char usb_devices[MAX_USB_CMDLINE][128];
8535 int usb_devices_index;
8536 int fds[2];
8537 const char *pid_file = NULL;
8538 VLANState *vlan;
8540 saved_argc = argc;
8541 saved_argv = argv;
8543 LIST_INIT (&vm_change_state_head);
8544 #ifndef _WIN32
8546 struct sigaction act;
8547 sigfillset(&act.sa_mask);
8548 act.sa_flags = 0;
8549 act.sa_handler = SIG_IGN;
8550 sigaction(SIGPIPE, &act, NULL);
8552 #else
8553 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8554 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8555 QEMU to run on a single CPU */
8557 HANDLE h;
8558 DWORD mask, smask;
8559 int i;
8560 h = GetCurrentProcess();
8561 if (GetProcessAffinityMask(h, &mask, &smask)) {
8562 for(i = 0; i < 32; i++) {
8563 if (mask & (1 << i))
8564 break;
8566 if (i != 32) {
8567 mask = 1 << i;
8568 SetProcessAffinityMask(h, mask);
8572 #endif
8574 register_machines();
8575 machine = first_machine;
8576 cpu_model = NULL;
8577 initrd_filename = NULL;
8578 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8579 vga_ram_size = VGA_RAM_SIZE;
8580 #ifdef CONFIG_GDBSTUB
8581 use_gdbstub = 0;
8582 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8583 #endif
8584 snapshot = 0;
8585 nographic = 0;
8586 kernel_filename = NULL;
8587 kernel_cmdline = "";
8588 cyls = heads = secs = 0;
8589 translation = BIOS_ATA_TRANSLATION_AUTO;
8590 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8592 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8593 vmchannel_devices[i][0] = '\0';
8594 vmchannel_device_index = 0;
8596 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8597 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8598 serial_devices[i][0] = '\0';
8599 serial_device_index = 0;
8601 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8602 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8603 parallel_devices[i][0] = '\0';
8604 parallel_device_index = 0;
8606 usb_devices_index = 0;
8608 nb_net_clients = 0;
8609 nb_drives = 0;
8610 nb_drives_opt = 0;
8611 hda_index = -1;
8613 nb_nics = 0;
8614 /* default mac address of the first network interface */
8616 optind = 1;
8617 for(;;) {
8618 if (optind >= argc)
8619 break;
8620 r = argv[optind];
8621 if (r[0] != '-') {
8622 hda_index = drive_add(HD_ALIAS, argv[optind++], 0);
8623 } else {
8624 const QEMUOption *popt;
8626 optind++;
8627 /* Treat --foo the same as -foo. */
8628 if (r[1] == '-')
8629 r++;
8630 popt = qemu_options;
8631 for(;;) {
8632 if (!popt->name) {
8633 fprintf(stderr, "%s: invalid option -- '%s'\n",
8634 argv[0], r);
8635 exit(1);
8637 if (!strcmp(popt->name, r + 1))
8638 break;
8639 popt++;
8641 if (popt->flags & HAS_ARG) {
8642 if (optind >= argc) {
8643 fprintf(stderr, "%s: option '%s' requires an argument\n",
8644 argv[0], r);
8645 exit(1);
8647 optarg = argv[optind++];
8648 } else {
8649 optarg = NULL;
8652 switch(popt->index) {
8653 case QEMU_OPTION_M:
8654 machine = find_machine(optarg);
8655 if (!machine) {
8656 QEMUMachine *m;
8657 printf("Supported machines are:\n");
8658 for(m = first_machine; m != NULL; m = m->next) {
8659 printf("%-10s %s%s\n",
8660 m->name, m->desc,
8661 m == first_machine ? " (default)" : "");
8663 exit(*optarg != '?');
8665 break;
8666 case QEMU_OPTION_cpu:
8667 /* hw initialization will check this */
8668 if (*optarg == '?') {
8669 /* XXX: implement xxx_cpu_list for targets that still miss it */
8670 #if defined(cpu_list)
8671 cpu_list(stdout, &fprintf);
8672 #endif
8673 exit(0);
8674 } else {
8675 cpu_model = optarg;
8677 break;
8678 case QEMU_OPTION_initrd:
8679 initrd_filename = optarg;
8680 break;
8681 case QEMU_OPTION_hda:
8682 if (cyls == 0)
8683 hda_index = drive_add(HD_ALIAS, optarg, 0);
8684 else
8685 hda_index = drive_add(HD_ALIAS
8686 ",cyls=%d,heads=%d,secs=%d%s",
8687 optarg, 0, cyls, heads, secs,
8688 translation == BIOS_ATA_TRANSLATION_LBA ?
8689 ",trans=lba" :
8690 translation == BIOS_ATA_TRANSLATION_NONE ?
8691 ",trans=none" : "");
8692 break;
8693 case QEMU_OPTION_hdb:
8694 case QEMU_OPTION_hdc:
8695 case QEMU_OPTION_hdd:
8696 drive_add(HD_ALIAS, optarg, popt->index - QEMU_OPTION_hda);
8697 break;
8698 case QEMU_OPTION_drive:
8699 drive_add("%s", optarg);
8700 break;
8701 case QEMU_OPTION_mtdblock:
8702 drive_add(MTD_ALIAS, optarg);
8703 break;
8704 case QEMU_OPTION_sd:
8705 drive_add("file=\"%s\"," SD_ALIAS, optarg);
8706 break;
8707 case QEMU_OPTION_pflash:
8708 drive_add(PFLASH_ALIAS, optarg);
8709 break;
8710 case QEMU_OPTION_snapshot:
8711 snapshot = 1;
8712 break;
8713 case QEMU_OPTION_hdachs:
8715 const char *p;
8716 p = optarg;
8717 cyls = strtol(p, (char **)&p, 0);
8718 if (cyls < 1 || cyls > 16383)
8719 goto chs_fail;
8720 if (*p != ',')
8721 goto chs_fail;
8722 p++;
8723 heads = strtol(p, (char **)&p, 0);
8724 if (heads < 1 || heads > 16)
8725 goto chs_fail;
8726 if (*p != ',')
8727 goto chs_fail;
8728 p++;
8729 secs = strtol(p, (char **)&p, 0);
8730 if (secs < 1 || secs > 63)
8731 goto chs_fail;
8732 if (*p == ',') {
8733 p++;
8734 if (!strcmp(p, "none"))
8735 translation = BIOS_ATA_TRANSLATION_NONE;
8736 else if (!strcmp(p, "lba"))
8737 translation = BIOS_ATA_TRANSLATION_LBA;
8738 else if (!strcmp(p, "auto"))
8739 translation = BIOS_ATA_TRANSLATION_AUTO;
8740 else
8741 goto chs_fail;
8742 } else if (*p != '\0') {
8743 chs_fail:
8744 fprintf(stderr, "qemu: invalid physical CHS format\n");
8745 exit(1);
8747 if (hda_index != -1)
8748 snprintf(drives_opt[hda_index] +
8749 strlen(drives_opt[hda_index]),
8750 sizeof(drives_opt[0]) -
8751 strlen(drives_opt[hda_index]),
8752 ",cyls=%d,heads=%d,secs=%d%s",
8753 cyls, heads, secs,
8754 translation == BIOS_ATA_TRANSLATION_LBA ?
8755 ",trans=lba" :
8756 translation == BIOS_ATA_TRANSLATION_NONE ?
8757 ",trans=none" : "");
8759 break;
8760 case QEMU_OPTION_nographic:
8761 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8762 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8763 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8764 nographic = 1;
8765 break;
8766 case QEMU_OPTION_portrait:
8767 graphic_rotate = 1;
8768 break;
8769 case QEMU_OPTION_kernel:
8770 kernel_filename = optarg;
8771 break;
8772 case QEMU_OPTION_append:
8773 kernel_cmdline = optarg;
8774 break;
8775 case QEMU_OPTION_cdrom:
8776 drive_add("file=\"%s\"," CDROM_ALIAS, optarg);
8777 break;
8778 case QEMU_OPTION_boot:
8779 boot_devices = optarg;
8780 /* We just do some generic consistency checks */
8782 /* Could easily be extended to 64 devices if needed */
8783 const char *p;
8785 boot_devices_bitmap = 0;
8786 for (p = boot_devices; *p != '\0'; p++) {
8787 /* Allowed boot devices are:
8788 * a b : floppy disk drives
8789 * c ... f : IDE disk drives
8790 * g ... m : machine implementation dependant drives
8791 * n ... p : network devices
8792 * It's up to each machine implementation to check
8793 * if the given boot devices match the actual hardware
8794 * implementation and firmware features.
8796 if (*p < 'a' || *p > 'q') {
8797 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8798 exit(1);
8800 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8801 fprintf(stderr,
8802 "Boot device '%c' was given twice\n",*p);
8803 exit(1);
8805 boot_devices_bitmap |= 1 << (*p - 'a');
8808 break;
8809 case QEMU_OPTION_fda:
8810 case QEMU_OPTION_fdb:
8811 drive_add("file=\"%s\"," FD_ALIAS, optarg,
8812 popt->index - QEMU_OPTION_fda);
8813 break;
8814 #ifdef TARGET_I386
8815 case QEMU_OPTION_no_fd_bootchk:
8816 fd_bootchk = 0;
8817 break;
8818 #endif
8819 case QEMU_OPTION_no_code_copy:
8820 code_copy_enabled = 0;
8821 break;
8822 case QEMU_OPTION_net:
8823 if (nb_net_clients >= MAX_NET_CLIENTS) {
8824 fprintf(stderr, "qemu: too many network clients\n");
8825 exit(1);
8827 pstrcpy(net_clients[nb_net_clients],
8828 sizeof(net_clients[0]),
8829 optarg);
8830 nb_net_clients++;
8831 break;
8832 #ifdef CONFIG_SLIRP
8833 case QEMU_OPTION_tftp:
8834 tftp_prefix = optarg;
8835 break;
8836 case QEMU_OPTION_bootp:
8837 bootp_filename = optarg;
8838 break;
8839 #ifndef _WIN32
8840 case QEMU_OPTION_smb:
8841 net_slirp_smb(optarg);
8842 break;
8843 #endif
8844 case QEMU_OPTION_redir:
8845 net_slirp_redir(optarg);
8846 break;
8847 #endif
8848 #ifdef HAS_AUDIO
8849 case QEMU_OPTION_audio_help:
8850 AUD_help ();
8851 exit (0);
8852 break;
8853 case QEMU_OPTION_soundhw:
8854 select_soundhw (optarg);
8855 break;
8856 #endif
8857 case QEMU_OPTION_h:
8858 help(0);
8859 break;
8860 case QEMU_OPTION_m:
8861 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
8862 if (ram_size <= 0)
8863 help(1);
8864 if (ram_size > PHYS_RAM_MAX_SIZE) {
8865 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8866 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8867 exit(1);
8869 break;
8870 case QEMU_OPTION_d:
8872 int mask;
8873 CPULogItem *item;
8875 mask = cpu_str_to_log_mask(optarg);
8876 if (!mask) {
8877 printf("Log items (comma separated):\n");
8878 for(item = cpu_log_items; item->mask != 0; item++) {
8879 printf("%-10s %s\n", item->name, item->help);
8881 exit(1);
8883 cpu_set_log(mask);
8885 break;
8886 #ifdef CONFIG_GDBSTUB
8887 case QEMU_OPTION_s:
8888 use_gdbstub = 1;
8889 break;
8890 case QEMU_OPTION_p:
8891 gdbstub_port = optarg;
8892 break;
8893 #endif
8894 case QEMU_OPTION_L:
8895 bios_dir = optarg;
8896 break;
8897 case QEMU_OPTION_bios:
8898 bios_name = optarg;
8899 break;
8900 case QEMU_OPTION_S:
8901 autostart = 0;
8902 break;
8903 case QEMU_OPTION_k:
8904 keyboard_layout = optarg;
8905 break;
8906 case QEMU_OPTION_localtime:
8907 rtc_utc = 0;
8908 break;
8909 case QEMU_OPTION_cirrusvga:
8910 cirrus_vga_enabled = 1;
8911 vmsvga_enabled = 0;
8912 break;
8913 case QEMU_OPTION_vmsvga:
8914 cirrus_vga_enabled = 0;
8915 vmsvga_enabled = 1;
8916 break;
8917 case QEMU_OPTION_std_vga:
8918 cirrus_vga_enabled = 0;
8919 vmsvga_enabled = 0;
8920 break;
8921 case QEMU_OPTION_g:
8923 const char *p;
8924 int w, h, depth;
8925 p = optarg;
8926 w = strtol(p, (char **)&p, 10);
8927 if (w <= 0) {
8928 graphic_error:
8929 fprintf(stderr, "qemu: invalid resolution or depth\n");
8930 exit(1);
8932 if (*p != 'x')
8933 goto graphic_error;
8934 p++;
8935 h = strtol(p, (char **)&p, 10);
8936 if (h <= 0)
8937 goto graphic_error;
8938 if (*p == 'x') {
8939 p++;
8940 depth = strtol(p, (char **)&p, 10);
8941 if (depth != 8 && depth != 15 && depth != 16 &&
8942 depth != 24 && depth != 32)
8943 goto graphic_error;
8944 } else if (*p == '\0') {
8945 depth = graphic_depth;
8946 } else {
8947 goto graphic_error;
8950 graphic_width = w;
8951 graphic_height = h;
8952 graphic_depth = depth;
8954 break;
8955 case QEMU_OPTION_echr:
8957 char *r;
8958 term_escape_char = strtol(optarg, &r, 0);
8959 if (r == optarg)
8960 printf("Bad argument to echr\n");
8961 break;
8963 case QEMU_OPTION_monitor:
8964 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8965 break;
8966 case QEMU_OPTION_balloon:
8967 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8968 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8969 exit(1);
8971 if (balloon_used) {
8972 fprintf(stderr, "qemu: only one balloon device can be used\n");
8973 exit(1);
8975 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
8976 vmchannel_device_index++;
8977 balloon_used = 1;
8978 break;
8979 case QEMU_OPTION_vmchannel:
8980 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8981 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8982 exit(1);
8984 pstrcpy(vmchannel_devices[vmchannel_device_index],
8985 sizeof(vmchannel_devices[0]), optarg);
8986 vmchannel_device_index++;
8987 break;
8988 case QEMU_OPTION_serial:
8989 if (serial_device_index >= MAX_SERIAL_PORTS) {
8990 fprintf(stderr, "qemu: too many serial ports\n");
8991 exit(1);
8993 pstrcpy(serial_devices[serial_device_index],
8994 sizeof(serial_devices[0]), optarg);
8995 serial_device_index++;
8996 break;
8997 case QEMU_OPTION_parallel:
8998 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8999 fprintf(stderr, "qemu: too many parallel ports\n");
9000 exit(1);
9002 pstrcpy(parallel_devices[parallel_device_index],
9003 sizeof(parallel_devices[0]), optarg);
9004 parallel_device_index++;
9005 break;
9006 case QEMU_OPTION_loadvm:
9007 loadvm = optarg;
9008 break;
9009 case QEMU_OPTION_incoming:
9010 incoming = optarg;
9011 break;
9012 case QEMU_OPTION_full_screen:
9013 full_screen = 1;
9014 break;
9015 #ifdef CONFIG_SDL
9016 case QEMU_OPTION_no_frame:
9017 no_frame = 1;
9018 break;
9019 case QEMU_OPTION_alt_grab:
9020 alt_grab = 1;
9021 break;
9022 case QEMU_OPTION_no_quit:
9023 no_quit = 1;
9024 break;
9025 #endif
9026 case QEMU_OPTION_pidfile:
9027 pid_file = optarg;
9028 break;
9029 #ifdef TARGET_I386
9030 case QEMU_OPTION_win2k_hack:
9031 win2k_install_hack = 1;
9032 break;
9033 #endif
9034 #ifdef USE_KQEMU
9035 case QEMU_OPTION_no_kqemu:
9036 kqemu_allowed = 0;
9037 break;
9038 case QEMU_OPTION_kernel_kqemu:
9039 kqemu_allowed = 2;
9040 break;
9041 #endif
9042 #ifdef USE_KVM
9043 case QEMU_OPTION_no_kvm:
9044 kvm_allowed = 0;
9045 break;
9046 case QEMU_OPTION_no_kvm_irqchip:
9047 kvm_irqchip = 0;
9048 break;
9049 #endif
9050 case QEMU_OPTION_usb:
9051 usb_enabled = 1;
9052 break;
9053 case QEMU_OPTION_usbdevice:
9054 usb_enabled = 1;
9055 if (usb_devices_index >= MAX_USB_CMDLINE) {
9056 fprintf(stderr, "Too many USB devices\n");
9057 exit(1);
9059 pstrcpy(usb_devices[usb_devices_index],
9060 sizeof(usb_devices[usb_devices_index]),
9061 optarg);
9062 usb_devices_index++;
9063 break;
9064 case QEMU_OPTION_smp:
9065 smp_cpus = atoi(optarg);
9066 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9067 fprintf(stderr, "Invalid number of CPUs\n");
9068 exit(1);
9070 break;
9071 case QEMU_OPTION_vnc:
9072 vnc_display = optarg;
9073 break;
9074 case QEMU_OPTION_no_acpi:
9075 acpi_enabled = 0;
9076 break;
9077 case QEMU_OPTION_no_reboot:
9078 no_reboot = 1;
9079 break;
9080 case QEMU_OPTION_show_cursor:
9081 cursor_hide = 0;
9082 break;
9083 case QEMU_OPTION_daemonize:
9084 daemonize = 1;
9085 break;
9086 case QEMU_OPTION_option_rom:
9087 if (nb_option_roms >= MAX_OPTION_ROMS) {
9088 fprintf(stderr, "Too many option ROMs\n");
9089 exit(1);
9091 option_rom[nb_option_roms] = optarg;
9092 nb_option_roms++;
9093 break;
9094 case QEMU_OPTION_semihosting:
9095 semihosting_enabled = 1;
9096 break;
9097 case QEMU_OPTION_tdf:
9098 time_drift_fix = 1;
9099 break;
9100 case QEMU_OPTION_kvm_shadow_memory:
9101 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9102 break;
9103 case QEMU_OPTION_name:
9104 qemu_name = optarg;
9105 break;
9106 #ifdef TARGET_SPARC
9107 case QEMU_OPTION_prom_env:
9108 if (nb_prom_envs >= MAX_PROM_ENVS) {
9109 fprintf(stderr, "Too many prom variables\n");
9110 exit(1);
9112 prom_envs[nb_prom_envs] = optarg;
9113 nb_prom_envs++;
9114 break;
9115 #endif
9116 case QEMU_OPTION_cpu_vendor:
9117 cpu_vendor_string = optarg;
9118 break;
9119 #ifdef TARGET_ARM
9120 case QEMU_OPTION_old_param:
9121 old_param = 1;
9122 #endif
9123 case QEMU_OPTION_clock:
9124 configure_alarms(optarg);
9125 break;
9126 case QEMU_OPTION_startdate:
9128 struct tm tm;
9129 if (!strcmp(optarg, "now")) {
9130 rtc_start_date = -1;
9131 } else {
9132 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9133 &tm.tm_year,
9134 &tm.tm_mon,
9135 &tm.tm_mday,
9136 &tm.tm_hour,
9137 &tm.tm_min,
9138 &tm.tm_sec) == 6) {
9139 /* OK */
9140 } else if (sscanf(optarg, "%d-%d-%d",
9141 &tm.tm_year,
9142 &tm.tm_mon,
9143 &tm.tm_mday) == 3) {
9144 tm.tm_hour = 0;
9145 tm.tm_min = 0;
9146 tm.tm_sec = 0;
9147 } else {
9148 goto date_fail;
9150 tm.tm_year -= 1900;
9151 tm.tm_mon--;
9152 rtc_start_date = mktimegm(&tm);
9153 if (rtc_start_date == -1) {
9154 date_fail:
9155 fprintf(stderr, "Invalid date format. Valid format are:\n"
9156 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9157 exit(1);
9161 break;
9166 #ifndef _WIN32
9167 if (daemonize) {
9168 pid_t pid;
9170 if (pipe(fds) == -1)
9171 exit(1);
9173 pid = fork();
9174 if (pid > 0) {
9175 uint8_t status;
9176 ssize_t len;
9178 close(fds[1]);
9180 again:
9181 len = read(fds[0], &status, 1);
9182 if (len == -1 && (errno == EINTR))
9183 goto again;
9185 if (len != 1)
9186 exit(1);
9187 else if (status == 1) {
9188 fprintf(stderr, "Could not acquire pidfile\n");
9189 exit(1);
9190 } else
9191 exit(0);
9192 } else if (pid < 0)
9193 exit(1);
9195 setsid();
9197 pid = fork();
9198 if (pid > 0)
9199 exit(0);
9200 else if (pid < 0)
9201 exit(1);
9203 umask(027);
9205 signal(SIGTSTP, SIG_IGN);
9206 signal(SIGTTOU, SIG_IGN);
9207 signal(SIGTTIN, SIG_IGN);
9209 #endif
9211 #if USE_KVM
9212 if (kvm_allowed) {
9213 if (kvm_qemu_init() < 0) {
9214 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9215 kvm_allowed = 0;
9218 #endif
9220 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9221 if (daemonize) {
9222 uint8_t status = 1;
9223 write(fds[1], &status, 1);
9224 } else
9225 fprintf(stderr, "Could not acquire pid file\n");
9226 exit(1);
9229 #ifdef USE_KQEMU
9230 if (smp_cpus > 1)
9231 kqemu_allowed = 0;
9232 #endif
9233 linux_boot = (kernel_filename != NULL);
9234 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9236 /* XXX: this should not be: some embedded targets just have flash */
9237 if (!linux_boot && net_boot == 0 &&
9238 nb_drives_opt == 0)
9239 help(1);
9241 /* boot to floppy or the default cd if no hard disk defined yet */
9242 if (!boot_devices[0]) {
9243 boot_devices = "cad";
9245 setvbuf(stdout, NULL, _IOLBF, 0);
9247 init_timers();
9248 init_timer_alarm();
9249 qemu_aio_init();
9251 #ifdef _WIN32
9252 socket_init();
9253 #endif
9255 /* init network clients */
9256 if (nb_net_clients == 0) {
9257 /* if no clients, we use a default config */
9258 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9259 "nic");
9260 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9261 "user");
9262 nb_net_clients = 2;
9265 for(i = 0;i < nb_net_clients; i++) {
9266 if (net_client_init(net_clients[i]) < 0)
9267 exit(1);
9269 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9270 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9271 continue;
9272 if (vlan->nb_guest_devs == 0) {
9273 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9274 exit(1);
9276 if (vlan->nb_host_devs == 0)
9277 fprintf(stderr,
9278 "Warning: vlan %d is not connected to host network\n",
9279 vlan->id);
9282 #ifdef TARGET_I386
9283 /* XXX: this should be moved in the PC machine instantiation code */
9284 if (net_boot != 0) {
9285 int netroms = 0;
9286 for (i = 0; i < nb_nics && i < 4; i++) {
9287 const char *model = nd_table[i].model;
9288 char buf[1024];
9289 if (net_boot & (1 << i)) {
9290 if (model == NULL)
9291 model = "ne2k_pci";
9292 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9293 if (get_image_size(buf) > 0) {
9294 if (nb_option_roms >= MAX_OPTION_ROMS) {
9295 fprintf(stderr, "Too many option ROMs\n");
9296 exit(1);
9298 option_rom[nb_option_roms] = strdup(buf);
9299 nb_option_roms++;
9300 netroms++;
9304 if (netroms == 0) {
9305 fprintf(stderr, "No valid PXE rom found for network device\n");
9306 exit(1);
9309 #endif
9311 /* init the memory */
9312 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9314 #if USE_KVM
9315 /* Initialize kvm */
9316 #ifdef TARGET_IA64
9317 #define KVM_EXTRA_PAGES 0
9318 #else
9319 #define KVM_EXTRA_PAGES 3
9320 #endif
9321 if (kvm_allowed) {
9322 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9323 if (kvm_qemu_create_context() < 0) {
9324 fprintf(stderr, "Could not create KVM context\n");
9325 exit(1);
9327 #ifdef KVM_CAP_USER_MEMORY
9329 int ret;
9331 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9332 if (ret) {
9333 phys_ram_base = qemu_vmalloc(phys_ram_size);
9334 if (!phys_ram_base) {
9335 fprintf(stderr, "Could not allocate physical memory\n");
9336 exit(1);
9340 #endif
9341 } else {
9342 phys_ram_base = qemu_vmalloc(phys_ram_size);
9343 if (!phys_ram_base) {
9344 fprintf(stderr, "Could not allocate physical memory\n");
9345 exit(1);
9348 #else
9349 phys_ram_base = qemu_vmalloc(phys_ram_size);
9350 if (!phys_ram_base) {
9351 fprintf(stderr, "Could not allocate physical memory\n");
9352 exit(1);
9354 #endif
9356 bdrv_init();
9358 /* we always create the cdrom drive, even if no disk is there */
9360 if (nb_drives_opt < MAX_DRIVES)
9361 drive_add(CDROM_ALIAS);
9363 /* we always create at least one floppy */
9365 if (nb_drives_opt < MAX_DRIVES)
9366 drive_add(FD_ALIAS, 0);
9368 /* we always create one sd slot, even if no card is in it */
9370 if (nb_drives_opt < MAX_DRIVES)
9371 drive_add(SD_ALIAS);
9373 /* open the virtual block devices */
9375 for(i = 0; i < nb_drives_opt; i++)
9376 if (drive_init(drives_opt[i], snapshot, machine) == -1)
9377 exit(1);
9379 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9380 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9382 init_ioports();
9384 /* terminal init */
9385 memset(&display_state, 0, sizeof(display_state));
9386 if (nographic) {
9387 /* nearly nothing to do */
9388 dumb_display_init(ds);
9389 } else if (vnc_display != NULL) {
9390 vnc_display_init(ds);
9391 if (vnc_display_open(ds, vnc_display) < 0)
9392 exit(1);
9393 } else {
9394 #if defined(CONFIG_SDL)
9395 sdl_display_init(ds, full_screen, no_frame);
9396 #elif defined(CONFIG_COCOA)
9397 cocoa_display_init(ds, full_screen);
9398 #else
9399 dumb_display_init(ds);
9400 #endif
9403 /* Maintain compatibility with multiple stdio monitors */
9404 if (!strcmp(monitor_device,"stdio")) {
9405 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9406 if (!strcmp(serial_devices[i],"mon:stdio")) {
9407 monitor_device[0] = '\0';
9408 break;
9409 } else if (!strcmp(serial_devices[i],"stdio")) {
9410 monitor_device[0] = '\0';
9411 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9412 break;
9416 if (monitor_device[0] != '\0') {
9417 monitor_hd = qemu_chr_open(monitor_device);
9418 if (!monitor_hd) {
9419 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9420 exit(1);
9422 monitor_init(monitor_hd, !nographic);
9425 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9426 const char *devname = vmchannel_devices[i];
9427 if (devname[0] != '\0' && strcmp(devname, "none")) {
9428 int devid;
9429 char *termn;
9431 if (strstart(devname, "di:", &devname)) {
9432 devid = strtol(devname, &termn, 16);
9433 devname = termn + 1;
9435 else {
9436 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9437 devname);
9438 exit(1);
9440 vmchannel_hds[i] = qemu_chr_open(devname);
9441 if (!vmchannel_hds[i]) {
9442 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9443 devname);
9444 exit(1);
9446 vmchannel_init(vmchannel_hds[i], devid, i);
9450 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9451 const char *devname = serial_devices[i];
9452 if (devname[0] != '\0' && strcmp(devname, "none")) {
9453 serial_hds[i] = qemu_chr_open(devname);
9454 if (!serial_hds[i]) {
9455 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9456 devname);
9457 exit(1);
9459 if (strstart(devname, "vc", 0))
9460 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9464 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9465 const char *devname = parallel_devices[i];
9466 if (devname[0] != '\0' && strcmp(devname, "none")) {
9467 parallel_hds[i] = qemu_chr_open(devname);
9468 if (!parallel_hds[i]) {
9469 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9470 devname);
9471 exit(1);
9473 if (strstart(devname, "vc", 0))
9474 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9478 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9479 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9481 /* init USB devices */
9482 if (usb_enabled) {
9483 for(i = 0; i < usb_devices_index; i++) {
9484 if (usb_device_add(usb_devices[i]) < 0) {
9485 fprintf(stderr, "Warning: could not add USB device %s\n",
9486 usb_devices[i]);
9491 if (display_state.dpy_refresh) {
9492 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9493 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9496 #ifdef USE_KVM
9497 if (kvm_allowed)
9498 kvm_init_ap();
9499 #endif
9501 #ifdef CONFIG_GDBSTUB
9502 if (use_gdbstub) {
9503 /* XXX: use standard host:port notation and modify options
9504 accordingly. */
9505 if (gdbserver_start(gdbstub_port) < 0) {
9506 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9507 gdbstub_port);
9508 exit(1);
9511 #endif
9512 if (loadvm)
9513 do_loadvm(loadvm);
9515 if (incoming) {
9516 int rc;
9518 rc = migrate_incoming(incoming);
9519 if (rc != 0) {
9520 fprintf(stderr, "Migration failed rc=%d\n", rc);
9521 exit(rc);
9526 /* XXX: simplify init */
9527 read_passwords();
9528 if (autostart) {
9529 vm_start();
9533 if (daemonize) {
9534 uint8_t status = 0;
9535 ssize_t len;
9536 int fd;
9538 again1:
9539 len = write(fds[1], &status, 1);
9540 if (len == -1 && (errno == EINTR))
9541 goto again1;
9543 if (len != 1)
9544 exit(1);
9546 chdir("/");
9547 TFR(fd = open("/dev/null", O_RDWR));
9548 if (fd == -1)
9549 exit(1);
9551 dup2(fd, 0);
9552 dup2(fd, 1);
9553 dup2(fd, 2);
9555 close(fd);
9558 main_loop();
9559 quit_timers();
9561 #if !defined(_WIN32)
9562 /* close network clients */
9563 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9564 VLANClientState *vc;
9566 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9567 if (vc->fd_read == tap_receive) {
9568 char ifname[64];
9569 TAPState *s = vc->opaque;
9571 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9572 s->down_script[0])
9573 launch_script(s->down_script, ifname, s->fd);
9577 #endif
9578 return 0;