Pci hotplug GPE support
[qemu-kvm/fedora.git] / vl.c
blob21c9b53c719e4751348af59514a3da37868df3af
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/fdc.h"
30 #include "hw/audiodev.h"
31 #include "hw/isa.h"
32 #include "net.h"
33 #include "console.h"
34 #include "sysemu.h"
35 #include "gdbstub.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
38 #include "block.h"
39 #include "audio/audio.h"
40 #include "migration.h"
41 #include "qemu-kvm.h"
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <time.h>
47 #include <errno.h>
48 #include <sys/time.h>
49 #include <zlib.h>
51 #ifndef _WIN32
52 #include <sys/times.h>
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <sys/poll.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <dirent.h>
61 #include <netdb.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
64 #ifdef _BSD
65 #include <sys/stat.h>
66 #ifndef __APPLE__
67 #include <libutil.h>
68 #endif
69 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
70 #include <freebsd/stdlib.h>
71 #else
72 #ifndef __sun__
73 #include <linux/if.h>
74 #include <linux/if_tun.h>
75 #include <pty.h>
76 #include <malloc.h>
77 #include <linux/rtc.h>
79 /* For the benefit of older linux systems which don't supply it,
80 we use a local copy of hpet.h. */
81 /* #include <linux/hpet.h> */
82 #include "hpet.h"
84 #include <linux/ppdev.h>
85 #include <linux/parport.h>
86 #else
87 #include <sys/stat.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
97 #include <net/if.h>
98 #include <syslog.h>
99 #include <stropts.h>
100 #endif
101 #endif
102 #else
103 #include <winsock2.h>
104 int inet_aton(const char *cp, struct in_addr *ia);
105 #endif
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
109 #endif
111 #ifdef _WIN32
112 #include <malloc.h>
113 #include <sys/timeb.h>
114 #include <mmsystem.h>
115 #define getopt_long_only getopt_long
116 #define memalign(align, size) malloc(size)
117 #endif
119 #include "qemu_socket.h"
121 #ifdef CONFIG_SDL
122 #ifdef __APPLE__
123 #include <SDL/SDL.h>
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "disas.h"
134 #include "exec-all.h"
136 #include "qemu-kvm.h"
138 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
140 #ifdef __sun__
141 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
142 #else
143 #define SMBD_COMMAND "/usr/sbin/smbd"
144 #endif
146 //#define DEBUG_UNUSED_IOPORT
147 //#define DEBUG_IOPORT
149 #if HOST_LONG_BITS < 64
150 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
151 #else
152 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024 * 1024ULL)
153 #endif
155 #ifdef TARGET_PPC
156 #define DEFAULT_RAM_SIZE 144
157 #else
158 #define DEFAULT_RAM_SIZE 128
159 #endif
160 /* in ms */
161 #define GUI_REFRESH_INTERVAL 30
163 /* Max number of USB devices that can be specified on the commandline. */
164 #define MAX_USB_CMDLINE 8
166 /* XXX: use a two level table to limit memory usage */
167 #define MAX_IOPORTS 65536
169 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
170 const char *bios_name = NULL;
171 void *ioport_opaque[MAX_IOPORTS];
172 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
173 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 DriveInfo drives_table[MAX_DRIVES+1];
177 int nb_drives;
178 int extboot_drive = -1;
179 /* point to the block driver where the snapshots are managed */
180 BlockDriverState *bs_snapshots;
181 int vga_ram_size;
182 static DisplayState display_state;
183 int nographic;
184 int curses;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
187 int64_t ram_size;
188 int pit_min_timer_count = 0;
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int cirrus_vga_enabled = 1;
195 int vmsvga_enabled = 0;
196 #ifdef TARGET_SPARC
197 int graphic_width = 1024;
198 int graphic_height = 768;
199 int graphic_depth = 8;
200 #else
201 int graphic_width = 800;
202 int graphic_height = 600;
203 int graphic_depth = 15;
204 #endif
205 int full_screen = 0;
206 int no_frame = 0;
207 int no_quit = 0;
208 int balloon_used = 0;
209 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
210 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
211 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
212 #ifdef TARGET_I386
213 int win2k_install_hack = 0;
214 #endif
215 int usb_enabled = 0;
216 static VLANState *first_vlan;
217 int smp_cpus = 1;
218 const char *vnc_display;
219 #if defined(TARGET_SPARC)
220 #define MAX_CPUS 16
221 #elif defined(TARGET_I386)
222 #define MAX_CPUS 255
223 #elif defined(TARGET_IA64)
224 #define MAX_CPUS 4
225 #else
226 #define MAX_CPUS 1
227 #endif
228 int acpi_enabled = 1;
229 int fd_bootchk = 1;
230 int no_reboot = 0;
231 int cursor_hide = 1;
232 int graphic_rotate = 0;
233 int daemonize = 0;
234 const char *incoming;
235 const char *option_rom[MAX_OPTION_ROMS];
236 int nb_option_roms;
237 int semihosting_enabled = 0;
238 int autostart = 1;
239 int time_drift_fix = 0;
240 unsigned int kvm_shadow_memory = 0;
241 const char *mem_path = NULL;
242 int hpagesize = 0;
243 const char *cpu_vendor_string;
244 #ifdef TARGET_ARM
245 int old_param = 0;
246 #endif
247 const char *qemu_name;
248 int alt_grab = 0;
249 #ifdef TARGET_SPARC
250 unsigned int nb_prom_envs = 0;
251 const char *prom_envs[MAX_PROM_ENVS];
252 #endif
253 int nb_drives_opt;
254 struct drive_opt {
255 const char *file;
256 char opt[1024];
257 } drives_opt[MAX_DRIVES];
259 static CPUState *cur_cpu;
260 static CPUState *next_cpu;
261 static int event_pending = 1;
263 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
265 void decorate_application_name(char *appname, int max_len)
267 if (kvm_enabled())
269 int remain = max_len - strlen(appname) - 1;
271 if (remain > 0)
272 strncat(appname, "/KVM", remain);
276 /***********************************************************/
277 /* x86 ISA bus support */
279 target_phys_addr_t isa_mem_base = 0;
280 PicState2 *isa_pic;
282 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
284 #ifdef DEBUG_UNUSED_IOPORT
285 fprintf(stderr, "unused inb: port=0x%04x\n", address);
286 #endif
287 return 0xff;
290 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
292 #ifdef DEBUG_UNUSED_IOPORT
293 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
294 #endif
297 /* default is to make two byte accesses */
298 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
300 uint32_t data;
301 data = ioport_read_table[0][address](ioport_opaque[address], address);
302 address = (address + 1) & (MAX_IOPORTS - 1);
303 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
304 return data;
307 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
309 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
310 address = (address + 1) & (MAX_IOPORTS - 1);
311 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
314 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
316 #ifdef DEBUG_UNUSED_IOPORT
317 fprintf(stderr, "unused inl: port=0x%04x\n", address);
318 #endif
319 return 0xffffffff;
322 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
324 #ifdef DEBUG_UNUSED_IOPORT
325 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
326 #endif
329 static void init_ioports(void)
331 int i;
333 for(i = 0; i < MAX_IOPORTS; i++) {
334 ioport_read_table[0][i] = default_ioport_readb;
335 ioport_write_table[0][i] = default_ioport_writeb;
336 ioport_read_table[1][i] = default_ioport_readw;
337 ioport_write_table[1][i] = default_ioport_writew;
338 ioport_read_table[2][i] = default_ioport_readl;
339 ioport_write_table[2][i] = default_ioport_writel;
343 /* size is the word size in byte */
344 int register_ioport_read(int start, int length, int size,
345 IOPortReadFunc *func, void *opaque)
347 int i, bsize;
349 if (size == 1) {
350 bsize = 0;
351 } else if (size == 2) {
352 bsize = 1;
353 } else if (size == 4) {
354 bsize = 2;
355 } else {
356 hw_error("register_ioport_read: invalid size");
357 return -1;
359 for(i = start; i < start + length; i += size) {
360 ioport_read_table[bsize][i] = func;
361 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
362 hw_error("register_ioport_read: invalid opaque");
363 ioport_opaque[i] = opaque;
365 return 0;
368 /* size is the word size in byte */
369 int register_ioport_write(int start, int length, int size,
370 IOPortWriteFunc *func, void *opaque)
372 int i, bsize;
374 if (size == 1) {
375 bsize = 0;
376 } else if (size == 2) {
377 bsize = 1;
378 } else if (size == 4) {
379 bsize = 2;
380 } else {
381 hw_error("register_ioport_write: invalid size");
382 return -1;
384 for(i = start; i < start + length; i += size) {
385 ioport_write_table[bsize][i] = func;
386 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
387 hw_error("register_ioport_write: invalid opaque");
388 ioport_opaque[i] = opaque;
390 return 0;
393 void isa_unassign_ioport(int start, int length)
395 int i;
397 for(i = start; i < start + length; i++) {
398 ioport_read_table[0][i] = default_ioport_readb;
399 ioport_read_table[1][i] = default_ioport_readw;
400 ioport_read_table[2][i] = default_ioport_readl;
402 ioport_write_table[0][i] = default_ioport_writeb;
403 ioport_write_table[1][i] = default_ioport_writew;
404 ioport_write_table[2][i] = default_ioport_writel;
408 /***********************************************************/
410 void cpu_outb(CPUState *env, int addr, int val)
412 #ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "outb: %04x %02x\n", addr, val);
415 #endif
416 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
417 #ifdef USE_KQEMU
418 if (env)
419 env->last_io_time = cpu_get_time_fast();
420 #endif
423 void cpu_outw(CPUState *env, int addr, int val)
425 #ifdef DEBUG_IOPORT
426 if (loglevel & CPU_LOG_IOPORT)
427 fprintf(logfile, "outw: %04x %04x\n", addr, val);
428 #endif
429 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
430 #ifdef USE_KQEMU
431 if (env)
432 env->last_io_time = cpu_get_time_fast();
433 #endif
436 void cpu_outl(CPUState *env, int addr, int val)
438 #ifdef DEBUG_IOPORT
439 if (loglevel & CPU_LOG_IOPORT)
440 fprintf(logfile, "outl: %04x %08x\n", addr, val);
441 #endif
442 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
443 #ifdef USE_KQEMU
444 if (env)
445 env->last_io_time = cpu_get_time_fast();
446 #endif
449 int cpu_inb(CPUState *env, int addr)
451 int val;
452 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
453 #ifdef DEBUG_IOPORT
454 if (loglevel & CPU_LOG_IOPORT)
455 fprintf(logfile, "inb : %04x %02x\n", addr, val);
456 #endif
457 #ifdef USE_KQEMU
458 if (env)
459 env->last_io_time = cpu_get_time_fast();
460 #endif
461 return val;
464 int cpu_inw(CPUState *env, int addr)
466 int val;
467 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
468 #ifdef DEBUG_IOPORT
469 if (loglevel & CPU_LOG_IOPORT)
470 fprintf(logfile, "inw : %04x %04x\n", addr, val);
471 #endif
472 #ifdef USE_KQEMU
473 if (env)
474 env->last_io_time = cpu_get_time_fast();
475 #endif
476 return val;
479 int cpu_inl(CPUState *env, int addr)
481 int val;
482 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
483 #ifdef DEBUG_IOPORT
484 if (loglevel & CPU_LOG_IOPORT)
485 fprintf(logfile, "inl : %04x %08x\n", addr, val);
486 #endif
487 #ifdef USE_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
491 return val;
494 /***********************************************************/
495 void hw_error(const char *fmt, ...)
497 va_list ap;
498 CPUState *env;
500 va_start(ap, fmt);
501 fprintf(stderr, "qemu: hardware error: ");
502 vfprintf(stderr, fmt, ap);
503 fprintf(stderr, "\n");
504 for(env = first_cpu; env != NULL; env = env->next_cpu) {
505 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
506 #ifdef TARGET_I386
507 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
508 #else
509 cpu_dump_state(env, stderr, fprintf, 0);
510 #endif
512 va_end(ap);
513 abort();
516 /***********************************************************/
517 /* keyboard/mouse */
519 static QEMUPutKBDEvent *qemu_put_kbd_event;
520 static void *qemu_put_kbd_event_opaque;
521 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
522 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
524 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
526 qemu_put_kbd_event_opaque = opaque;
527 qemu_put_kbd_event = func;
530 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
531 void *opaque, int absolute,
532 const char *name)
534 QEMUPutMouseEntry *s, *cursor;
536 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
537 if (!s)
538 return NULL;
540 s->qemu_put_mouse_event = func;
541 s->qemu_put_mouse_event_opaque = opaque;
542 s->qemu_put_mouse_event_absolute = absolute;
543 s->qemu_put_mouse_event_name = qemu_strdup(name);
544 s->next = NULL;
546 if (!qemu_put_mouse_event_head) {
547 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
548 return s;
551 cursor = qemu_put_mouse_event_head;
552 while (cursor->next != NULL)
553 cursor = cursor->next;
555 cursor->next = s;
556 qemu_put_mouse_event_current = s;
558 return s;
561 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
563 QEMUPutMouseEntry *prev = NULL, *cursor;
565 if (!qemu_put_mouse_event_head || entry == NULL)
566 return;
568 cursor = qemu_put_mouse_event_head;
569 while (cursor != NULL && cursor != entry) {
570 prev = cursor;
571 cursor = cursor->next;
574 if (cursor == NULL) // does not exist or list empty
575 return;
576 else if (prev == NULL) { // entry is head
577 qemu_put_mouse_event_head = cursor->next;
578 if (qemu_put_mouse_event_current == entry)
579 qemu_put_mouse_event_current = cursor->next;
580 qemu_free(entry->qemu_put_mouse_event_name);
581 qemu_free(entry);
582 return;
585 prev->next = entry->next;
587 if (qemu_put_mouse_event_current == entry)
588 qemu_put_mouse_event_current = prev;
590 qemu_free(entry->qemu_put_mouse_event_name);
591 qemu_free(entry);
594 void kbd_put_keycode(int keycode)
596 if (qemu_put_kbd_event) {
597 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
601 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
603 QEMUPutMouseEvent *mouse_event;
604 void *mouse_event_opaque;
605 int width;
607 if (!qemu_put_mouse_event_current) {
608 return;
611 mouse_event =
612 qemu_put_mouse_event_current->qemu_put_mouse_event;
613 mouse_event_opaque =
614 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
616 if (mouse_event) {
617 if (graphic_rotate) {
618 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
619 width = 0x7fff;
620 else
621 width = graphic_width;
622 mouse_event(mouse_event_opaque,
623 width - dy, dx, dz, buttons_state);
624 } else
625 mouse_event(mouse_event_opaque,
626 dx, dy, dz, buttons_state);
630 int kbd_mouse_is_absolute(void)
632 if (!qemu_put_mouse_event_current)
633 return 0;
635 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
638 void do_info_mice(void)
640 QEMUPutMouseEntry *cursor;
641 int index = 0;
643 if (!qemu_put_mouse_event_head) {
644 term_printf("No mouse devices connected\n");
645 return;
648 term_printf("Mouse devices available:\n");
649 cursor = qemu_put_mouse_event_head;
650 while (cursor != NULL) {
651 term_printf("%c Mouse #%d: %s\n",
652 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
653 index, cursor->qemu_put_mouse_event_name);
654 index++;
655 cursor = cursor->next;
659 void do_mouse_set(int index)
661 QEMUPutMouseEntry *cursor;
662 int i = 0;
664 if (!qemu_put_mouse_event_head) {
665 term_printf("No mouse devices connected\n");
666 return;
669 cursor = qemu_put_mouse_event_head;
670 while (cursor != NULL && index != i) {
671 i++;
672 cursor = cursor->next;
675 if (cursor != NULL)
676 qemu_put_mouse_event_current = cursor;
677 else
678 term_printf("Mouse at given index not found\n");
681 /* compute with 96 bit intermediate result: (a*b)/c */
682 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
684 union {
685 uint64_t ll;
686 struct {
687 #ifdef WORDS_BIGENDIAN
688 uint32_t high, low;
689 #else
690 uint32_t low, high;
691 #endif
692 } l;
693 } u, res;
694 uint64_t rl, rh;
696 u.ll = a;
697 rl = (uint64_t)u.l.low * (uint64_t)b;
698 rh = (uint64_t)u.l.high * (uint64_t)b;
699 rh += (rl >> 32);
700 res.l.high = rh / c;
701 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
702 return res.ll;
705 /***********************************************************/
706 /* real time host monotonic timer */
708 #define QEMU_TIMER_BASE 1000000000LL
710 #ifdef WIN32
712 static int64_t clock_freq;
714 static void init_get_clock(void)
716 LARGE_INTEGER freq;
717 int ret;
718 ret = QueryPerformanceFrequency(&freq);
719 if (ret == 0) {
720 fprintf(stderr, "Could not calibrate ticks\n");
721 exit(1);
723 clock_freq = freq.QuadPart;
726 static int64_t get_clock(void)
728 LARGE_INTEGER ti;
729 QueryPerformanceCounter(&ti);
730 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
733 #else
735 static int use_rt_clock;
737 static void init_get_clock(void)
739 use_rt_clock = 0;
740 #if defined(__linux__)
742 struct timespec ts;
743 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
744 use_rt_clock = 1;
747 #endif
750 static int64_t get_clock(void)
752 #if defined(__linux__)
753 if (use_rt_clock) {
754 struct timespec ts;
755 clock_gettime(CLOCK_MONOTONIC, &ts);
756 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
757 } else
758 #endif
760 /* XXX: using gettimeofday leads to problems if the date
761 changes, so it should be avoided. */
762 struct timeval tv;
763 gettimeofday(&tv, NULL);
764 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
768 #endif
770 /***********************************************************/
771 /* guest cycle counter */
773 static int64_t cpu_ticks_prev;
774 static int64_t cpu_ticks_offset;
775 static int64_t cpu_clock_offset;
776 static int cpu_ticks_enabled;
778 /* return the host CPU cycle counter and handle stop/restart */
779 int64_t cpu_get_ticks(void)
781 if (!cpu_ticks_enabled) {
782 return cpu_ticks_offset;
783 } else {
784 int64_t ticks;
785 ticks = cpu_get_real_ticks();
786 if (cpu_ticks_prev > ticks) {
787 /* Note: non increasing ticks may happen if the host uses
788 software suspend */
789 cpu_ticks_offset += cpu_ticks_prev - ticks;
791 cpu_ticks_prev = ticks;
792 return ticks + cpu_ticks_offset;
796 /* return the host CPU monotonic timer and handle stop/restart */
797 static int64_t cpu_get_clock(void)
799 int64_t ti;
800 if (!cpu_ticks_enabled) {
801 return cpu_clock_offset;
802 } else {
803 ti = get_clock();
804 return ti + cpu_clock_offset;
808 /* enable cpu_get_ticks() */
809 void cpu_enable_ticks(void)
811 if (!cpu_ticks_enabled) {
812 cpu_ticks_offset -= cpu_get_real_ticks();
813 cpu_clock_offset -= get_clock();
814 cpu_ticks_enabled = 1;
818 /* disable cpu_get_ticks() : the clock is stopped. You must not call
819 cpu_get_ticks() after that. */
820 void cpu_disable_ticks(void)
822 if (cpu_ticks_enabled) {
823 cpu_ticks_offset = cpu_get_ticks();
824 cpu_clock_offset = cpu_get_clock();
825 cpu_ticks_enabled = 0;
829 /***********************************************************/
830 /* timers */
832 #define QEMU_TIMER_REALTIME 0
833 #define QEMU_TIMER_VIRTUAL 1
835 struct QEMUClock {
836 int type;
837 /* XXX: add frequency */
840 struct QEMUTimer {
841 QEMUClock *clock;
842 int64_t expire_time;
843 QEMUTimerCB *cb;
844 void *opaque;
845 struct QEMUTimer *next;
848 struct qemu_alarm_timer {
849 char const *name;
850 unsigned int flags;
852 int (*start)(struct qemu_alarm_timer *t);
853 void (*stop)(struct qemu_alarm_timer *t);
854 void (*rearm)(struct qemu_alarm_timer *t);
855 void *priv;
858 #define ALARM_FLAG_DYNTICKS 0x1
859 #define ALARM_FLAG_EXPIRED 0x2
861 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
863 return t->flags & ALARM_FLAG_DYNTICKS;
866 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
868 if (!alarm_has_dynticks(t))
869 return;
871 t->rearm(t);
874 /* TODO: MIN_TIMER_REARM_US should be optimized */
875 #define MIN_TIMER_REARM_US 250
877 static struct qemu_alarm_timer *alarm_timer;
879 #ifdef _WIN32
881 struct qemu_alarm_win32 {
882 MMRESULT timerId;
883 HANDLE host_alarm;
884 unsigned int period;
885 } alarm_win32_data = {0, NULL, -1};
887 static int win32_start_timer(struct qemu_alarm_timer *t);
888 static void win32_stop_timer(struct qemu_alarm_timer *t);
889 static void win32_rearm_timer(struct qemu_alarm_timer *t);
891 #else
893 static int unix_start_timer(struct qemu_alarm_timer *t);
894 static void unix_stop_timer(struct qemu_alarm_timer *t);
896 #ifdef __linux__
898 static int dynticks_start_timer(struct qemu_alarm_timer *t);
899 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
900 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
902 static int hpet_start_timer(struct qemu_alarm_timer *t);
903 static void hpet_stop_timer(struct qemu_alarm_timer *t);
905 static int rtc_start_timer(struct qemu_alarm_timer *t);
906 static void rtc_stop_timer(struct qemu_alarm_timer *t);
908 #endif /* __linux__ */
910 #endif /* _WIN32 */
912 static struct qemu_alarm_timer alarm_timers[] = {
913 #ifndef _WIN32
914 #ifdef __linux__
915 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
916 dynticks_stop_timer, dynticks_rearm_timer, NULL},
917 /* HPET - if available - is preferred */
918 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
919 /* ...otherwise try RTC */
920 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
921 #endif
922 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
923 #else
924 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
925 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
926 {"win32", 0, win32_start_timer,
927 win32_stop_timer, NULL, &alarm_win32_data},
928 #endif
929 {NULL, }
932 static void show_available_alarms()
934 int i;
936 printf("Available alarm timers, in order of precedence:\n");
937 for (i = 0; alarm_timers[i].name; i++)
938 printf("%s\n", alarm_timers[i].name);
941 static void configure_alarms(char const *opt)
943 int i;
944 int cur = 0;
945 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
946 char *arg;
947 char *name;
949 if (!strcmp(opt, "help")) {
950 show_available_alarms();
951 exit(0);
954 arg = strdup(opt);
956 /* Reorder the array */
957 name = strtok(arg, ",");
958 while (name) {
959 struct qemu_alarm_timer tmp;
961 for (i = 0; i < count && alarm_timers[i].name; i++) {
962 if (!strcmp(alarm_timers[i].name, name))
963 break;
966 if (i == count) {
967 fprintf(stderr, "Unknown clock %s\n", name);
968 goto next;
971 if (i < cur)
972 /* Ignore */
973 goto next;
975 /* Swap */
976 tmp = alarm_timers[i];
977 alarm_timers[i] = alarm_timers[cur];
978 alarm_timers[cur] = tmp;
980 cur++;
981 next:
982 name = strtok(NULL, ",");
985 free(arg);
987 if (cur) {
988 /* Disable remaining timers */
989 for (i = cur; i < count; i++)
990 alarm_timers[i].name = NULL;
993 /* debug */
994 show_available_alarms();
997 QEMUClock *rt_clock;
998 QEMUClock *vm_clock;
1000 static QEMUTimer *active_timers[2];
1002 static QEMUClock *qemu_new_clock(int type)
1004 QEMUClock *clock;
1005 clock = qemu_mallocz(sizeof(QEMUClock));
1006 if (!clock)
1007 return NULL;
1008 clock->type = type;
1009 return clock;
1012 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1014 QEMUTimer *ts;
1016 ts = qemu_mallocz(sizeof(QEMUTimer));
1017 ts->clock = clock;
1018 ts->cb = cb;
1019 ts->opaque = opaque;
1020 return ts;
1023 void qemu_free_timer(QEMUTimer *ts)
1025 qemu_free(ts);
1028 /* stop a timer, but do not dealloc it */
1029 void qemu_del_timer(QEMUTimer *ts)
1031 QEMUTimer **pt, *t;
1033 /* NOTE: this code must be signal safe because
1034 qemu_timer_expired() can be called from a signal. */
1035 pt = &active_timers[ts->clock->type];
1036 for(;;) {
1037 t = *pt;
1038 if (!t)
1039 break;
1040 if (t == ts) {
1041 *pt = t->next;
1042 break;
1044 pt = &t->next;
1048 /* modify the current timer so that it will be fired when current_time
1049 >= expire_time. The corresponding callback will be called. */
1050 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1052 QEMUTimer **pt, *t;
1054 qemu_del_timer(ts);
1056 /* add the timer in the sorted list */
1057 /* NOTE: this code must be signal safe because
1058 qemu_timer_expired() can be called from a signal. */
1059 pt = &active_timers[ts->clock->type];
1060 for(;;) {
1061 t = *pt;
1062 if (!t)
1063 break;
1064 if (t->expire_time > expire_time)
1065 break;
1066 pt = &t->next;
1068 ts->expire_time = expire_time;
1069 ts->next = *pt;
1070 *pt = ts;
1072 /* Rearm if necessary */
1073 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1074 pt == &active_timers[ts->clock->type])
1075 qemu_rearm_alarm_timer(alarm_timer);
1078 int qemu_timer_pending(QEMUTimer *ts)
1080 QEMUTimer *t;
1081 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1082 if (t == ts)
1083 return 1;
1085 return 0;
1088 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1090 if (!timer_head)
1091 return 0;
1092 return (timer_head->expire_time <= current_time);
1095 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1097 QEMUTimer *ts;
1099 for(;;) {
1100 ts = *ptimer_head;
1101 if (!ts || ts->expire_time > current_time)
1102 break;
1103 /* remove timer from the list before calling the callback */
1104 *ptimer_head = ts->next;
1105 ts->next = NULL;
1107 /* run the callback (the timer list can be modified) */
1108 ts->cb(ts->opaque);
1112 int64_t qemu_get_clock(QEMUClock *clock)
1114 switch(clock->type) {
1115 case QEMU_TIMER_REALTIME:
1116 return get_clock() / 1000000;
1117 default:
1118 case QEMU_TIMER_VIRTUAL:
1119 return cpu_get_clock();
1123 static void init_timers(void)
1125 init_get_clock();
1126 ticks_per_sec = QEMU_TIMER_BASE;
1127 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1128 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1131 /* save a timer */
1132 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1134 uint64_t expire_time;
1136 if (qemu_timer_pending(ts)) {
1137 expire_time = ts->expire_time;
1138 } else {
1139 expire_time = -1;
1141 qemu_put_be64(f, expire_time);
1144 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1146 uint64_t expire_time;
1148 expire_time = qemu_get_be64(f);
1149 if (expire_time != -1) {
1150 qemu_mod_timer(ts, expire_time);
1151 } else {
1152 qemu_del_timer(ts);
1156 static void timer_save(QEMUFile *f, void *opaque)
1158 if (cpu_ticks_enabled) {
1159 hw_error("cannot save state if virtual timers are running");
1161 qemu_put_be64(f, cpu_ticks_offset);
1162 qemu_put_be64(f, ticks_per_sec);
1163 qemu_put_be64(f, cpu_clock_offset);
1166 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1168 if (version_id != 1 && version_id != 2)
1169 return -EINVAL;
1170 if (cpu_ticks_enabled) {
1171 return -EINVAL;
1173 cpu_ticks_offset=qemu_get_be64(f);
1174 ticks_per_sec=qemu_get_be64(f);
1175 if (version_id == 2) {
1176 cpu_clock_offset=qemu_get_be64(f);
1178 return 0;
1181 #ifdef _WIN32
1182 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1183 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1184 #else
1185 static void host_alarm_handler(int host_signum)
1186 #endif
1188 #if 0
1189 #define DISP_FREQ 1000
1191 static int64_t delta_min = INT64_MAX;
1192 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1193 static int count;
1194 ti = qemu_get_clock(vm_clock);
1195 if (last_clock != 0) {
1196 delta = ti - last_clock;
1197 if (delta < delta_min)
1198 delta_min = delta;
1199 if (delta > delta_max)
1200 delta_max = delta;
1201 delta_cum += delta;
1202 if (++count == DISP_FREQ) {
1203 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1204 muldiv64(delta_min, 1000000, ticks_per_sec),
1205 muldiv64(delta_max, 1000000, ticks_per_sec),
1206 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1207 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1208 count = 0;
1209 delta_min = INT64_MAX;
1210 delta_max = 0;
1211 delta_cum = 0;
1214 last_clock = ti;
1216 #endif
1217 if (1 ||
1218 alarm_has_dynticks(alarm_timer) ||
1219 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1220 qemu_get_clock(vm_clock)) ||
1221 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1222 qemu_get_clock(rt_clock))) {
1223 #ifdef _WIN32
1224 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1225 SetEvent(data->host_alarm);
1226 #endif
1227 CPUState *env = next_cpu;
1229 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1231 if (env) {
1232 /* stop the currently executing cpu because a timer occured */
1233 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1234 #ifdef USE_KQEMU
1235 if (env->kqemu_enabled) {
1236 kqemu_cpu_interrupt(env);
1238 #endif
1240 event_pending = 1;
1244 static uint64_t qemu_next_deadline(void)
1246 int64_t nearest_delta_us = INT64_MAX;
1247 int64_t vmdelta_us;
1249 if (active_timers[QEMU_TIMER_REALTIME])
1250 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1251 qemu_get_clock(rt_clock))*1000;
1253 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1254 /* round up */
1255 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1256 qemu_get_clock(vm_clock)+999)/1000;
1257 if (vmdelta_us < nearest_delta_us)
1258 nearest_delta_us = vmdelta_us;
1261 /* Avoid arming the timer to negative, zero, or too low values */
1262 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1263 nearest_delta_us = MIN_TIMER_REARM_US;
1265 return nearest_delta_us;
1268 #ifndef _WIN32
1270 #if defined(__linux__)
1272 #define RTC_FREQ 1024
1274 static void enable_sigio_timer(int fd)
1276 struct sigaction act;
1278 /* timer signal */
1279 sigfillset(&act.sa_mask);
1280 act.sa_flags = 0;
1281 act.sa_handler = host_alarm_handler;
1283 sigaction(SIGIO, &act, NULL);
1284 fcntl(fd, F_SETFL, O_ASYNC);
1285 fcntl(fd, F_SETOWN, getpid());
1288 static int hpet_start_timer(struct qemu_alarm_timer *t)
1290 struct hpet_info info;
1291 int r, fd;
1293 fd = open("/dev/hpet", O_RDONLY);
1294 if (fd < 0)
1295 return -1;
1297 /* Set frequency */
1298 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1299 if (r < 0) {
1300 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1301 "error, but for better emulation accuracy type:\n"
1302 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1303 goto fail;
1306 /* Check capabilities */
1307 r = ioctl(fd, HPET_INFO, &info);
1308 if (r < 0)
1309 goto fail;
1311 /* Enable periodic mode */
1312 r = ioctl(fd, HPET_EPI, 0);
1313 if (info.hi_flags && (r < 0))
1314 goto fail;
1316 /* Enable interrupt */
1317 r = ioctl(fd, HPET_IE_ON, 0);
1318 if (r < 0)
1319 goto fail;
1321 enable_sigio_timer(fd);
1322 t->priv = (void *)(long)fd;
1324 return 0;
1325 fail:
1326 close(fd);
1327 return -1;
1330 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1332 int fd = (long)t->priv;
1334 close(fd);
1337 static int rtc_start_timer(struct qemu_alarm_timer *t)
1339 int rtc_fd;
1340 unsigned long current_rtc_freq = 0;
1342 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1343 if (rtc_fd < 0)
1344 return -1;
1345 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1346 if (current_rtc_freq != RTC_FREQ &&
1347 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1348 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1349 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1350 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1351 goto fail;
1353 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1354 fail:
1355 close(rtc_fd);
1356 return -1;
1359 enable_sigio_timer(rtc_fd);
1361 t->priv = (void *)(long)rtc_fd;
1363 return 0;
1366 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1368 int rtc_fd = (long)t->priv;
1370 close(rtc_fd);
1373 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1375 struct sigevent ev;
1376 timer_t host_timer;
1377 struct sigaction act;
1379 sigfillset(&act.sa_mask);
1380 act.sa_flags = 0;
1381 act.sa_handler = host_alarm_handler;
1383 sigaction(SIGALRM, &act, NULL);
1385 ev.sigev_value.sival_int = 0;
1386 ev.sigev_notify = SIGEV_SIGNAL;
1387 ev.sigev_signo = SIGALRM;
1389 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1390 perror("timer_create");
1392 /* disable dynticks */
1393 fprintf(stderr, "Dynamic Ticks disabled\n");
1395 return -1;
1398 t->priv = (void *)host_timer;
1400 return 0;
1403 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1405 timer_t host_timer = (timer_t)t->priv;
1407 timer_delete(host_timer);
1410 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1412 timer_t host_timer = (timer_t)t->priv;
1413 struct itimerspec timeout;
1414 int64_t nearest_delta_us = INT64_MAX;
1415 int64_t current_us;
1417 if (!active_timers[QEMU_TIMER_REALTIME] &&
1418 !active_timers[QEMU_TIMER_VIRTUAL])
1419 return;
1421 nearest_delta_us = qemu_next_deadline();
1423 /* check whether a timer is already running */
1424 if (timer_gettime(host_timer, &timeout)) {
1425 perror("gettime");
1426 fprintf(stderr, "Internal timer error: aborting\n");
1427 exit(1);
1429 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1430 if (current_us && current_us <= nearest_delta_us)
1431 return;
1433 timeout.it_interval.tv_sec = 0;
1434 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1435 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1436 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1437 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1438 perror("settime");
1439 fprintf(stderr, "Internal timer error: aborting\n");
1440 exit(1);
1444 #endif /* defined(__linux__) */
1446 static int unix_start_timer(struct qemu_alarm_timer *t)
1448 struct sigaction act;
1449 struct itimerval itv;
1450 int err;
1452 /* timer signal */
1453 sigfillset(&act.sa_mask);
1454 act.sa_flags = 0;
1455 act.sa_handler = host_alarm_handler;
1457 sigaction(SIGALRM, &act, NULL);
1459 itv.it_interval.tv_sec = 0;
1460 /* for i386 kernel 2.6 to get 1 ms */
1461 itv.it_interval.tv_usec = 999;
1462 itv.it_value.tv_sec = 0;
1463 itv.it_value.tv_usec = 10 * 1000;
1465 err = setitimer(ITIMER_REAL, &itv, NULL);
1466 if (err)
1467 return -1;
1469 return 0;
1472 static void unix_stop_timer(struct qemu_alarm_timer *t)
1474 struct itimerval itv;
1476 memset(&itv, 0, sizeof(itv));
1477 setitimer(ITIMER_REAL, &itv, NULL);
1480 #endif /* !defined(_WIN32) */
1482 #ifdef _WIN32
1484 static int win32_start_timer(struct qemu_alarm_timer *t)
1486 TIMECAPS tc;
1487 struct qemu_alarm_win32 *data = t->priv;
1488 UINT flags;
1490 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1491 if (!data->host_alarm) {
1492 perror("Failed CreateEvent");
1493 return -1;
1496 memset(&tc, 0, sizeof(tc));
1497 timeGetDevCaps(&tc, sizeof(tc));
1499 if (data->period < tc.wPeriodMin)
1500 data->period = tc.wPeriodMin;
1502 timeBeginPeriod(data->period);
1504 flags = TIME_CALLBACK_FUNCTION;
1505 if (alarm_has_dynticks(t))
1506 flags |= TIME_ONESHOT;
1507 else
1508 flags |= TIME_PERIODIC;
1510 data->timerId = timeSetEvent(1, // interval (ms)
1511 data->period, // resolution
1512 host_alarm_handler, // function
1513 (DWORD)t, // parameter
1514 flags);
1516 if (!data->timerId) {
1517 perror("Failed to initialize win32 alarm timer");
1519 timeEndPeriod(data->period);
1520 CloseHandle(data->host_alarm);
1521 return -1;
1524 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1526 return 0;
1529 static void win32_stop_timer(struct qemu_alarm_timer *t)
1531 struct qemu_alarm_win32 *data = t->priv;
1533 timeKillEvent(data->timerId);
1534 timeEndPeriod(data->period);
1536 CloseHandle(data->host_alarm);
1539 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1541 struct qemu_alarm_win32 *data = t->priv;
1542 uint64_t nearest_delta_us;
1544 if (!active_timers[QEMU_TIMER_REALTIME] &&
1545 !active_timers[QEMU_TIMER_VIRTUAL])
1546 return;
1548 nearest_delta_us = qemu_next_deadline();
1549 nearest_delta_us /= 1000;
1551 timeKillEvent(data->timerId);
1553 data->timerId = timeSetEvent(1,
1554 data->period,
1555 host_alarm_handler,
1556 (DWORD)t,
1557 TIME_ONESHOT | TIME_PERIODIC);
1559 if (!data->timerId) {
1560 perror("Failed to re-arm win32 alarm timer");
1562 timeEndPeriod(data->period);
1563 CloseHandle(data->host_alarm);
1564 exit(1);
1568 #endif /* _WIN32 */
1570 static void init_timer_alarm(void)
1572 struct qemu_alarm_timer *t;
1573 int i, err = -1;
1575 for (i = 0; alarm_timers[i].name; i++) {
1576 t = &alarm_timers[i];
1578 err = t->start(t);
1579 if (!err)
1580 break;
1583 if (err) {
1584 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1585 fprintf(stderr, "Terminating\n");
1586 exit(1);
1589 alarm_timer = t;
1592 static void quit_timers(void)
1594 alarm_timer->stop(alarm_timer);
1595 alarm_timer = NULL;
1598 /***********************************************************/
1599 /* host time/date access */
1600 void qemu_get_timedate(struct tm *tm, int offset)
1602 time_t ti;
1603 struct tm *ret;
1605 time(&ti);
1606 ti += offset;
1607 if (rtc_date_offset == -1) {
1608 if (rtc_utc)
1609 ret = gmtime(&ti);
1610 else
1611 ret = localtime(&ti);
1612 } else {
1613 ti -= rtc_date_offset;
1614 ret = gmtime(&ti);
1617 memcpy(tm, ret, sizeof(struct tm));
1620 int qemu_timedate_diff(struct tm *tm)
1622 time_t seconds;
1624 if (rtc_date_offset == -1)
1625 if (rtc_utc)
1626 seconds = mktimegm(tm);
1627 else
1628 seconds = mktime(tm);
1629 else
1630 seconds = mktimegm(tm) + rtc_date_offset;
1632 return seconds - time(NULL);
1635 /***********************************************************/
1636 /* character device */
1638 static void qemu_chr_event(CharDriverState *s, int event)
1640 if (!s->chr_event)
1641 return;
1642 s->chr_event(s->handler_opaque, event);
1645 static void qemu_chr_reset_bh(void *opaque)
1647 CharDriverState *s = opaque;
1648 qemu_chr_event(s, CHR_EVENT_RESET);
1649 qemu_bh_delete(s->bh);
1650 s->bh = NULL;
1653 void qemu_chr_reset(CharDriverState *s)
1655 if (s->bh == NULL) {
1656 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1657 qemu_bh_schedule(s->bh);
1661 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1663 return s->chr_write(s, buf, len);
1666 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1668 if (!s->chr_ioctl)
1669 return -ENOTSUP;
1670 return s->chr_ioctl(s, cmd, arg);
1673 int qemu_chr_can_read(CharDriverState *s)
1675 if (!s->chr_can_read)
1676 return 0;
1677 return s->chr_can_read(s->handler_opaque);
1680 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1682 s->chr_read(s->handler_opaque, buf, len);
1685 void qemu_chr_accept_input(CharDriverState *s)
1687 if (s->chr_accept_input)
1688 s->chr_accept_input(s);
1691 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1693 char buf[4096];
1694 va_list ap;
1695 va_start(ap, fmt);
1696 vsnprintf(buf, sizeof(buf), fmt, ap);
1697 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1698 va_end(ap);
1701 void qemu_chr_send_event(CharDriverState *s, int event)
1703 if (s->chr_send_event)
1704 s->chr_send_event(s, event);
1707 void qemu_chr_add_handlers(CharDriverState *s,
1708 IOCanRWHandler *fd_can_read,
1709 IOReadHandler *fd_read,
1710 IOEventHandler *fd_event,
1711 void *opaque)
1713 s->chr_can_read = fd_can_read;
1714 s->chr_read = fd_read;
1715 s->chr_event = fd_event;
1716 s->handler_opaque = opaque;
1717 if (s->chr_update_read_handler)
1718 s->chr_update_read_handler(s);
1721 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1723 return len;
1726 static CharDriverState *qemu_chr_open_null(void)
1728 CharDriverState *chr;
1730 chr = qemu_mallocz(sizeof(CharDriverState));
1731 if (!chr)
1732 return NULL;
1733 chr->chr_write = null_chr_write;
1734 return chr;
1737 /* MUX driver for serial I/O splitting */
1738 static int term_timestamps;
1739 static int64_t term_timestamps_start;
1740 #define MAX_MUX 4
1741 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1742 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1743 typedef struct {
1744 IOCanRWHandler *chr_can_read[MAX_MUX];
1745 IOReadHandler *chr_read[MAX_MUX];
1746 IOEventHandler *chr_event[MAX_MUX];
1747 void *ext_opaque[MAX_MUX];
1748 CharDriverState *drv;
1749 unsigned char buffer[MUX_BUFFER_SIZE];
1750 int prod;
1751 int cons;
1752 int mux_cnt;
1753 int term_got_escape;
1754 int max_size;
1755 } MuxDriver;
1758 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1760 MuxDriver *d = chr->opaque;
1761 int ret;
1762 if (!term_timestamps) {
1763 ret = d->drv->chr_write(d->drv, buf, len);
1764 } else {
1765 int i;
1767 ret = 0;
1768 for(i = 0; i < len; i++) {
1769 ret += d->drv->chr_write(d->drv, buf+i, 1);
1770 if (buf[i] == '\n') {
1771 char buf1[64];
1772 int64_t ti;
1773 int secs;
1775 ti = get_clock();
1776 if (term_timestamps_start == -1)
1777 term_timestamps_start = ti;
1778 ti -= term_timestamps_start;
1779 secs = ti / 1000000000;
1780 snprintf(buf1, sizeof(buf1),
1781 "[%02d:%02d:%02d.%03d] ",
1782 secs / 3600,
1783 (secs / 60) % 60,
1784 secs % 60,
1785 (int)((ti / 1000000) % 1000));
1786 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1790 return ret;
1793 static char *mux_help[] = {
1794 "% h print this help\n\r",
1795 "% x exit emulator\n\r",
1796 "% s save disk data back to file (if -snapshot)\n\r",
1797 "% t toggle console timestamps\n\r"
1798 "% b send break (magic sysrq)\n\r",
1799 "% c switch between console and monitor\n\r",
1800 "% % sends %\n\r",
1801 NULL
1804 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1805 static void mux_print_help(CharDriverState *chr)
1807 int i, j;
1808 char ebuf[15] = "Escape-Char";
1809 char cbuf[50] = "\n\r";
1811 if (term_escape_char > 0 && term_escape_char < 26) {
1812 sprintf(cbuf,"\n\r");
1813 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1814 } else {
1815 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1816 term_escape_char);
1818 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1819 for (i = 0; mux_help[i] != NULL; i++) {
1820 for (j=0; mux_help[i][j] != '\0'; j++) {
1821 if (mux_help[i][j] == '%')
1822 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1823 else
1824 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1829 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1831 if (d->term_got_escape) {
1832 d->term_got_escape = 0;
1833 if (ch == term_escape_char)
1834 goto send_char;
1835 switch(ch) {
1836 case '?':
1837 case 'h':
1838 mux_print_help(chr);
1839 break;
1840 case 'x':
1842 char *term = "QEMU: Terminated\n\r";
1843 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1844 exit(0);
1845 break;
1847 case 's':
1849 int i;
1850 for (i = 0; i < nb_drives; i++) {
1851 bdrv_commit(drives_table[i].bdrv);
1854 break;
1855 case 'b':
1856 qemu_chr_event(chr, CHR_EVENT_BREAK);
1857 break;
1858 case 'c':
1859 /* Switch to the next registered device */
1860 chr->focus++;
1861 if (chr->focus >= d->mux_cnt)
1862 chr->focus = 0;
1863 break;
1864 case 't':
1865 term_timestamps = !term_timestamps;
1866 term_timestamps_start = -1;
1867 break;
1869 } else if (ch == term_escape_char) {
1870 d->term_got_escape = 1;
1871 } else {
1872 send_char:
1873 return 1;
1875 return 0;
1878 static void mux_chr_accept_input(CharDriverState *chr)
1880 int m = chr->focus;
1881 MuxDriver *d = chr->opaque;
1883 while (d->prod != d->cons &&
1884 d->chr_can_read[m] &&
1885 d->chr_can_read[m](d->ext_opaque[m])) {
1886 d->chr_read[m](d->ext_opaque[m],
1887 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1891 static int mux_chr_can_read(void *opaque)
1893 CharDriverState *chr = opaque;
1894 MuxDriver *d = chr->opaque;
1896 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1897 return 1;
1898 if (d->chr_can_read[chr->focus])
1899 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1900 return 0;
1903 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1905 CharDriverState *chr = opaque;
1906 MuxDriver *d = chr->opaque;
1907 int m = chr->focus;
1908 int i;
1910 mux_chr_accept_input (opaque);
1912 for(i = 0; i < size; i++)
1913 if (mux_proc_byte(chr, d, buf[i])) {
1914 if (d->prod == d->cons &&
1915 d->chr_can_read[m] &&
1916 d->chr_can_read[m](d->ext_opaque[m]))
1917 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1918 else
1919 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1923 static void mux_chr_event(void *opaque, int event)
1925 CharDriverState *chr = opaque;
1926 MuxDriver *d = chr->opaque;
1927 int i;
1929 /* Send the event to all registered listeners */
1930 for (i = 0; i < d->mux_cnt; i++)
1931 if (d->chr_event[i])
1932 d->chr_event[i](d->ext_opaque[i], event);
1935 static void mux_chr_update_read_handler(CharDriverState *chr)
1937 MuxDriver *d = chr->opaque;
1939 if (d->mux_cnt >= MAX_MUX) {
1940 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1941 return;
1943 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1944 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1945 d->chr_read[d->mux_cnt] = chr->chr_read;
1946 d->chr_event[d->mux_cnt] = chr->chr_event;
1947 /* Fix up the real driver with mux routines */
1948 if (d->mux_cnt == 0) {
1949 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1950 mux_chr_event, chr);
1952 chr->focus = d->mux_cnt;
1953 d->mux_cnt++;
1956 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1958 CharDriverState *chr;
1959 MuxDriver *d;
1961 chr = qemu_mallocz(sizeof(CharDriverState));
1962 if (!chr)
1963 return NULL;
1964 d = qemu_mallocz(sizeof(MuxDriver));
1965 if (!d) {
1966 free(chr);
1967 return NULL;
1970 chr->opaque = d;
1971 d->drv = drv;
1972 chr->focus = -1;
1973 chr->chr_write = mux_chr_write;
1974 chr->chr_update_read_handler = mux_chr_update_read_handler;
1975 chr->chr_accept_input = mux_chr_accept_input;
1976 return chr;
1980 #ifdef _WIN32
1982 static void socket_cleanup(void)
1984 WSACleanup();
1987 static int socket_init(void)
1989 WSADATA Data;
1990 int ret, err;
1992 ret = WSAStartup(MAKEWORD(2,2), &Data);
1993 if (ret != 0) {
1994 err = WSAGetLastError();
1995 fprintf(stderr, "WSAStartup: %d\n", err);
1996 return -1;
1998 atexit(socket_cleanup);
1999 return 0;
2002 static int send_all(int fd, const uint8_t *buf, int len1)
2004 int ret, len;
2006 len = len1;
2007 while (len > 0) {
2008 ret = send(fd, buf, len, 0);
2009 if (ret < 0) {
2010 int errno;
2011 errno = WSAGetLastError();
2012 if (errno != WSAEWOULDBLOCK) {
2013 return -1;
2015 } else if (ret == 0) {
2016 break;
2017 } else {
2018 buf += ret;
2019 len -= ret;
2022 return len1 - len;
2025 void socket_set_nonblock(int fd)
2027 unsigned long opt = 1;
2028 ioctlsocket(fd, FIONBIO, &opt);
2031 #else
2033 static int unix_write(int fd, const uint8_t *buf, int len1)
2035 int ret, len;
2037 len = len1;
2038 while (len > 0) {
2039 ret = write(fd, buf, len);
2040 if (ret < 0) {
2041 if (errno != EINTR && errno != EAGAIN)
2042 return -1;
2043 } else if (ret == 0) {
2044 break;
2045 } else {
2046 buf += ret;
2047 len -= ret;
2050 return len1 - len;
2053 static inline int send_all(int fd, const uint8_t *buf, int len1)
2055 return unix_write(fd, buf, len1);
2058 void socket_set_nonblock(int fd)
2060 fcntl(fd, F_SETFL, O_NONBLOCK);
2062 #endif /* !_WIN32 */
2064 #ifndef _WIN32
2066 typedef struct {
2067 int fd_in, fd_out;
2068 int max_size;
2069 } FDCharDriver;
2071 #define STDIO_MAX_CLIENTS 1
2072 static int stdio_nb_clients = 0;
2074 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2076 FDCharDriver *s = chr->opaque;
2077 return unix_write(s->fd_out, buf, len);
2080 static int fd_chr_read_poll(void *opaque)
2082 CharDriverState *chr = opaque;
2083 FDCharDriver *s = chr->opaque;
2085 s->max_size = qemu_chr_can_read(chr);
2086 return s->max_size;
2089 static void fd_chr_read(void *opaque)
2091 CharDriverState *chr = opaque;
2092 FDCharDriver *s = chr->opaque;
2093 int size, len;
2094 uint8_t buf[1024];
2096 len = sizeof(buf);
2097 if (len > s->max_size)
2098 len = s->max_size;
2099 if (len == 0)
2100 return;
2101 size = read(s->fd_in, buf, len);
2102 if (size == 0) {
2103 /* FD has been closed. Remove it from the active list. */
2104 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2105 return;
2107 if (size > 0) {
2108 qemu_chr_read(chr, buf, size);
2112 static void fd_chr_update_read_handler(CharDriverState *chr)
2114 FDCharDriver *s = chr->opaque;
2116 if (s->fd_in >= 0) {
2117 if (nographic && s->fd_in == 0) {
2118 } else {
2119 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2120 fd_chr_read, NULL, chr);
2125 static void fd_chr_close(struct CharDriverState *chr)
2127 FDCharDriver *s = chr->opaque;
2129 if (s->fd_in >= 0) {
2130 if (nographic && s->fd_in == 0) {
2131 } else {
2132 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2136 qemu_free(s);
2139 /* open a character device to a unix fd */
2140 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2142 CharDriverState *chr;
2143 FDCharDriver *s;
2145 chr = qemu_mallocz(sizeof(CharDriverState));
2146 if (!chr)
2147 return NULL;
2148 s = qemu_mallocz(sizeof(FDCharDriver));
2149 if (!s) {
2150 free(chr);
2151 return NULL;
2153 s->fd_in = fd_in;
2154 s->fd_out = fd_out;
2155 chr->opaque = s;
2156 chr->chr_write = fd_chr_write;
2157 chr->chr_update_read_handler = fd_chr_update_read_handler;
2158 chr->chr_close = fd_chr_close;
2160 qemu_chr_reset(chr);
2162 return chr;
2165 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2167 int fd_out;
2169 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2170 if (fd_out < 0)
2171 return NULL;
2172 return qemu_chr_open_fd(-1, fd_out);
2175 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2177 int fd_in, fd_out;
2178 char filename_in[256], filename_out[256];
2180 snprintf(filename_in, 256, "%s.in", filename);
2181 snprintf(filename_out, 256, "%s.out", filename);
2182 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2183 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2184 if (fd_in < 0 || fd_out < 0) {
2185 if (fd_in >= 0)
2186 close(fd_in);
2187 if (fd_out >= 0)
2188 close(fd_out);
2189 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2190 if (fd_in < 0)
2191 return NULL;
2193 return qemu_chr_open_fd(fd_in, fd_out);
2197 /* for STDIO, we handle the case where several clients use it
2198 (nographic mode) */
2200 #define TERM_FIFO_MAX_SIZE 1
2202 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2203 static int term_fifo_size;
2205 static int stdio_read_poll(void *opaque)
2207 CharDriverState *chr = opaque;
2209 /* try to flush the queue if needed */
2210 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2211 qemu_chr_read(chr, term_fifo, 1);
2212 term_fifo_size = 0;
2214 /* see if we can absorb more chars */
2215 if (term_fifo_size == 0)
2216 return 1;
2217 else
2218 return 0;
2221 static void stdio_read(void *opaque)
2223 int size;
2224 uint8_t buf[1];
2225 CharDriverState *chr = opaque;
2227 size = read(0, buf, 1);
2228 if (size == 0) {
2229 /* stdin has been closed. Remove it from the active list. */
2230 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2231 return;
2233 if (size > 0) {
2234 if (qemu_chr_can_read(chr) > 0) {
2235 qemu_chr_read(chr, buf, 1);
2236 } else if (term_fifo_size == 0) {
2237 term_fifo[term_fifo_size++] = buf[0];
2242 /* init terminal so that we can grab keys */
2243 static struct termios oldtty;
2244 static int old_fd0_flags;
2245 static int term_atexit_done;
2247 static void term_exit(void)
2249 tcsetattr (0, TCSANOW, &oldtty);
2250 fcntl(0, F_SETFL, old_fd0_flags);
2253 static void term_init(void)
2255 struct termios tty;
2257 tcgetattr (0, &tty);
2258 oldtty = tty;
2259 old_fd0_flags = fcntl(0, F_GETFL);
2261 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2262 |INLCR|IGNCR|ICRNL|IXON);
2263 tty.c_oflag |= OPOST;
2264 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2265 /* if graphical mode, we allow Ctrl-C handling */
2266 if (nographic)
2267 tty.c_lflag &= ~ISIG;
2268 tty.c_cflag &= ~(CSIZE|PARENB);
2269 tty.c_cflag |= CS8;
2270 tty.c_cc[VMIN] = 1;
2271 tty.c_cc[VTIME] = 0;
2273 tcsetattr (0, TCSANOW, &tty);
2275 if (!term_atexit_done++)
2276 atexit(term_exit);
2278 fcntl(0, F_SETFL, O_NONBLOCK);
2281 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2283 term_exit();
2284 stdio_nb_clients--;
2285 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2286 fd_chr_close(chr);
2289 static CharDriverState *qemu_chr_open_stdio(void)
2291 CharDriverState *chr;
2293 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2294 return NULL;
2295 chr = qemu_chr_open_fd(0, 1);
2296 chr->chr_close = qemu_chr_close_stdio;
2297 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2298 stdio_nb_clients++;
2299 term_init();
2301 return chr;
2304 #if defined(__linux__) || defined(__sun__)
2305 static CharDriverState *qemu_chr_open_pty(void)
2307 struct termios tty;
2308 char slave_name[1024];
2309 int master_fd, slave_fd;
2311 #if defined(__linux__)
2312 /* Not satisfying */
2313 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2314 return NULL;
2316 #endif
2318 /* Disabling local echo and line-buffered output */
2319 tcgetattr (master_fd, &tty);
2320 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2321 tty.c_cc[VMIN] = 1;
2322 tty.c_cc[VTIME] = 0;
2323 tcsetattr (master_fd, TCSAFLUSH, &tty);
2325 fprintf(stderr, "char device redirected to %s\n", slave_name);
2326 return qemu_chr_open_fd(master_fd, master_fd);
2329 static void tty_serial_init(int fd, int speed,
2330 int parity, int data_bits, int stop_bits)
2332 struct termios tty;
2333 speed_t spd;
2335 #if 0
2336 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2337 speed, parity, data_bits, stop_bits);
2338 #endif
2339 tcgetattr (fd, &tty);
2341 #define MARGIN 1.1
2342 if (speed <= 50 * MARGIN)
2343 spd = B50;
2344 else if (speed <= 75 * MARGIN)
2345 spd = B75;
2346 else if (speed <= 300 * MARGIN)
2347 spd = B300;
2348 else if (speed <= 600 * MARGIN)
2349 spd = B600;
2350 else if (speed <= 1200 * MARGIN)
2351 spd = B1200;
2352 else if (speed <= 2400 * MARGIN)
2353 spd = B2400;
2354 else if (speed <= 4800 * MARGIN)
2355 spd = B4800;
2356 else if (speed <= 9600 * MARGIN)
2357 spd = B9600;
2358 else if (speed <= 19200 * MARGIN)
2359 spd = B19200;
2360 else if (speed <= 38400 * MARGIN)
2361 spd = B38400;
2362 else if (speed <= 57600 * MARGIN)
2363 spd = B57600;
2364 else if (speed <= 115200 * MARGIN)
2365 spd = B115200;
2366 else
2367 spd = B115200;
2369 cfsetispeed(&tty, spd);
2370 cfsetospeed(&tty, spd);
2372 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2373 |INLCR|IGNCR|ICRNL|IXON);
2374 tty.c_oflag |= OPOST;
2375 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2376 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2377 switch(data_bits) {
2378 default:
2379 case 8:
2380 tty.c_cflag |= CS8;
2381 break;
2382 case 7:
2383 tty.c_cflag |= CS7;
2384 break;
2385 case 6:
2386 tty.c_cflag |= CS6;
2387 break;
2388 case 5:
2389 tty.c_cflag |= CS5;
2390 break;
2392 switch(parity) {
2393 default:
2394 case 'N':
2395 break;
2396 case 'E':
2397 tty.c_cflag |= PARENB;
2398 break;
2399 case 'O':
2400 tty.c_cflag |= PARENB | PARODD;
2401 break;
2403 if (stop_bits == 2)
2404 tty.c_cflag |= CSTOPB;
2406 tcsetattr (fd, TCSANOW, &tty);
2409 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2411 FDCharDriver *s = chr->opaque;
2413 switch(cmd) {
2414 case CHR_IOCTL_SERIAL_SET_PARAMS:
2416 QEMUSerialSetParams *ssp = arg;
2417 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2418 ssp->data_bits, ssp->stop_bits);
2420 break;
2421 case CHR_IOCTL_SERIAL_SET_BREAK:
2423 int enable = *(int *)arg;
2424 if (enable)
2425 tcsendbreak(s->fd_in, 1);
2427 break;
2428 default:
2429 return -ENOTSUP;
2431 return 0;
2434 static CharDriverState *qemu_chr_open_tty(const char *filename)
2436 CharDriverState *chr;
2437 int fd;
2439 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2440 fcntl(fd, F_SETFL, O_NONBLOCK);
2441 tty_serial_init(fd, 115200, 'N', 8, 1);
2442 chr = qemu_chr_open_fd(fd, fd);
2443 if (!chr) {
2444 close(fd);
2445 return NULL;
2447 chr->chr_ioctl = tty_serial_ioctl;
2448 qemu_chr_reset(chr);
2449 return chr;
2451 #else /* ! __linux__ && ! __sun__ */
2452 static CharDriverState *qemu_chr_open_pty(void)
2454 return NULL;
2456 #endif /* __linux__ || __sun__ */
2458 #if defined(__linux__)
2459 typedef struct {
2460 int fd;
2461 int mode;
2462 } ParallelCharDriver;
2464 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2466 if (s->mode != mode) {
2467 int m = mode;
2468 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2469 return 0;
2470 s->mode = mode;
2472 return 1;
2475 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2477 ParallelCharDriver *drv = chr->opaque;
2478 int fd = drv->fd;
2479 uint8_t b;
2481 switch(cmd) {
2482 case CHR_IOCTL_PP_READ_DATA:
2483 if (ioctl(fd, PPRDATA, &b) < 0)
2484 return -ENOTSUP;
2485 *(uint8_t *)arg = b;
2486 break;
2487 case CHR_IOCTL_PP_WRITE_DATA:
2488 b = *(uint8_t *)arg;
2489 if (ioctl(fd, PPWDATA, &b) < 0)
2490 return -ENOTSUP;
2491 break;
2492 case CHR_IOCTL_PP_READ_CONTROL:
2493 if (ioctl(fd, PPRCONTROL, &b) < 0)
2494 return -ENOTSUP;
2495 /* Linux gives only the lowest bits, and no way to know data
2496 direction! For better compatibility set the fixed upper
2497 bits. */
2498 *(uint8_t *)arg = b | 0xc0;
2499 break;
2500 case CHR_IOCTL_PP_WRITE_CONTROL:
2501 b = *(uint8_t *)arg;
2502 if (ioctl(fd, PPWCONTROL, &b) < 0)
2503 return -ENOTSUP;
2504 break;
2505 case CHR_IOCTL_PP_READ_STATUS:
2506 if (ioctl(fd, PPRSTATUS, &b) < 0)
2507 return -ENOTSUP;
2508 *(uint8_t *)arg = b;
2509 break;
2510 case CHR_IOCTL_PP_EPP_READ_ADDR:
2511 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2512 struct ParallelIOArg *parg = arg;
2513 int n = read(fd, parg->buffer, parg->count);
2514 if (n != parg->count) {
2515 return -EIO;
2518 break;
2519 case CHR_IOCTL_PP_EPP_READ:
2520 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2521 struct ParallelIOArg *parg = arg;
2522 int n = read(fd, parg->buffer, parg->count);
2523 if (n != parg->count) {
2524 return -EIO;
2527 break;
2528 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2529 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2530 struct ParallelIOArg *parg = arg;
2531 int n = write(fd, parg->buffer, parg->count);
2532 if (n != parg->count) {
2533 return -EIO;
2536 break;
2537 case CHR_IOCTL_PP_EPP_WRITE:
2538 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2539 struct ParallelIOArg *parg = arg;
2540 int n = write(fd, parg->buffer, parg->count);
2541 if (n != parg->count) {
2542 return -EIO;
2545 break;
2546 default:
2547 return -ENOTSUP;
2549 return 0;
2552 static void pp_close(CharDriverState *chr)
2554 ParallelCharDriver *drv = chr->opaque;
2555 int fd = drv->fd;
2557 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2558 ioctl(fd, PPRELEASE);
2559 close(fd);
2560 qemu_free(drv);
2563 static CharDriverState *qemu_chr_open_pp(const char *filename)
2565 CharDriverState *chr;
2566 ParallelCharDriver *drv;
2567 int fd;
2569 TFR(fd = open(filename, O_RDWR));
2570 if (fd < 0)
2571 return NULL;
2573 if (ioctl(fd, PPCLAIM) < 0) {
2574 close(fd);
2575 return NULL;
2578 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2579 if (!drv) {
2580 close(fd);
2581 return NULL;
2583 drv->fd = fd;
2584 drv->mode = IEEE1284_MODE_COMPAT;
2586 chr = qemu_mallocz(sizeof(CharDriverState));
2587 if (!chr) {
2588 qemu_free(drv);
2589 close(fd);
2590 return NULL;
2592 chr->chr_write = null_chr_write;
2593 chr->chr_ioctl = pp_ioctl;
2594 chr->chr_close = pp_close;
2595 chr->opaque = drv;
2597 qemu_chr_reset(chr);
2599 return chr;
2601 #endif /* __linux__ */
2603 #else /* _WIN32 */
2605 typedef struct {
2606 int max_size;
2607 HANDLE hcom, hrecv, hsend;
2608 OVERLAPPED orecv, osend;
2609 BOOL fpipe;
2610 DWORD len;
2611 } WinCharState;
2613 #define NSENDBUF 2048
2614 #define NRECVBUF 2048
2615 #define MAXCONNECT 1
2616 #define NTIMEOUT 5000
2618 static int win_chr_poll(void *opaque);
2619 static int win_chr_pipe_poll(void *opaque);
2621 static void win_chr_close(CharDriverState *chr)
2623 WinCharState *s = chr->opaque;
2625 if (s->hsend) {
2626 CloseHandle(s->hsend);
2627 s->hsend = NULL;
2629 if (s->hrecv) {
2630 CloseHandle(s->hrecv);
2631 s->hrecv = NULL;
2633 if (s->hcom) {
2634 CloseHandle(s->hcom);
2635 s->hcom = NULL;
2637 if (s->fpipe)
2638 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2639 else
2640 qemu_del_polling_cb(win_chr_poll, chr);
2643 static int win_chr_init(CharDriverState *chr, const char *filename)
2645 WinCharState *s = chr->opaque;
2646 COMMCONFIG comcfg;
2647 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2648 COMSTAT comstat;
2649 DWORD size;
2650 DWORD err;
2652 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2653 if (!s->hsend) {
2654 fprintf(stderr, "Failed CreateEvent\n");
2655 goto fail;
2657 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2658 if (!s->hrecv) {
2659 fprintf(stderr, "Failed CreateEvent\n");
2660 goto fail;
2663 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2664 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2665 if (s->hcom == INVALID_HANDLE_VALUE) {
2666 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2667 s->hcom = NULL;
2668 goto fail;
2671 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2672 fprintf(stderr, "Failed SetupComm\n");
2673 goto fail;
2676 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2677 size = sizeof(COMMCONFIG);
2678 GetDefaultCommConfig(filename, &comcfg, &size);
2679 comcfg.dcb.DCBlength = sizeof(DCB);
2680 CommConfigDialog(filename, NULL, &comcfg);
2682 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2683 fprintf(stderr, "Failed SetCommState\n");
2684 goto fail;
2687 if (!SetCommMask(s->hcom, EV_ERR)) {
2688 fprintf(stderr, "Failed SetCommMask\n");
2689 goto fail;
2692 cto.ReadIntervalTimeout = MAXDWORD;
2693 if (!SetCommTimeouts(s->hcom, &cto)) {
2694 fprintf(stderr, "Failed SetCommTimeouts\n");
2695 goto fail;
2698 if (!ClearCommError(s->hcom, &err, &comstat)) {
2699 fprintf(stderr, "Failed ClearCommError\n");
2700 goto fail;
2702 qemu_add_polling_cb(win_chr_poll, chr);
2703 return 0;
2705 fail:
2706 win_chr_close(chr);
2707 return -1;
2710 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2712 WinCharState *s = chr->opaque;
2713 DWORD len, ret, size, err;
2715 len = len1;
2716 ZeroMemory(&s->osend, sizeof(s->osend));
2717 s->osend.hEvent = s->hsend;
2718 while (len > 0) {
2719 if (s->hsend)
2720 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2721 else
2722 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2723 if (!ret) {
2724 err = GetLastError();
2725 if (err == ERROR_IO_PENDING) {
2726 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2727 if (ret) {
2728 buf += size;
2729 len -= size;
2730 } else {
2731 break;
2733 } else {
2734 break;
2736 } else {
2737 buf += size;
2738 len -= size;
2741 return len1 - len;
2744 static int win_chr_read_poll(CharDriverState *chr)
2746 WinCharState *s = chr->opaque;
2748 s->max_size = qemu_chr_can_read(chr);
2749 return s->max_size;
2752 static void win_chr_readfile(CharDriverState *chr)
2754 WinCharState *s = chr->opaque;
2755 int ret, err;
2756 uint8_t buf[1024];
2757 DWORD size;
2759 ZeroMemory(&s->orecv, sizeof(s->orecv));
2760 s->orecv.hEvent = s->hrecv;
2761 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2762 if (!ret) {
2763 err = GetLastError();
2764 if (err == ERROR_IO_PENDING) {
2765 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2769 if (size > 0) {
2770 qemu_chr_read(chr, buf, size);
2774 static void win_chr_read(CharDriverState *chr)
2776 WinCharState *s = chr->opaque;
2778 if (s->len > s->max_size)
2779 s->len = s->max_size;
2780 if (s->len == 0)
2781 return;
2783 win_chr_readfile(chr);
2786 static int win_chr_poll(void *opaque)
2788 CharDriverState *chr = opaque;
2789 WinCharState *s = chr->opaque;
2790 COMSTAT status;
2791 DWORD comerr;
2793 ClearCommError(s->hcom, &comerr, &status);
2794 if (status.cbInQue > 0) {
2795 s->len = status.cbInQue;
2796 win_chr_read_poll(chr);
2797 win_chr_read(chr);
2798 return 1;
2800 return 0;
2803 static CharDriverState *qemu_chr_open_win(const char *filename)
2805 CharDriverState *chr;
2806 WinCharState *s;
2808 chr = qemu_mallocz(sizeof(CharDriverState));
2809 if (!chr)
2810 return NULL;
2811 s = qemu_mallocz(sizeof(WinCharState));
2812 if (!s) {
2813 free(chr);
2814 return NULL;
2816 chr->opaque = s;
2817 chr->chr_write = win_chr_write;
2818 chr->chr_close = win_chr_close;
2820 if (win_chr_init(chr, filename) < 0) {
2821 free(s);
2822 free(chr);
2823 return NULL;
2825 qemu_chr_reset(chr);
2826 return chr;
2829 static int win_chr_pipe_poll(void *opaque)
2831 CharDriverState *chr = opaque;
2832 WinCharState *s = chr->opaque;
2833 DWORD size;
2835 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2836 if (size > 0) {
2837 s->len = size;
2838 win_chr_read_poll(chr);
2839 win_chr_read(chr);
2840 return 1;
2842 return 0;
2845 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2847 WinCharState *s = chr->opaque;
2848 OVERLAPPED ov;
2849 int ret;
2850 DWORD size;
2851 char openname[256];
2853 s->fpipe = TRUE;
2855 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2856 if (!s->hsend) {
2857 fprintf(stderr, "Failed CreateEvent\n");
2858 goto fail;
2860 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2861 if (!s->hrecv) {
2862 fprintf(stderr, "Failed CreateEvent\n");
2863 goto fail;
2866 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2867 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2868 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2869 PIPE_WAIT,
2870 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2871 if (s->hcom == INVALID_HANDLE_VALUE) {
2872 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2873 s->hcom = NULL;
2874 goto fail;
2877 ZeroMemory(&ov, sizeof(ov));
2878 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2879 ret = ConnectNamedPipe(s->hcom, &ov);
2880 if (ret) {
2881 fprintf(stderr, "Failed ConnectNamedPipe\n");
2882 goto fail;
2885 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2886 if (!ret) {
2887 fprintf(stderr, "Failed GetOverlappedResult\n");
2888 if (ov.hEvent) {
2889 CloseHandle(ov.hEvent);
2890 ov.hEvent = NULL;
2892 goto fail;
2895 if (ov.hEvent) {
2896 CloseHandle(ov.hEvent);
2897 ov.hEvent = NULL;
2899 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2900 return 0;
2902 fail:
2903 win_chr_close(chr);
2904 return -1;
2908 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2910 CharDriverState *chr;
2911 WinCharState *s;
2913 chr = qemu_mallocz(sizeof(CharDriverState));
2914 if (!chr)
2915 return NULL;
2916 s = qemu_mallocz(sizeof(WinCharState));
2917 if (!s) {
2918 free(chr);
2919 return NULL;
2921 chr->opaque = s;
2922 chr->chr_write = win_chr_write;
2923 chr->chr_close = win_chr_close;
2925 if (win_chr_pipe_init(chr, filename) < 0) {
2926 free(s);
2927 free(chr);
2928 return NULL;
2930 qemu_chr_reset(chr);
2931 return chr;
2934 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2936 CharDriverState *chr;
2937 WinCharState *s;
2939 chr = qemu_mallocz(sizeof(CharDriverState));
2940 if (!chr)
2941 return NULL;
2942 s = qemu_mallocz(sizeof(WinCharState));
2943 if (!s) {
2944 free(chr);
2945 return NULL;
2947 s->hcom = fd_out;
2948 chr->opaque = s;
2949 chr->chr_write = win_chr_write;
2950 qemu_chr_reset(chr);
2951 return chr;
2954 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2956 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2959 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2961 HANDLE fd_out;
2963 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2964 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2965 if (fd_out == INVALID_HANDLE_VALUE)
2966 return NULL;
2968 return qemu_chr_open_win_file(fd_out);
2970 #endif /* !_WIN32 */
2972 /***********************************************************/
2973 /* UDP Net console */
2975 typedef struct {
2976 int fd;
2977 struct sockaddr_in daddr;
2978 uint8_t buf[1024];
2979 int bufcnt;
2980 int bufptr;
2981 int max_size;
2982 } NetCharDriver;
2984 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2986 NetCharDriver *s = chr->opaque;
2988 return sendto(s->fd, buf, len, 0,
2989 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2992 static int udp_chr_read_poll(void *opaque)
2994 CharDriverState *chr = opaque;
2995 NetCharDriver *s = chr->opaque;
2997 s->max_size = qemu_chr_can_read(chr);
2999 /* If there were any stray characters in the queue process them
3000 * first
3002 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3003 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3004 s->bufptr++;
3005 s->max_size = qemu_chr_can_read(chr);
3007 return s->max_size;
3010 static void udp_chr_read(void *opaque)
3012 CharDriverState *chr = opaque;
3013 NetCharDriver *s = chr->opaque;
3015 if (s->max_size == 0)
3016 return;
3017 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3018 s->bufptr = s->bufcnt;
3019 if (s->bufcnt <= 0)
3020 return;
3022 s->bufptr = 0;
3023 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3024 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3025 s->bufptr++;
3026 s->max_size = qemu_chr_can_read(chr);
3030 static void udp_chr_update_read_handler(CharDriverState *chr)
3032 NetCharDriver *s = chr->opaque;
3034 if (s->fd >= 0) {
3035 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3036 udp_chr_read, NULL, chr);
3040 #ifndef _WIN32
3041 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3042 #endif
3043 int parse_host_src_port(struct sockaddr_in *haddr,
3044 struct sockaddr_in *saddr,
3045 const char *str);
3047 static CharDriverState *qemu_chr_open_udp(const char *def)
3049 CharDriverState *chr = NULL;
3050 NetCharDriver *s = NULL;
3051 int fd = -1;
3052 struct sockaddr_in saddr;
3054 chr = qemu_mallocz(sizeof(CharDriverState));
3055 if (!chr)
3056 goto return_err;
3057 s = qemu_mallocz(sizeof(NetCharDriver));
3058 if (!s)
3059 goto return_err;
3061 fd = socket(PF_INET, SOCK_DGRAM, 0);
3062 if (fd < 0) {
3063 perror("socket(PF_INET, SOCK_DGRAM)");
3064 goto return_err;
3067 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3068 printf("Could not parse: %s\n", def);
3069 goto return_err;
3072 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3074 perror("bind");
3075 goto return_err;
3078 s->fd = fd;
3079 s->bufcnt = 0;
3080 s->bufptr = 0;
3081 chr->opaque = s;
3082 chr->chr_write = udp_chr_write;
3083 chr->chr_update_read_handler = udp_chr_update_read_handler;
3084 return chr;
3086 return_err:
3087 if (chr)
3088 free(chr);
3089 if (s)
3090 free(s);
3091 if (fd >= 0)
3092 closesocket(fd);
3093 return NULL;
3096 /***********************************************************/
3097 /* TCP Net console */
3099 typedef struct {
3100 int fd, listen_fd;
3101 int connected;
3102 int max_size;
3103 int do_telnetopt;
3104 int do_nodelay;
3105 int is_unix;
3106 } TCPCharDriver;
3108 static void tcp_chr_accept(void *opaque);
3110 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3112 TCPCharDriver *s = chr->opaque;
3113 if (s->connected) {
3114 return send_all(s->fd, buf, len);
3115 } else {
3116 /* XXX: indicate an error ? */
3117 return len;
3121 static int tcp_chr_read_poll(void *opaque)
3123 CharDriverState *chr = opaque;
3124 TCPCharDriver *s = chr->opaque;
3125 if (!s->connected)
3126 return 0;
3127 s->max_size = qemu_chr_can_read(chr);
3128 return s->max_size;
3131 #define IAC 255
3132 #define IAC_BREAK 243
3133 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3134 TCPCharDriver *s,
3135 uint8_t *buf, int *size)
3137 /* Handle any telnet client's basic IAC options to satisfy char by
3138 * char mode with no echo. All IAC options will be removed from
3139 * the buf and the do_telnetopt variable will be used to track the
3140 * state of the width of the IAC information.
3142 * IAC commands come in sets of 3 bytes with the exception of the
3143 * "IAC BREAK" command and the double IAC.
3146 int i;
3147 int j = 0;
3149 for (i = 0; i < *size; i++) {
3150 if (s->do_telnetopt > 1) {
3151 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3152 /* Double IAC means send an IAC */
3153 if (j != i)
3154 buf[j] = buf[i];
3155 j++;
3156 s->do_telnetopt = 1;
3157 } else {
3158 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3159 /* Handle IAC break commands by sending a serial break */
3160 qemu_chr_event(chr, CHR_EVENT_BREAK);
3161 s->do_telnetopt++;
3163 s->do_telnetopt++;
3165 if (s->do_telnetopt >= 4) {
3166 s->do_telnetopt = 1;
3168 } else {
3169 if ((unsigned char)buf[i] == IAC) {
3170 s->do_telnetopt = 2;
3171 } else {
3172 if (j != i)
3173 buf[j] = buf[i];
3174 j++;
3178 *size = j;
3181 static void tcp_chr_read(void *opaque)
3183 CharDriverState *chr = opaque;
3184 TCPCharDriver *s = chr->opaque;
3185 uint8_t buf[1024];
3186 int len, size;
3188 if (!s->connected || s->max_size <= 0)
3189 return;
3190 len = sizeof(buf);
3191 if (len > s->max_size)
3192 len = s->max_size;
3193 size = recv(s->fd, buf, len, 0);
3194 if (size == 0) {
3195 /* connection closed */
3196 s->connected = 0;
3197 if (s->listen_fd >= 0) {
3198 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3200 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3201 closesocket(s->fd);
3202 s->fd = -1;
3203 } else if (size > 0) {
3204 if (s->do_telnetopt)
3205 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3206 if (size > 0)
3207 qemu_chr_read(chr, buf, size);
3211 static void tcp_chr_connect(void *opaque)
3213 CharDriverState *chr = opaque;
3214 TCPCharDriver *s = chr->opaque;
3216 s->connected = 1;
3217 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3218 tcp_chr_read, NULL, chr);
3219 qemu_chr_reset(chr);
3222 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3223 static void tcp_chr_telnet_init(int fd)
3225 char buf[3];
3226 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3227 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3228 send(fd, (char *)buf, 3, 0);
3229 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3230 send(fd, (char *)buf, 3, 0);
3231 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3232 send(fd, (char *)buf, 3, 0);
3233 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3234 send(fd, (char *)buf, 3, 0);
3237 static void socket_set_nodelay(int fd)
3239 int val = 1;
3240 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3243 static void tcp_chr_accept(void *opaque)
3245 CharDriverState *chr = opaque;
3246 TCPCharDriver *s = chr->opaque;
3247 struct sockaddr_in saddr;
3248 #ifndef _WIN32
3249 struct sockaddr_un uaddr;
3250 #endif
3251 struct sockaddr *addr;
3252 socklen_t len;
3253 int fd;
3255 for(;;) {
3256 #ifndef _WIN32
3257 if (s->is_unix) {
3258 len = sizeof(uaddr);
3259 addr = (struct sockaddr *)&uaddr;
3260 } else
3261 #endif
3263 len = sizeof(saddr);
3264 addr = (struct sockaddr *)&saddr;
3266 fd = accept(s->listen_fd, addr, &len);
3267 if (fd < 0 && errno != EINTR) {
3268 return;
3269 } else if (fd >= 0) {
3270 if (s->do_telnetopt)
3271 tcp_chr_telnet_init(fd);
3272 break;
3275 socket_set_nonblock(fd);
3276 if (s->do_nodelay)
3277 socket_set_nodelay(fd);
3278 s->fd = fd;
3279 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3280 tcp_chr_connect(chr);
3283 static void tcp_chr_close(CharDriverState *chr)
3285 TCPCharDriver *s = chr->opaque;
3286 if (s->fd >= 0)
3287 closesocket(s->fd);
3288 if (s->listen_fd >= 0)
3289 closesocket(s->listen_fd);
3290 qemu_free(s);
3293 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3294 int is_telnet,
3295 int is_unix)
3297 CharDriverState *chr = NULL;
3298 TCPCharDriver *s = NULL;
3299 int fd = -1, ret, err, val;
3300 int is_listen = 0;
3301 int is_waitconnect = 1;
3302 int do_nodelay = 0;
3303 const char *ptr;
3304 struct sockaddr_in saddr;
3305 #ifndef _WIN32
3306 struct sockaddr_un uaddr;
3307 #endif
3308 struct sockaddr *addr;
3309 socklen_t addrlen;
3311 #ifndef _WIN32
3312 if (is_unix) {
3313 addr = (struct sockaddr *)&uaddr;
3314 addrlen = sizeof(uaddr);
3315 if (parse_unix_path(&uaddr, host_str) < 0)
3316 goto fail;
3317 } else
3318 #endif
3320 addr = (struct sockaddr *)&saddr;
3321 addrlen = sizeof(saddr);
3322 if (parse_host_port(&saddr, host_str) < 0)
3323 goto fail;
3326 ptr = host_str;
3327 while((ptr = strchr(ptr,','))) {
3328 ptr++;
3329 if (!strncmp(ptr,"server",6)) {
3330 is_listen = 1;
3331 } else if (!strncmp(ptr,"nowait",6)) {
3332 is_waitconnect = 0;
3333 } else if (!strncmp(ptr,"nodelay",6)) {
3334 do_nodelay = 1;
3335 } else {
3336 printf("Unknown option: %s\n", ptr);
3337 goto fail;
3340 if (!is_listen)
3341 is_waitconnect = 0;
3343 chr = qemu_mallocz(sizeof(CharDriverState));
3344 if (!chr)
3345 goto fail;
3346 s = qemu_mallocz(sizeof(TCPCharDriver));
3347 if (!s)
3348 goto fail;
3350 #ifndef _WIN32
3351 if (is_unix)
3352 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3353 else
3354 #endif
3355 fd = socket(PF_INET, SOCK_STREAM, 0);
3357 if (fd < 0)
3358 goto fail;
3360 if (!is_waitconnect)
3361 socket_set_nonblock(fd);
3363 s->connected = 0;
3364 s->fd = -1;
3365 s->listen_fd = -1;
3366 s->is_unix = is_unix;
3367 s->do_nodelay = do_nodelay && !is_unix;
3369 chr->opaque = s;
3370 chr->chr_write = tcp_chr_write;
3371 chr->chr_close = tcp_chr_close;
3373 if (is_listen) {
3374 /* allow fast reuse */
3375 #ifndef _WIN32
3376 if (is_unix) {
3377 char path[109];
3378 strncpy(path, uaddr.sun_path, 108);
3379 path[108] = 0;
3380 unlink(path);
3381 } else
3382 #endif
3384 val = 1;
3385 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3388 ret = bind(fd, addr, addrlen);
3389 if (ret < 0)
3390 goto fail;
3392 ret = listen(fd, 0);
3393 if (ret < 0)
3394 goto fail;
3396 s->listen_fd = fd;
3397 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3398 if (is_telnet)
3399 s->do_telnetopt = 1;
3400 } else {
3401 for(;;) {
3402 ret = connect(fd, addr, addrlen);
3403 if (ret < 0) {
3404 err = socket_error();
3405 if (err == EINTR || err == EWOULDBLOCK) {
3406 } else if (err == EINPROGRESS) {
3407 break;
3408 #ifdef _WIN32
3409 } else if (err == WSAEALREADY) {
3410 break;
3411 #endif
3412 } else {
3413 goto fail;
3415 } else {
3416 s->connected = 1;
3417 break;
3420 s->fd = fd;
3421 socket_set_nodelay(fd);
3422 if (s->connected)
3423 tcp_chr_connect(chr);
3424 else
3425 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3428 if (is_listen && is_waitconnect) {
3429 printf("QEMU waiting for connection on: %s\n", host_str);
3430 tcp_chr_accept(chr);
3431 socket_set_nonblock(s->listen_fd);
3434 return chr;
3435 fail:
3436 if (fd >= 0)
3437 closesocket(fd);
3438 qemu_free(s);
3439 qemu_free(chr);
3440 return NULL;
3443 CharDriverState *qemu_chr_open(const char *filename)
3445 const char *p;
3447 if (!strcmp(filename, "vc")) {
3448 return text_console_init(&display_state, 0);
3449 } else if (strstart(filename, "vc:", &p)) {
3450 return text_console_init(&display_state, p);
3451 } else if (!strcmp(filename, "null")) {
3452 return qemu_chr_open_null();
3453 } else
3454 if (strstart(filename, "tcp:", &p)) {
3455 return qemu_chr_open_tcp(p, 0, 0);
3456 } else
3457 if (strstart(filename, "telnet:", &p)) {
3458 return qemu_chr_open_tcp(p, 1, 0);
3459 } else
3460 if (strstart(filename, "udp:", &p)) {
3461 return qemu_chr_open_udp(p);
3462 } else
3463 if (strstart(filename, "mon:", &p)) {
3464 CharDriverState *drv = qemu_chr_open(p);
3465 if (drv) {
3466 drv = qemu_chr_open_mux(drv);
3467 monitor_init(drv, !nographic);
3468 return drv;
3470 printf("Unable to open driver: %s\n", p);
3471 return 0;
3472 } else
3473 #ifndef _WIN32
3474 if (strstart(filename, "unix:", &p)) {
3475 return qemu_chr_open_tcp(p, 0, 1);
3476 } else if (strstart(filename, "file:", &p)) {
3477 return qemu_chr_open_file_out(p);
3478 } else if (strstart(filename, "pipe:", &p)) {
3479 return qemu_chr_open_pipe(p);
3480 } else if (!strcmp(filename, "pty")) {
3481 return qemu_chr_open_pty();
3482 } else if (!strcmp(filename, "stdio")) {
3483 return qemu_chr_open_stdio();
3484 } else
3485 #if defined(__linux__)
3486 if (strstart(filename, "/dev/parport", NULL)) {
3487 return qemu_chr_open_pp(filename);
3488 } else
3489 #endif
3490 #if defined(__linux__) || defined(__sun__)
3491 if (strstart(filename, "/dev/", NULL)) {
3492 return qemu_chr_open_tty(filename);
3493 } else
3494 #endif
3495 #else /* !_WIN32 */
3496 if (strstart(filename, "COM", NULL)) {
3497 return qemu_chr_open_win(filename);
3498 } else
3499 if (strstart(filename, "pipe:", &p)) {
3500 return qemu_chr_open_win_pipe(p);
3501 } else
3502 if (strstart(filename, "con:", NULL)) {
3503 return qemu_chr_open_win_con(filename);
3504 } else
3505 if (strstart(filename, "file:", &p)) {
3506 return qemu_chr_open_win_file_out(p);
3508 #endif
3510 return NULL;
3514 void qemu_chr_close(CharDriverState *chr)
3516 if (chr->chr_close)
3517 chr->chr_close(chr);
3518 qemu_free(chr);
3521 /***********************************************************/
3522 /* network device redirectors */
3524 __attribute__ (( unused ))
3525 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3527 int len, i, j, c;
3529 for(i=0;i<size;i+=16) {
3530 len = size - i;
3531 if (len > 16)
3532 len = 16;
3533 fprintf(f, "%08x ", i);
3534 for(j=0;j<16;j++) {
3535 if (j < len)
3536 fprintf(f, " %02x", buf[i+j]);
3537 else
3538 fprintf(f, " ");
3540 fprintf(f, " ");
3541 for(j=0;j<len;j++) {
3542 c = buf[i+j];
3543 if (c < ' ' || c > '~')
3544 c = '.';
3545 fprintf(f, "%c", c);
3547 fprintf(f, "\n");
3551 static int parse_macaddr(uint8_t *macaddr, const char *p)
3553 int i;
3554 char *last_char;
3555 long int offset;
3557 errno = 0;
3558 offset = strtol(p, &last_char, 0);
3559 if (0 == errno && '\0' == *last_char &&
3560 offset >= 0 && offset <= 0xFFFFFF) {
3561 macaddr[3] = (offset & 0xFF0000) >> 16;
3562 macaddr[4] = (offset & 0xFF00) >> 8;
3563 macaddr[5] = offset & 0xFF;
3564 return 0;
3565 } else {
3566 for(i = 0; i < 6; i++) {
3567 macaddr[i] = strtol(p, (char **)&p, 16);
3568 if (i == 5) {
3569 if (*p != '\0')
3570 return -1;
3571 } else {
3572 if (*p != ':' && *p != '-')
3573 return -1;
3574 p++;
3577 return 0;
3580 return -1;
3583 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3585 const char *p, *p1;
3586 int len;
3587 p = *pp;
3588 p1 = strchr(p, sep);
3589 if (!p1)
3590 return -1;
3591 len = p1 - p;
3592 p1++;
3593 if (buf_size > 0) {
3594 if (len > buf_size - 1)
3595 len = buf_size - 1;
3596 memcpy(buf, p, len);
3597 buf[len] = '\0';
3599 *pp = p1;
3600 return 0;
3603 int parse_host_src_port(struct sockaddr_in *haddr,
3604 struct sockaddr_in *saddr,
3605 const char *input_str)
3607 char *str = strdup(input_str);
3608 char *host_str = str;
3609 char *src_str;
3610 char *ptr;
3613 * Chop off any extra arguments at the end of the string which
3614 * would start with a comma, then fill in the src port information
3615 * if it was provided else use the "any address" and "any port".
3617 if ((ptr = strchr(str,',')))
3618 *ptr = '\0';
3620 if ((src_str = strchr(input_str,'@'))) {
3621 *src_str = '\0';
3622 src_str++;
3625 if (parse_host_port(haddr, host_str) < 0)
3626 goto fail;
3628 if (!src_str || *src_str == '\0')
3629 src_str = ":0";
3631 if (parse_host_port(saddr, src_str) < 0)
3632 goto fail;
3634 free(str);
3635 return(0);
3637 fail:
3638 free(str);
3639 return -1;
3642 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3644 char buf[512];
3645 struct hostent *he;
3646 const char *p, *r;
3647 int port;
3649 p = str;
3650 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3651 return -1;
3652 saddr->sin_family = AF_INET;
3653 if (buf[0] == '\0') {
3654 saddr->sin_addr.s_addr = 0;
3655 } else {
3656 if (isdigit(buf[0])) {
3657 if (!inet_aton(buf, &saddr->sin_addr))
3658 return -1;
3659 } else {
3660 if ((he = gethostbyname(buf)) == NULL)
3661 return - 1;
3662 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3665 port = strtol(p, (char **)&r, 0);
3666 if (r == p)
3667 return -1;
3668 saddr->sin_port = htons(port);
3669 return 0;
3672 #ifndef _WIN32
3673 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3675 const char *p;
3676 int len;
3678 len = MIN(108, strlen(str));
3679 p = strchr(str, ',');
3680 if (p)
3681 len = MIN(len, p - str);
3683 memset(uaddr, 0, sizeof(*uaddr));
3685 uaddr->sun_family = AF_UNIX;
3686 memcpy(uaddr->sun_path, str, len);
3688 return 0;
3690 #endif
3692 /* find or alloc a new VLAN */
3693 VLANState *qemu_find_vlan(int id)
3695 VLANState **pvlan, *vlan;
3696 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3697 if (vlan->id == id)
3698 return vlan;
3700 vlan = qemu_mallocz(sizeof(VLANState));
3701 if (!vlan)
3702 return NULL;
3703 vlan->id = id;
3704 vlan->next = NULL;
3705 pvlan = &first_vlan;
3706 while (*pvlan != NULL)
3707 pvlan = &(*pvlan)->next;
3708 *pvlan = vlan;
3709 return vlan;
3712 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3713 IOReadHandler *fd_read,
3714 IOCanRWHandler *fd_can_read,
3715 void *opaque)
3717 VLANClientState *vc, **pvc;
3718 vc = qemu_mallocz(sizeof(VLANClientState));
3719 if (!vc)
3720 return NULL;
3721 vc->fd_read = fd_read;
3722 vc->fd_can_read = fd_can_read;
3723 vc->opaque = opaque;
3724 vc->vlan = vlan;
3726 vc->next = NULL;
3727 pvc = &vlan->first_client;
3728 while (*pvc != NULL)
3729 pvc = &(*pvc)->next;
3730 *pvc = vc;
3731 return vc;
3734 int qemu_can_send_packet(VLANClientState *vc1)
3736 VLANState *vlan = vc1->vlan;
3737 VLANClientState *vc;
3739 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3740 if (vc != vc1) {
3741 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3742 return 1;
3745 return 0;
3748 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3750 VLANState *vlan = vc1->vlan;
3751 VLANClientState *vc;
3753 #if 0
3754 printf("vlan %d send:\n", vlan->id);
3755 hex_dump(stdout, buf, size);
3756 #endif
3757 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3758 if (vc != vc1) {
3759 vc->fd_read(vc->opaque, buf, size);
3764 #if defined(CONFIG_SLIRP)
3766 /* slirp network adapter */
3768 static int slirp_inited;
3769 static VLANClientState *slirp_vc;
3771 int slirp_can_output(void)
3773 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3776 void slirp_output(const uint8_t *pkt, int pkt_len)
3778 #if 0
3779 printf("slirp output:\n");
3780 hex_dump(stdout, pkt, pkt_len);
3781 #endif
3782 if (!slirp_vc)
3783 return;
3784 qemu_send_packet(slirp_vc, pkt, pkt_len);
3787 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3789 #if 0
3790 printf("slirp input:\n");
3791 hex_dump(stdout, buf, size);
3792 #endif
3793 slirp_input(buf, size);
3796 static int net_slirp_init(VLANState *vlan)
3798 if (!slirp_inited) {
3799 slirp_inited = 1;
3800 slirp_init();
3802 slirp_vc = qemu_new_vlan_client(vlan,
3803 slirp_receive, NULL, NULL);
3804 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3805 return 0;
3808 static void net_slirp_redir(const char *redir_str)
3810 int is_udp;
3811 char buf[256], *r;
3812 const char *p;
3813 struct in_addr guest_addr;
3814 int host_port, guest_port;
3816 if (!slirp_inited) {
3817 slirp_inited = 1;
3818 slirp_init();
3821 p = redir_str;
3822 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3823 goto fail;
3824 if (!strcmp(buf, "tcp")) {
3825 is_udp = 0;
3826 } else if (!strcmp(buf, "udp")) {
3827 is_udp = 1;
3828 } else {
3829 goto fail;
3832 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3833 goto fail;
3834 host_port = strtol(buf, &r, 0);
3835 if (r == buf)
3836 goto fail;
3838 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3839 goto fail;
3840 if (buf[0] == '\0') {
3841 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3843 if (!inet_aton(buf, &guest_addr))
3844 goto fail;
3846 guest_port = strtol(p, &r, 0);
3847 if (r == p)
3848 goto fail;
3850 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3851 fprintf(stderr, "qemu: could not set up redirection\n");
3852 exit(1);
3854 return;
3855 fail:
3856 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3857 exit(1);
3860 #ifndef _WIN32
3862 char smb_dir[1024];
3864 static void erase_dir(char *dir_name)
3866 DIR *d;
3867 struct dirent *de;
3868 char filename[1024];
3870 /* erase all the files in the directory */
3871 if ((d = opendir(dir_name)) != 0) {
3872 for(;;) {
3873 de = readdir(d);
3874 if (!de)
3875 break;
3876 if (strcmp(de->d_name, ".") != 0 &&
3877 strcmp(de->d_name, "..") != 0) {
3878 snprintf(filename, sizeof(filename), "%s/%s",
3879 smb_dir, de->d_name);
3880 if (unlink(filename) != 0) /* is it a directory? */
3881 erase_dir(filename);
3884 closedir(d);
3885 rmdir(dir_name);
3889 /* automatic user mode samba server configuration */
3890 static void smb_exit(void)
3892 erase_dir(smb_dir);
3895 /* automatic user mode samba server configuration */
3896 static void net_slirp_smb(const char *exported_dir)
3898 char smb_conf[1024];
3899 char smb_cmdline[1024];
3900 FILE *f;
3902 if (!slirp_inited) {
3903 slirp_inited = 1;
3904 slirp_init();
3907 /* XXX: better tmp dir construction */
3908 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3909 if (mkdir(smb_dir, 0700) < 0) {
3910 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3911 exit(1);
3913 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3915 f = fopen(smb_conf, "w");
3916 if (!f) {
3917 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3918 exit(1);
3920 fprintf(f,
3921 "[global]\n"
3922 "private dir=%s\n"
3923 "smb ports=0\n"
3924 "socket address=127.0.0.1\n"
3925 "pid directory=%s\n"
3926 "lock directory=%s\n"
3927 "log file=%s/log.smbd\n"
3928 "smb passwd file=%s/smbpasswd\n"
3929 "security = share\n"
3930 "[qemu]\n"
3931 "path=%s\n"
3932 "read only=no\n"
3933 "guest ok=yes\n",
3934 smb_dir,
3935 smb_dir,
3936 smb_dir,
3937 smb_dir,
3938 smb_dir,
3939 exported_dir
3941 fclose(f);
3942 atexit(smb_exit);
3944 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3945 SMBD_COMMAND, smb_conf);
3947 slirp_add_exec(0, smb_cmdline, 4, 139);
3950 #endif /* !defined(_WIN32) */
3951 void do_info_slirp(void)
3953 slirp_stats();
3956 #endif /* CONFIG_SLIRP */
3958 #if !defined(_WIN32)
3960 typedef struct TAPState {
3961 VLANClientState *vc;
3962 int fd;
3963 char down_script[1024];
3964 int no_poll;
3965 } TAPState;
3967 static int tap_read_poll(void *opaque)
3969 TAPState *s = opaque;
3970 return (!s->no_poll);
3973 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3975 TAPState *s = opaque;
3976 int ret;
3977 for(;;) {
3978 ret = write(s->fd, buf, size);
3979 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3980 } else {
3981 break;
3986 static void tap_send(void *opaque)
3988 TAPState *s = opaque;
3989 uint8_t buf[4096];
3990 int size;
3992 #ifdef __sun__
3993 struct strbuf sbuf;
3994 int f = 0;
3995 sbuf.maxlen = sizeof(buf);
3996 sbuf.buf = buf;
3997 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3998 #else
3999 size = read(s->fd, buf, sizeof(buf));
4000 #endif
4001 if (size > 0) {
4002 qemu_send_packet(s->vc, buf, size);
4006 int hack_around_tap(void *opaque)
4008 VLANClientState *vc = opaque;
4009 TAPState *ts = vc->opaque;
4011 if (vc->fd_read != tap_receive)
4012 return -1;
4014 if (ts) {
4015 ts->no_poll = 1;
4016 return ts->fd;
4019 return -1;
4022 /* fd support */
4024 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4026 TAPState *s;
4028 s = qemu_mallocz(sizeof(TAPState));
4029 if (!s)
4030 return NULL;
4031 s->fd = fd;
4032 s->no_poll = 0;
4033 enable_sigio_timer(fd);
4034 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4035 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
4036 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4037 return s;
4040 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4041 static int tap_open(char *ifname, int ifname_size)
4043 int fd;
4044 char *dev;
4045 struct stat s;
4047 TFR(fd = open("/dev/tap", O_RDWR));
4048 if (fd < 0) {
4049 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4050 return -1;
4053 fstat(fd, &s);
4054 dev = devname(s.st_rdev, S_IFCHR);
4055 pstrcpy(ifname, ifname_size, dev);
4057 fcntl(fd, F_SETFL, O_NONBLOCK);
4058 return fd;
4060 #elif defined(__sun__)
4061 #define TUNNEWPPA (('T'<<16) | 0x0001)
4063 * Allocate TAP device, returns opened fd.
4064 * Stores dev name in the first arg(must be large enough).
4066 int tap_alloc(char *dev)
4068 int tap_fd, if_fd, ppa = -1;
4069 static int ip_fd = 0;
4070 char *ptr;
4072 static int arp_fd = 0;
4073 int ip_muxid, arp_muxid;
4074 struct strioctl strioc_if, strioc_ppa;
4075 int link_type = I_PLINK;;
4076 struct lifreq ifr;
4077 char actual_name[32] = "";
4079 memset(&ifr, 0x0, sizeof(ifr));
4081 if( *dev ){
4082 ptr = dev;
4083 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4084 ppa = atoi(ptr);
4087 /* Check if IP device was opened */
4088 if( ip_fd )
4089 close(ip_fd);
4091 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4092 if (ip_fd < 0) {
4093 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4094 return -1;
4097 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4098 if (tap_fd < 0) {
4099 syslog(LOG_ERR, "Can't open /dev/tap");
4100 return -1;
4103 /* Assign a new PPA and get its unit number. */
4104 strioc_ppa.ic_cmd = TUNNEWPPA;
4105 strioc_ppa.ic_timout = 0;
4106 strioc_ppa.ic_len = sizeof(ppa);
4107 strioc_ppa.ic_dp = (char *)&ppa;
4108 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4109 syslog (LOG_ERR, "Can't assign new interface");
4111 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4112 if (if_fd < 0) {
4113 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4114 return -1;
4116 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4117 syslog(LOG_ERR, "Can't push IP module");
4118 return -1;
4121 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4122 syslog(LOG_ERR, "Can't get flags\n");
4124 snprintf (actual_name, 32, "tap%d", ppa);
4125 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4127 ifr.lifr_ppa = ppa;
4128 /* Assign ppa according to the unit number returned by tun device */
4130 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4131 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4132 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4133 syslog (LOG_ERR, "Can't get flags\n");
4134 /* Push arp module to if_fd */
4135 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4136 syslog (LOG_ERR, "Can't push ARP module (2)");
4138 /* Push arp module to ip_fd */
4139 if (ioctl (ip_fd, I_POP, NULL) < 0)
4140 syslog (LOG_ERR, "I_POP failed\n");
4141 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4142 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4143 /* Open arp_fd */
4144 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4145 if (arp_fd < 0)
4146 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4148 /* Set ifname to arp */
4149 strioc_if.ic_cmd = SIOCSLIFNAME;
4150 strioc_if.ic_timout = 0;
4151 strioc_if.ic_len = sizeof(ifr);
4152 strioc_if.ic_dp = (char *)&ifr;
4153 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4154 syslog (LOG_ERR, "Can't set ifname to arp\n");
4157 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4158 syslog(LOG_ERR, "Can't link TAP device to IP");
4159 return -1;
4162 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4163 syslog (LOG_ERR, "Can't link TAP device to ARP");
4165 close (if_fd);
4167 memset(&ifr, 0x0, sizeof(ifr));
4168 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4169 ifr.lifr_ip_muxid = ip_muxid;
4170 ifr.lifr_arp_muxid = arp_muxid;
4172 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4174 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4175 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4176 syslog (LOG_ERR, "Can't set multiplexor id");
4179 sprintf(dev, "tap%d", ppa);
4180 return tap_fd;
4183 static int tap_open(char *ifname, int ifname_size)
4185 char dev[10]="";
4186 int fd;
4187 if( (fd = tap_alloc(dev)) < 0 ){
4188 fprintf(stderr, "Cannot allocate TAP device\n");
4189 return -1;
4191 pstrcpy(ifname, ifname_size, dev);
4192 fcntl(fd, F_SETFL, O_NONBLOCK);
4193 return fd;
4195 #else
4196 static int tap_open(char *ifname, int ifname_size)
4198 struct ifreq ifr;
4199 int fd, ret;
4201 TFR(fd = open("/dev/net/tun", O_RDWR));
4202 if (fd < 0) {
4203 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4204 return -1;
4206 memset(&ifr, 0, sizeof(ifr));
4207 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4208 if (ifname[0] != '\0')
4209 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4210 else
4211 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4212 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4213 if (ret != 0) {
4214 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4215 close(fd);
4216 return -1;
4218 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4219 fcntl(fd, F_SETFL, O_NONBLOCK);
4220 return fd;
4222 #endif
4224 static int launch_script(const char *setup_script, const char *ifname, int fd)
4226 int pid, status;
4227 char *args[3];
4228 char **parg;
4230 /* try to launch network script */
4231 pid = fork();
4232 if (pid >= 0) {
4233 if (pid == 0) {
4234 int open_max = sysconf (_SC_OPEN_MAX), i;
4235 for (i = 0; i < open_max; i++)
4236 if (i != STDIN_FILENO &&
4237 i != STDOUT_FILENO &&
4238 i != STDERR_FILENO &&
4239 i != fd)
4240 close(i);
4242 parg = args;
4243 *parg++ = (char *)setup_script;
4244 *parg++ = (char *)ifname;
4245 *parg++ = NULL;
4246 execv(setup_script, args);
4247 _exit(1);
4249 while (waitpid(pid, &status, 0) != pid);
4250 if (!WIFEXITED(status) ||
4251 WEXITSTATUS(status) != 0) {
4252 fprintf(stderr, "%s: could not launch network script\n",
4253 setup_script);
4254 return -1;
4257 return 0;
4260 static int net_tap_init(VLANState *vlan, const char *ifname1,
4261 const char *setup_script, const char *down_script)
4263 TAPState *s;
4264 int fd;
4265 char ifname[128];
4267 if (ifname1 != NULL)
4268 pstrcpy(ifname, sizeof(ifname), ifname1);
4269 else
4270 ifname[0] = '\0';
4271 TFR(fd = tap_open(ifname, sizeof(ifname)));
4272 if (fd < 0)
4273 return -1;
4275 if (!setup_script || !strcmp(setup_script, "no"))
4276 setup_script = "";
4277 if (setup_script[0] != '\0') {
4278 if (launch_script(setup_script, ifname, fd))
4279 return -1;
4281 s = net_tap_fd_init(vlan, fd);
4282 if (!s)
4283 return -1;
4284 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4285 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4286 if (down_script && strcmp(down_script, "no"))
4287 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4288 return 0;
4291 #endif /* !_WIN32 */
4293 /* network connection */
4294 typedef struct NetSocketState {
4295 VLANClientState *vc;
4296 int fd;
4297 int state; /* 0 = getting length, 1 = getting data */
4298 int index;
4299 int packet_len;
4300 uint8_t buf[4096];
4301 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4302 } NetSocketState;
4304 typedef struct NetSocketListenState {
4305 VLANState *vlan;
4306 int fd;
4307 } NetSocketListenState;
4309 /* XXX: we consider we can send the whole packet without blocking */
4310 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4312 NetSocketState *s = opaque;
4313 uint32_t len;
4314 len = htonl(size);
4316 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4317 send_all(s->fd, buf, size);
4320 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4322 NetSocketState *s = opaque;
4323 sendto(s->fd, buf, size, 0,
4324 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4327 static void net_socket_send(void *opaque)
4329 NetSocketState *s = opaque;
4330 int l, size, err;
4331 uint8_t buf1[4096];
4332 const uint8_t *buf;
4334 size = recv(s->fd, buf1, sizeof(buf1), 0);
4335 if (size < 0) {
4336 err = socket_error();
4337 if (err != EWOULDBLOCK)
4338 goto eoc;
4339 } else if (size == 0) {
4340 /* end of connection */
4341 eoc:
4342 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4343 closesocket(s->fd);
4344 return;
4346 buf = buf1;
4347 while (size > 0) {
4348 /* reassemble a packet from the network */
4349 switch(s->state) {
4350 case 0:
4351 l = 4 - s->index;
4352 if (l > size)
4353 l = size;
4354 memcpy(s->buf + s->index, buf, l);
4355 buf += l;
4356 size -= l;
4357 s->index += l;
4358 if (s->index == 4) {
4359 /* got length */
4360 s->packet_len = ntohl(*(uint32_t *)s->buf);
4361 s->index = 0;
4362 s->state = 1;
4364 break;
4365 case 1:
4366 l = s->packet_len - s->index;
4367 if (l > size)
4368 l = size;
4369 memcpy(s->buf + s->index, buf, l);
4370 s->index += l;
4371 buf += l;
4372 size -= l;
4373 if (s->index >= s->packet_len) {
4374 qemu_send_packet(s->vc, s->buf, s->packet_len);
4375 s->index = 0;
4376 s->state = 0;
4378 break;
4383 static void net_socket_send_dgram(void *opaque)
4385 NetSocketState *s = opaque;
4386 int size;
4388 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4389 if (size < 0)
4390 return;
4391 if (size == 0) {
4392 /* end of connection */
4393 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4394 return;
4396 qemu_send_packet(s->vc, s->buf, size);
4399 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4401 struct ip_mreq imr;
4402 int fd;
4403 int val, ret;
4404 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4405 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4406 inet_ntoa(mcastaddr->sin_addr),
4407 (int)ntohl(mcastaddr->sin_addr.s_addr));
4408 return -1;
4411 fd = socket(PF_INET, SOCK_DGRAM, 0);
4412 if (fd < 0) {
4413 perror("socket(PF_INET, SOCK_DGRAM)");
4414 return -1;
4417 val = 1;
4418 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4419 (const char *)&val, sizeof(val));
4420 if (ret < 0) {
4421 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4422 goto fail;
4425 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4426 if (ret < 0) {
4427 perror("bind");
4428 goto fail;
4431 /* Add host to multicast group */
4432 imr.imr_multiaddr = mcastaddr->sin_addr;
4433 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4435 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4436 (const char *)&imr, sizeof(struct ip_mreq));
4437 if (ret < 0) {
4438 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4439 goto fail;
4442 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4443 val = 1;
4444 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4445 (const char *)&val, sizeof(val));
4446 if (ret < 0) {
4447 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4448 goto fail;
4451 socket_set_nonblock(fd);
4452 return fd;
4453 fail:
4454 if (fd >= 0)
4455 closesocket(fd);
4456 return -1;
4459 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4460 int is_connected)
4462 struct sockaddr_in saddr;
4463 int newfd;
4464 socklen_t saddr_len;
4465 NetSocketState *s;
4467 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4468 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4469 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4472 if (is_connected) {
4473 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4474 /* must be bound */
4475 if (saddr.sin_addr.s_addr==0) {
4476 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4477 fd);
4478 return NULL;
4480 /* clone dgram socket */
4481 newfd = net_socket_mcast_create(&saddr);
4482 if (newfd < 0) {
4483 /* error already reported by net_socket_mcast_create() */
4484 close(fd);
4485 return NULL;
4487 /* clone newfd to fd, close newfd */
4488 dup2(newfd, fd);
4489 close(newfd);
4491 } else {
4492 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4493 fd, strerror(errno));
4494 return NULL;
4498 s = qemu_mallocz(sizeof(NetSocketState));
4499 if (!s)
4500 return NULL;
4501 s->fd = fd;
4503 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4504 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4506 /* mcast: save bound address as dst */
4507 if (is_connected) s->dgram_dst=saddr;
4509 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4510 "socket: fd=%d (%s mcast=%s:%d)",
4511 fd, is_connected? "cloned" : "",
4512 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4513 return s;
4516 static void net_socket_connect(void *opaque)
4518 NetSocketState *s = opaque;
4519 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4522 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4523 int is_connected)
4525 NetSocketState *s;
4526 s = qemu_mallocz(sizeof(NetSocketState));
4527 if (!s)
4528 return NULL;
4529 s->fd = fd;
4530 s->vc = qemu_new_vlan_client(vlan,
4531 net_socket_receive, NULL, s);
4532 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4533 "socket: fd=%d", fd);
4534 if (is_connected) {
4535 net_socket_connect(s);
4536 } else {
4537 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4539 return s;
4542 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4543 int is_connected)
4545 int so_type=-1, optlen=sizeof(so_type);
4547 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4548 (socklen_t *)&optlen)< 0) {
4549 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4550 return NULL;
4552 switch(so_type) {
4553 case SOCK_DGRAM:
4554 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4555 case SOCK_STREAM:
4556 return net_socket_fd_init_stream(vlan, fd, is_connected);
4557 default:
4558 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4559 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4560 return net_socket_fd_init_stream(vlan, fd, is_connected);
4562 return NULL;
4565 static void net_socket_accept(void *opaque)
4567 NetSocketListenState *s = opaque;
4568 NetSocketState *s1;
4569 struct sockaddr_in saddr;
4570 socklen_t len;
4571 int fd;
4573 for(;;) {
4574 len = sizeof(saddr);
4575 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4576 if (fd < 0 && errno != EINTR) {
4577 return;
4578 } else if (fd >= 0) {
4579 break;
4582 s1 = net_socket_fd_init(s->vlan, fd, 1);
4583 if (!s1) {
4584 closesocket(fd);
4585 } else {
4586 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4587 "socket: connection from %s:%d",
4588 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4592 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4594 NetSocketListenState *s;
4595 int fd, val, ret;
4596 struct sockaddr_in saddr;
4598 if (parse_host_port(&saddr, host_str) < 0)
4599 return -1;
4601 s = qemu_mallocz(sizeof(NetSocketListenState));
4602 if (!s)
4603 return -1;
4605 fd = socket(PF_INET, SOCK_STREAM, 0);
4606 if (fd < 0) {
4607 perror("socket");
4608 return -1;
4610 socket_set_nonblock(fd);
4612 /* allow fast reuse */
4613 val = 1;
4614 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4616 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4617 if (ret < 0) {
4618 perror("bind");
4619 return -1;
4621 ret = listen(fd, 0);
4622 if (ret < 0) {
4623 perror("listen");
4624 return -1;
4626 s->vlan = vlan;
4627 s->fd = fd;
4628 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4629 return 0;
4632 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4634 NetSocketState *s;
4635 int fd, connected, ret, err;
4636 struct sockaddr_in saddr;
4638 if (parse_host_port(&saddr, host_str) < 0)
4639 return -1;
4641 fd = socket(PF_INET, SOCK_STREAM, 0);
4642 if (fd < 0) {
4643 perror("socket");
4644 return -1;
4646 socket_set_nonblock(fd);
4648 connected = 0;
4649 for(;;) {
4650 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4651 if (ret < 0) {
4652 err = socket_error();
4653 if (err == EINTR || err == EWOULDBLOCK) {
4654 } else if (err == EINPROGRESS) {
4655 break;
4656 #ifdef _WIN32
4657 } else if (err == WSAEALREADY) {
4658 break;
4659 #endif
4660 } else {
4661 perror("connect");
4662 closesocket(fd);
4663 return -1;
4665 } else {
4666 connected = 1;
4667 break;
4670 s = net_socket_fd_init(vlan, fd, connected);
4671 if (!s)
4672 return -1;
4673 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4674 "socket: connect to %s:%d",
4675 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4676 return 0;
4679 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4681 NetSocketState *s;
4682 int fd;
4683 struct sockaddr_in saddr;
4685 if (parse_host_port(&saddr, host_str) < 0)
4686 return -1;
4689 fd = net_socket_mcast_create(&saddr);
4690 if (fd < 0)
4691 return -1;
4693 s = net_socket_fd_init(vlan, fd, 0);
4694 if (!s)
4695 return -1;
4697 s->dgram_dst = saddr;
4699 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4700 "socket: mcast=%s:%d",
4701 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4702 return 0;
4706 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4708 char *q;
4710 q = buf;
4711 while (*p != '\0' && *p != '=') {
4712 if (q && (q - buf) < buf_size - 1)
4713 *q++ = *p;
4714 p++;
4716 if (q)
4717 *q = '\0';
4719 return p;
4722 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4724 char *q;
4726 q = buf;
4727 while (*p != '\0') {
4728 if (*p == ',') {
4729 if (*(p + 1) != ',')
4730 break;
4731 p++;
4733 if (q && (q - buf) < buf_size - 1)
4734 *q++ = *p;
4735 p++;
4737 if (q)
4738 *q = '\0';
4740 return p;
4743 static int get_param_value(char *buf, int buf_size,
4744 const char *tag, const char *str)
4746 const char *p;
4747 char option[128];
4749 p = str;
4750 for(;;) {
4751 p = get_opt_name(option, sizeof(option), p);
4752 if (*p != '=')
4753 break;
4754 p++;
4755 if (!strcmp(tag, option)) {
4756 (void)get_opt_value(buf, buf_size, p);
4757 return strlen(buf);
4758 } else {
4759 p = get_opt_value(NULL, 0, p);
4761 if (*p != ',')
4762 break;
4763 p++;
4765 return 0;
4768 static int check_params(char *buf, int buf_size,
4769 char **params, const char *str)
4771 const char *p;
4772 int i;
4774 p = str;
4775 for(;;) {
4776 p = get_opt_name(buf, buf_size, p);
4777 if (*p != '=')
4778 return -1;
4779 p++;
4780 for(i = 0; params[i] != NULL; i++)
4781 if (!strcmp(params[i], buf))
4782 break;
4783 if (params[i] == NULL)
4784 return -1;
4785 p = get_opt_value(NULL, 0, p);
4786 if (*p != ',')
4787 break;
4788 p++;
4790 return 0;
4794 static int net_client_init(const char *str)
4796 const char *p;
4797 char *q;
4798 char device[64];
4799 char buf[1024];
4800 int vlan_id, ret;
4801 VLANState *vlan;
4803 p = str;
4804 q = device;
4805 while (*p != '\0' && *p != ',') {
4806 if ((q - device) < sizeof(device) - 1)
4807 *q++ = *p;
4808 p++;
4810 *q = '\0';
4811 if (*p == ',')
4812 p++;
4813 vlan_id = 0;
4814 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4815 vlan_id = strtol(buf, NULL, 0);
4817 vlan = qemu_find_vlan(vlan_id);
4818 if (!vlan) {
4819 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4820 return -1;
4822 if (!strcmp(device, "nic")) {
4823 NICInfo *nd;
4824 uint8_t *macaddr;
4826 if (nb_nics >= MAX_NICS) {
4827 fprintf(stderr, "Too Many NICs\n");
4828 return -1;
4830 nd = &nd_table[nb_nics];
4831 macaddr = nd->macaddr;
4832 macaddr[0] = 0x52;
4833 macaddr[1] = 0x54;
4834 macaddr[2] = 0x00;
4835 macaddr[3] = 0x12;
4836 macaddr[4] = 0x34;
4837 macaddr[5] = 0x56 + nb_nics;
4839 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4840 if (parse_macaddr(macaddr, buf) < 0) {
4841 fprintf(stderr, "invalid syntax for ethernet address\n");
4842 return -1;
4845 if (get_param_value(buf, sizeof(buf), "model", p)) {
4846 nd->model = strdup(buf);
4848 nd->vlan = vlan;
4849 nb_nics++;
4850 vlan->nb_guest_devs++;
4851 ret = 0;
4852 } else
4853 if (!strcmp(device, "none")) {
4854 /* does nothing. It is needed to signal that no network cards
4855 are wanted */
4856 ret = 0;
4857 } else
4858 #ifdef CONFIG_SLIRP
4859 if (!strcmp(device, "user")) {
4860 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4861 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4863 vlan->nb_host_devs++;
4864 ret = net_slirp_init(vlan);
4865 } else
4866 #endif
4867 #ifdef _WIN32
4868 if (!strcmp(device, "tap")) {
4869 char ifname[64];
4870 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4871 fprintf(stderr, "tap: no interface name\n");
4872 return -1;
4874 vlan->nb_host_devs++;
4875 ret = tap_win32_init(vlan, ifname);
4876 } else
4877 #else
4878 if (!strcmp(device, "tap")) {
4879 char ifname[64];
4880 char setup_script[1024], down_script[1024];
4881 int fd;
4882 vlan->nb_host_devs++;
4883 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4884 fd = strtol(buf, NULL, 0);
4885 ret = -1;
4886 if (net_tap_fd_init(vlan, fd))
4887 ret = 0;
4888 } else {
4889 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4890 ifname[0] = '\0';
4892 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4893 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4895 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4896 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4898 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4900 } else
4901 #endif
4902 if (!strcmp(device, "socket")) {
4903 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4904 int fd;
4905 fd = strtol(buf, NULL, 0);
4906 ret = -1;
4907 if (net_socket_fd_init(vlan, fd, 1))
4908 ret = 0;
4909 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4910 ret = net_socket_listen_init(vlan, buf);
4911 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4912 ret = net_socket_connect_init(vlan, buf);
4913 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4914 ret = net_socket_mcast_init(vlan, buf);
4915 } else {
4916 fprintf(stderr, "Unknown socket options: %s\n", p);
4917 return -1;
4919 vlan->nb_host_devs++;
4920 } else
4922 fprintf(stderr, "Unknown network device: %s\n", device);
4923 return -1;
4925 if (ret < 0) {
4926 fprintf(stderr, "Could not initialize device '%s'\n", device);
4929 return ret;
4932 void do_info_network(void)
4934 VLANState *vlan;
4935 VLANClientState *vc;
4937 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4938 term_printf("VLAN %d devices:\n", vlan->id);
4939 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4940 term_printf(" %s\n", vc->info_str);
4944 #define HD_ALIAS "index=%d,media=disk"
4945 #ifdef TARGET_PPC
4946 #define CDROM_ALIAS "index=1,media=cdrom"
4947 #else
4948 #define CDROM_ALIAS "index=2,media=cdrom"
4949 #endif
4950 #define FD_ALIAS "index=%d,if=floppy"
4951 #define PFLASH_ALIAS "if=pflash"
4952 #define MTD_ALIAS "if=mtd"
4953 #define SD_ALIAS "index=0,if=sd"
4955 static int drive_add(const char *file, const char *fmt, ...)
4957 va_list ap;
4959 if (nb_drives_opt >= MAX_DRIVES) {
4960 fprintf(stderr, "qemu: too many drives\n");
4961 exit(1);
4964 drives_opt[nb_drives_opt].file = file;
4965 va_start(ap, fmt);
4966 vsnprintf(drives_opt[nb_drives_opt].opt,
4967 sizeof(drives_opt[0].opt), fmt, ap);
4968 va_end(ap);
4970 return nb_drives_opt++;
4973 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4975 int index;
4977 /* seek interface, bus and unit */
4979 for (index = 0; index < nb_drives; index++)
4980 if (drives_table[index].type == type &&
4981 drives_table[index].bus == bus &&
4982 drives_table[index].unit == unit)
4983 return index;
4985 return -1;
4988 int drive_get_max_bus(BlockInterfaceType type)
4990 int max_bus;
4991 int index;
4993 max_bus = -1;
4994 for (index = 0; index < nb_drives; index++) {
4995 if(drives_table[index].type == type &&
4996 drives_table[index].bus > max_bus)
4997 max_bus = drives_table[index].bus;
4999 return max_bus;
5002 static int drive_init(struct drive_opt *arg, int snapshot,
5003 QEMUMachine *machine)
5005 char buf[128];
5006 char file[1024];
5007 char devname[128];
5008 const char *mediastr = "";
5009 BlockInterfaceType type;
5010 enum { MEDIA_DISK, MEDIA_CDROM } media;
5011 int bus_id, unit_id;
5012 int cyls, heads, secs, translation;
5013 BlockDriverState *bdrv;
5014 int max_devs;
5015 int index;
5016 int cache;
5017 int bdrv_flags;
5018 char *str = arg->opt;
5019 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5020 "secs", "trans", "media", "snapshot", "file",
5021 "cache", "boot", NULL };
5023 if (check_params(buf, sizeof(buf), params, str) < 0) {
5024 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5025 buf, str);
5026 return -1;
5029 file[0] = 0;
5030 cyls = heads = secs = 0;
5031 bus_id = 0;
5032 unit_id = -1;
5033 translation = BIOS_ATA_TRANSLATION_AUTO;
5034 index = -1;
5035 cache = 1;
5037 if (!strcmp(machine->name, "realview") ||
5038 !strcmp(machine->name, "SS-5") ||
5039 !strcmp(machine->name, "SS-10") ||
5040 !strcmp(machine->name, "SS-600MP") ||
5041 !strcmp(machine->name, "versatilepb") ||
5042 !strcmp(machine->name, "versatileab")) {
5043 type = IF_SCSI;
5044 max_devs = MAX_SCSI_DEVS;
5045 strcpy(devname, "scsi");
5046 } else {
5047 type = IF_IDE;
5048 max_devs = MAX_IDE_DEVS;
5049 strcpy(devname, "ide");
5051 media = MEDIA_DISK;
5053 /* extract parameters */
5055 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5056 bus_id = strtol(buf, NULL, 0);
5057 if (bus_id < 0) {
5058 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5059 return -1;
5063 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5064 unit_id = strtol(buf, NULL, 0);
5065 if (unit_id < 0) {
5066 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5067 return -1;
5071 if (get_param_value(buf, sizeof(buf), "if", str)) {
5072 strncpy(devname, buf, sizeof(devname));
5073 if (!strcmp(buf, "ide")) {
5074 type = IF_IDE;
5075 max_devs = MAX_IDE_DEVS;
5076 } else if (!strcmp(buf, "scsi")) {
5077 type = IF_SCSI;
5078 max_devs = MAX_SCSI_DEVS;
5079 } else if (!strcmp(buf, "floppy")) {
5080 type = IF_FLOPPY;
5081 max_devs = 0;
5082 } else if (!strcmp(buf, "pflash")) {
5083 type = IF_PFLASH;
5084 max_devs = 0;
5085 } else if (!strcmp(buf, "mtd")) {
5086 type = IF_MTD;
5087 max_devs = 0;
5088 } else if (!strcmp(buf, "sd")) {
5089 type = IF_SD;
5090 max_devs = 0;
5091 } else if (!strcmp(buf, "virtio")) {
5092 type = IF_VIRTIO;
5093 max_devs = 0;
5094 } else {
5095 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5096 return -1;
5100 if (get_param_value(buf, sizeof(buf), "index", str)) {
5101 index = strtol(buf, NULL, 0);
5102 if (index < 0) {
5103 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5104 return -1;
5108 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5109 cyls = strtol(buf, NULL, 0);
5112 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5113 heads = strtol(buf, NULL, 0);
5116 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5117 secs = strtol(buf, NULL, 0);
5120 if (cyls || heads || secs) {
5121 if (cyls < 1 || cyls > 16383) {
5122 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5123 return -1;
5125 if (heads < 1 || heads > 16) {
5126 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5127 return -1;
5129 if (secs < 1 || secs > 63) {
5130 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5131 return -1;
5135 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5136 if (!cyls) {
5137 fprintf(stderr,
5138 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5139 str);
5140 return -1;
5142 if (!strcmp(buf, "none"))
5143 translation = BIOS_ATA_TRANSLATION_NONE;
5144 else if (!strcmp(buf, "lba"))
5145 translation = BIOS_ATA_TRANSLATION_LBA;
5146 else if (!strcmp(buf, "auto"))
5147 translation = BIOS_ATA_TRANSLATION_AUTO;
5148 else {
5149 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5150 return -1;
5154 if (get_param_value(buf, sizeof(buf), "media", str)) {
5155 if (!strcmp(buf, "disk")) {
5156 media = MEDIA_DISK;
5157 } else if (!strcmp(buf, "cdrom")) {
5158 if (cyls || secs || heads) {
5159 fprintf(stderr,
5160 "qemu: '%s' invalid physical CHS format\n", str);
5161 return -1;
5163 media = MEDIA_CDROM;
5164 } else {
5165 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5166 return -1;
5170 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5171 if (!strcmp(buf, "on"))
5172 snapshot = 1;
5173 else if (!strcmp(buf, "off"))
5174 snapshot = 0;
5175 else {
5176 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5177 return -1;
5181 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5182 if (!strcmp(buf, "off"))
5183 cache = 0;
5184 else if (!strcmp(buf, "on"))
5185 cache = 1;
5186 else {
5187 fprintf(stderr, "qemu: invalid cache option\n");
5188 return -1;
5192 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5193 if (!strcmp(buf, "on")) {
5194 if (extboot_drive != -1) {
5195 fprintf(stderr, "qemu: two bootable drives specified\n");
5196 return -1;
5198 extboot_drive = nb_drives;
5199 } else if (strcmp(buf, "off")) {
5200 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5201 return -1;
5205 if (arg->file == NULL)
5206 get_param_value(file, sizeof(file), "file", str);
5207 else
5208 pstrcpy(file, sizeof(file), arg->file);
5210 /* compute bus and unit according index */
5212 if (index != -1) {
5213 if (bus_id != 0 || unit_id != -1) {
5214 fprintf(stderr,
5215 "qemu: '%s' index cannot be used with bus and unit\n", str);
5216 return -1;
5218 if (max_devs == 0)
5220 unit_id = index;
5221 bus_id = 0;
5222 } else {
5223 unit_id = index % max_devs;
5224 bus_id = index / max_devs;
5228 /* if user doesn't specify a unit_id,
5229 * try to find the first free
5232 if (unit_id == -1) {
5233 unit_id = 0;
5234 while (drive_get_index(type, bus_id, unit_id) != -1) {
5235 unit_id++;
5236 if (max_devs && unit_id >= max_devs) {
5237 unit_id -= max_devs;
5238 bus_id++;
5243 /* check unit id */
5245 if (max_devs && unit_id >= max_devs) {
5246 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5247 str, unit_id, max_devs - 1);
5248 return -1;
5252 * ignore multiple definitions
5255 if (drive_get_index(type, bus_id, unit_id) != -1)
5256 return 0;
5258 /* init */
5260 if (type == IF_IDE || type == IF_SCSI)
5261 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5262 if (max_devs)
5263 snprintf(buf, sizeof(buf), "%s%i%s%i",
5264 devname, bus_id, mediastr, unit_id);
5265 else
5266 snprintf(buf, sizeof(buf), "%s%s%i",
5267 devname, mediastr, unit_id);
5268 bdrv = bdrv_new(buf);
5269 drives_table[nb_drives].bdrv = bdrv;
5270 drives_table[nb_drives].type = type;
5271 drives_table[nb_drives].bus = bus_id;
5272 drives_table[nb_drives].unit = unit_id;
5273 nb_drives++;
5275 switch(type) {
5276 case IF_IDE:
5277 case IF_SCSI:
5278 switch(media) {
5279 case MEDIA_DISK:
5280 if (cyls != 0) {
5281 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5282 bdrv_set_translation_hint(bdrv, translation);
5284 break;
5285 case MEDIA_CDROM:
5286 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5287 break;
5289 break;
5290 case IF_SD:
5291 /* FIXME: This isn't really a floppy, but it's a reasonable
5292 approximation. */
5293 case IF_FLOPPY:
5294 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5295 break;
5296 case IF_PFLASH:
5297 case IF_MTD:
5298 case IF_VIRTIO:
5299 break;
5301 if (!file[0])
5302 return 0;
5303 bdrv_flags = 0;
5304 if (snapshot)
5305 bdrv_flags |= BDRV_O_SNAPSHOT;
5306 if (!cache)
5307 bdrv_flags |= BDRV_O_DIRECT;
5308 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5309 fprintf(stderr, "qemu: could not open disk image %s\n",
5310 file);
5311 return -1;
5313 return 0;
5316 /***********************************************************/
5317 /* USB devices */
5319 static USBPort *used_usb_ports;
5320 static USBPort *free_usb_ports;
5322 /* ??? Maybe change this to register a hub to keep track of the topology. */
5323 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5324 usb_attachfn attach)
5326 port->opaque = opaque;
5327 port->index = index;
5328 port->attach = attach;
5329 port->next = free_usb_ports;
5330 free_usb_ports = port;
5333 static int usb_device_add(const char *devname)
5335 const char *p;
5336 USBDevice *dev;
5337 USBPort *port;
5339 if (!free_usb_ports)
5340 return -1;
5342 if (strstart(devname, "host:", &p)) {
5343 dev = usb_host_device_open(p);
5344 } else if (!strcmp(devname, "mouse")) {
5345 dev = usb_mouse_init();
5346 } else if (!strcmp(devname, "tablet")) {
5347 dev = usb_tablet_init();
5348 } else if (!strcmp(devname, "keyboard")) {
5349 dev = usb_keyboard_init();
5350 } else if (strstart(devname, "disk:", &p)) {
5351 dev = usb_msd_init(p);
5352 } else if (!strcmp(devname, "wacom-tablet")) {
5353 dev = usb_wacom_init();
5354 } else if (strstart(devname, "serial:", &p)) {
5355 dev = usb_serial_init(p);
5356 } else {
5357 return -1;
5359 if (!dev)
5360 return -1;
5362 /* Find a USB port to add the device to. */
5363 port = free_usb_ports;
5364 if (!port->next) {
5365 USBDevice *hub;
5367 /* Create a new hub and chain it on. */
5368 free_usb_ports = NULL;
5369 port->next = used_usb_ports;
5370 used_usb_ports = port;
5372 hub = usb_hub_init(VM_USB_HUB_SIZE);
5373 usb_attach(port, hub);
5374 port = free_usb_ports;
5377 free_usb_ports = port->next;
5378 port->next = used_usb_ports;
5379 used_usb_ports = port;
5380 usb_attach(port, dev);
5381 return 0;
5384 static int usb_device_del(const char *devname)
5386 USBPort *port;
5387 USBPort **lastp;
5388 USBDevice *dev;
5389 int bus_num, addr;
5390 const char *p;
5392 if (!used_usb_ports)
5393 return -1;
5395 p = strchr(devname, '.');
5396 if (!p)
5397 return -1;
5398 bus_num = strtoul(devname, NULL, 0);
5399 addr = strtoul(p + 1, NULL, 0);
5400 if (bus_num != 0)
5401 return -1;
5403 lastp = &used_usb_ports;
5404 port = used_usb_ports;
5405 while (port && port->dev->addr != addr) {
5406 lastp = &port->next;
5407 port = port->next;
5410 if (!port)
5411 return -1;
5413 dev = port->dev;
5414 *lastp = port->next;
5415 usb_attach(port, NULL);
5416 dev->handle_destroy(dev);
5417 port->next = free_usb_ports;
5418 free_usb_ports = port;
5419 return 0;
5422 void do_usb_add(const char *devname)
5424 int ret;
5425 ret = usb_device_add(devname);
5426 if (ret < 0)
5427 term_printf("Could not add USB device '%s'\n", devname);
5430 void do_usb_del(const char *devname)
5432 int ret;
5433 ret = usb_device_del(devname);
5434 if (ret < 0)
5435 term_printf("Could not remove USB device '%s'\n", devname);
5438 void usb_info(void)
5440 USBDevice *dev;
5441 USBPort *port;
5442 const char *speed_str;
5444 if (!usb_enabled) {
5445 term_printf("USB support not enabled\n");
5446 return;
5449 for (port = used_usb_ports; port; port = port->next) {
5450 dev = port->dev;
5451 if (!dev)
5452 continue;
5453 switch(dev->speed) {
5454 case USB_SPEED_LOW:
5455 speed_str = "1.5";
5456 break;
5457 case USB_SPEED_FULL:
5458 speed_str = "12";
5459 break;
5460 case USB_SPEED_HIGH:
5461 speed_str = "480";
5462 break;
5463 default:
5464 speed_str = "?";
5465 break;
5467 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5468 0, dev->addr, speed_str, dev->devname);
5472 /***********************************************************/
5473 /* PCMCIA/Cardbus */
5475 static struct pcmcia_socket_entry_s {
5476 struct pcmcia_socket_s *socket;
5477 struct pcmcia_socket_entry_s *next;
5478 } *pcmcia_sockets = 0;
5480 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5482 struct pcmcia_socket_entry_s *entry;
5484 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5485 entry->socket = socket;
5486 entry->next = pcmcia_sockets;
5487 pcmcia_sockets = entry;
5490 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5492 struct pcmcia_socket_entry_s *entry, **ptr;
5494 ptr = &pcmcia_sockets;
5495 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5496 if (entry->socket == socket) {
5497 *ptr = entry->next;
5498 qemu_free(entry);
5502 void pcmcia_info(void)
5504 struct pcmcia_socket_entry_s *iter;
5505 if (!pcmcia_sockets)
5506 term_printf("No PCMCIA sockets\n");
5508 for (iter = pcmcia_sockets; iter; iter = iter->next)
5509 term_printf("%s: %s\n", iter->socket->slot_string,
5510 iter->socket->attached ? iter->socket->card_string :
5511 "Empty");
5514 /***********************************************************/
5515 /* dumb display */
5517 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5521 static void dumb_resize(DisplayState *ds, int w, int h)
5525 static void dumb_refresh(DisplayState *ds)
5527 #if defined(CONFIG_SDL)
5528 vga_hw_update();
5529 #endif
5532 static void dumb_display_init(DisplayState *ds)
5534 ds->data = NULL;
5535 ds->linesize = 0;
5536 ds->depth = 0;
5537 ds->dpy_update = dumb_update;
5538 ds->dpy_resize = dumb_resize;
5539 ds->dpy_refresh = dumb_refresh;
5542 /***********************************************************/
5543 /* I/O handling */
5545 #define MAX_IO_HANDLERS 64
5547 typedef struct IOHandlerRecord {
5548 int fd;
5549 IOCanRWHandler *fd_read_poll;
5550 IOHandler *fd_read;
5551 IOHandler *fd_write;
5552 int deleted;
5553 void *opaque;
5554 /* temporary data */
5555 struct pollfd *ufd;
5556 struct IOHandlerRecord *next;
5557 } IOHandlerRecord;
5559 static IOHandlerRecord *first_io_handler;
5561 /* XXX: fd_read_poll should be suppressed, but an API change is
5562 necessary in the character devices to suppress fd_can_read(). */
5563 int qemu_set_fd_handler2(int fd,
5564 IOCanRWHandler *fd_read_poll,
5565 IOHandler *fd_read,
5566 IOHandler *fd_write,
5567 void *opaque)
5569 IOHandlerRecord **pioh, *ioh;
5571 if (!fd_read && !fd_write) {
5572 pioh = &first_io_handler;
5573 for(;;) {
5574 ioh = *pioh;
5575 if (ioh == NULL)
5576 break;
5577 if (ioh->fd == fd) {
5578 ioh->deleted = 1;
5579 break;
5581 pioh = &ioh->next;
5583 } else {
5584 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5585 if (ioh->fd == fd)
5586 goto found;
5588 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5589 if (!ioh)
5590 return -1;
5591 ioh->next = first_io_handler;
5592 first_io_handler = ioh;
5593 found:
5594 ioh->fd = fd;
5595 ioh->fd_read_poll = fd_read_poll;
5596 ioh->fd_read = fd_read;
5597 ioh->fd_write = fd_write;
5598 ioh->opaque = opaque;
5599 ioh->deleted = 0;
5601 return 0;
5604 int qemu_set_fd_handler(int fd,
5605 IOHandler *fd_read,
5606 IOHandler *fd_write,
5607 void *opaque)
5609 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5612 /***********************************************************/
5613 /* Polling handling */
5615 typedef struct PollingEntry {
5616 PollingFunc *func;
5617 void *opaque;
5618 struct PollingEntry *next;
5619 } PollingEntry;
5621 static PollingEntry *first_polling_entry;
5623 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5625 PollingEntry **ppe, *pe;
5626 pe = qemu_mallocz(sizeof(PollingEntry));
5627 if (!pe)
5628 return -1;
5629 pe->func = func;
5630 pe->opaque = opaque;
5631 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5632 *ppe = pe;
5633 return 0;
5636 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5638 PollingEntry **ppe, *pe;
5639 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5640 pe = *ppe;
5641 if (pe->func == func && pe->opaque == opaque) {
5642 *ppe = pe->next;
5643 qemu_free(pe);
5644 break;
5649 #ifdef _WIN32
5650 /***********************************************************/
5651 /* Wait objects support */
5652 typedef struct WaitObjects {
5653 int num;
5654 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5655 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5656 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5657 } WaitObjects;
5659 static WaitObjects wait_objects = {0};
5661 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5663 WaitObjects *w = &wait_objects;
5665 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5666 return -1;
5667 w->events[w->num] = handle;
5668 w->func[w->num] = func;
5669 w->opaque[w->num] = opaque;
5670 w->num++;
5671 return 0;
5674 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5676 int i, found;
5677 WaitObjects *w = &wait_objects;
5679 found = 0;
5680 for (i = 0; i < w->num; i++) {
5681 if (w->events[i] == handle)
5682 found = 1;
5683 if (found) {
5684 w->events[i] = w->events[i + 1];
5685 w->func[i] = w->func[i + 1];
5686 w->opaque[i] = w->opaque[i + 1];
5689 if (found)
5690 w->num--;
5692 #endif
5694 #define SELF_ANNOUNCE_ROUNDS 5
5695 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5696 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5697 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5699 static int announce_self_create(uint8_t *buf,
5700 uint8_t *mac_addr)
5702 uint32_t magic = EXPERIMENTAL_MAGIC;
5703 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5705 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5707 memset(buf, 0xff, 6); /* h_dst */
5708 memcpy(buf + 6, mac_addr, 6); /* h_src */
5709 memcpy(buf + 12, &proto, 2); /* h_proto */
5710 memcpy(buf + 14, &magic, 4); /* magic */
5712 return 18; /* len */
5715 static void qemu_announce_self(void)
5717 int i, j, len;
5718 VLANState *vlan;
5719 VLANClientState *vc;
5720 uint8_t buf[256];
5722 for (i = 0; i < nb_nics; i++) {
5723 len = announce_self_create(buf, nd_table[i].macaddr);
5724 vlan = nd_table[i].vlan;
5725 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5726 if (vc->fd_read == tap_receive) /* send only if tap */
5727 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5728 vc->fd_read(vc->opaque, buf, len);
5733 /***********************************************************/
5734 /* savevm/loadvm support */
5736 #define IO_BUF_SIZE 32768
5738 struct QEMUFile {
5739 QEMUFilePutBufferFunc *put_buffer;
5740 QEMUFileGetBufferFunc *get_buffer;
5741 QEMUFileCloseFunc *close;
5742 void *opaque;
5744 int64_t buf_offset; /* start of buffer when writing, end of buffer
5745 when reading */
5746 int buf_index;
5747 int buf_size; /* 0 when writing */
5748 uint8_t buf[IO_BUF_SIZE];
5751 typedef struct QEMUFileFD
5753 int fd;
5754 } QEMUFileFD;
5756 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5758 QEMUFileFD *s = opaque;
5759 int offset = 0;
5760 ssize_t len;
5762 again:
5763 len = read(s->fd, buf + offset, size - offset);
5764 if (len == -1) {
5765 if (errno == EINTR || errno == EAGAIN)
5766 goto again;
5769 return len;
5772 QEMUFile *qemu_fopen_fd(int fd)
5774 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5775 s->fd = fd;
5776 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5779 typedef struct QEMUFileUnix
5781 FILE *outfile;
5782 } QEMUFileUnix;
5784 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5786 QEMUFileUnix *s = opaque;
5787 fseek(s->outfile, pos, SEEK_SET);
5788 fwrite(buf, 1, size, s->outfile);
5791 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5793 QEMUFileUnix *s = opaque;
5794 fseek(s->outfile, pos, SEEK_SET);
5795 return fread(buf, 1, size, s->outfile);
5798 static void file_close(void *opaque)
5800 QEMUFileUnix *s = opaque;
5801 fclose(s->outfile);
5802 qemu_free(s);
5805 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5807 QEMUFileUnix *s;
5809 s = qemu_mallocz(sizeof(QEMUFileUnix));
5810 if (!s)
5811 return NULL;
5813 s->outfile = fopen(filename, mode);
5814 if (!s->outfile)
5815 goto fail;
5817 if (!strcmp(mode, "wb"))
5818 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5819 else if (!strcmp(mode, "rb"))
5820 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5822 fail:
5823 if (s->outfile)
5824 fclose(s->outfile);
5825 qemu_free(s);
5826 return NULL;
5829 typedef struct QEMUFileBdrv
5831 BlockDriverState *bs;
5832 int64_t base_offset;
5833 } QEMUFileBdrv;
5835 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5837 QEMUFileBdrv *s = opaque;
5838 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5841 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5843 QEMUFileBdrv *s = opaque;
5844 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5847 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5849 QEMUFileBdrv *s;
5851 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5852 if (!s)
5853 return NULL;
5855 s->bs = bs;
5856 s->base_offset = offset;
5858 if (is_writable)
5859 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5861 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5864 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5865 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5867 QEMUFile *f;
5869 f = qemu_mallocz(sizeof(QEMUFile));
5870 if (!f)
5871 return NULL;
5873 f->opaque = opaque;
5874 f->put_buffer = put_buffer;
5875 f->get_buffer = get_buffer;
5876 f->close = close;
5878 return f;
5881 void qemu_fflush(QEMUFile *f)
5883 if (!f->put_buffer)
5884 return;
5886 if (f->buf_index > 0) {
5887 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5888 f->buf_offset += f->buf_index;
5889 f->buf_index = 0;
5893 static void qemu_fill_buffer(QEMUFile *f)
5895 int len;
5897 if (!f->get_buffer)
5898 return;
5900 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5901 if (len < 0)
5902 len = 0;
5904 f->buf_index = 0;
5905 f->buf_size = len;
5906 f->buf_offset += len;
5909 void qemu_fclose(QEMUFile *f)
5911 qemu_fflush(f);
5912 if (f->close)
5913 f->close(f->opaque);
5914 qemu_free(f);
5917 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5919 int l;
5920 while (size > 0) {
5921 l = IO_BUF_SIZE - f->buf_index;
5922 if (l > size)
5923 l = size;
5924 memcpy(f->buf + f->buf_index, buf, l);
5925 f->buf_index += l;
5926 buf += l;
5927 size -= l;
5928 if (f->buf_index >= IO_BUF_SIZE)
5929 qemu_fflush(f);
5933 void qemu_put_byte(QEMUFile *f, int v)
5935 f->buf[f->buf_index++] = v;
5936 if (f->buf_index >= IO_BUF_SIZE)
5937 qemu_fflush(f);
5940 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5942 int size, l;
5944 size = size1;
5945 while (size > 0) {
5946 l = f->buf_size - f->buf_index;
5947 if (l == 0) {
5948 qemu_fill_buffer(f);
5949 l = f->buf_size - f->buf_index;
5950 if (l == 0)
5951 break;
5953 if (l > size)
5954 l = size;
5955 memcpy(buf, f->buf + f->buf_index, l);
5956 f->buf_index += l;
5957 buf += l;
5958 size -= l;
5960 return size1 - size;
5963 int qemu_get_byte(QEMUFile *f)
5965 if (f->buf_index >= f->buf_size) {
5966 qemu_fill_buffer(f);
5967 if (f->buf_index >= f->buf_size)
5968 return 0;
5970 return f->buf[f->buf_index++];
5973 int64_t qemu_ftell(QEMUFile *f)
5975 return f->buf_offset - f->buf_size + f->buf_index;
5978 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5980 if (whence == SEEK_SET) {
5981 /* nothing to do */
5982 } else if (whence == SEEK_CUR) {
5983 pos += qemu_ftell(f);
5984 } else {
5985 /* SEEK_END not supported */
5986 return -1;
5988 if (f->put_buffer) {
5989 qemu_fflush(f);
5990 f->buf_offset = pos;
5991 } else {
5992 f->buf_offset = pos;
5993 f->buf_index = 0;
5994 f->buf_size = 0;
5996 return pos;
5999 void qemu_put_be16(QEMUFile *f, unsigned int v)
6001 qemu_put_byte(f, v >> 8);
6002 qemu_put_byte(f, v);
6005 void qemu_put_be32(QEMUFile *f, unsigned int v)
6007 qemu_put_byte(f, v >> 24);
6008 qemu_put_byte(f, v >> 16);
6009 qemu_put_byte(f, v >> 8);
6010 qemu_put_byte(f, v);
6013 void qemu_put_be64(QEMUFile *f, uint64_t v)
6015 qemu_put_be32(f, v >> 32);
6016 qemu_put_be32(f, v);
6019 unsigned int qemu_get_be16(QEMUFile *f)
6021 unsigned int v;
6022 v = qemu_get_byte(f) << 8;
6023 v |= qemu_get_byte(f);
6024 return v;
6027 unsigned int qemu_get_be32(QEMUFile *f)
6029 unsigned int v;
6030 v = qemu_get_byte(f) << 24;
6031 v |= qemu_get_byte(f) << 16;
6032 v |= qemu_get_byte(f) << 8;
6033 v |= qemu_get_byte(f);
6034 return v;
6037 uint64_t qemu_get_be64(QEMUFile *f)
6039 uint64_t v;
6040 v = (uint64_t)qemu_get_be32(f) << 32;
6041 v |= qemu_get_be32(f);
6042 return v;
6045 typedef struct SaveStateEntry {
6046 char idstr[256];
6047 int instance_id;
6048 int version_id;
6049 SaveStateHandler *save_state;
6050 LoadStateHandler *load_state;
6051 void *opaque;
6052 struct SaveStateEntry *next;
6053 } SaveStateEntry;
6055 static SaveStateEntry *first_se;
6057 int register_savevm(const char *idstr,
6058 int instance_id,
6059 int version_id,
6060 SaveStateHandler *save_state,
6061 LoadStateHandler *load_state,
6062 void *opaque)
6064 SaveStateEntry *se, **pse;
6066 se = qemu_malloc(sizeof(SaveStateEntry));
6067 if (!se)
6068 return -1;
6069 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6070 se->instance_id = instance_id;
6071 se->version_id = version_id;
6072 se->save_state = save_state;
6073 se->load_state = load_state;
6074 se->opaque = opaque;
6075 se->next = NULL;
6077 /* add at the end of list */
6078 pse = &first_se;
6079 while (*pse != NULL)
6080 pse = &(*pse)->next;
6081 *pse = se;
6082 return 0;
6085 #define QEMU_VM_FILE_MAGIC 0x5145564d
6086 #define QEMU_VM_FILE_VERSION 0x00000002
6088 static int qemu_savevm_state(QEMUFile *f)
6090 SaveStateEntry *se;
6091 int len, ret;
6092 int64_t cur_pos, len_pos, total_len_pos;
6094 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6095 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6096 total_len_pos = qemu_ftell(f);
6097 qemu_put_be64(f, 0); /* total size */
6099 for(se = first_se; se != NULL; se = se->next) {
6100 /* ID string */
6101 len = strlen(se->idstr);
6102 qemu_put_byte(f, len);
6103 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6105 qemu_put_be32(f, se->instance_id);
6106 qemu_put_be32(f, se->version_id);
6108 /* record size: filled later */
6109 len_pos = qemu_ftell(f);
6110 qemu_put_be32(f, 0);
6111 se->save_state(f, se->opaque);
6113 /* fill record size */
6114 cur_pos = qemu_ftell(f);
6115 len = cur_pos - len_pos - 4;
6116 qemu_fseek(f, len_pos, SEEK_SET);
6117 qemu_put_be32(f, len);
6118 qemu_fseek(f, cur_pos, SEEK_SET);
6120 cur_pos = qemu_ftell(f);
6121 qemu_fseek(f, total_len_pos, SEEK_SET);
6122 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6123 qemu_fseek(f, cur_pos, SEEK_SET);
6125 ret = 0;
6126 return ret;
6129 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6131 SaveStateEntry *se;
6133 for(se = first_se; se != NULL; se = se->next) {
6134 if (!strcmp(se->idstr, idstr) &&
6135 instance_id == se->instance_id)
6136 return se;
6138 return NULL;
6141 static int qemu_loadvm_state(QEMUFile *f)
6143 SaveStateEntry *se;
6144 int len, ret, instance_id, record_len, version_id;
6145 int64_t total_len, end_pos, cur_pos;
6146 unsigned int v;
6147 char idstr[256];
6149 v = qemu_get_be32(f);
6150 if (v != QEMU_VM_FILE_MAGIC)
6151 goto fail;
6152 v = qemu_get_be32(f);
6153 if (v != QEMU_VM_FILE_VERSION) {
6154 fail:
6155 ret = -1;
6156 goto the_end;
6158 total_len = qemu_get_be64(f);
6159 end_pos = total_len + qemu_ftell(f);
6160 for(;;) {
6161 if (qemu_ftell(f) >= end_pos)
6162 break;
6163 len = qemu_get_byte(f);
6164 qemu_get_buffer(f, (uint8_t *)idstr, len);
6165 idstr[len] = '\0';
6166 instance_id = qemu_get_be32(f);
6167 version_id = qemu_get_be32(f);
6168 record_len = qemu_get_be32(f);
6169 #if 0
6170 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6171 idstr, instance_id, version_id, record_len);
6172 #endif
6173 cur_pos = qemu_ftell(f);
6174 se = find_se(idstr, instance_id);
6175 if (!se) {
6176 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6177 instance_id, idstr);
6178 } else {
6179 ret = se->load_state(f, se->opaque, version_id);
6180 if (ret < 0) {
6181 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6182 instance_id, idstr);
6183 goto the_end;
6186 /* always seek to exact end of record */
6187 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6189 ret = 0;
6190 the_end:
6191 return ret;
6194 int qemu_live_savevm_state(QEMUFile *f)
6196 SaveStateEntry *se;
6197 int len, ret;
6199 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6200 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6202 for(se = first_se; se != NULL; se = se->next) {
6203 len = strlen(se->idstr);
6205 qemu_put_byte(f, len);
6206 qemu_put_buffer(f, se->idstr, len);
6207 qemu_put_be32(f, se->instance_id);
6208 qemu_put_be32(f, se->version_id);
6210 se->save_state(f, se->opaque);
6213 qemu_put_byte(f, 0);
6215 ret = 0;
6216 return ret;
6219 int qemu_live_loadvm_state(QEMUFile *f)
6221 SaveStateEntry *se;
6222 int len, ret, instance_id, version_id;
6223 unsigned int v;
6224 char idstr[256];
6226 v = qemu_get_be32(f);
6227 if (v != QEMU_VM_FILE_MAGIC)
6228 goto fail;
6229 v = qemu_get_be32(f);
6230 if (v != QEMU_VM_FILE_VERSION) {
6231 fail:
6232 ret = -1;
6233 goto the_end;
6236 for(;;) {
6237 len = qemu_get_byte(f);
6238 if (len == 0)
6239 break;
6240 qemu_get_buffer(f, idstr, len);
6241 idstr[len] = '\0';
6242 instance_id = qemu_get_be32(f);
6243 version_id = qemu_get_be32(f);
6244 se = find_se(idstr, instance_id);
6245 if (!se) {
6246 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6247 instance_id, idstr);
6248 } else {
6249 if (version_id > se->version_id) { /* src version > dst version */
6250 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6251 idstr, version_id, se->version_id);
6252 ret = -1;
6253 goto the_end;
6255 ret = se->load_state(f, se->opaque, version_id);
6256 if (ret < 0) {
6257 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6258 instance_id, idstr);
6259 goto the_end;
6263 ret = 0;
6265 qemu_announce_self();
6267 the_end:
6268 return ret;
6271 /* device can contain snapshots */
6272 static int bdrv_can_snapshot(BlockDriverState *bs)
6274 return (bs &&
6275 !bdrv_is_removable(bs) &&
6276 !bdrv_is_read_only(bs));
6279 /* device must be snapshots in order to have a reliable snapshot */
6280 static int bdrv_has_snapshot(BlockDriverState *bs)
6282 return (bs &&
6283 !bdrv_is_removable(bs) &&
6284 !bdrv_is_read_only(bs));
6287 static BlockDriverState *get_bs_snapshots(void)
6289 BlockDriverState *bs;
6290 int i;
6292 if (bs_snapshots)
6293 return bs_snapshots;
6294 for(i = 0; i <= nb_drives; i++) {
6295 bs = drives_table[i].bdrv;
6296 if (bdrv_can_snapshot(bs))
6297 goto ok;
6299 return NULL;
6301 bs_snapshots = bs;
6302 return bs;
6305 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6306 const char *name)
6308 QEMUSnapshotInfo *sn_tab, *sn;
6309 int nb_sns, i, ret;
6311 ret = -ENOENT;
6312 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6313 if (nb_sns < 0)
6314 return ret;
6315 for(i = 0; i < nb_sns; i++) {
6316 sn = &sn_tab[i];
6317 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6318 *sn_info = *sn;
6319 ret = 0;
6320 break;
6323 qemu_free(sn_tab);
6324 return ret;
6327 void do_savevm(const char *name)
6329 BlockDriverState *bs, *bs1;
6330 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6331 int must_delete, ret, i;
6332 BlockDriverInfo bdi1, *bdi = &bdi1;
6333 QEMUFile *f;
6334 int saved_vm_running;
6335 #ifdef _WIN32
6336 struct _timeb tb;
6337 #else
6338 struct timeval tv;
6339 #endif
6341 bs = get_bs_snapshots();
6342 if (!bs) {
6343 term_printf("No block device can accept snapshots\n");
6344 return;
6347 /* ??? Should this occur after vm_stop? */
6348 qemu_aio_flush();
6350 saved_vm_running = vm_running;
6351 vm_stop(0);
6353 must_delete = 0;
6354 if (name) {
6355 ret = bdrv_snapshot_find(bs, old_sn, name);
6356 if (ret >= 0) {
6357 must_delete = 1;
6360 memset(sn, 0, sizeof(*sn));
6361 if (must_delete) {
6362 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6363 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6364 } else {
6365 if (name)
6366 pstrcpy(sn->name, sizeof(sn->name), name);
6369 /* fill auxiliary fields */
6370 #ifdef _WIN32
6371 _ftime(&tb);
6372 sn->date_sec = tb.time;
6373 sn->date_nsec = tb.millitm * 1000000;
6374 #else
6375 gettimeofday(&tv, NULL);
6376 sn->date_sec = tv.tv_sec;
6377 sn->date_nsec = tv.tv_usec * 1000;
6378 #endif
6379 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6381 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6382 term_printf("Device %s does not support VM state snapshots\n",
6383 bdrv_get_device_name(bs));
6384 goto the_end;
6387 /* save the VM state */
6388 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6389 if (!f) {
6390 term_printf("Could not open VM state file\n");
6391 goto the_end;
6393 ret = qemu_savevm_state(f);
6394 sn->vm_state_size = qemu_ftell(f);
6395 qemu_fclose(f);
6396 if (ret < 0) {
6397 term_printf("Error %d while writing VM\n", ret);
6398 goto the_end;
6401 /* create the snapshots */
6403 for(i = 0; i < nb_drives; i++) {
6404 bs1 = drives_table[i].bdrv;
6405 if (bdrv_has_snapshot(bs1)) {
6406 if (must_delete) {
6407 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6408 if (ret < 0) {
6409 term_printf("Error while deleting snapshot on '%s'\n",
6410 bdrv_get_device_name(bs1));
6413 ret = bdrv_snapshot_create(bs1, sn);
6414 if (ret < 0) {
6415 term_printf("Error while creating snapshot on '%s'\n",
6416 bdrv_get_device_name(bs1));
6421 the_end:
6422 if (saved_vm_running)
6423 vm_start();
6426 void do_loadvm(const char *name)
6428 BlockDriverState *bs, *bs1;
6429 BlockDriverInfo bdi1, *bdi = &bdi1;
6430 QEMUFile *f;
6431 int i, ret;
6432 int saved_vm_running;
6434 bs = get_bs_snapshots();
6435 if (!bs) {
6436 term_printf("No block device supports snapshots\n");
6437 return;
6440 /* Flush all IO requests so they don't interfere with the new state. */
6441 qemu_aio_flush();
6443 saved_vm_running = vm_running;
6444 vm_stop(0);
6446 for(i = 0; i <= nb_drives; i++) {
6447 bs1 = drives_table[i].bdrv;
6448 if (bdrv_has_snapshot(bs1)) {
6449 ret = bdrv_snapshot_goto(bs1, name);
6450 if (ret < 0) {
6451 if (bs != bs1)
6452 term_printf("Warning: ");
6453 switch(ret) {
6454 case -ENOTSUP:
6455 term_printf("Snapshots not supported on device '%s'\n",
6456 bdrv_get_device_name(bs1));
6457 break;
6458 case -ENOENT:
6459 term_printf("Could not find snapshot '%s' on device '%s'\n",
6460 name, bdrv_get_device_name(bs1));
6461 break;
6462 default:
6463 term_printf("Error %d while activating snapshot on '%s'\n",
6464 ret, bdrv_get_device_name(bs1));
6465 break;
6467 /* fatal on snapshot block device */
6468 if (bs == bs1)
6469 goto the_end;
6474 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6475 term_printf("Device %s does not support VM state snapshots\n",
6476 bdrv_get_device_name(bs));
6477 return;
6480 /* restore the VM state */
6481 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6482 if (!f) {
6483 term_printf("Could not open VM state file\n");
6484 goto the_end;
6486 ret = qemu_loadvm_state(f);
6487 qemu_fclose(f);
6488 if (ret < 0) {
6489 term_printf("Error %d while loading VM state\n", ret);
6491 the_end:
6492 if (saved_vm_running)
6493 vm_start();
6496 void do_delvm(const char *name)
6498 BlockDriverState *bs, *bs1;
6499 int i, ret;
6501 bs = get_bs_snapshots();
6502 if (!bs) {
6503 term_printf("No block device supports snapshots\n");
6504 return;
6507 for(i = 0; i <= nb_drives; i++) {
6508 bs1 = drives_table[i].bdrv;
6509 if (bdrv_has_snapshot(bs1)) {
6510 ret = bdrv_snapshot_delete(bs1, name);
6511 if (ret < 0) {
6512 if (ret == -ENOTSUP)
6513 term_printf("Snapshots not supported on device '%s'\n",
6514 bdrv_get_device_name(bs1));
6515 else
6516 term_printf("Error %d while deleting snapshot on '%s'\n",
6517 ret, bdrv_get_device_name(bs1));
6523 void do_info_snapshots(void)
6525 BlockDriverState *bs, *bs1;
6526 QEMUSnapshotInfo *sn_tab, *sn;
6527 int nb_sns, i;
6528 char buf[256];
6530 bs = get_bs_snapshots();
6531 if (!bs) {
6532 term_printf("No available block device supports snapshots\n");
6533 return;
6535 term_printf("Snapshot devices:");
6536 for(i = 0; i <= nb_drives; i++) {
6537 bs1 = drives_table[i].bdrv;
6538 if (bdrv_has_snapshot(bs1)) {
6539 if (bs == bs1)
6540 term_printf(" %s", bdrv_get_device_name(bs1));
6543 term_printf("\n");
6545 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6546 if (nb_sns < 0) {
6547 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6548 return;
6550 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6551 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6552 for(i = 0; i < nb_sns; i++) {
6553 sn = &sn_tab[i];
6554 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6556 qemu_free(sn_tab);
6559 /***********************************************************/
6560 /* cpu save/restore */
6562 #if defined(TARGET_I386)
6564 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6566 qemu_put_be32(f, dt->selector);
6567 qemu_put_betl(f, dt->base);
6568 qemu_put_be32(f, dt->limit);
6569 qemu_put_be32(f, dt->flags);
6572 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6574 dt->selector = qemu_get_be32(f);
6575 dt->base = qemu_get_betl(f);
6576 dt->limit = qemu_get_be32(f);
6577 dt->flags = qemu_get_be32(f);
6580 void cpu_save(QEMUFile *f, void *opaque)
6582 CPUState *env = opaque;
6583 uint16_t fptag, fpus, fpuc, fpregs_format;
6584 uint32_t hflags;
6585 int i;
6587 if (kvm_enabled())
6588 kvm_save_registers(env);
6590 for(i = 0; i < CPU_NB_REGS; i++)
6591 qemu_put_betls(f, &env->regs[i]);
6592 qemu_put_betls(f, &env->eip);
6593 qemu_put_betls(f, &env->eflags);
6594 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6595 qemu_put_be32s(f, &hflags);
6597 /* FPU */
6598 fpuc = env->fpuc;
6599 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6600 fptag = 0;
6601 for(i = 0; i < 8; i++) {
6602 fptag |= ((!env->fptags[i]) << i);
6605 qemu_put_be16s(f, &fpuc);
6606 qemu_put_be16s(f, &fpus);
6607 qemu_put_be16s(f, &fptag);
6609 #ifdef USE_X86LDOUBLE
6610 fpregs_format = 0;
6611 #else
6612 fpregs_format = 1;
6613 #endif
6614 qemu_put_be16s(f, &fpregs_format);
6616 for(i = 0; i < 8; i++) {
6617 #ifdef USE_X86LDOUBLE
6619 uint64_t mant;
6620 uint16_t exp;
6621 /* we save the real CPU data (in case of MMX usage only 'mant'
6622 contains the MMX register */
6623 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6624 qemu_put_be64(f, mant);
6625 qemu_put_be16(f, exp);
6627 #else
6628 /* if we use doubles for float emulation, we save the doubles to
6629 avoid losing information in case of MMX usage. It can give
6630 problems if the image is restored on a CPU where long
6631 doubles are used instead. */
6632 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6633 #endif
6636 for(i = 0; i < 6; i++)
6637 cpu_put_seg(f, &env->segs[i]);
6638 cpu_put_seg(f, &env->ldt);
6639 cpu_put_seg(f, &env->tr);
6640 cpu_put_seg(f, &env->gdt);
6641 cpu_put_seg(f, &env->idt);
6643 qemu_put_be32s(f, &env->sysenter_cs);
6644 qemu_put_be32s(f, &env->sysenter_esp);
6645 qemu_put_be32s(f, &env->sysenter_eip);
6647 qemu_put_betls(f, &env->cr[0]);
6648 qemu_put_betls(f, &env->cr[2]);
6649 qemu_put_betls(f, &env->cr[3]);
6650 qemu_put_betls(f, &env->cr[4]);
6652 for(i = 0; i < 8; i++)
6653 qemu_put_betls(f, &env->dr[i]);
6655 /* MMU */
6656 qemu_put_be32s(f, &env->a20_mask);
6658 /* XMM */
6659 qemu_put_be32s(f, &env->mxcsr);
6660 for(i = 0; i < CPU_NB_REGS; i++) {
6661 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6662 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6665 #ifdef TARGET_X86_64
6666 qemu_put_be64s(f, &env->efer);
6667 qemu_put_be64s(f, &env->star);
6668 qemu_put_be64s(f, &env->lstar);
6669 qemu_put_be64s(f, &env->cstar);
6670 qemu_put_be64s(f, &env->fmask);
6671 qemu_put_be64s(f, &env->kernelgsbase);
6672 #endif
6673 qemu_put_be32s(f, &env->smbase);
6675 if (kvm_enabled()) {
6676 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6677 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6679 qemu_put_be64s(f, &env->tsc);
6683 #ifdef USE_X86LDOUBLE
6684 /* XXX: add that in a FPU generic layer */
6685 union x86_longdouble {
6686 uint64_t mant;
6687 uint16_t exp;
6690 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6691 #define EXPBIAS1 1023
6692 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6693 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6695 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6697 int e;
6698 /* mantissa */
6699 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6700 /* exponent + sign */
6701 e = EXPD1(temp) - EXPBIAS1 + 16383;
6702 e |= SIGND1(temp) >> 16;
6703 p->exp = e;
6705 #endif
6707 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6709 CPUState *env = opaque;
6710 int i, guess_mmx;
6711 uint32_t hflags;
6712 uint16_t fpus, fpuc, fptag, fpregs_format;
6714 if (version_id != 3 && version_id != 4)
6715 return -EINVAL;
6716 for(i = 0; i < CPU_NB_REGS; i++)
6717 qemu_get_betls(f, &env->regs[i]);
6718 qemu_get_betls(f, &env->eip);
6719 qemu_get_betls(f, &env->eflags);
6720 qemu_get_be32s(f, &hflags);
6722 qemu_get_be16s(f, &fpuc);
6723 qemu_get_be16s(f, &fpus);
6724 qemu_get_be16s(f, &fptag);
6725 qemu_get_be16s(f, &fpregs_format);
6727 /* NOTE: we cannot always restore the FPU state if the image come
6728 from a host with a different 'USE_X86LDOUBLE' define. We guess
6729 if we are in an MMX state to restore correctly in that case. */
6730 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6731 for(i = 0; i < 8; i++) {
6732 uint64_t mant;
6733 uint16_t exp;
6735 switch(fpregs_format) {
6736 case 0:
6737 mant = qemu_get_be64(f);
6738 exp = qemu_get_be16(f);
6739 #ifdef USE_X86LDOUBLE
6740 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6741 #else
6742 /* difficult case */
6743 if (guess_mmx)
6744 env->fpregs[i].mmx.MMX_Q(0) = mant;
6745 else
6746 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6747 #endif
6748 break;
6749 case 1:
6750 mant = qemu_get_be64(f);
6751 #ifdef USE_X86LDOUBLE
6753 union x86_longdouble *p;
6754 /* difficult case */
6755 p = (void *)&env->fpregs[i];
6756 if (guess_mmx) {
6757 p->mant = mant;
6758 p->exp = 0xffff;
6759 } else {
6760 fp64_to_fp80(p, mant);
6763 #else
6764 env->fpregs[i].mmx.MMX_Q(0) = mant;
6765 #endif
6766 break;
6767 default:
6768 return -EINVAL;
6772 env->fpuc = fpuc;
6773 /* XXX: restore FPU round state */
6774 env->fpstt = (fpus >> 11) & 7;
6775 env->fpus = fpus & ~0x3800;
6776 fptag ^= 0xff;
6777 for(i = 0; i < 8; i++) {
6778 env->fptags[i] = (fptag >> i) & 1;
6781 for(i = 0; i < 6; i++)
6782 cpu_get_seg(f, &env->segs[i]);
6783 cpu_get_seg(f, &env->ldt);
6784 cpu_get_seg(f, &env->tr);
6785 cpu_get_seg(f, &env->gdt);
6786 cpu_get_seg(f, &env->idt);
6788 qemu_get_be32s(f, &env->sysenter_cs);
6789 qemu_get_be32s(f, &env->sysenter_esp);
6790 qemu_get_be32s(f, &env->sysenter_eip);
6792 qemu_get_betls(f, &env->cr[0]);
6793 qemu_get_betls(f, &env->cr[2]);
6794 qemu_get_betls(f, &env->cr[3]);
6795 qemu_get_betls(f, &env->cr[4]);
6797 for(i = 0; i < 8; i++)
6798 qemu_get_betls(f, &env->dr[i]);
6800 /* MMU */
6801 qemu_get_be32s(f, &env->a20_mask);
6803 qemu_get_be32s(f, &env->mxcsr);
6804 for(i = 0; i < CPU_NB_REGS; i++) {
6805 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6806 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6809 #ifdef TARGET_X86_64
6810 qemu_get_be64s(f, &env->efer);
6811 qemu_get_be64s(f, &env->star);
6812 qemu_get_be64s(f, &env->lstar);
6813 qemu_get_be64s(f, &env->cstar);
6814 qemu_get_be64s(f, &env->fmask);
6815 qemu_get_be64s(f, &env->kernelgsbase);
6816 #endif
6817 if (version_id >= 4)
6818 qemu_get_be32s(f, &env->smbase);
6820 /* XXX: compute hflags from scratch, except for CPL and IIF */
6821 env->hflags = hflags;
6822 tlb_flush(env, 1);
6823 if (kvm_enabled()) {
6824 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6825 because no userspace IRQs will ever clear this flag */
6826 env->hflags &= ~HF_HALTED_MASK;
6827 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6828 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6830 qemu_get_be64s(f, &env->tsc);
6831 kvm_load_registers(env);
6833 return 0;
6836 #elif defined(TARGET_PPC)
6837 void cpu_save(QEMUFile *f, void *opaque)
6841 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6843 return 0;
6846 #elif defined(TARGET_MIPS)
6847 void cpu_save(QEMUFile *f, void *opaque)
6851 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6853 return 0;
6856 #elif defined(TARGET_SPARC)
6857 void cpu_save(QEMUFile *f, void *opaque)
6859 CPUState *env = opaque;
6860 int i;
6861 uint32_t tmp;
6863 for(i = 0; i < 8; i++)
6864 qemu_put_betls(f, &env->gregs[i]);
6865 for(i = 0; i < NWINDOWS * 16; i++)
6866 qemu_put_betls(f, &env->regbase[i]);
6868 /* FPU */
6869 for(i = 0; i < TARGET_FPREGS; i++) {
6870 union {
6871 float32 f;
6872 uint32_t i;
6873 } u;
6874 u.f = env->fpr[i];
6875 qemu_put_be32(f, u.i);
6878 qemu_put_betls(f, &env->pc);
6879 qemu_put_betls(f, &env->npc);
6880 qemu_put_betls(f, &env->y);
6881 tmp = GET_PSR(env);
6882 qemu_put_be32(f, tmp);
6883 qemu_put_betls(f, &env->fsr);
6884 qemu_put_betls(f, &env->tbr);
6885 #ifndef TARGET_SPARC64
6886 qemu_put_be32s(f, &env->wim);
6887 /* MMU */
6888 for(i = 0; i < 16; i++)
6889 qemu_put_be32s(f, &env->mmuregs[i]);
6890 #endif
6893 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6895 CPUState *env = opaque;
6896 int i;
6897 uint32_t tmp;
6899 for(i = 0; i < 8; i++)
6900 qemu_get_betls(f, &env->gregs[i]);
6901 for(i = 0; i < NWINDOWS * 16; i++)
6902 qemu_get_betls(f, &env->regbase[i]);
6904 /* FPU */
6905 for(i = 0; i < TARGET_FPREGS; i++) {
6906 union {
6907 float32 f;
6908 uint32_t i;
6909 } u;
6910 u.i = qemu_get_be32(f);
6911 env->fpr[i] = u.f;
6914 qemu_get_betls(f, &env->pc);
6915 qemu_get_betls(f, &env->npc);
6916 qemu_get_betls(f, &env->y);
6917 tmp = qemu_get_be32(f);
6918 env->cwp = 0; /* needed to ensure that the wrapping registers are
6919 correctly updated */
6920 PUT_PSR(env, tmp);
6921 qemu_get_betls(f, &env->fsr);
6922 qemu_get_betls(f, &env->tbr);
6923 #ifndef TARGET_SPARC64
6924 qemu_get_be32s(f, &env->wim);
6925 /* MMU */
6926 for(i = 0; i < 16; i++)
6927 qemu_get_be32s(f, &env->mmuregs[i]);
6928 #endif
6929 tlb_flush(env, 1);
6930 return 0;
6933 #elif defined(TARGET_ARM)
6935 void cpu_save(QEMUFile *f, void *opaque)
6937 int i;
6938 CPUARMState *env = (CPUARMState *)opaque;
6940 for (i = 0; i < 16; i++) {
6941 qemu_put_be32(f, env->regs[i]);
6943 qemu_put_be32(f, cpsr_read(env));
6944 qemu_put_be32(f, env->spsr);
6945 for (i = 0; i < 6; i++) {
6946 qemu_put_be32(f, env->banked_spsr[i]);
6947 qemu_put_be32(f, env->banked_r13[i]);
6948 qemu_put_be32(f, env->banked_r14[i]);
6950 for (i = 0; i < 5; i++) {
6951 qemu_put_be32(f, env->usr_regs[i]);
6952 qemu_put_be32(f, env->fiq_regs[i]);
6954 qemu_put_be32(f, env->cp15.c0_cpuid);
6955 qemu_put_be32(f, env->cp15.c0_cachetype);
6956 qemu_put_be32(f, env->cp15.c1_sys);
6957 qemu_put_be32(f, env->cp15.c1_coproc);
6958 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6959 qemu_put_be32(f, env->cp15.c2_base0);
6960 qemu_put_be32(f, env->cp15.c2_base1);
6961 qemu_put_be32(f, env->cp15.c2_mask);
6962 qemu_put_be32(f, env->cp15.c2_data);
6963 qemu_put_be32(f, env->cp15.c2_insn);
6964 qemu_put_be32(f, env->cp15.c3);
6965 qemu_put_be32(f, env->cp15.c5_insn);
6966 qemu_put_be32(f, env->cp15.c5_data);
6967 for (i = 0; i < 8; i++) {
6968 qemu_put_be32(f, env->cp15.c6_region[i]);
6970 qemu_put_be32(f, env->cp15.c6_insn);
6971 qemu_put_be32(f, env->cp15.c6_data);
6972 qemu_put_be32(f, env->cp15.c9_insn);
6973 qemu_put_be32(f, env->cp15.c9_data);
6974 qemu_put_be32(f, env->cp15.c13_fcse);
6975 qemu_put_be32(f, env->cp15.c13_context);
6976 qemu_put_be32(f, env->cp15.c13_tls1);
6977 qemu_put_be32(f, env->cp15.c13_tls2);
6978 qemu_put_be32(f, env->cp15.c13_tls3);
6979 qemu_put_be32(f, env->cp15.c15_cpar);
6981 qemu_put_be32(f, env->features);
6983 if (arm_feature(env, ARM_FEATURE_VFP)) {
6984 for (i = 0; i < 16; i++) {
6985 CPU_DoubleU u;
6986 u.d = env->vfp.regs[i];
6987 qemu_put_be32(f, u.l.upper);
6988 qemu_put_be32(f, u.l.lower);
6990 for (i = 0; i < 16; i++) {
6991 qemu_put_be32(f, env->vfp.xregs[i]);
6994 /* TODO: Should use proper FPSCR access functions. */
6995 qemu_put_be32(f, env->vfp.vec_len);
6996 qemu_put_be32(f, env->vfp.vec_stride);
6998 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6999 for (i = 16; i < 32; i++) {
7000 CPU_DoubleU u;
7001 u.d = env->vfp.regs[i];
7002 qemu_put_be32(f, u.l.upper);
7003 qemu_put_be32(f, u.l.lower);
7008 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7009 for (i = 0; i < 16; i++) {
7010 qemu_put_be64(f, env->iwmmxt.regs[i]);
7012 for (i = 0; i < 16; i++) {
7013 qemu_put_be32(f, env->iwmmxt.cregs[i]);
7017 if (arm_feature(env, ARM_FEATURE_M)) {
7018 qemu_put_be32(f, env->v7m.other_sp);
7019 qemu_put_be32(f, env->v7m.vecbase);
7020 qemu_put_be32(f, env->v7m.basepri);
7021 qemu_put_be32(f, env->v7m.control);
7022 qemu_put_be32(f, env->v7m.current_sp);
7023 qemu_put_be32(f, env->v7m.exception);
7027 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7029 CPUARMState *env = (CPUARMState *)opaque;
7030 int i;
7032 if (version_id != ARM_CPU_SAVE_VERSION)
7033 return -EINVAL;
7035 for (i = 0; i < 16; i++) {
7036 env->regs[i] = qemu_get_be32(f);
7038 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
7039 env->spsr = qemu_get_be32(f);
7040 for (i = 0; i < 6; i++) {
7041 env->banked_spsr[i] = qemu_get_be32(f);
7042 env->banked_r13[i] = qemu_get_be32(f);
7043 env->banked_r14[i] = qemu_get_be32(f);
7045 for (i = 0; i < 5; i++) {
7046 env->usr_regs[i] = qemu_get_be32(f);
7047 env->fiq_regs[i] = qemu_get_be32(f);
7049 env->cp15.c0_cpuid = qemu_get_be32(f);
7050 env->cp15.c0_cachetype = qemu_get_be32(f);
7051 env->cp15.c1_sys = qemu_get_be32(f);
7052 env->cp15.c1_coproc = qemu_get_be32(f);
7053 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
7054 env->cp15.c2_base0 = qemu_get_be32(f);
7055 env->cp15.c2_base1 = qemu_get_be32(f);
7056 env->cp15.c2_mask = qemu_get_be32(f);
7057 env->cp15.c2_data = qemu_get_be32(f);
7058 env->cp15.c2_insn = qemu_get_be32(f);
7059 env->cp15.c3 = qemu_get_be32(f);
7060 env->cp15.c5_insn = qemu_get_be32(f);
7061 env->cp15.c5_data = qemu_get_be32(f);
7062 for (i = 0; i < 8; i++) {
7063 env->cp15.c6_region[i] = qemu_get_be32(f);
7065 env->cp15.c6_insn = qemu_get_be32(f);
7066 env->cp15.c6_data = qemu_get_be32(f);
7067 env->cp15.c9_insn = qemu_get_be32(f);
7068 env->cp15.c9_data = qemu_get_be32(f);
7069 env->cp15.c13_fcse = qemu_get_be32(f);
7070 env->cp15.c13_context = qemu_get_be32(f);
7071 env->cp15.c13_tls1 = qemu_get_be32(f);
7072 env->cp15.c13_tls2 = qemu_get_be32(f);
7073 env->cp15.c13_tls3 = qemu_get_be32(f);
7074 env->cp15.c15_cpar = qemu_get_be32(f);
7076 env->features = qemu_get_be32(f);
7078 if (arm_feature(env, ARM_FEATURE_VFP)) {
7079 for (i = 0; i < 16; i++) {
7080 CPU_DoubleU u;
7081 u.l.upper = qemu_get_be32(f);
7082 u.l.lower = qemu_get_be32(f);
7083 env->vfp.regs[i] = u.d;
7085 for (i = 0; i < 16; i++) {
7086 env->vfp.xregs[i] = qemu_get_be32(f);
7089 /* TODO: Should use proper FPSCR access functions. */
7090 env->vfp.vec_len = qemu_get_be32(f);
7091 env->vfp.vec_stride = qemu_get_be32(f);
7093 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7094 for (i = 0; i < 16; i++) {
7095 CPU_DoubleU u;
7096 u.l.upper = qemu_get_be32(f);
7097 u.l.lower = qemu_get_be32(f);
7098 env->vfp.regs[i] = u.d;
7103 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7104 for (i = 0; i < 16; i++) {
7105 env->iwmmxt.regs[i] = qemu_get_be64(f);
7107 for (i = 0; i < 16; i++) {
7108 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7112 if (arm_feature(env, ARM_FEATURE_M)) {
7113 env->v7m.other_sp = qemu_get_be32(f);
7114 env->v7m.vecbase = qemu_get_be32(f);
7115 env->v7m.basepri = qemu_get_be32(f);
7116 env->v7m.control = qemu_get_be32(f);
7117 env->v7m.current_sp = qemu_get_be32(f);
7118 env->v7m.exception = qemu_get_be32(f);
7121 return 0;
7124 #elif defined(TARGET_IA64)
7125 void cpu_save(QEMUFile *f, void *opaque)
7129 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7131 return 0;
7133 #else
7135 //#warning No CPU save/restore functions
7137 #endif
7139 /***********************************************************/
7140 /* ram save/restore */
7142 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7144 int v;
7146 v = qemu_get_byte(f);
7147 switch(v) {
7148 case 0:
7149 if (qemu_get_buffer(f, buf, len) != len)
7150 return -EIO;
7151 break;
7152 case 1:
7153 v = qemu_get_byte(f);
7154 memset(buf, v, len);
7155 break;
7156 default:
7157 return -EINVAL;
7159 return 0;
7162 static int ram_load_v1(QEMUFile *f, void *opaque)
7164 int i, ret;
7166 if (qemu_get_be32(f) != phys_ram_size)
7167 return -EINVAL;
7168 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7169 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7170 continue;
7171 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7172 if (ret)
7173 return ret;
7175 return 0;
7178 #define BDRV_HASH_BLOCK_SIZE 1024
7179 #define IOBUF_SIZE 4096
7180 #define RAM_CBLOCK_MAGIC 0xfabe
7182 typedef struct RamCompressState {
7183 z_stream zstream;
7184 QEMUFile *f;
7185 uint8_t buf[IOBUF_SIZE];
7186 } RamCompressState;
7188 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7190 int ret;
7191 memset(s, 0, sizeof(*s));
7192 s->f = f;
7193 ret = deflateInit2(&s->zstream, 1,
7194 Z_DEFLATED, 15,
7195 9, Z_DEFAULT_STRATEGY);
7196 if (ret != Z_OK)
7197 return -1;
7198 s->zstream.avail_out = IOBUF_SIZE;
7199 s->zstream.next_out = s->buf;
7200 return 0;
7203 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7205 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7206 qemu_put_be16(s->f, len);
7207 qemu_put_buffer(s->f, buf, len);
7210 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7212 int ret;
7214 s->zstream.avail_in = len;
7215 s->zstream.next_in = (uint8_t *)buf;
7216 while (s->zstream.avail_in > 0) {
7217 ret = deflate(&s->zstream, Z_NO_FLUSH);
7218 if (ret != Z_OK)
7219 return -1;
7220 if (s->zstream.avail_out == 0) {
7221 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7222 s->zstream.avail_out = IOBUF_SIZE;
7223 s->zstream.next_out = s->buf;
7226 return 0;
7229 static void ram_compress_close(RamCompressState *s)
7231 int len, ret;
7233 /* compress last bytes */
7234 for(;;) {
7235 ret = deflate(&s->zstream, Z_FINISH);
7236 if (ret == Z_OK || ret == Z_STREAM_END) {
7237 len = IOBUF_SIZE - s->zstream.avail_out;
7238 if (len > 0) {
7239 ram_put_cblock(s, s->buf, len);
7241 s->zstream.avail_out = IOBUF_SIZE;
7242 s->zstream.next_out = s->buf;
7243 if (ret == Z_STREAM_END)
7244 break;
7245 } else {
7246 goto fail;
7249 fail:
7250 deflateEnd(&s->zstream);
7253 typedef struct RamDecompressState {
7254 z_stream zstream;
7255 QEMUFile *f;
7256 uint8_t buf[IOBUF_SIZE];
7257 } RamDecompressState;
7259 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7261 int ret;
7262 memset(s, 0, sizeof(*s));
7263 s->f = f;
7264 ret = inflateInit(&s->zstream);
7265 if (ret != Z_OK)
7266 return -1;
7267 return 0;
7270 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7272 int ret, clen;
7274 s->zstream.avail_out = len;
7275 s->zstream.next_out = buf;
7276 while (s->zstream.avail_out > 0) {
7277 if (s->zstream.avail_in == 0) {
7278 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7279 return -1;
7280 clen = qemu_get_be16(s->f);
7281 if (clen > IOBUF_SIZE)
7282 return -1;
7283 qemu_get_buffer(s->f, s->buf, clen);
7284 s->zstream.avail_in = clen;
7285 s->zstream.next_in = s->buf;
7287 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7288 if (ret != Z_OK && ret != Z_STREAM_END) {
7289 return -1;
7292 return 0;
7295 static void ram_decompress_close(RamDecompressState *s)
7297 inflateEnd(&s->zstream);
7300 static void ram_save_live(QEMUFile *f, void *opaque)
7302 target_ulong addr;
7304 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7305 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7306 continue;
7307 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7308 qemu_put_be32(f, addr);
7309 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7312 qemu_put_be32(f, 1);
7315 static void ram_save_static(QEMUFile *f, void *opaque)
7317 int i;
7318 RamCompressState s1, *s = &s1;
7319 uint8_t buf[10];
7321 qemu_put_be32(f, phys_ram_size);
7322 if (ram_compress_open(s, f) < 0)
7323 return;
7324 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7325 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7326 continue;
7327 #if 0
7328 if (tight_savevm_enabled) {
7329 int64_t sector_num;
7330 int j;
7332 /* find if the memory block is available on a virtual
7333 block device */
7334 sector_num = -1;
7335 for(j = 0; j < nb_drives; j++) {
7336 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7337 phys_ram_base + i,
7338 BDRV_HASH_BLOCK_SIZE);
7339 if (sector_num >= 0)
7340 break;
7342 if (j == nb_drives)
7343 goto normal_compress;
7344 buf[0] = 1;
7345 buf[1] = j;
7346 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7347 ram_compress_buf(s, buf, 10);
7348 } else
7349 #endif
7351 // normal_compress:
7352 buf[0] = 0;
7353 ram_compress_buf(s, buf, 1);
7354 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7357 ram_compress_close(s);
7360 static void ram_save(QEMUFile *f, void *opaque)
7362 int in_migration = cpu_physical_memory_get_dirty_tracking();
7364 qemu_put_byte(f, in_migration);
7366 if (in_migration)
7367 ram_save_live(f, opaque);
7368 else
7369 ram_save_static(f, opaque);
7372 static int ram_load_live(QEMUFile *f, void *opaque)
7374 target_ulong addr;
7376 do {
7377 addr = qemu_get_be32(f);
7378 if (addr == 1)
7379 break;
7381 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7382 } while (1);
7384 return 0;
7387 static int ram_load_static(QEMUFile *f, void *opaque)
7389 RamDecompressState s1, *s = &s1;
7390 uint8_t buf[10];
7391 int i;
7393 if (qemu_get_be32(f) != phys_ram_size)
7394 return -EINVAL;
7395 if (ram_decompress_open(s, f) < 0)
7396 return -EINVAL;
7397 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7398 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7399 continue;
7400 if (ram_decompress_buf(s, buf, 1) < 0) {
7401 fprintf(stderr, "Error while reading ram block header\n");
7402 goto error;
7404 if (buf[0] == 0) {
7405 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7406 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7407 goto error;
7409 } else
7410 #if 0
7411 if (buf[0] == 1) {
7412 int bs_index;
7413 int64_t sector_num;
7415 ram_decompress_buf(s, buf + 1, 9);
7416 bs_index = buf[1];
7417 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7418 if (bs_index >= nb_drives) {
7419 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7420 goto error;
7422 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7423 phys_ram_base + i,
7424 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7425 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7426 bs_index, sector_num);
7427 goto error;
7429 } else
7430 #endif
7432 error:
7433 printf("Error block header\n");
7434 return -EINVAL;
7437 ram_decompress_close(s);
7438 return 0;
7441 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7443 int ret;
7445 switch (version_id) {
7446 case 1:
7447 ret = ram_load_v1(f, opaque);
7448 break;
7449 case 3:
7450 if (qemu_get_byte(f)) {
7451 ret = ram_load_live(f, opaque);
7452 break;
7454 case 2:
7455 ret = ram_load_static(f, opaque);
7456 break;
7457 default:
7458 ret = -EINVAL;
7459 break;
7462 return ret;
7465 /***********************************************************/
7466 /* bottom halves (can be seen as timers which expire ASAP) */
7468 struct QEMUBH {
7469 QEMUBHFunc *cb;
7470 void *opaque;
7471 int scheduled;
7472 QEMUBH *next;
7475 static QEMUBH *first_bh = NULL;
7477 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7479 QEMUBH *bh;
7480 bh = qemu_mallocz(sizeof(QEMUBH));
7481 if (!bh)
7482 return NULL;
7483 bh->cb = cb;
7484 bh->opaque = opaque;
7485 return bh;
7488 int qemu_bh_poll(void)
7490 QEMUBH *bh, **pbh;
7491 int ret;
7493 ret = 0;
7494 for(;;) {
7495 pbh = &first_bh;
7496 bh = *pbh;
7497 if (!bh)
7498 break;
7499 ret = 1;
7500 *pbh = bh->next;
7501 bh->scheduled = 0;
7502 bh->cb(bh->opaque);
7504 return ret;
7507 void qemu_bh_schedule(QEMUBH *bh)
7509 CPUState *env = cpu_single_env;
7510 if (bh->scheduled)
7511 return;
7512 bh->scheduled = 1;
7513 bh->next = first_bh;
7514 first_bh = bh;
7516 /* stop the currently executing CPU to execute the BH ASAP */
7517 if (env) {
7518 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7522 void qemu_bh_cancel(QEMUBH *bh)
7524 QEMUBH **pbh;
7525 if (bh->scheduled) {
7526 pbh = &first_bh;
7527 while (*pbh != bh)
7528 pbh = &(*pbh)->next;
7529 *pbh = bh->next;
7530 bh->scheduled = 0;
7534 void qemu_bh_delete(QEMUBH *bh)
7536 qemu_bh_cancel(bh);
7537 qemu_free(bh);
7540 /***********************************************************/
7541 /* machine registration */
7543 QEMUMachine *first_machine = NULL;
7545 int qemu_register_machine(QEMUMachine *m)
7547 QEMUMachine **pm;
7548 pm = &first_machine;
7549 while (*pm != NULL)
7550 pm = &(*pm)->next;
7551 m->next = NULL;
7552 *pm = m;
7553 return 0;
7556 static QEMUMachine *find_machine(const char *name)
7558 QEMUMachine *m;
7560 for(m = first_machine; m != NULL; m = m->next) {
7561 if (!strcmp(m->name, name))
7562 return m;
7564 return NULL;
7567 /***********************************************************/
7568 /* main execution loop */
7570 static void gui_update(void *opaque)
7572 DisplayState *ds = opaque;
7573 ds->dpy_refresh(ds);
7574 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7577 struct vm_change_state_entry {
7578 VMChangeStateHandler *cb;
7579 void *opaque;
7580 LIST_ENTRY (vm_change_state_entry) entries;
7583 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7585 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7586 void *opaque)
7588 VMChangeStateEntry *e;
7590 e = qemu_mallocz(sizeof (*e));
7591 if (!e)
7592 return NULL;
7594 e->cb = cb;
7595 e->opaque = opaque;
7596 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7597 return e;
7600 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7602 LIST_REMOVE (e, entries);
7603 qemu_free (e);
7606 static void vm_state_notify(int running)
7608 VMChangeStateEntry *e;
7610 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7611 e->cb(e->opaque, running);
7615 /* XXX: support several handlers */
7616 static VMStopHandler *vm_stop_cb;
7617 static void *vm_stop_opaque;
7619 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7621 vm_stop_cb = cb;
7622 vm_stop_opaque = opaque;
7623 return 0;
7626 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7628 vm_stop_cb = NULL;
7631 void vm_start(void)
7633 if (!vm_running) {
7634 cpu_enable_ticks();
7635 vm_running = 1;
7636 vm_state_notify(1);
7637 qemu_rearm_alarm_timer(alarm_timer);
7641 void vm_stop(int reason)
7643 if (vm_running) {
7644 cpu_disable_ticks();
7645 vm_running = 0;
7646 if (reason != 0) {
7647 if (vm_stop_cb) {
7648 vm_stop_cb(vm_stop_opaque, reason);
7651 vm_state_notify(0);
7655 /* reset/shutdown handler */
7657 typedef struct QEMUResetEntry {
7658 QEMUResetHandler *func;
7659 void *opaque;
7660 struct QEMUResetEntry *next;
7661 } QEMUResetEntry;
7663 static QEMUResetEntry *first_reset_entry;
7664 static int reset_requested;
7665 static int shutdown_requested;
7666 static int powerdown_requested;
7668 int qemu_shutdown_requested(void)
7670 int r = shutdown_requested;
7671 shutdown_requested = 0;
7672 return r;
7675 int qemu_reset_requested(void)
7677 int r = reset_requested;
7678 reset_requested = 0;
7679 return r;
7682 int qemu_powerdown_requested(void)
7684 int r = powerdown_requested;
7685 powerdown_requested = 0;
7686 return r;
7689 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7691 QEMUResetEntry **pre, *re;
7693 pre = &first_reset_entry;
7694 while (*pre != NULL)
7695 pre = &(*pre)->next;
7696 re = qemu_mallocz(sizeof(QEMUResetEntry));
7697 re->func = func;
7698 re->opaque = opaque;
7699 re->next = NULL;
7700 *pre = re;
7703 void qemu_system_reset(void)
7705 QEMUResetEntry *re;
7707 /* reset all devices */
7708 for(re = first_reset_entry; re != NULL; re = re->next) {
7709 re->func(re->opaque);
7713 void qemu_system_reset_request(void)
7715 if (no_reboot) {
7716 shutdown_requested = 1;
7717 } else {
7718 reset_requested = 1;
7720 if (cpu_single_env)
7721 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7724 void qemu_system_shutdown_request(void)
7726 shutdown_requested = 1;
7727 if (cpu_single_env)
7728 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7731 void qemu_system_powerdown_request(void)
7733 powerdown_requested = 1;
7734 if (cpu_single_env)
7735 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7738 void main_loop_wait(int timeout)
7740 IOHandlerRecord *ioh;
7741 fd_set rfds, wfds, xfds;
7742 int ret, nfds;
7743 #ifdef _WIN32
7744 int ret2, i;
7745 #endif
7746 struct timeval tv;
7747 PollingEntry *pe;
7750 /* XXX: need to suppress polling by better using win32 events */
7751 ret = 0;
7752 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7753 ret |= pe->func(pe->opaque);
7755 #ifdef _WIN32
7756 if (ret == 0) {
7757 int err;
7758 WaitObjects *w = &wait_objects;
7760 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7761 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7762 if (w->func[ret - WAIT_OBJECT_0])
7763 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7765 /* Check for additional signaled events */
7766 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7768 /* Check if event is signaled */
7769 ret2 = WaitForSingleObject(w->events[i], 0);
7770 if(ret2 == WAIT_OBJECT_0) {
7771 if (w->func[i])
7772 w->func[i](w->opaque[i]);
7773 } else if (ret2 == WAIT_TIMEOUT) {
7774 } else {
7775 err = GetLastError();
7776 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7779 } else if (ret == WAIT_TIMEOUT) {
7780 } else {
7781 err = GetLastError();
7782 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7785 #endif
7786 /* poll any events */
7787 /* XXX: separate device handlers from system ones */
7788 nfds = -1;
7789 FD_ZERO(&rfds);
7790 FD_ZERO(&wfds);
7791 FD_ZERO(&xfds);
7792 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7793 if (ioh->deleted)
7794 continue;
7795 if (ioh->fd_read &&
7796 (!ioh->fd_read_poll ||
7797 ioh->fd_read_poll(ioh->opaque) != 0)) {
7798 FD_SET(ioh->fd, &rfds);
7799 if (ioh->fd > nfds)
7800 nfds = ioh->fd;
7802 if (ioh->fd_write) {
7803 FD_SET(ioh->fd, &wfds);
7804 if (ioh->fd > nfds)
7805 nfds = ioh->fd;
7809 tv.tv_sec = 0;
7810 #ifdef _WIN32
7811 tv.tv_usec = 0;
7812 #else
7813 tv.tv_usec = timeout * 1000;
7814 #endif
7815 #if defined(CONFIG_SLIRP)
7816 if (slirp_inited) {
7817 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7819 #endif
7820 moreio:
7821 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7822 if (ret > 0) {
7823 IOHandlerRecord **pioh;
7824 int more = 0;
7826 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7827 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7828 ioh->fd_read(ioh->opaque);
7829 if (!ioh->fd_read_poll || ioh->fd_read_poll(ioh->opaque))
7830 more = 1;
7831 else
7832 FD_CLR(ioh->fd, &rfds);
7834 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7835 ioh->fd_write(ioh->opaque);
7836 more = 1;
7840 /* remove deleted IO handlers */
7841 pioh = &first_io_handler;
7842 while (*pioh) {
7843 ioh = *pioh;
7844 if (ioh->deleted) {
7845 *pioh = ioh->next;
7846 qemu_free(ioh);
7847 } else
7848 pioh = &ioh->next;
7850 if (more)
7851 goto moreio;
7853 #if defined(CONFIG_SLIRP)
7854 if (slirp_inited) {
7855 if (ret < 0) {
7856 FD_ZERO(&rfds);
7857 FD_ZERO(&wfds);
7858 FD_ZERO(&xfds);
7860 slirp_select_poll(&rfds, &wfds, &xfds);
7862 #endif
7863 virtio_net_poll();
7865 qemu_aio_poll();
7867 if (vm_running) {
7868 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7869 qemu_get_clock(vm_clock));
7870 /* run dma transfers, if any */
7871 DMA_run();
7874 /* real time timers */
7875 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7876 qemu_get_clock(rt_clock));
7878 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7879 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7880 qemu_rearm_alarm_timer(alarm_timer);
7883 /* Check bottom-halves last in case any of the earlier events triggered
7884 them. */
7885 qemu_bh_poll();
7889 static int main_loop(void)
7891 int ret, timeout;
7892 #ifdef CONFIG_PROFILER
7893 int64_t ti;
7894 #endif
7895 CPUState *env;
7898 if (kvm_enabled()) {
7899 kvm_main_loop();
7900 cpu_disable_ticks();
7901 return 0;
7904 cur_cpu = first_cpu;
7905 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7906 for(;;) {
7907 if (vm_running) {
7909 for(;;) {
7910 /* get next cpu */
7911 env = next_cpu;
7912 #ifdef CONFIG_PROFILER
7913 ti = profile_getclock();
7914 #endif
7915 ret = cpu_exec(env);
7916 #ifdef CONFIG_PROFILER
7917 qemu_time += profile_getclock() - ti;
7918 #endif
7919 next_cpu = env->next_cpu ?: first_cpu;
7920 if (event_pending) {
7921 ret = EXCP_INTERRUPT;
7922 event_pending = 0;
7923 break;
7925 if (ret == EXCP_HLT) {
7926 /* Give the next CPU a chance to run. */
7927 cur_cpu = env;
7928 continue;
7930 if (ret != EXCP_HALTED)
7931 break;
7932 /* all CPUs are halted ? */
7933 if (env == cur_cpu)
7934 break;
7936 cur_cpu = env;
7938 if (shutdown_requested) {
7939 ret = EXCP_INTERRUPT;
7940 break;
7942 if (reset_requested) {
7943 reset_requested = 0;
7944 qemu_system_reset();
7945 if (kvm_enabled())
7946 kvm_load_registers(env);
7947 ret = EXCP_INTERRUPT;
7949 if (powerdown_requested) {
7950 powerdown_requested = 0;
7951 qemu_system_powerdown();
7952 ret = EXCP_INTERRUPT;
7954 if (ret == EXCP_DEBUG) {
7955 vm_stop(EXCP_DEBUG);
7957 /* If all cpus are halted then wait until the next IRQ */
7958 /* XXX: use timeout computed from timers */
7959 if (ret == EXCP_HALTED)
7960 timeout = 10;
7961 else
7962 timeout = 0;
7963 } else {
7964 timeout = 10;
7966 #ifdef CONFIG_PROFILER
7967 ti = profile_getclock();
7968 #endif
7969 main_loop_wait(timeout);
7970 #ifdef CONFIG_PROFILER
7971 dev_time += profile_getclock() - ti;
7972 #endif
7974 cpu_disable_ticks();
7975 return ret;
7978 static void help(int exitcode)
7980 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
7981 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7982 "usage: %s [options] [disk_image]\n"
7983 "\n"
7984 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7985 "\n"
7986 "Standard options:\n"
7987 "-M machine select emulated machine (-M ? for list)\n"
7988 "-cpu cpu select CPU (-cpu ? for list)\n"
7989 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7990 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7991 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7992 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7993 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7994 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7995 " [,cache=on|off][,boot=on|off]\n"
7996 " use 'file' as a drive image\n"
7997 "-mtdblock file use 'file' as on-board Flash memory image\n"
7998 "-sd file use 'file' as SecureDigital card image\n"
7999 "-pflash file use 'file' as a parallel flash image\n"
8000 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8001 "-snapshot write to temporary files instead of disk image files\n"
8002 #ifdef CONFIG_SDL
8003 "-no-frame open SDL window without a frame and window decorations\n"
8004 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8005 "-no-quit disable SDL window close capability\n"
8006 #endif
8007 #ifdef TARGET_I386
8008 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8009 #endif
8010 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8011 "-smp n set the number of CPUs to 'n' [default=1]\n"
8012 "-nographic disable graphical output and redirect serial I/Os to console\n"
8013 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8014 #ifndef _WIN32
8015 "-k language use keyboard layout (for example \"fr\" for French)\n"
8016 #endif
8017 #ifdef HAS_AUDIO
8018 "-audio-help print list of audio drivers and their options\n"
8019 "-soundhw c1,... enable audio support\n"
8020 " and only specified sound cards (comma separated list)\n"
8021 " use -soundhw ? to get the list of supported cards\n"
8022 " use -soundhw all to enable all of them\n"
8023 #endif
8024 "-localtime set the real time clock to local time [default=utc]\n"
8025 "-full-screen start in full screen\n"
8026 #ifdef TARGET_I386
8027 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8028 #endif
8029 "-usb enable the USB driver (will be the default soon)\n"
8030 "-usbdevice name add the host or guest USB device 'name'\n"
8031 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8032 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8033 #endif
8034 "-name string set the name of the guest\n"
8035 "\n"
8036 "Network options:\n"
8037 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8038 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8039 #ifdef CONFIG_SLIRP
8040 "-net user[,vlan=n][,hostname=host]\n"
8041 " connect the user mode network stack to VLAN 'n' and send\n"
8042 " hostname 'host' to DHCP clients\n"
8043 #endif
8044 #ifdef _WIN32
8045 "-net tap[,vlan=n],ifname=name\n"
8046 " connect the host TAP network interface to VLAN 'n'\n"
8047 #else
8048 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8049 " connect the host TAP network interface to VLAN 'n' and use the\n"
8050 " network scripts 'file' (default=%s)\n"
8051 " and 'dfile' (default=%s);\n"
8052 " use '[down]script=no' to disable script execution;\n"
8053 " use 'fd=h' to connect to an already opened TAP interface\n"
8054 #endif
8055 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8056 " connect the vlan 'n' to another VLAN using a socket connection\n"
8057 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8058 " connect the vlan 'n' to multicast maddr and port\n"
8059 "-net none use it alone to have zero network devices; if no -net option\n"
8060 " is provided, the default is '-net nic -net user'\n"
8061 "\n"
8062 #ifdef CONFIG_SLIRP
8063 "-tftp dir allow tftp access to files in dir [-net user]\n"
8064 "-bootp file advertise file in BOOTP replies\n"
8065 #ifndef _WIN32
8066 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8067 #endif
8068 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8069 " redirect TCP or UDP connections from host to guest [-net user]\n"
8070 #endif
8071 "\n"
8072 "Linux boot specific:\n"
8073 "-kernel bzImage use 'bzImage' as kernel image\n"
8074 "-append cmdline use 'cmdline' as kernel command line\n"
8075 "-initrd file use 'file' as initial ram disk\n"
8076 "\n"
8077 "Debug/Expert options:\n"
8078 "-monitor dev redirect the monitor to char device 'dev'\n"
8079 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8080 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8081 "-serial dev redirect the serial port to char device 'dev'\n"
8082 "-parallel dev redirect the parallel port to char device 'dev'\n"
8083 "-pidfile file Write PID to 'file'\n"
8084 "-S freeze CPU at startup (use 'c' to start execution)\n"
8085 "-s wait gdb connection to port\n"
8086 "-p port set gdb connection port [default=%s]\n"
8087 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8088 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8089 " translation (t=none or lba) (usually qemu can guess them)\n"
8090 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8091 #ifdef USE_KQEMU
8092 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8093 "-no-kqemu disable KQEMU kernel module usage\n"
8094 #endif
8095 #ifdef USE_KVM
8096 #ifndef NO_CPU_EMULATION
8097 "-no-kvm disable KVM hardware virtualization\n"
8098 #endif
8099 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8100 "-no-kvm-pit disable KVM kernel mode PIT\n"
8101 #endif
8102 #ifdef TARGET_I386
8103 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8104 " (default is CL-GD5446 PCI VGA)\n"
8105 "-no-acpi disable ACPI\n"
8106 #endif
8107 #ifdef CONFIG_CURSES
8108 "-curses use a curses/ncurses interface instead of SDL\n"
8109 #endif
8110 "-no-reboot exit instead of rebooting\n"
8111 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8112 "-vnc display start a VNC server on display\n"
8113 #ifndef _WIN32
8114 "-daemonize daemonize QEMU after initializing\n"
8115 #endif
8116 "-tdf inject timer interrupts that got lost\n"
8117 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8118 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8119 "-option-rom rom load a file, rom, into the option ROM space\n"
8120 #ifdef TARGET_SPARC
8121 "-prom-env variable=value set OpenBIOS nvram variables\n"
8122 #endif
8123 "-clock force the use of the given methods for timer alarm.\n"
8124 " To see what timers are available use -clock help\n"
8125 "-startdate select initial date of the clock\n"
8126 "\n"
8127 "During emulation, the following keys are useful:\n"
8128 "ctrl-alt-f toggle full screen\n"
8129 "ctrl-alt-n switch to virtual console 'n'\n"
8130 "ctrl-alt toggle mouse and keyboard grab\n"
8131 "\n"
8132 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8134 "qemu",
8135 DEFAULT_RAM_SIZE,
8136 #ifndef _WIN32
8137 DEFAULT_NETWORK_SCRIPT,
8138 DEFAULT_NETWORK_DOWN_SCRIPT,
8139 #endif
8140 DEFAULT_GDBSTUB_PORT,
8141 "/tmp/qemu.log");
8142 exit(exitcode);
8145 #define HAS_ARG 0x0001
8147 enum {
8148 QEMU_OPTION_h,
8150 QEMU_OPTION_M,
8151 QEMU_OPTION_cpu,
8152 QEMU_OPTION_fda,
8153 QEMU_OPTION_fdb,
8154 QEMU_OPTION_hda,
8155 QEMU_OPTION_hdb,
8156 QEMU_OPTION_hdc,
8157 QEMU_OPTION_hdd,
8158 QEMU_OPTION_drive,
8159 QEMU_OPTION_cdrom,
8160 QEMU_OPTION_mtdblock,
8161 QEMU_OPTION_sd,
8162 QEMU_OPTION_pflash,
8163 QEMU_OPTION_boot,
8164 QEMU_OPTION_snapshot,
8165 #ifdef TARGET_I386
8166 QEMU_OPTION_no_fd_bootchk,
8167 #endif
8168 QEMU_OPTION_m,
8169 QEMU_OPTION_nographic,
8170 QEMU_OPTION_portrait,
8171 #ifdef HAS_AUDIO
8172 QEMU_OPTION_audio_help,
8173 QEMU_OPTION_soundhw,
8174 #endif
8176 QEMU_OPTION_net,
8177 QEMU_OPTION_tftp,
8178 QEMU_OPTION_bootp,
8179 QEMU_OPTION_smb,
8180 QEMU_OPTION_redir,
8182 QEMU_OPTION_kernel,
8183 QEMU_OPTION_append,
8184 QEMU_OPTION_initrd,
8186 QEMU_OPTION_S,
8187 QEMU_OPTION_s,
8188 QEMU_OPTION_p,
8189 QEMU_OPTION_d,
8190 QEMU_OPTION_hdachs,
8191 QEMU_OPTION_L,
8192 QEMU_OPTION_bios,
8193 QEMU_OPTION_no_code_copy,
8194 QEMU_OPTION_k,
8195 QEMU_OPTION_localtime,
8196 QEMU_OPTION_cirrusvga,
8197 QEMU_OPTION_vmsvga,
8198 QEMU_OPTION_g,
8199 QEMU_OPTION_std_vga,
8200 QEMU_OPTION_echr,
8201 QEMU_OPTION_monitor,
8202 QEMU_OPTION_balloon,
8203 QEMU_OPTION_vmchannel,
8204 QEMU_OPTION_serial,
8205 QEMU_OPTION_parallel,
8206 QEMU_OPTION_loadvm,
8207 QEMU_OPTION_full_screen,
8208 QEMU_OPTION_no_frame,
8209 QEMU_OPTION_alt_grab,
8210 QEMU_OPTION_no_quit,
8211 QEMU_OPTION_pidfile,
8212 QEMU_OPTION_no_kqemu,
8213 QEMU_OPTION_kernel_kqemu,
8214 QEMU_OPTION_win2k_hack,
8215 QEMU_OPTION_usb,
8216 QEMU_OPTION_usbdevice,
8217 QEMU_OPTION_smp,
8218 QEMU_OPTION_vnc,
8219 QEMU_OPTION_no_acpi,
8220 QEMU_OPTION_curses,
8221 QEMU_OPTION_no_kvm,
8222 QEMU_OPTION_no_kvm_irqchip,
8223 QEMU_OPTION_no_kvm_pit,
8224 QEMU_OPTION_no_reboot,
8225 QEMU_OPTION_show_cursor,
8226 QEMU_OPTION_daemonize,
8227 QEMU_OPTION_option_rom,
8228 QEMU_OPTION_semihosting,
8229 QEMU_OPTION_cpu_vendor,
8230 QEMU_OPTION_name,
8231 QEMU_OPTION_prom_env,
8232 QEMU_OPTION_old_param,
8233 QEMU_OPTION_clock,
8234 QEMU_OPTION_startdate,
8235 QEMU_OPTION_translation,
8236 QEMU_OPTION_incoming,
8237 QEMU_OPTION_tdf,
8238 QEMU_OPTION_kvm_shadow_memory,
8239 QEMU_OPTION_mempath,
8242 typedef struct QEMUOption {
8243 const char *name;
8244 int flags;
8245 int index;
8246 } QEMUOption;
8248 const QEMUOption qemu_options[] = {
8249 { "h", 0, QEMU_OPTION_h },
8250 { "help", 0, QEMU_OPTION_h },
8252 { "M", HAS_ARG, QEMU_OPTION_M },
8253 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8254 { "fda", HAS_ARG, QEMU_OPTION_fda },
8255 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8256 { "hda", HAS_ARG, QEMU_OPTION_hda },
8257 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8258 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8259 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8260 { "drive", HAS_ARG, QEMU_OPTION_drive },
8261 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8262 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8263 { "sd", HAS_ARG, QEMU_OPTION_sd },
8264 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8265 { "boot", HAS_ARG, QEMU_OPTION_boot },
8266 { "snapshot", 0, QEMU_OPTION_snapshot },
8267 #ifdef TARGET_I386
8268 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8269 #endif
8270 { "m", HAS_ARG, QEMU_OPTION_m },
8271 { "nographic", 0, QEMU_OPTION_nographic },
8272 { "portrait", 0, QEMU_OPTION_portrait },
8273 { "k", HAS_ARG, QEMU_OPTION_k },
8274 #ifdef HAS_AUDIO
8275 { "audio-help", 0, QEMU_OPTION_audio_help },
8276 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8277 #endif
8279 { "net", HAS_ARG, QEMU_OPTION_net},
8280 #ifdef CONFIG_SLIRP
8281 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8282 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8283 #ifndef _WIN32
8284 { "smb", HAS_ARG, QEMU_OPTION_smb },
8285 #endif
8286 { "redir", HAS_ARG, QEMU_OPTION_redir },
8287 #endif
8289 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8290 { "append", HAS_ARG, QEMU_OPTION_append },
8291 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8293 { "S", 0, QEMU_OPTION_S },
8294 { "s", 0, QEMU_OPTION_s },
8295 { "p", HAS_ARG, QEMU_OPTION_p },
8296 { "d", HAS_ARG, QEMU_OPTION_d },
8297 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8298 { "L", HAS_ARG, QEMU_OPTION_L },
8299 { "bios", HAS_ARG, QEMU_OPTION_bios },
8300 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8301 #ifdef USE_KQEMU
8302 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8303 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8304 #endif
8305 #ifdef USE_KVM
8306 #ifndef NO_CPU_EMULATION
8307 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8308 #endif
8309 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8310 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8311 #endif
8312 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8313 { "g", 1, QEMU_OPTION_g },
8314 #endif
8315 { "localtime", 0, QEMU_OPTION_localtime },
8316 { "std-vga", 0, QEMU_OPTION_std_vga },
8317 { "monitor", 1, QEMU_OPTION_monitor },
8318 { "balloon", 1, QEMU_OPTION_balloon },
8319 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8320 { "echr", HAS_ARG, QEMU_OPTION_echr },
8321 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8322 { "serial", HAS_ARG, QEMU_OPTION_serial },
8323 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8324 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8325 { "incoming", 1, QEMU_OPTION_incoming },
8326 { "full-screen", 0, QEMU_OPTION_full_screen },
8327 #ifdef CONFIG_SDL
8328 { "no-frame", 0, QEMU_OPTION_no_frame },
8329 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8330 { "no-quit", 0, QEMU_OPTION_no_quit },
8331 #endif
8332 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8333 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8334 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8335 { "smp", HAS_ARG, QEMU_OPTION_smp },
8336 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8337 #ifdef CONFIG_CURSES
8338 { "curses", 0, QEMU_OPTION_curses },
8339 #endif
8341 /* temporary options */
8342 { "usb", 0, QEMU_OPTION_usb },
8343 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8344 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8345 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8346 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8347 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8348 { "daemonize", 0, QEMU_OPTION_daemonize },
8349 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8350 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8351 { "semihosting", 0, QEMU_OPTION_semihosting },
8352 #endif
8353 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8354 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8355 { "name", HAS_ARG, QEMU_OPTION_name },
8356 #if defined(TARGET_SPARC)
8357 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8358 #endif
8359 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8360 #if defined(TARGET_ARM)
8361 { "old-param", 0, QEMU_OPTION_old_param },
8362 #endif
8363 { "clock", HAS_ARG, QEMU_OPTION_clock },
8364 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8365 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8366 { NULL },
8369 /* password input */
8371 int qemu_key_check(BlockDriverState *bs, const char *name)
8373 char password[256];
8374 int i;
8376 if (!bdrv_is_encrypted(bs))
8377 return 0;
8379 term_printf("%s is encrypted.\n", name);
8380 for(i = 0; i < 3; i++) {
8381 monitor_readline("Password: ", 1, password, sizeof(password));
8382 if (bdrv_set_key(bs, password) == 0)
8383 return 0;
8384 term_printf("invalid password\n");
8386 return -EPERM;
8389 static BlockDriverState *get_bdrv(int index)
8391 if (index > nb_drives)
8392 return NULL;
8393 return drives_table[index].bdrv;
8396 static void read_passwords(void)
8398 BlockDriverState *bs;
8399 int i;
8401 for(i = 0; i < 6; i++) {
8402 bs = get_bdrv(i);
8403 if (bs)
8404 qemu_key_check(bs, bdrv_get_device_name(bs));
8408 /* XXX: currently we cannot use simultaneously different CPUs */
8409 static void register_machines(void)
8411 #if defined(TARGET_I386)
8412 qemu_register_machine(&pc_machine);
8413 qemu_register_machine(&isapc_machine);
8414 #elif defined(TARGET_PPC)
8415 qemu_register_machine(&heathrow_machine);
8416 qemu_register_machine(&core99_machine);
8417 qemu_register_machine(&prep_machine);
8418 qemu_register_machine(&ref405ep_machine);
8419 qemu_register_machine(&taihu_machine);
8420 qemu_register_machine(&bamboo_machine);
8421 #elif defined(TARGET_MIPS)
8422 qemu_register_machine(&mips_machine);
8423 qemu_register_machine(&mips_malta_machine);
8424 qemu_register_machine(&mips_pica61_machine);
8425 qemu_register_machine(&mips_mipssim_machine);
8426 #elif defined(TARGET_SPARC)
8427 #ifdef TARGET_SPARC64
8428 qemu_register_machine(&sun4u_machine);
8429 #else
8430 qemu_register_machine(&ss5_machine);
8431 qemu_register_machine(&ss10_machine);
8432 qemu_register_machine(&ss600mp_machine);
8433 qemu_register_machine(&ss20_machine);
8434 qemu_register_machine(&ss2_machine);
8435 qemu_register_machine(&ss1000_machine);
8436 qemu_register_machine(&ss2000_machine);
8437 #endif
8438 #elif defined(TARGET_ARM)
8439 qemu_register_machine(&integratorcp_machine);
8440 qemu_register_machine(&versatilepb_machine);
8441 qemu_register_machine(&versatileab_machine);
8442 qemu_register_machine(&realview_machine);
8443 qemu_register_machine(&akitapda_machine);
8444 qemu_register_machine(&spitzpda_machine);
8445 qemu_register_machine(&borzoipda_machine);
8446 qemu_register_machine(&terrierpda_machine);
8447 qemu_register_machine(&palmte_machine);
8448 qemu_register_machine(&lm3s811evb_machine);
8449 qemu_register_machine(&lm3s6965evb_machine);
8450 qemu_register_machine(&connex_machine);
8451 qemu_register_machine(&verdex_machine);
8452 qemu_register_machine(&mainstone2_machine);
8453 #elif defined(TARGET_SH4)
8454 qemu_register_machine(&shix_machine);
8455 qemu_register_machine(&r2d_machine);
8456 #elif defined(TARGET_ALPHA)
8457 /* XXX: TODO */
8458 #elif defined(TARGET_M68K)
8459 qemu_register_machine(&mcf5208evb_machine);
8460 qemu_register_machine(&an5206_machine);
8461 qemu_register_machine(&dummy_m68k_machine);
8462 #elif defined(TARGET_CRIS)
8463 qemu_register_machine(&bareetraxfs_machine);
8464 #elif defined(TARGET_IA64)
8465 qemu_register_machine(&ipf_machine);
8466 #else
8467 #error unsupported CPU
8468 #endif
8471 #ifdef HAS_AUDIO
8472 struct soundhw soundhw[] = {
8473 #ifdef HAS_AUDIO_CHOICE
8474 #ifdef TARGET_I386
8476 "pcspk",
8477 "PC speaker",
8480 { .init_isa = pcspk_audio_init }
8482 #endif
8484 "sb16",
8485 "Creative Sound Blaster 16",
8488 { .init_isa = SB16_init }
8491 #ifdef CONFIG_ADLIB
8493 "adlib",
8494 #ifdef HAS_YMF262
8495 "Yamaha YMF262 (OPL3)",
8496 #else
8497 "Yamaha YM3812 (OPL2)",
8498 #endif
8501 { .init_isa = Adlib_init }
8503 #endif
8505 #ifdef CONFIG_GUS
8507 "gus",
8508 "Gravis Ultrasound GF1",
8511 { .init_isa = GUS_init }
8513 #endif
8515 #ifdef CONFIG_AC97
8517 "ac97",
8518 "Intel 82801AA AC97 Audio",
8521 { .init_pci = ac97_init }
8523 #endif
8526 "es1370",
8527 "ENSONIQ AudioPCI ES1370",
8530 { .init_pci = es1370_init }
8532 #endif
8534 { NULL, NULL, 0, 0, { NULL } }
8537 static void select_soundhw (const char *optarg)
8539 struct soundhw *c;
8541 if (*optarg == '?') {
8542 show_valid_cards:
8544 printf ("Valid sound card names (comma separated):\n");
8545 for (c = soundhw; c->name; ++c) {
8546 printf ("%-11s %s\n", c->name, c->descr);
8548 printf ("\n-soundhw all will enable all of the above\n");
8549 exit (*optarg != '?');
8551 else {
8552 size_t l;
8553 const char *p;
8554 char *e;
8555 int bad_card = 0;
8557 if (!strcmp (optarg, "all")) {
8558 for (c = soundhw; c->name; ++c) {
8559 c->enabled = 1;
8561 return;
8564 p = optarg;
8565 while (*p) {
8566 e = strchr (p, ',');
8567 l = !e ? strlen (p) : (size_t) (e - p);
8569 for (c = soundhw; c->name; ++c) {
8570 if (!strncmp (c->name, p, l)) {
8571 c->enabled = 1;
8572 break;
8576 if (!c->name) {
8577 if (l > 80) {
8578 fprintf (stderr,
8579 "Unknown sound card name (too big to show)\n");
8581 else {
8582 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8583 (int) l, p);
8585 bad_card = 1;
8587 p += l + (e != NULL);
8590 if (bad_card)
8591 goto show_valid_cards;
8594 #endif
8596 #ifdef _WIN32
8597 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8599 exit(STATUS_CONTROL_C_EXIT);
8600 return TRUE;
8602 #endif
8604 #define MAX_NET_CLIENTS 32
8606 static int saved_argc;
8607 static char **saved_argv;
8609 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8611 *argc = saved_argc;
8612 *argv = saved_argv;
8613 *opt_daemonize = daemonize;
8614 *opt_incoming = incoming;
8618 static int gethugepagesize(void)
8620 int ret, fd;
8621 char buf[4096];
8622 char *needle = "Hugepagesize:";
8623 char *size;
8624 unsigned long hugepagesize;
8626 fd = open("/proc/meminfo", O_RDONLY);
8627 if (fd < 0) {
8628 perror("open");
8629 exit(0);
8632 ret = read(fd, buf, sizeof(buf));
8633 if (ret < 0) {
8634 perror("read");
8635 exit(0);
8638 size = strstr(buf, needle);
8639 if (!size)
8640 return 0;
8641 size += strlen(needle);
8642 hugepagesize = strtol(size, NULL, 0);
8643 return hugepagesize;
8646 void *alloc_mem_area(unsigned long memory, const char *path)
8648 char *filename;
8649 void *area;
8650 int fd;
8652 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8653 return NULL;
8655 hpagesize = gethugepagesize() * 1024;
8656 if (!hpagesize)
8657 return NULL;
8659 fd = mkstemp(filename);
8660 if (fd < 0) {
8661 perror("mkstemp");
8662 free(filename);
8663 return NULL;
8665 unlink(filename);
8666 free(filename);
8668 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8670 if (ftruncate(fd, memory) == -1) {
8671 perror("ftruncate");
8672 close(fd);
8673 return NULL;
8676 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8677 if (area == MAP_FAILED) {
8678 perror("mmap");
8679 close(fd);
8680 return NULL;
8683 return area;
8686 void *qemu_alloc_physram(unsigned long memory)
8688 void *area = NULL;
8690 if (mem_path)
8691 area = alloc_mem_area(memory, mem_path);
8692 if (!area)
8693 area = qemu_vmalloc(memory);
8695 return area;
8698 int main(int argc, char **argv)
8700 #ifdef CONFIG_GDBSTUB
8701 int use_gdbstub;
8702 const char *gdbstub_port;
8703 #endif
8704 uint32_t boot_devices_bitmap = 0;
8705 int i;
8706 int snapshot, linux_boot, net_boot;
8707 const char *initrd_filename;
8708 const char *kernel_filename, *kernel_cmdline;
8709 const char *boot_devices = "";
8710 DisplayState *ds = &display_state;
8711 int cyls, heads, secs, translation;
8712 char net_clients[MAX_NET_CLIENTS][256];
8713 int nb_net_clients;
8714 int hda_index;
8715 int optind;
8716 const char *r, *optarg;
8717 CharDriverState *monitor_hd;
8718 char monitor_device[128];
8719 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8720 int vmchannel_device_index;
8721 char serial_devices[MAX_SERIAL_PORTS][128];
8722 int serial_device_index;
8723 char parallel_devices[MAX_PARALLEL_PORTS][128];
8724 int parallel_device_index;
8725 const char *loadvm = NULL;
8726 QEMUMachine *machine;
8727 const char *cpu_model;
8728 char usb_devices[MAX_USB_CMDLINE][128];
8729 int usb_devices_index;
8730 int fds[2];
8731 const char *pid_file = NULL;
8732 VLANState *vlan;
8734 saved_argc = argc;
8735 saved_argv = argv;
8737 LIST_INIT (&vm_change_state_head);
8738 #ifndef _WIN32
8740 struct sigaction act;
8741 sigfillset(&act.sa_mask);
8742 act.sa_flags = 0;
8743 act.sa_handler = SIG_IGN;
8744 sigaction(SIGPIPE, &act, NULL);
8746 #else
8747 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8748 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8749 QEMU to run on a single CPU */
8751 HANDLE h;
8752 DWORD mask, smask;
8753 int i;
8754 h = GetCurrentProcess();
8755 if (GetProcessAffinityMask(h, &mask, &smask)) {
8756 for(i = 0; i < 32; i++) {
8757 if (mask & (1 << i))
8758 break;
8760 if (i != 32) {
8761 mask = 1 << i;
8762 SetProcessAffinityMask(h, mask);
8766 #endif
8768 register_machines();
8769 machine = first_machine;
8770 cpu_model = NULL;
8771 initrd_filename = NULL;
8772 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8773 vga_ram_size = VGA_RAM_SIZE;
8774 #ifdef CONFIG_GDBSTUB
8775 use_gdbstub = 0;
8776 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8777 #endif
8778 snapshot = 0;
8779 nographic = 0;
8780 curses = 0;
8781 kernel_filename = NULL;
8782 kernel_cmdline = "";
8783 cyls = heads = secs = 0;
8784 translation = BIOS_ATA_TRANSLATION_AUTO;
8785 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8787 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8788 vmchannel_devices[i][0] = '\0';
8789 vmchannel_device_index = 0;
8791 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8792 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8793 serial_devices[i][0] = '\0';
8794 serial_device_index = 0;
8796 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8797 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8798 parallel_devices[i][0] = '\0';
8799 parallel_device_index = 0;
8801 usb_devices_index = 0;
8803 nb_net_clients = 0;
8804 nb_drives = 0;
8805 nb_drives_opt = 0;
8806 hda_index = -1;
8808 nb_nics = 0;
8809 /* default mac address of the first network interface */
8811 optind = 1;
8812 for(;;) {
8813 if (optind >= argc)
8814 break;
8815 r = argv[optind];
8816 if (r[0] != '-') {
8817 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8818 } else {
8819 const QEMUOption *popt;
8821 optind++;
8822 /* Treat --foo the same as -foo. */
8823 if (r[1] == '-')
8824 r++;
8825 popt = qemu_options;
8826 for(;;) {
8827 if (!popt->name) {
8828 fprintf(stderr, "%s: invalid option -- '%s'\n",
8829 argv[0], r);
8830 exit(1);
8832 if (!strcmp(popt->name, r + 1))
8833 break;
8834 popt++;
8836 if (popt->flags & HAS_ARG) {
8837 if (optind >= argc) {
8838 fprintf(stderr, "%s: option '%s' requires an argument\n",
8839 argv[0], r);
8840 exit(1);
8842 optarg = argv[optind++];
8843 } else {
8844 optarg = NULL;
8847 switch(popt->index) {
8848 case QEMU_OPTION_M:
8849 machine = find_machine(optarg);
8850 if (!machine) {
8851 QEMUMachine *m;
8852 printf("Supported machines are:\n");
8853 for(m = first_machine; m != NULL; m = m->next) {
8854 printf("%-10s %s%s\n",
8855 m->name, m->desc,
8856 m == first_machine ? " (default)" : "");
8858 exit(*optarg != '?');
8860 break;
8861 case QEMU_OPTION_cpu:
8862 /* hw initialization will check this */
8863 if (*optarg == '?') {
8864 /* XXX: implement xxx_cpu_list for targets that still miss it */
8865 #if defined(cpu_list)
8866 cpu_list(stdout, &fprintf);
8867 #endif
8868 exit(0);
8869 } else {
8870 cpu_model = optarg;
8872 break;
8873 case QEMU_OPTION_initrd:
8874 initrd_filename = optarg;
8875 break;
8876 case QEMU_OPTION_hda:
8877 if (cyls == 0)
8878 hda_index = drive_add(optarg, HD_ALIAS, 0);
8879 else
8880 hda_index = drive_add(optarg, HD_ALIAS
8881 ",cyls=%d,heads=%d,secs=%d%s",
8882 0, cyls, heads, secs,
8883 translation == BIOS_ATA_TRANSLATION_LBA ?
8884 ",trans=lba" :
8885 translation == BIOS_ATA_TRANSLATION_NONE ?
8886 ",trans=none" : "");
8887 break;
8888 case QEMU_OPTION_hdb:
8889 case QEMU_OPTION_hdc:
8890 case QEMU_OPTION_hdd:
8891 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8892 break;
8893 case QEMU_OPTION_drive:
8894 drive_add(NULL, "%s", optarg);
8895 break;
8896 case QEMU_OPTION_mtdblock:
8897 drive_add(optarg, MTD_ALIAS);
8898 break;
8899 case QEMU_OPTION_sd:
8900 drive_add(optarg, SD_ALIAS);
8901 break;
8902 case QEMU_OPTION_pflash:
8903 drive_add(optarg, PFLASH_ALIAS);
8904 break;
8905 case QEMU_OPTION_snapshot:
8906 snapshot = 1;
8907 break;
8908 case QEMU_OPTION_hdachs:
8910 const char *p;
8911 p = optarg;
8912 cyls = strtol(p, (char **)&p, 0);
8913 if (cyls < 1 || cyls > 16383)
8914 goto chs_fail;
8915 if (*p != ',')
8916 goto chs_fail;
8917 p++;
8918 heads = strtol(p, (char **)&p, 0);
8919 if (heads < 1 || heads > 16)
8920 goto chs_fail;
8921 if (*p != ',')
8922 goto chs_fail;
8923 p++;
8924 secs = strtol(p, (char **)&p, 0);
8925 if (secs < 1 || secs > 63)
8926 goto chs_fail;
8927 if (*p == ',') {
8928 p++;
8929 if (!strcmp(p, "none"))
8930 translation = BIOS_ATA_TRANSLATION_NONE;
8931 else if (!strcmp(p, "lba"))
8932 translation = BIOS_ATA_TRANSLATION_LBA;
8933 else if (!strcmp(p, "auto"))
8934 translation = BIOS_ATA_TRANSLATION_AUTO;
8935 else
8936 goto chs_fail;
8937 } else if (*p != '\0') {
8938 chs_fail:
8939 fprintf(stderr, "qemu: invalid physical CHS format\n");
8940 exit(1);
8942 if (hda_index != -1)
8943 snprintf(drives_opt[hda_index].opt,
8944 sizeof(drives_opt[hda_index].opt),
8945 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8946 0, cyls, heads, secs,
8947 translation == BIOS_ATA_TRANSLATION_LBA ?
8948 ",trans=lba" :
8949 translation == BIOS_ATA_TRANSLATION_NONE ?
8950 ",trans=none" : "");
8952 break;
8953 case QEMU_OPTION_nographic:
8954 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8955 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8956 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8957 nographic = 1;
8958 break;
8959 #ifdef CONFIG_CURSES
8960 case QEMU_OPTION_curses:
8961 curses = 1;
8962 break;
8963 #endif
8964 case QEMU_OPTION_portrait:
8965 graphic_rotate = 1;
8966 break;
8967 case QEMU_OPTION_kernel:
8968 kernel_filename = optarg;
8969 break;
8970 case QEMU_OPTION_append:
8971 kernel_cmdline = optarg;
8972 break;
8973 case QEMU_OPTION_cdrom:
8974 drive_add(optarg, CDROM_ALIAS);
8975 break;
8976 case QEMU_OPTION_boot:
8977 boot_devices = optarg;
8978 /* We just do some generic consistency checks */
8980 /* Could easily be extended to 64 devices if needed */
8981 const char *p;
8983 boot_devices_bitmap = 0;
8984 for (p = boot_devices; *p != '\0'; p++) {
8985 /* Allowed boot devices are:
8986 * a b : floppy disk drives
8987 * c ... f : IDE disk drives
8988 * g ... m : machine implementation dependant drives
8989 * n ... p : network devices
8990 * It's up to each machine implementation to check
8991 * if the given boot devices match the actual hardware
8992 * implementation and firmware features.
8994 if (*p < 'a' || *p > 'q') {
8995 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8996 exit(1);
8998 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8999 fprintf(stderr,
9000 "Boot device '%c' was given twice\n",*p);
9001 exit(1);
9003 boot_devices_bitmap |= 1 << (*p - 'a');
9006 break;
9007 case QEMU_OPTION_fda:
9008 case QEMU_OPTION_fdb:
9009 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9010 break;
9011 #ifdef TARGET_I386
9012 case QEMU_OPTION_no_fd_bootchk:
9013 fd_bootchk = 0;
9014 break;
9015 #endif
9016 case QEMU_OPTION_no_code_copy:
9017 code_copy_enabled = 0;
9018 break;
9019 case QEMU_OPTION_net:
9020 if (nb_net_clients >= MAX_NET_CLIENTS) {
9021 fprintf(stderr, "qemu: too many network clients\n");
9022 exit(1);
9024 pstrcpy(net_clients[nb_net_clients],
9025 sizeof(net_clients[0]),
9026 optarg);
9027 nb_net_clients++;
9028 break;
9029 #ifdef CONFIG_SLIRP
9030 case QEMU_OPTION_tftp:
9031 tftp_prefix = optarg;
9032 break;
9033 case QEMU_OPTION_bootp:
9034 bootp_filename = optarg;
9035 break;
9036 #ifndef _WIN32
9037 case QEMU_OPTION_smb:
9038 net_slirp_smb(optarg);
9039 break;
9040 #endif
9041 case QEMU_OPTION_redir:
9042 net_slirp_redir(optarg);
9043 break;
9044 #endif
9045 #ifdef HAS_AUDIO
9046 case QEMU_OPTION_audio_help:
9047 AUD_help ();
9048 exit (0);
9049 break;
9050 case QEMU_OPTION_soundhw:
9051 select_soundhw (optarg);
9052 break;
9053 #endif
9054 case QEMU_OPTION_h:
9055 help(0);
9056 break;
9057 case QEMU_OPTION_m:
9058 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
9059 if (ram_size <= 0)
9060 help(1);
9061 if (ram_size > PHYS_RAM_MAX_SIZE) {
9062 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
9063 PHYS_RAM_MAX_SIZE / (1024 * 1024));
9064 exit(1);
9066 break;
9067 case QEMU_OPTION_d:
9069 int mask;
9070 CPULogItem *item;
9072 mask = cpu_str_to_log_mask(optarg);
9073 if (!mask) {
9074 printf("Log items (comma separated):\n");
9075 for(item = cpu_log_items; item->mask != 0; item++) {
9076 printf("%-10s %s\n", item->name, item->help);
9078 exit(1);
9080 cpu_set_log(mask);
9082 break;
9083 #ifdef CONFIG_GDBSTUB
9084 case QEMU_OPTION_s:
9085 use_gdbstub = 1;
9086 break;
9087 case QEMU_OPTION_p:
9088 gdbstub_port = optarg;
9089 break;
9090 #endif
9091 case QEMU_OPTION_L:
9092 bios_dir = optarg;
9093 break;
9094 case QEMU_OPTION_bios:
9095 bios_name = optarg;
9096 break;
9097 case QEMU_OPTION_S:
9098 autostart = 0;
9099 break;
9100 case QEMU_OPTION_k:
9101 keyboard_layout = optarg;
9102 break;
9103 case QEMU_OPTION_localtime:
9104 rtc_utc = 0;
9105 break;
9106 case QEMU_OPTION_cirrusvga:
9107 cirrus_vga_enabled = 1;
9108 vmsvga_enabled = 0;
9109 break;
9110 case QEMU_OPTION_vmsvga:
9111 cirrus_vga_enabled = 0;
9112 vmsvga_enabled = 1;
9113 break;
9114 case QEMU_OPTION_std_vga:
9115 cirrus_vga_enabled = 0;
9116 vmsvga_enabled = 0;
9117 break;
9118 case QEMU_OPTION_g:
9120 const char *p;
9121 int w, h, depth;
9122 p = optarg;
9123 w = strtol(p, (char **)&p, 10);
9124 if (w <= 0) {
9125 graphic_error:
9126 fprintf(stderr, "qemu: invalid resolution or depth\n");
9127 exit(1);
9129 if (*p != 'x')
9130 goto graphic_error;
9131 p++;
9132 h = strtol(p, (char **)&p, 10);
9133 if (h <= 0)
9134 goto graphic_error;
9135 if (*p == 'x') {
9136 p++;
9137 depth = strtol(p, (char **)&p, 10);
9138 if (depth != 8 && depth != 15 && depth != 16 &&
9139 depth != 24 && depth != 32)
9140 goto graphic_error;
9141 } else if (*p == '\0') {
9142 depth = graphic_depth;
9143 } else {
9144 goto graphic_error;
9147 graphic_width = w;
9148 graphic_height = h;
9149 graphic_depth = depth;
9151 break;
9152 case QEMU_OPTION_echr:
9154 char *r;
9155 term_escape_char = strtol(optarg, &r, 0);
9156 if (r == optarg)
9157 printf("Bad argument to echr\n");
9158 break;
9160 case QEMU_OPTION_monitor:
9161 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
9162 break;
9163 case QEMU_OPTION_balloon:
9164 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9165 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9166 exit(1);
9168 if (balloon_used) {
9169 fprintf(stderr, "qemu: only one balloon device can be used\n");
9170 exit(1);
9172 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
9173 vmchannel_device_index++;
9174 balloon_used = 1;
9175 break;
9176 case QEMU_OPTION_vmchannel:
9177 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9178 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9179 exit(1);
9181 pstrcpy(vmchannel_devices[vmchannel_device_index],
9182 sizeof(vmchannel_devices[0]), optarg);
9183 vmchannel_device_index++;
9184 break;
9185 case QEMU_OPTION_serial:
9186 if (serial_device_index >= MAX_SERIAL_PORTS) {
9187 fprintf(stderr, "qemu: too many serial ports\n");
9188 exit(1);
9190 pstrcpy(serial_devices[serial_device_index],
9191 sizeof(serial_devices[0]), optarg);
9192 serial_device_index++;
9193 break;
9194 case QEMU_OPTION_parallel:
9195 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9196 fprintf(stderr, "qemu: too many parallel ports\n");
9197 exit(1);
9199 pstrcpy(parallel_devices[parallel_device_index],
9200 sizeof(parallel_devices[0]), optarg);
9201 parallel_device_index++;
9202 break;
9203 case QEMU_OPTION_loadvm:
9204 loadvm = optarg;
9205 break;
9206 case QEMU_OPTION_incoming:
9207 incoming = optarg;
9208 break;
9209 case QEMU_OPTION_full_screen:
9210 full_screen = 1;
9211 break;
9212 #ifdef CONFIG_SDL
9213 case QEMU_OPTION_no_frame:
9214 no_frame = 1;
9215 break;
9216 case QEMU_OPTION_alt_grab:
9217 alt_grab = 1;
9218 break;
9219 case QEMU_OPTION_no_quit:
9220 no_quit = 1;
9221 break;
9222 #endif
9223 case QEMU_OPTION_pidfile:
9224 pid_file = optarg;
9225 break;
9226 #ifdef TARGET_I386
9227 case QEMU_OPTION_win2k_hack:
9228 win2k_install_hack = 1;
9229 break;
9230 #endif
9231 #ifdef USE_KQEMU
9232 case QEMU_OPTION_no_kqemu:
9233 kqemu_allowed = 0;
9234 break;
9235 case QEMU_OPTION_kernel_kqemu:
9236 kqemu_allowed = 2;
9237 break;
9238 #endif
9239 #ifdef USE_KVM
9240 case QEMU_OPTION_no_kvm:
9241 kvm_allowed = 0;
9242 break;
9243 case QEMU_OPTION_no_kvm_irqchip: {
9244 extern int kvm_irqchip, kvm_pit;
9245 kvm_irqchip = 0;
9246 kvm_pit = 0;
9247 break;
9249 case QEMU_OPTION_no_kvm_pit: {
9250 extern int kvm_pit;
9251 kvm_pit = 0;
9252 break;
9254 #endif
9255 case QEMU_OPTION_usb:
9256 usb_enabled = 1;
9257 break;
9258 case QEMU_OPTION_usbdevice:
9259 usb_enabled = 1;
9260 if (usb_devices_index >= MAX_USB_CMDLINE) {
9261 fprintf(stderr, "Too many USB devices\n");
9262 exit(1);
9264 pstrcpy(usb_devices[usb_devices_index],
9265 sizeof(usb_devices[usb_devices_index]),
9266 optarg);
9267 usb_devices_index++;
9268 break;
9269 case QEMU_OPTION_smp:
9270 smp_cpus = atoi(optarg);
9271 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9272 fprintf(stderr, "Invalid number of CPUs\n");
9273 exit(1);
9275 break;
9276 case QEMU_OPTION_vnc:
9277 vnc_display = optarg;
9278 break;
9279 case QEMU_OPTION_no_acpi:
9280 acpi_enabled = 0;
9281 break;
9282 case QEMU_OPTION_no_reboot:
9283 no_reboot = 1;
9284 break;
9285 case QEMU_OPTION_show_cursor:
9286 cursor_hide = 0;
9287 break;
9288 case QEMU_OPTION_daemonize:
9289 daemonize = 1;
9290 break;
9291 case QEMU_OPTION_option_rom:
9292 if (nb_option_roms >= MAX_OPTION_ROMS) {
9293 fprintf(stderr, "Too many option ROMs\n");
9294 exit(1);
9296 option_rom[nb_option_roms] = optarg;
9297 nb_option_roms++;
9298 break;
9299 case QEMU_OPTION_semihosting:
9300 semihosting_enabled = 1;
9301 break;
9302 case QEMU_OPTION_tdf:
9303 time_drift_fix = 1;
9304 break;
9305 case QEMU_OPTION_kvm_shadow_memory:
9306 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9307 break;
9308 case QEMU_OPTION_mempath:
9309 mem_path = optarg;
9310 break;
9311 case QEMU_OPTION_name:
9312 qemu_name = optarg;
9313 break;
9314 #ifdef TARGET_SPARC
9315 case QEMU_OPTION_prom_env:
9316 if (nb_prom_envs >= MAX_PROM_ENVS) {
9317 fprintf(stderr, "Too many prom variables\n");
9318 exit(1);
9320 prom_envs[nb_prom_envs] = optarg;
9321 nb_prom_envs++;
9322 break;
9323 #endif
9324 case QEMU_OPTION_cpu_vendor:
9325 cpu_vendor_string = optarg;
9326 break;
9327 #ifdef TARGET_ARM
9328 case QEMU_OPTION_old_param:
9329 old_param = 1;
9330 break;
9331 #endif
9332 case QEMU_OPTION_clock:
9333 configure_alarms(optarg);
9334 break;
9335 case QEMU_OPTION_startdate:
9337 struct tm tm;
9338 time_t rtc_start_date;
9339 if (!strcmp(optarg, "now")) {
9340 rtc_date_offset = -1;
9341 } else {
9342 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9343 &tm.tm_year,
9344 &tm.tm_mon,
9345 &tm.tm_mday,
9346 &tm.tm_hour,
9347 &tm.tm_min,
9348 &tm.tm_sec) == 6) {
9349 /* OK */
9350 } else if (sscanf(optarg, "%d-%d-%d",
9351 &tm.tm_year,
9352 &tm.tm_mon,
9353 &tm.tm_mday) == 3) {
9354 tm.tm_hour = 0;
9355 tm.tm_min = 0;
9356 tm.tm_sec = 0;
9357 } else {
9358 goto date_fail;
9360 tm.tm_year -= 1900;
9361 tm.tm_mon--;
9362 rtc_start_date = mktimegm(&tm);
9363 if (rtc_start_date == -1) {
9364 date_fail:
9365 fprintf(stderr, "Invalid date format. Valid format are:\n"
9366 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9367 exit(1);
9369 rtc_date_offset = time(NULL) - rtc_start_date;
9372 break;
9377 #ifndef _WIN32
9378 if (daemonize) {
9379 pid_t pid;
9381 if (pipe(fds) == -1)
9382 exit(1);
9384 pid = fork();
9385 if (pid > 0) {
9386 uint8_t status;
9387 ssize_t len;
9389 close(fds[1]);
9391 again:
9392 len = read(fds[0], &status, 1);
9393 if (len == -1 && (errno == EINTR))
9394 goto again;
9396 if (len != 1)
9397 exit(1);
9398 else if (status == 1) {
9399 fprintf(stderr, "Could not acquire pidfile\n");
9400 exit(1);
9401 } else
9402 exit(0);
9403 } else if (pid < 0)
9404 exit(1);
9406 setsid();
9408 pid = fork();
9409 if (pid > 0)
9410 exit(0);
9411 else if (pid < 0)
9412 exit(1);
9414 umask(027);
9416 signal(SIGTSTP, SIG_IGN);
9417 signal(SIGTTOU, SIG_IGN);
9418 signal(SIGTTIN, SIG_IGN);
9420 #endif
9422 #if USE_KVM
9423 if (kvm_enabled()) {
9424 if (kvm_qemu_init() < 0) {
9425 extern int kvm_allowed;
9426 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9427 #ifdef NO_CPU_EMULATION
9428 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9429 exit(1);
9430 #endif
9431 kvm_allowed = 0;
9434 #endif
9436 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9437 if (daemonize) {
9438 uint8_t status = 1;
9439 write(fds[1], &status, 1);
9440 } else
9441 fprintf(stderr, "Could not acquire pid file\n");
9442 exit(1);
9445 #ifdef USE_KQEMU
9446 if (smp_cpus > 1)
9447 kqemu_allowed = 0;
9448 #endif
9449 linux_boot = (kernel_filename != NULL);
9450 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9452 /* XXX: this should not be: some embedded targets just have flash */
9453 if (!linux_boot && net_boot == 0 &&
9454 nb_drives_opt == 0)
9455 help(1);
9457 /* boot to floppy or the default cd if no hard disk defined yet */
9458 if (!boot_devices[0]) {
9459 boot_devices = "cad";
9461 setvbuf(stdout, NULL, _IOLBF, 0);
9463 init_timers();
9464 init_timer_alarm();
9465 qemu_aio_init();
9467 #ifdef _WIN32
9468 socket_init();
9469 #endif
9471 /* init network clients */
9472 if (nb_net_clients == 0) {
9473 /* if no clients, we use a default config */
9474 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9475 "nic");
9476 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9477 "user");
9478 nb_net_clients = 2;
9481 for(i = 0;i < nb_net_clients; i++) {
9482 if (net_client_init(net_clients[i]) < 0)
9483 exit(1);
9485 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9486 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9487 continue;
9488 if (vlan->nb_guest_devs == 0) {
9489 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9490 exit(1);
9492 if (vlan->nb_host_devs == 0)
9493 fprintf(stderr,
9494 "Warning: vlan %d is not connected to host network\n",
9495 vlan->id);
9498 #ifdef TARGET_I386
9499 /* XXX: this should be moved in the PC machine instantiation code */
9500 if (net_boot != 0) {
9501 int netroms = 0;
9502 for (i = 0; i < nb_nics && i < 4; i++) {
9503 const char *model = nd_table[i].model;
9504 char buf[1024];
9505 if (net_boot & (1 << i)) {
9506 if (model == NULL)
9507 model = "rtl8139";
9508 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9509 if (get_image_size(buf) > 0) {
9510 if (nb_option_roms >= MAX_OPTION_ROMS) {
9511 fprintf(stderr, "Too many option ROMs\n");
9512 exit(1);
9514 option_rom[nb_option_roms] = strdup(buf);
9515 nb_option_roms++;
9516 netroms++;
9520 if (netroms == 0) {
9521 fprintf(stderr, "No valid PXE rom found for network device\n");
9522 exit(1);
9525 #endif
9527 /* init the memory */
9528 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9530 /* Initialize kvm */
9531 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9532 #define KVM_EXTRA_PAGES 3
9533 #else
9534 #define KVM_EXTRA_PAGES 0
9535 #endif
9536 if (kvm_enabled()) {
9537 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9538 if (kvm_qemu_create_context() < 0) {
9539 fprintf(stderr, "Could not create KVM context\n");
9540 exit(1);
9542 #ifdef KVM_CAP_USER_MEMORY
9544 int ret;
9546 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9547 if (ret) {
9548 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9549 if (!phys_ram_base) {
9550 fprintf(stderr, "Could not allocate physical memory\n");
9551 exit(1);
9555 #endif
9556 } else {
9557 phys_ram_base = qemu_vmalloc(phys_ram_size);
9558 if (!phys_ram_base) {
9559 fprintf(stderr, "Could not allocate physical memory\n");
9560 exit(1);
9564 bdrv_init();
9566 /* we always create the cdrom drive, even if no disk is there */
9568 if (nb_drives_opt < MAX_DRIVES)
9569 drive_add(NULL, CDROM_ALIAS);
9571 /* we always create at least one floppy */
9573 if (nb_drives_opt < MAX_DRIVES)
9574 drive_add(NULL, FD_ALIAS, 0);
9576 /* we always create one sd slot, even if no card is in it */
9578 if (nb_drives_opt < MAX_DRIVES)
9579 drive_add(NULL, SD_ALIAS);
9581 /* open the virtual block devices */
9583 for(i = 0; i < nb_drives_opt; i++)
9584 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9585 exit(1);
9587 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9588 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9590 init_ioports();
9592 /* terminal init */
9593 memset(&display_state, 0, sizeof(display_state));
9594 if (nographic) {
9595 if (curses) {
9596 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9597 exit(1);
9599 /* nearly nothing to do */
9600 dumb_display_init(ds);
9601 } else if (vnc_display != NULL) {
9602 vnc_display_init(ds);
9603 if (vnc_display_open(ds, vnc_display) < 0)
9604 exit(1);
9605 } else
9606 #if defined(CONFIG_CURSES)
9607 if (curses) {
9608 curses_display_init(ds, full_screen);
9609 } else
9610 #endif
9612 #if defined(CONFIG_SDL)
9613 sdl_display_init(ds, full_screen, no_frame);
9614 #elif defined(CONFIG_COCOA)
9615 cocoa_display_init(ds, full_screen);
9616 #else
9617 dumb_display_init(ds);
9618 #endif
9621 /* Maintain compatibility with multiple stdio monitors */
9622 if (!strcmp(monitor_device,"stdio")) {
9623 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9624 if (!strcmp(serial_devices[i],"mon:stdio")) {
9625 monitor_device[0] = '\0';
9626 break;
9627 } else if (!strcmp(serial_devices[i],"stdio")) {
9628 monitor_device[0] = '\0';
9629 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9630 break;
9634 if (monitor_device[0] != '\0') {
9635 monitor_hd = qemu_chr_open(monitor_device);
9636 if (!monitor_hd) {
9637 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9638 exit(1);
9640 monitor_init(monitor_hd, !nographic);
9643 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9644 const char *devname = vmchannel_devices[i];
9645 if (devname[0] != '\0' && strcmp(devname, "none")) {
9646 int devid;
9647 char *termn;
9649 if (strstart(devname, "di:", &devname)) {
9650 devid = strtol(devname, &termn, 16);
9651 devname = termn + 1;
9653 else {
9654 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9655 devname);
9656 exit(1);
9658 vmchannel_hds[i] = qemu_chr_open(devname);
9659 if (!vmchannel_hds[i]) {
9660 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9661 devname);
9662 exit(1);
9664 vmchannel_init(vmchannel_hds[i], devid, i);
9668 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9669 const char *devname = serial_devices[i];
9670 if (devname[0] != '\0' && strcmp(devname, "none")) {
9671 serial_hds[i] = qemu_chr_open(devname);
9672 if (!serial_hds[i]) {
9673 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9674 devname);
9675 exit(1);
9677 if (strstart(devname, "vc", 0))
9678 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9682 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9683 const char *devname = parallel_devices[i];
9684 if (devname[0] != '\0' && strcmp(devname, "none")) {
9685 parallel_hds[i] = qemu_chr_open(devname);
9686 if (!parallel_hds[i]) {
9687 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9688 devname);
9689 exit(1);
9691 if (strstart(devname, "vc", 0))
9692 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9696 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9697 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9699 /* init USB devices */
9700 if (usb_enabled) {
9701 for(i = 0; i < usb_devices_index; i++) {
9702 if (usb_device_add(usb_devices[i]) < 0) {
9703 fprintf(stderr, "Warning: could not add USB device %s\n",
9704 usb_devices[i]);
9709 if (display_state.dpy_refresh) {
9710 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9711 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9714 if (kvm_enabled())
9715 kvm_init_ap();
9717 #ifdef CONFIG_GDBSTUB
9718 if (use_gdbstub) {
9719 /* XXX: use standard host:port notation and modify options
9720 accordingly. */
9721 if (gdbserver_start(gdbstub_port) < 0) {
9722 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9723 gdbstub_port);
9724 exit(1);
9727 #endif
9728 if (loadvm)
9729 do_loadvm(loadvm);
9731 if (incoming) {
9732 int rc;
9734 rc = migrate_incoming(incoming);
9735 if (rc != 0) {
9736 fprintf(stderr, "Migration failed rc=%d\n", rc);
9737 exit(rc);
9742 /* XXX: simplify init */
9743 read_passwords();
9744 if (autostart) {
9745 vm_start();
9749 if (daemonize) {
9750 uint8_t status = 0;
9751 ssize_t len;
9752 int fd;
9754 again1:
9755 len = write(fds[1], &status, 1);
9756 if (len == -1 && (errno == EINTR))
9757 goto again1;
9759 if (len != 1)
9760 exit(1);
9762 chdir("/");
9763 TFR(fd = open("/dev/null", O_RDWR));
9764 if (fd == -1)
9765 exit(1);
9767 dup2(fd, 0);
9768 dup2(fd, 1);
9769 dup2(fd, 2);
9771 close(fd);
9774 main_loop();
9775 quit_timers();
9777 #if !defined(_WIN32)
9778 /* close network clients */
9779 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9780 VLANClientState *vc;
9782 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9783 if (vc->fd_read == tap_receive) {
9784 char ifname[64];
9785 TAPState *s = vc->opaque;
9787 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9788 s->down_script[0])
9789 launch_script(s->down_script, ifname, s->fd);
9793 #endif
9794 return 0;