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