Manipulate the gpe bits and send sci up the os
[qemu-kvm/fedora.git] / vl.c
blobc9ed3f02e29a093e3af0b3ceaa41ff0f22e06a29
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 const char* keyboard_layout = NULL;
185 int64_t ticks_per_sec;
186 int64_t ram_size;
187 int pit_min_timer_count = 0;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 int rtc_utc = 1;
192 int rtc_start_date = -1; /* -1 means now */
193 int cirrus_vga_enabled = 1;
194 int vmsvga_enabled = 0;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 int full_screen = 0;
205 int no_frame = 0;
206 int no_quit = 0;
207 int balloon_used = 0;
208 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 #ifdef TARGET_I386
212 int win2k_install_hack = 0;
213 #endif
214 int usb_enabled = 0;
215 static VLANState *first_vlan;
216 int smp_cpus = 1;
217 const char *vnc_display;
218 #if defined(TARGET_SPARC)
219 #define MAX_CPUS 16
220 #elif defined(TARGET_I386)
221 #define MAX_CPUS 255
222 #elif defined(TARGET_IA64)
223 #define MAX_CPUS 4
224 #else
225 #define MAX_CPUS 1
226 #endif
227 int acpi_enabled = 1;
228 int fd_bootchk = 1;
229 int no_reboot = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 int daemonize = 0;
233 const char *incoming;
234 const char *option_rom[MAX_OPTION_ROMS];
235 int nb_option_roms;
236 int semihosting_enabled = 0;
237 int autostart = 1;
238 int time_drift_fix = 0;
239 unsigned int kvm_shadow_memory = 0;
240 const char *hugetlbpath = NULL;
241 const char *hugetlbfile = NULL;
242 int hpagesize = 0;
243 const char *cpu_vendor_string;
244 #ifdef TARGET_ARM
245 int old_param = 0;
246 #endif
247 const char *qemu_name;
248 int alt_grab = 0;
249 #ifdef TARGET_SPARC
250 unsigned int nb_prom_envs = 0;
251 const char *prom_envs[MAX_PROM_ENVS];
252 #endif
253 int nb_drives_opt;
254 struct drive_opt {
255 const char *file;
256 char opt[1024];
257 } drives_opt[MAX_DRIVES];
259 static CPUState *cur_cpu;
260 static CPUState *next_cpu;
261 static int event_pending = 1;
263 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
265 void decorate_application_name(char *appname, int max_len)
267 if (kvm_enabled())
269 int remain = max_len - strlen(appname) - 1;
271 if (remain > 0)
272 strncat(appname, "/KVM", remain);
276 /***********************************************************/
277 /* x86 ISA bus support */
279 target_phys_addr_t isa_mem_base = 0;
280 PicState2 *isa_pic;
282 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
284 #ifdef DEBUG_UNUSED_IOPORT
285 fprintf(stderr, "unused inb: port=0x%04x\n", address);
286 #endif
287 return 0xff;
290 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
292 #ifdef DEBUG_UNUSED_IOPORT
293 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
294 #endif
297 /* default is to make two byte accesses */
298 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
300 uint32_t data;
301 data = ioport_read_table[0][address](ioport_opaque[address], address);
302 address = (address + 1) & (MAX_IOPORTS - 1);
303 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
304 return data;
307 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
309 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
310 address = (address + 1) & (MAX_IOPORTS - 1);
311 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
314 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
316 #ifdef DEBUG_UNUSED_IOPORT
317 fprintf(stderr, "unused inl: port=0x%04x\n", address);
318 #endif
319 return 0xffffffff;
322 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
324 #ifdef DEBUG_UNUSED_IOPORT
325 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
326 #endif
329 static void init_ioports(void)
331 int i;
333 for(i = 0; i < MAX_IOPORTS; i++) {
334 ioport_read_table[0][i] = default_ioport_readb;
335 ioport_write_table[0][i] = default_ioport_writeb;
336 ioport_read_table[1][i] = default_ioport_readw;
337 ioport_write_table[1][i] = default_ioport_writew;
338 ioport_read_table[2][i] = default_ioport_readl;
339 ioport_write_table[2][i] = default_ioport_writel;
343 /* size is the word size in byte */
344 int register_ioport_read(int start, int length, int size,
345 IOPortReadFunc *func, void *opaque)
347 int i, bsize;
349 if (size == 1) {
350 bsize = 0;
351 } else if (size == 2) {
352 bsize = 1;
353 } else if (size == 4) {
354 bsize = 2;
355 } else {
356 hw_error("register_ioport_read: invalid size");
357 return -1;
359 for(i = start; i < start + length; i += size) {
360 ioport_read_table[bsize][i] = func;
361 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
362 hw_error("register_ioport_read: invalid opaque");
363 ioport_opaque[i] = opaque;
365 return 0;
368 /* size is the word size in byte */
369 int register_ioport_write(int start, int length, int size,
370 IOPortWriteFunc *func, void *opaque)
372 int i, bsize;
374 if (size == 1) {
375 bsize = 0;
376 } else if (size == 2) {
377 bsize = 1;
378 } else if (size == 4) {
379 bsize = 2;
380 } else {
381 hw_error("register_ioport_write: invalid size");
382 return -1;
384 for(i = start; i < start + length; i += size) {
385 ioport_write_table[bsize][i] = func;
386 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
387 hw_error("register_ioport_write: invalid opaque");
388 ioport_opaque[i] = opaque;
390 return 0;
393 void isa_unassign_ioport(int start, int length)
395 int i;
397 for(i = start; i < start + length; i++) {
398 ioport_read_table[0][i] = default_ioport_readb;
399 ioport_read_table[1][i] = default_ioport_readw;
400 ioport_read_table[2][i] = default_ioport_readl;
402 ioport_write_table[0][i] = default_ioport_writeb;
403 ioport_write_table[1][i] = default_ioport_writew;
404 ioport_write_table[2][i] = default_ioport_writel;
408 /***********************************************************/
410 void cpu_outb(CPUState *env, int addr, int val)
412 #ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "outb: %04x %02x\n", addr, val);
415 #endif
416 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
417 #ifdef USE_KQEMU
418 if (env)
419 env->last_io_time = cpu_get_time_fast();
420 #endif
423 void cpu_outw(CPUState *env, int addr, int val)
425 #ifdef DEBUG_IOPORT
426 if (loglevel & CPU_LOG_IOPORT)
427 fprintf(logfile, "outw: %04x %04x\n", addr, val);
428 #endif
429 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
430 #ifdef USE_KQEMU
431 if (env)
432 env->last_io_time = cpu_get_time_fast();
433 #endif
436 void cpu_outl(CPUState *env, int addr, int val)
438 #ifdef DEBUG_IOPORT
439 if (loglevel & CPU_LOG_IOPORT)
440 fprintf(logfile, "outl: %04x %08x\n", addr, val);
441 #endif
442 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
443 #ifdef USE_KQEMU
444 if (env)
445 env->last_io_time = cpu_get_time_fast();
446 #endif
449 int cpu_inb(CPUState *env, int addr)
451 int val;
452 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
453 #ifdef DEBUG_IOPORT
454 if (loglevel & CPU_LOG_IOPORT)
455 fprintf(logfile, "inb : %04x %02x\n", addr, val);
456 #endif
457 #ifdef USE_KQEMU
458 if (env)
459 env->last_io_time = cpu_get_time_fast();
460 #endif
461 return val;
464 int cpu_inw(CPUState *env, int addr)
466 int val;
467 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
468 #ifdef DEBUG_IOPORT
469 if (loglevel & CPU_LOG_IOPORT)
470 fprintf(logfile, "inw : %04x %04x\n", addr, val);
471 #endif
472 #ifdef USE_KQEMU
473 if (env)
474 env->last_io_time = cpu_get_time_fast();
475 #endif
476 return val;
479 int cpu_inl(CPUState *env, int addr)
481 int val;
482 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
483 #ifdef DEBUG_IOPORT
484 if (loglevel & CPU_LOG_IOPORT)
485 fprintf(logfile, "inl : %04x %08x\n", addr, val);
486 #endif
487 #ifdef USE_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
491 return val;
494 /***********************************************************/
495 void hw_error(const char *fmt, ...)
497 va_list ap;
498 CPUState *env;
500 va_start(ap, fmt);
501 fprintf(stderr, "qemu: hardware error: ");
502 vfprintf(stderr, fmt, ap);
503 fprintf(stderr, "\n");
504 for(env = first_cpu; env != NULL; env = env->next_cpu) {
505 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
506 #ifdef TARGET_I386
507 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
508 #else
509 cpu_dump_state(env, stderr, fprintf, 0);
510 #endif
512 va_end(ap);
513 abort();
516 /***********************************************************/
517 /* keyboard/mouse */
519 static QEMUPutKBDEvent *qemu_put_kbd_event;
520 static void *qemu_put_kbd_event_opaque;
521 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
522 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
524 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
526 qemu_put_kbd_event_opaque = opaque;
527 qemu_put_kbd_event = func;
530 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
531 void *opaque, int absolute,
532 const char *name)
534 QEMUPutMouseEntry *s, *cursor;
536 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
537 if (!s)
538 return NULL;
540 s->qemu_put_mouse_event = func;
541 s->qemu_put_mouse_event_opaque = opaque;
542 s->qemu_put_mouse_event_absolute = absolute;
543 s->qemu_put_mouse_event_name = qemu_strdup(name);
544 s->next = NULL;
546 if (!qemu_put_mouse_event_head) {
547 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
548 return s;
551 cursor = qemu_put_mouse_event_head;
552 while (cursor->next != NULL)
553 cursor = cursor->next;
555 cursor->next = s;
556 qemu_put_mouse_event_current = s;
558 return s;
561 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
563 QEMUPutMouseEntry *prev = NULL, *cursor;
565 if (!qemu_put_mouse_event_head || entry == NULL)
566 return;
568 cursor = qemu_put_mouse_event_head;
569 while (cursor != NULL && cursor != entry) {
570 prev = cursor;
571 cursor = cursor->next;
574 if (cursor == NULL) // does not exist or list empty
575 return;
576 else if (prev == NULL) { // entry is head
577 qemu_put_mouse_event_head = cursor->next;
578 if (qemu_put_mouse_event_current == entry)
579 qemu_put_mouse_event_current = cursor->next;
580 qemu_free(entry->qemu_put_mouse_event_name);
581 qemu_free(entry);
582 return;
585 prev->next = entry->next;
587 if (qemu_put_mouse_event_current == entry)
588 qemu_put_mouse_event_current = prev;
590 qemu_free(entry->qemu_put_mouse_event_name);
591 qemu_free(entry);
594 void kbd_put_keycode(int keycode)
596 if (qemu_put_kbd_event) {
597 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
601 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
603 QEMUPutMouseEvent *mouse_event;
604 void *mouse_event_opaque;
605 int width;
607 if (!qemu_put_mouse_event_current) {
608 return;
611 mouse_event =
612 qemu_put_mouse_event_current->qemu_put_mouse_event;
613 mouse_event_opaque =
614 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
616 if (mouse_event) {
617 if (graphic_rotate) {
618 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
619 width = 0x7fff;
620 else
621 width = graphic_width;
622 mouse_event(mouse_event_opaque,
623 width - dy, dx, dz, buttons_state);
624 } else
625 mouse_event(mouse_event_opaque,
626 dx, dy, dz, buttons_state);
630 int kbd_mouse_is_absolute(void)
632 if (!qemu_put_mouse_event_current)
633 return 0;
635 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
638 void do_info_mice(void)
640 QEMUPutMouseEntry *cursor;
641 int index = 0;
643 if (!qemu_put_mouse_event_head) {
644 term_printf("No mouse devices connected\n");
645 return;
648 term_printf("Mouse devices available:\n");
649 cursor = qemu_put_mouse_event_head;
650 while (cursor != NULL) {
651 term_printf("%c Mouse #%d: %s\n",
652 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
653 index, cursor->qemu_put_mouse_event_name);
654 index++;
655 cursor = cursor->next;
659 void do_mouse_set(int index)
661 QEMUPutMouseEntry *cursor;
662 int i = 0;
664 if (!qemu_put_mouse_event_head) {
665 term_printf("No mouse devices connected\n");
666 return;
669 cursor = qemu_put_mouse_event_head;
670 while (cursor != NULL && index != i) {
671 i++;
672 cursor = cursor->next;
675 if (cursor != NULL)
676 qemu_put_mouse_event_current = cursor;
677 else
678 term_printf("Mouse at given index not found\n");
681 /* compute with 96 bit intermediate result: (a*b)/c */
682 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
684 union {
685 uint64_t ll;
686 struct {
687 #ifdef WORDS_BIGENDIAN
688 uint32_t high, low;
689 #else
690 uint32_t low, high;
691 #endif
692 } l;
693 } u, res;
694 uint64_t rl, rh;
696 u.ll = a;
697 rl = (uint64_t)u.l.low * (uint64_t)b;
698 rh = (uint64_t)u.l.high * (uint64_t)b;
699 rh += (rl >> 32);
700 res.l.high = rh / c;
701 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
702 return res.ll;
705 /***********************************************************/
706 /* real time host monotonic timer */
708 #define QEMU_TIMER_BASE 1000000000LL
710 #ifdef WIN32
712 static int64_t clock_freq;
714 static void init_get_clock(void)
716 LARGE_INTEGER freq;
717 int ret;
718 ret = QueryPerformanceFrequency(&freq);
719 if (ret == 0) {
720 fprintf(stderr, "Could not calibrate ticks\n");
721 exit(1);
723 clock_freq = freq.QuadPart;
726 static int64_t get_clock(void)
728 LARGE_INTEGER ti;
729 QueryPerformanceCounter(&ti);
730 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
733 #else
735 static int use_rt_clock;
737 static void init_get_clock(void)
739 use_rt_clock = 0;
740 #if defined(__linux__)
742 struct timespec ts;
743 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
744 use_rt_clock = 1;
747 #endif
750 static int64_t get_clock(void)
752 #if defined(__linux__)
753 if (use_rt_clock) {
754 struct timespec ts;
755 clock_gettime(CLOCK_MONOTONIC, &ts);
756 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
757 } else
758 #endif
760 /* XXX: using gettimeofday leads to problems if the date
761 changes, so it should be avoided. */
762 struct timeval tv;
763 gettimeofday(&tv, NULL);
764 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
768 #endif
770 /***********************************************************/
771 /* guest cycle counter */
773 static int64_t cpu_ticks_prev;
774 static int64_t cpu_ticks_offset;
775 static int64_t cpu_clock_offset;
776 static int cpu_ticks_enabled;
778 /* return the host CPU cycle counter and handle stop/restart */
779 int64_t cpu_get_ticks(void)
781 if (!cpu_ticks_enabled) {
782 return cpu_ticks_offset;
783 } else {
784 int64_t ticks;
785 ticks = cpu_get_real_ticks();
786 if (cpu_ticks_prev > ticks) {
787 /* Note: non increasing ticks may happen if the host uses
788 software suspend */
789 cpu_ticks_offset += cpu_ticks_prev - ticks;
791 cpu_ticks_prev = ticks;
792 return ticks + cpu_ticks_offset;
796 /* return the host CPU monotonic timer and handle stop/restart */
797 static int64_t cpu_get_clock(void)
799 int64_t ti;
800 if (!cpu_ticks_enabled) {
801 return cpu_clock_offset;
802 } else {
803 ti = get_clock();
804 return ti + cpu_clock_offset;
808 /* enable cpu_get_ticks() */
809 void cpu_enable_ticks(void)
811 if (!cpu_ticks_enabled) {
812 cpu_ticks_offset -= cpu_get_real_ticks();
813 cpu_clock_offset -= get_clock();
814 cpu_ticks_enabled = 1;
818 /* disable cpu_get_ticks() : the clock is stopped. You must not call
819 cpu_get_ticks() after that. */
820 void cpu_disable_ticks(void)
822 if (cpu_ticks_enabled) {
823 cpu_ticks_offset = cpu_get_ticks();
824 cpu_clock_offset = cpu_get_clock();
825 cpu_ticks_enabled = 0;
829 /***********************************************************/
830 /* timers */
832 #define QEMU_TIMER_REALTIME 0
833 #define QEMU_TIMER_VIRTUAL 1
835 struct QEMUClock {
836 int type;
837 /* XXX: add frequency */
840 struct QEMUTimer {
841 QEMUClock *clock;
842 int64_t expire_time;
843 QEMUTimerCB *cb;
844 void *opaque;
845 struct QEMUTimer *next;
848 struct qemu_alarm_timer {
849 char const *name;
850 unsigned int flags;
852 int (*start)(struct qemu_alarm_timer *t);
853 void (*stop)(struct qemu_alarm_timer *t);
854 void (*rearm)(struct qemu_alarm_timer *t);
855 void *priv;
858 #define ALARM_FLAG_DYNTICKS 0x1
859 #define ALARM_FLAG_EXPIRED 0x2
861 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
863 return t->flags & ALARM_FLAG_DYNTICKS;
866 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
868 if (!alarm_has_dynticks(t))
869 return;
871 t->rearm(t);
874 /* TODO: MIN_TIMER_REARM_US should be optimized */
875 #define MIN_TIMER_REARM_US 250
877 static struct qemu_alarm_timer *alarm_timer;
879 #ifdef _WIN32
881 struct qemu_alarm_win32 {
882 MMRESULT timerId;
883 HANDLE host_alarm;
884 unsigned int period;
885 } alarm_win32_data = {0, NULL, -1};
887 static int win32_start_timer(struct qemu_alarm_timer *t);
888 static void win32_stop_timer(struct qemu_alarm_timer *t);
889 static void win32_rearm_timer(struct qemu_alarm_timer *t);
891 #else
893 static int unix_start_timer(struct qemu_alarm_timer *t);
894 static void unix_stop_timer(struct qemu_alarm_timer *t);
896 #ifdef __linux__
898 static int dynticks_start_timer(struct qemu_alarm_timer *t);
899 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
900 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
902 static int hpet_start_timer(struct qemu_alarm_timer *t);
903 static void hpet_stop_timer(struct qemu_alarm_timer *t);
905 static int rtc_start_timer(struct qemu_alarm_timer *t);
906 static void rtc_stop_timer(struct qemu_alarm_timer *t);
908 #endif /* __linux__ */
910 #endif /* _WIN32 */
912 static struct qemu_alarm_timer alarm_timers[] = {
913 #ifndef _WIN32
914 #ifdef __linux__
915 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
916 dynticks_stop_timer, dynticks_rearm_timer, NULL},
917 /* HPET - if available - is preferred */
918 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
919 /* ...otherwise try RTC */
920 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
921 #endif
922 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
923 #else
924 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
925 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
926 {"win32", 0, win32_start_timer,
927 win32_stop_timer, NULL, &alarm_win32_data},
928 #endif
929 {NULL, }
932 static void show_available_alarms()
934 int i;
936 printf("Available alarm timers, in order of precedence:\n");
937 for (i = 0; alarm_timers[i].name; i++)
938 printf("%s\n", alarm_timers[i].name);
941 static void configure_alarms(char const *opt)
943 int i;
944 int cur = 0;
945 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
946 char *arg;
947 char *name;
949 if (!strcmp(opt, "help")) {
950 show_available_alarms();
951 exit(0);
954 arg = strdup(opt);
956 /* Reorder the array */
957 name = strtok(arg, ",");
958 while (name) {
959 struct qemu_alarm_timer tmp;
961 for (i = 0; i < count && alarm_timers[i].name; i++) {
962 if (!strcmp(alarm_timers[i].name, name))
963 break;
966 if (i == count) {
967 fprintf(stderr, "Unknown clock %s\n", name);
968 goto next;
971 if (i < cur)
972 /* Ignore */
973 goto next;
975 /* Swap */
976 tmp = alarm_timers[i];
977 alarm_timers[i] = alarm_timers[cur];
978 alarm_timers[cur] = tmp;
980 cur++;
981 next:
982 name = strtok(NULL, ",");
985 free(arg);
987 if (cur) {
988 /* Disable remaining timers */
989 for (i = cur; i < count; i++)
990 alarm_timers[i].name = NULL;
993 /* debug */
994 show_available_alarms();
997 QEMUClock *rt_clock;
998 QEMUClock *vm_clock;
1000 static QEMUTimer *active_timers[2];
1002 static QEMUClock *qemu_new_clock(int type)
1004 QEMUClock *clock;
1005 clock = qemu_mallocz(sizeof(QEMUClock));
1006 if (!clock)
1007 return NULL;
1008 clock->type = type;
1009 return clock;
1012 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1014 QEMUTimer *ts;
1016 ts = qemu_mallocz(sizeof(QEMUTimer));
1017 ts->clock = clock;
1018 ts->cb = cb;
1019 ts->opaque = opaque;
1020 return ts;
1023 void qemu_free_timer(QEMUTimer *ts)
1025 qemu_free(ts);
1028 /* stop a timer, but do not dealloc it */
1029 void qemu_del_timer(QEMUTimer *ts)
1031 QEMUTimer **pt, *t;
1033 /* NOTE: this code must be signal safe because
1034 qemu_timer_expired() can be called from a signal. */
1035 pt = &active_timers[ts->clock->type];
1036 for(;;) {
1037 t = *pt;
1038 if (!t)
1039 break;
1040 if (t == ts) {
1041 *pt = t->next;
1042 break;
1044 pt = &t->next;
1048 /* modify the current timer so that it will be fired when current_time
1049 >= expire_time. The corresponding callback will be called. */
1050 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1052 QEMUTimer **pt, *t;
1054 qemu_del_timer(ts);
1056 /* add the timer in the sorted list */
1057 /* NOTE: this code must be signal safe because
1058 qemu_timer_expired() can be called from a signal. */
1059 pt = &active_timers[ts->clock->type];
1060 for(;;) {
1061 t = *pt;
1062 if (!t)
1063 break;
1064 if (t->expire_time > expire_time)
1065 break;
1066 pt = &t->next;
1068 ts->expire_time = expire_time;
1069 ts->next = *pt;
1070 *pt = ts;
1072 /* Rearm if necessary */
1073 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1074 pt == &active_timers[ts->clock->type])
1075 qemu_rearm_alarm_timer(alarm_timer);
1078 int qemu_timer_pending(QEMUTimer *ts)
1080 QEMUTimer *t;
1081 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1082 if (t == ts)
1083 return 1;
1085 return 0;
1088 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1090 if (!timer_head)
1091 return 0;
1092 return (timer_head->expire_time <= current_time);
1095 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1097 QEMUTimer *ts;
1099 for(;;) {
1100 ts = *ptimer_head;
1101 if (!ts || ts->expire_time > current_time)
1102 break;
1103 /* remove timer from the list before calling the callback */
1104 *ptimer_head = ts->next;
1105 ts->next = NULL;
1107 /* run the callback (the timer list can be modified) */
1108 ts->cb(ts->opaque);
1112 int64_t qemu_get_clock(QEMUClock *clock)
1114 switch(clock->type) {
1115 case QEMU_TIMER_REALTIME:
1116 return get_clock() / 1000000;
1117 default:
1118 case QEMU_TIMER_VIRTUAL:
1119 return cpu_get_clock();
1123 static void init_timers(void)
1125 init_get_clock();
1126 ticks_per_sec = QEMU_TIMER_BASE;
1127 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1128 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1131 /* save a timer */
1132 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1134 uint64_t expire_time;
1136 if (qemu_timer_pending(ts)) {
1137 expire_time = ts->expire_time;
1138 } else {
1139 expire_time = -1;
1141 qemu_put_be64(f, expire_time);
1144 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1146 uint64_t expire_time;
1148 expire_time = qemu_get_be64(f);
1149 if (expire_time != -1) {
1150 qemu_mod_timer(ts, expire_time);
1151 } else {
1152 qemu_del_timer(ts);
1156 static void timer_save(QEMUFile *f, void *opaque)
1158 if (cpu_ticks_enabled) {
1159 hw_error("cannot save state if virtual timers are running");
1161 qemu_put_be64(f, cpu_ticks_offset);
1162 qemu_put_be64(f, ticks_per_sec);
1163 qemu_put_be64(f, cpu_clock_offset);
1166 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1168 if (version_id != 1 && version_id != 2)
1169 return -EINVAL;
1170 if (cpu_ticks_enabled) {
1171 return -EINVAL;
1173 cpu_ticks_offset=qemu_get_be64(f);
1174 ticks_per_sec=qemu_get_be64(f);
1175 if (version_id == 2) {
1176 cpu_clock_offset=qemu_get_be64(f);
1178 return 0;
1181 #ifdef _WIN32
1182 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1183 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1184 #else
1185 static void host_alarm_handler(int host_signum)
1186 #endif
1188 #if 0
1189 #define DISP_FREQ 1000
1191 static int64_t delta_min = INT64_MAX;
1192 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1193 static int count;
1194 ti = qemu_get_clock(vm_clock);
1195 if (last_clock != 0) {
1196 delta = ti - last_clock;
1197 if (delta < delta_min)
1198 delta_min = delta;
1199 if (delta > delta_max)
1200 delta_max = delta;
1201 delta_cum += delta;
1202 if (++count == DISP_FREQ) {
1203 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1204 muldiv64(delta_min, 1000000, ticks_per_sec),
1205 muldiv64(delta_max, 1000000, ticks_per_sec),
1206 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1207 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1208 count = 0;
1209 delta_min = INT64_MAX;
1210 delta_max = 0;
1211 delta_cum = 0;
1214 last_clock = ti;
1216 #endif
1217 if (1 ||
1218 alarm_has_dynticks(alarm_timer) ||
1219 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1220 qemu_get_clock(vm_clock)) ||
1221 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1222 qemu_get_clock(rt_clock))) {
1223 #ifdef _WIN32
1224 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1225 SetEvent(data->host_alarm);
1226 #endif
1227 CPUState *env = next_cpu;
1229 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1231 if (env) {
1232 /* stop the currently executing cpu because a timer occured */
1233 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1234 #ifdef USE_KQEMU
1235 if (env->kqemu_enabled) {
1236 kqemu_cpu_interrupt(env);
1238 #endif
1240 event_pending = 1;
1244 static uint64_t qemu_next_deadline(void)
1246 int64_t nearest_delta_us = INT64_MAX;
1247 int64_t vmdelta_us;
1249 if (active_timers[QEMU_TIMER_REALTIME])
1250 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1251 qemu_get_clock(rt_clock))*1000;
1253 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1254 /* round up */
1255 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1256 qemu_get_clock(vm_clock)+999)/1000;
1257 if (vmdelta_us < nearest_delta_us)
1258 nearest_delta_us = vmdelta_us;
1261 /* Avoid arming the timer to negative, zero, or too low values */
1262 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1263 nearest_delta_us = MIN_TIMER_REARM_US;
1265 return nearest_delta_us;
1268 #ifndef _WIN32
1270 #if defined(__linux__)
1272 #define RTC_FREQ 1024
1274 static void enable_sigio_timer(int fd)
1276 struct sigaction act;
1278 /* timer signal */
1279 sigfillset(&act.sa_mask);
1280 act.sa_flags = 0;
1281 act.sa_handler = host_alarm_handler;
1283 sigaction(SIGIO, &act, NULL);
1284 fcntl(fd, F_SETFL, O_ASYNC);
1285 fcntl(fd, F_SETOWN, getpid());
1288 static int hpet_start_timer(struct qemu_alarm_timer *t)
1290 struct hpet_info info;
1291 int r, fd;
1293 fd = open("/dev/hpet", O_RDONLY);
1294 if (fd < 0)
1295 return -1;
1297 /* Set frequency */
1298 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1299 if (r < 0) {
1300 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1301 "error, but for better emulation accuracy type:\n"
1302 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1303 goto fail;
1306 /* Check capabilities */
1307 r = ioctl(fd, HPET_INFO, &info);
1308 if (r < 0)
1309 goto fail;
1311 /* Enable periodic mode */
1312 r = ioctl(fd, HPET_EPI, 0);
1313 if (info.hi_flags && (r < 0))
1314 goto fail;
1316 /* Enable interrupt */
1317 r = ioctl(fd, HPET_IE_ON, 0);
1318 if (r < 0)
1319 goto fail;
1321 enable_sigio_timer(fd);
1322 t->priv = (void *)(long)fd;
1324 return 0;
1325 fail:
1326 close(fd);
1327 return -1;
1330 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1332 int fd = (long)t->priv;
1334 close(fd);
1337 static int rtc_start_timer(struct qemu_alarm_timer *t)
1339 int rtc_fd;
1340 unsigned long current_rtc_freq = 0;
1342 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1343 if (rtc_fd < 0)
1344 return -1;
1345 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1346 if (current_rtc_freq != RTC_FREQ &&
1347 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1348 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1349 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1350 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1351 goto fail;
1353 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1354 fail:
1355 close(rtc_fd);
1356 return -1;
1359 enable_sigio_timer(rtc_fd);
1361 t->priv = (void *)(long)rtc_fd;
1363 return 0;
1366 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1368 int rtc_fd = (long)t->priv;
1370 close(rtc_fd);
1373 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1375 struct sigevent ev;
1376 timer_t host_timer;
1377 struct sigaction act;
1379 sigfillset(&act.sa_mask);
1380 act.sa_flags = 0;
1381 act.sa_handler = host_alarm_handler;
1383 sigaction(SIGALRM, &act, NULL);
1385 ev.sigev_value.sival_int = 0;
1386 ev.sigev_notify = SIGEV_SIGNAL;
1387 ev.sigev_signo = SIGALRM;
1389 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1390 perror("timer_create");
1392 /* disable dynticks */
1393 fprintf(stderr, "Dynamic Ticks disabled\n");
1395 return -1;
1398 t->priv = (void *)host_timer;
1400 return 0;
1403 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1405 timer_t host_timer = (timer_t)t->priv;
1407 timer_delete(host_timer);
1410 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1412 timer_t host_timer = (timer_t)t->priv;
1413 struct itimerspec timeout;
1414 int64_t nearest_delta_us = INT64_MAX;
1415 int64_t current_us;
1417 if (!active_timers[QEMU_TIMER_REALTIME] &&
1418 !active_timers[QEMU_TIMER_VIRTUAL])
1419 return;
1421 nearest_delta_us = qemu_next_deadline();
1423 /* check whether a timer is already running */
1424 if (timer_gettime(host_timer, &timeout)) {
1425 perror("gettime");
1426 fprintf(stderr, "Internal timer error: aborting\n");
1427 exit(1);
1429 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1430 if (current_us && current_us <= nearest_delta_us)
1431 return;
1433 timeout.it_interval.tv_sec = 0;
1434 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1435 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1436 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1437 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1438 perror("settime");
1439 fprintf(stderr, "Internal timer error: aborting\n");
1440 exit(1);
1444 #endif /* defined(__linux__) */
1446 static int unix_start_timer(struct qemu_alarm_timer *t)
1448 struct sigaction act;
1449 struct itimerval itv;
1450 int err;
1452 /* timer signal */
1453 sigfillset(&act.sa_mask);
1454 act.sa_flags = 0;
1455 act.sa_handler = host_alarm_handler;
1457 sigaction(SIGALRM, &act, NULL);
1459 itv.it_interval.tv_sec = 0;
1460 /* for i386 kernel 2.6 to get 1 ms */
1461 itv.it_interval.tv_usec = 999;
1462 itv.it_value.tv_sec = 0;
1463 itv.it_value.tv_usec = 10 * 1000;
1465 err = setitimer(ITIMER_REAL, &itv, NULL);
1466 if (err)
1467 return -1;
1469 return 0;
1472 static void unix_stop_timer(struct qemu_alarm_timer *t)
1474 struct itimerval itv;
1476 memset(&itv, 0, sizeof(itv));
1477 setitimer(ITIMER_REAL, &itv, NULL);
1480 #endif /* !defined(_WIN32) */
1482 #ifdef _WIN32
1484 static int win32_start_timer(struct qemu_alarm_timer *t)
1486 TIMECAPS tc;
1487 struct qemu_alarm_win32 *data = t->priv;
1488 UINT flags;
1490 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1491 if (!data->host_alarm) {
1492 perror("Failed CreateEvent");
1493 return -1;
1496 memset(&tc, 0, sizeof(tc));
1497 timeGetDevCaps(&tc, sizeof(tc));
1499 if (data->period < tc.wPeriodMin)
1500 data->period = tc.wPeriodMin;
1502 timeBeginPeriod(data->period);
1504 flags = TIME_CALLBACK_FUNCTION;
1505 if (alarm_has_dynticks(t))
1506 flags |= TIME_ONESHOT;
1507 else
1508 flags |= TIME_PERIODIC;
1510 data->timerId = timeSetEvent(1, // interval (ms)
1511 data->period, // resolution
1512 host_alarm_handler, // function
1513 (DWORD)t, // parameter
1514 flags);
1516 if (!data->timerId) {
1517 perror("Failed to initialize win32 alarm timer");
1519 timeEndPeriod(data->period);
1520 CloseHandle(data->host_alarm);
1521 return -1;
1524 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1526 return 0;
1529 static void win32_stop_timer(struct qemu_alarm_timer *t)
1531 struct qemu_alarm_win32 *data = t->priv;
1533 timeKillEvent(data->timerId);
1534 timeEndPeriod(data->period);
1536 CloseHandle(data->host_alarm);
1539 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1541 struct qemu_alarm_win32 *data = t->priv;
1542 uint64_t nearest_delta_us;
1544 if (!active_timers[QEMU_TIMER_REALTIME] &&
1545 !active_timers[QEMU_TIMER_VIRTUAL])
1546 return;
1548 nearest_delta_us = qemu_next_deadline();
1549 nearest_delta_us /= 1000;
1551 timeKillEvent(data->timerId);
1553 data->timerId = timeSetEvent(1,
1554 data->period,
1555 host_alarm_handler,
1556 (DWORD)t,
1557 TIME_ONESHOT | TIME_PERIODIC);
1559 if (!data->timerId) {
1560 perror("Failed to re-arm win32 alarm timer");
1562 timeEndPeriod(data->period);
1563 CloseHandle(data->host_alarm);
1564 exit(1);
1568 #endif /* _WIN32 */
1570 static void init_timer_alarm(void)
1572 struct qemu_alarm_timer *t;
1573 int i, err = -1;
1575 for (i = 0; alarm_timers[i].name; i++) {
1576 t = &alarm_timers[i];
1578 err = t->start(t);
1579 if (!err)
1580 break;
1583 if (err) {
1584 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1585 fprintf(stderr, "Terminating\n");
1586 exit(1);
1589 alarm_timer = t;
1592 static void quit_timers(void)
1594 alarm_timer->stop(alarm_timer);
1595 alarm_timer = NULL;
1598 /***********************************************************/
1599 /* character device */
1601 static void qemu_chr_event(CharDriverState *s, int event)
1603 if (!s->chr_event)
1604 return;
1605 s->chr_event(s->handler_opaque, event);
1608 static void qemu_chr_reset_bh(void *opaque)
1610 CharDriverState *s = opaque;
1611 qemu_chr_event(s, CHR_EVENT_RESET);
1612 qemu_bh_delete(s->bh);
1613 s->bh = NULL;
1616 void qemu_chr_reset(CharDriverState *s)
1618 if (s->bh == NULL) {
1619 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1620 qemu_bh_schedule(s->bh);
1624 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1626 return s->chr_write(s, buf, len);
1629 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1631 if (!s->chr_ioctl)
1632 return -ENOTSUP;
1633 return s->chr_ioctl(s, cmd, arg);
1636 int qemu_chr_can_read(CharDriverState *s)
1638 if (!s->chr_can_read)
1639 return 0;
1640 return s->chr_can_read(s->handler_opaque);
1643 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1645 s->chr_read(s->handler_opaque, buf, len);
1648 void qemu_chr_accept_input(CharDriverState *s)
1650 if (s->chr_accept_input)
1651 s->chr_accept_input(s);
1654 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1656 char buf[4096];
1657 va_list ap;
1658 va_start(ap, fmt);
1659 vsnprintf(buf, sizeof(buf), fmt, ap);
1660 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1661 va_end(ap);
1664 void qemu_chr_send_event(CharDriverState *s, int event)
1666 if (s->chr_send_event)
1667 s->chr_send_event(s, event);
1670 void qemu_chr_add_handlers(CharDriverState *s,
1671 IOCanRWHandler *fd_can_read,
1672 IOReadHandler *fd_read,
1673 IOEventHandler *fd_event,
1674 void *opaque)
1676 s->chr_can_read = fd_can_read;
1677 s->chr_read = fd_read;
1678 s->chr_event = fd_event;
1679 s->handler_opaque = opaque;
1680 if (s->chr_update_read_handler)
1681 s->chr_update_read_handler(s);
1684 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1686 return len;
1689 static CharDriverState *qemu_chr_open_null(void)
1691 CharDriverState *chr;
1693 chr = qemu_mallocz(sizeof(CharDriverState));
1694 if (!chr)
1695 return NULL;
1696 chr->chr_write = null_chr_write;
1697 return chr;
1700 /* MUX driver for serial I/O splitting */
1701 static int term_timestamps;
1702 static int64_t term_timestamps_start;
1703 #define MAX_MUX 4
1704 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1705 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1706 typedef struct {
1707 IOCanRWHandler *chr_can_read[MAX_MUX];
1708 IOReadHandler *chr_read[MAX_MUX];
1709 IOEventHandler *chr_event[MAX_MUX];
1710 void *ext_opaque[MAX_MUX];
1711 CharDriverState *drv;
1712 unsigned char buffer[MUX_BUFFER_SIZE];
1713 int prod;
1714 int cons;
1715 int mux_cnt;
1716 int term_got_escape;
1717 int max_size;
1718 } MuxDriver;
1721 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1723 MuxDriver *d = chr->opaque;
1724 int ret;
1725 if (!term_timestamps) {
1726 ret = d->drv->chr_write(d->drv, buf, len);
1727 } else {
1728 int i;
1730 ret = 0;
1731 for(i = 0; i < len; i++) {
1732 ret += d->drv->chr_write(d->drv, buf+i, 1);
1733 if (buf[i] == '\n') {
1734 char buf1[64];
1735 int64_t ti;
1736 int secs;
1738 ti = get_clock();
1739 if (term_timestamps_start == -1)
1740 term_timestamps_start = ti;
1741 ti -= term_timestamps_start;
1742 secs = ti / 1000000000;
1743 snprintf(buf1, sizeof(buf1),
1744 "[%02d:%02d:%02d.%03d] ",
1745 secs / 3600,
1746 (secs / 60) % 60,
1747 secs % 60,
1748 (int)((ti / 1000000) % 1000));
1749 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1753 return ret;
1756 static char *mux_help[] = {
1757 "% h print this help\n\r",
1758 "% x exit emulator\n\r",
1759 "% s save disk data back to file (if -snapshot)\n\r",
1760 "% t toggle console timestamps\n\r"
1761 "% b send break (magic sysrq)\n\r",
1762 "% c switch between console and monitor\n\r",
1763 "% % sends %\n\r",
1764 NULL
1767 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1768 static void mux_print_help(CharDriverState *chr)
1770 int i, j;
1771 char ebuf[15] = "Escape-Char";
1772 char cbuf[50] = "\n\r";
1774 if (term_escape_char > 0 && term_escape_char < 26) {
1775 sprintf(cbuf,"\n\r");
1776 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1777 } else {
1778 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1779 term_escape_char);
1781 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1782 for (i = 0; mux_help[i] != NULL; i++) {
1783 for (j=0; mux_help[i][j] != '\0'; j++) {
1784 if (mux_help[i][j] == '%')
1785 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1786 else
1787 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1792 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1794 if (d->term_got_escape) {
1795 d->term_got_escape = 0;
1796 if (ch == term_escape_char)
1797 goto send_char;
1798 switch(ch) {
1799 case '?':
1800 case 'h':
1801 mux_print_help(chr);
1802 break;
1803 case 'x':
1805 char *term = "QEMU: Terminated\n\r";
1806 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1807 exit(0);
1808 break;
1810 case 's':
1812 int i;
1813 for (i = 0; i < nb_drives; i++) {
1814 bdrv_commit(drives_table[i].bdrv);
1817 break;
1818 case 'b':
1819 qemu_chr_event(chr, CHR_EVENT_BREAK);
1820 break;
1821 case 'c':
1822 /* Switch to the next registered device */
1823 chr->focus++;
1824 if (chr->focus >= d->mux_cnt)
1825 chr->focus = 0;
1826 break;
1827 case 't':
1828 term_timestamps = !term_timestamps;
1829 term_timestamps_start = -1;
1830 break;
1832 } else if (ch == term_escape_char) {
1833 d->term_got_escape = 1;
1834 } else {
1835 send_char:
1836 return 1;
1838 return 0;
1841 static void mux_chr_accept_input(CharDriverState *chr)
1843 int m = chr->focus;
1844 MuxDriver *d = chr->opaque;
1846 while (d->prod != d->cons &&
1847 d->chr_can_read[m] &&
1848 d->chr_can_read[m](d->ext_opaque[m])) {
1849 d->chr_read[m](d->ext_opaque[m],
1850 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1854 static int mux_chr_can_read(void *opaque)
1856 CharDriverState *chr = opaque;
1857 MuxDriver *d = chr->opaque;
1859 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1860 return 1;
1861 if (d->chr_can_read[chr->focus])
1862 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1863 return 0;
1866 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1868 CharDriverState *chr = opaque;
1869 MuxDriver *d = chr->opaque;
1870 int m = chr->focus;
1871 int i;
1873 mux_chr_accept_input (opaque);
1875 for(i = 0; i < size; i++)
1876 if (mux_proc_byte(chr, d, buf[i])) {
1877 if (d->prod == d->cons &&
1878 d->chr_can_read[m] &&
1879 d->chr_can_read[m](d->ext_opaque[m]))
1880 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1881 else
1882 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1886 static void mux_chr_event(void *opaque, int event)
1888 CharDriverState *chr = opaque;
1889 MuxDriver *d = chr->opaque;
1890 int i;
1892 /* Send the event to all registered listeners */
1893 for (i = 0; i < d->mux_cnt; i++)
1894 if (d->chr_event[i])
1895 d->chr_event[i](d->ext_opaque[i], event);
1898 static void mux_chr_update_read_handler(CharDriverState *chr)
1900 MuxDriver *d = chr->opaque;
1902 if (d->mux_cnt >= MAX_MUX) {
1903 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1904 return;
1906 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1907 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1908 d->chr_read[d->mux_cnt] = chr->chr_read;
1909 d->chr_event[d->mux_cnt] = chr->chr_event;
1910 /* Fix up the real driver with mux routines */
1911 if (d->mux_cnt == 0) {
1912 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1913 mux_chr_event, chr);
1915 chr->focus = d->mux_cnt;
1916 d->mux_cnt++;
1919 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1921 CharDriverState *chr;
1922 MuxDriver *d;
1924 chr = qemu_mallocz(sizeof(CharDriverState));
1925 if (!chr)
1926 return NULL;
1927 d = qemu_mallocz(sizeof(MuxDriver));
1928 if (!d) {
1929 free(chr);
1930 return NULL;
1933 chr->opaque = d;
1934 d->drv = drv;
1935 chr->focus = -1;
1936 chr->chr_write = mux_chr_write;
1937 chr->chr_update_read_handler = mux_chr_update_read_handler;
1938 chr->chr_accept_input = mux_chr_accept_input;
1939 return chr;
1943 #ifdef _WIN32
1945 static void socket_cleanup(void)
1947 WSACleanup();
1950 static int socket_init(void)
1952 WSADATA Data;
1953 int ret, err;
1955 ret = WSAStartup(MAKEWORD(2,2), &Data);
1956 if (ret != 0) {
1957 err = WSAGetLastError();
1958 fprintf(stderr, "WSAStartup: %d\n", err);
1959 return -1;
1961 atexit(socket_cleanup);
1962 return 0;
1965 static int send_all(int fd, const uint8_t *buf, int len1)
1967 int ret, len;
1969 len = len1;
1970 while (len > 0) {
1971 ret = send(fd, buf, len, 0);
1972 if (ret < 0) {
1973 int errno;
1974 errno = WSAGetLastError();
1975 if (errno != WSAEWOULDBLOCK) {
1976 return -1;
1978 } else if (ret == 0) {
1979 break;
1980 } else {
1981 buf += ret;
1982 len -= ret;
1985 return len1 - len;
1988 void socket_set_nonblock(int fd)
1990 unsigned long opt = 1;
1991 ioctlsocket(fd, FIONBIO, &opt);
1994 #else
1996 static int unix_write(int fd, const uint8_t *buf, int len1)
1998 int ret, len;
2000 len = len1;
2001 while (len > 0) {
2002 ret = write(fd, buf, len);
2003 if (ret < 0) {
2004 if (errno != EINTR && errno != EAGAIN)
2005 return -1;
2006 } else if (ret == 0) {
2007 break;
2008 } else {
2009 buf += ret;
2010 len -= ret;
2013 return len1 - len;
2016 static inline int send_all(int fd, const uint8_t *buf, int len1)
2018 return unix_write(fd, buf, len1);
2021 void socket_set_nonblock(int fd)
2023 fcntl(fd, F_SETFL, O_NONBLOCK);
2025 #endif /* !_WIN32 */
2027 #ifndef _WIN32
2029 typedef struct {
2030 int fd_in, fd_out;
2031 int max_size;
2032 } FDCharDriver;
2034 #define STDIO_MAX_CLIENTS 1
2035 static int stdio_nb_clients = 0;
2037 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2039 FDCharDriver *s = chr->opaque;
2040 return unix_write(s->fd_out, buf, len);
2043 static int fd_chr_read_poll(void *opaque)
2045 CharDriverState *chr = opaque;
2046 FDCharDriver *s = chr->opaque;
2048 s->max_size = qemu_chr_can_read(chr);
2049 return s->max_size;
2052 static void fd_chr_read(void *opaque)
2054 CharDriverState *chr = opaque;
2055 FDCharDriver *s = chr->opaque;
2056 int size, len;
2057 uint8_t buf[1024];
2059 len = sizeof(buf);
2060 if (len > s->max_size)
2061 len = s->max_size;
2062 if (len == 0)
2063 return;
2064 size = read(s->fd_in, buf, len);
2065 if (size == 0) {
2066 /* FD has been closed. Remove it from the active list. */
2067 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2068 return;
2070 if (size > 0) {
2071 qemu_chr_read(chr, buf, size);
2075 static void fd_chr_update_read_handler(CharDriverState *chr)
2077 FDCharDriver *s = chr->opaque;
2079 if (s->fd_in >= 0) {
2080 if (nographic && s->fd_in == 0) {
2081 } else {
2082 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2083 fd_chr_read, NULL, chr);
2088 static void fd_chr_close(struct CharDriverState *chr)
2090 FDCharDriver *s = chr->opaque;
2092 if (s->fd_in >= 0) {
2093 if (nographic && s->fd_in == 0) {
2094 } else {
2095 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2099 qemu_free(s);
2102 /* open a character device to a unix fd */
2103 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2105 CharDriverState *chr;
2106 FDCharDriver *s;
2108 chr = qemu_mallocz(sizeof(CharDriverState));
2109 if (!chr)
2110 return NULL;
2111 s = qemu_mallocz(sizeof(FDCharDriver));
2112 if (!s) {
2113 free(chr);
2114 return NULL;
2116 s->fd_in = fd_in;
2117 s->fd_out = fd_out;
2118 chr->opaque = s;
2119 chr->chr_write = fd_chr_write;
2120 chr->chr_update_read_handler = fd_chr_update_read_handler;
2121 chr->chr_close = fd_chr_close;
2123 qemu_chr_reset(chr);
2125 return chr;
2128 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2130 int fd_out;
2132 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2133 if (fd_out < 0)
2134 return NULL;
2135 return qemu_chr_open_fd(-1, fd_out);
2138 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2140 int fd_in, fd_out;
2141 char filename_in[256], filename_out[256];
2143 snprintf(filename_in, 256, "%s.in", filename);
2144 snprintf(filename_out, 256, "%s.out", filename);
2145 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2146 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2147 if (fd_in < 0 || fd_out < 0) {
2148 if (fd_in >= 0)
2149 close(fd_in);
2150 if (fd_out >= 0)
2151 close(fd_out);
2152 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2153 if (fd_in < 0)
2154 return NULL;
2156 return qemu_chr_open_fd(fd_in, fd_out);
2160 /* for STDIO, we handle the case where several clients use it
2161 (nographic mode) */
2163 #define TERM_FIFO_MAX_SIZE 1
2165 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2166 static int term_fifo_size;
2168 static int stdio_read_poll(void *opaque)
2170 CharDriverState *chr = opaque;
2172 /* try to flush the queue if needed */
2173 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2174 qemu_chr_read(chr, term_fifo, 1);
2175 term_fifo_size = 0;
2177 /* see if we can absorb more chars */
2178 if (term_fifo_size == 0)
2179 return 1;
2180 else
2181 return 0;
2184 static void stdio_read(void *opaque)
2186 int size;
2187 uint8_t buf[1];
2188 CharDriverState *chr = opaque;
2190 size = read(0, buf, 1);
2191 if (size == 0) {
2192 /* stdin has been closed. Remove it from the active list. */
2193 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2194 return;
2196 if (size > 0) {
2197 if (qemu_chr_can_read(chr) > 0) {
2198 qemu_chr_read(chr, buf, 1);
2199 } else if (term_fifo_size == 0) {
2200 term_fifo[term_fifo_size++] = buf[0];
2205 /* init terminal so that we can grab keys */
2206 static struct termios oldtty;
2207 static int old_fd0_flags;
2208 static int term_atexit_done;
2210 static void term_exit(void)
2212 tcsetattr (0, TCSANOW, &oldtty);
2213 fcntl(0, F_SETFL, old_fd0_flags);
2216 static void term_init(void)
2218 struct termios tty;
2220 tcgetattr (0, &tty);
2221 oldtty = tty;
2222 old_fd0_flags = fcntl(0, F_GETFL);
2224 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2225 |INLCR|IGNCR|ICRNL|IXON);
2226 tty.c_oflag |= OPOST;
2227 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2228 /* if graphical mode, we allow Ctrl-C handling */
2229 if (nographic)
2230 tty.c_lflag &= ~ISIG;
2231 tty.c_cflag &= ~(CSIZE|PARENB);
2232 tty.c_cflag |= CS8;
2233 tty.c_cc[VMIN] = 1;
2234 tty.c_cc[VTIME] = 0;
2236 tcsetattr (0, TCSANOW, &tty);
2238 if (!term_atexit_done++)
2239 atexit(term_exit);
2241 fcntl(0, F_SETFL, O_NONBLOCK);
2244 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2246 term_exit();
2247 stdio_nb_clients--;
2248 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2249 fd_chr_close(chr);
2252 static CharDriverState *qemu_chr_open_stdio(void)
2254 CharDriverState *chr;
2256 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2257 return NULL;
2258 chr = qemu_chr_open_fd(0, 1);
2259 chr->chr_close = qemu_chr_close_stdio;
2260 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2261 stdio_nb_clients++;
2262 term_init();
2264 return chr;
2267 #if defined(__linux__) || defined(__sun__)
2268 static CharDriverState *qemu_chr_open_pty(void)
2270 struct termios tty;
2271 char slave_name[1024];
2272 int master_fd, slave_fd;
2274 #if defined(__linux__)
2275 /* Not satisfying */
2276 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2277 return NULL;
2279 #endif
2281 /* Disabling local echo and line-buffered output */
2282 tcgetattr (master_fd, &tty);
2283 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2284 tty.c_cc[VMIN] = 1;
2285 tty.c_cc[VTIME] = 0;
2286 tcsetattr (master_fd, TCSAFLUSH, &tty);
2288 fprintf(stderr, "char device redirected to %s\n", slave_name);
2289 return qemu_chr_open_fd(master_fd, master_fd);
2292 static void tty_serial_init(int fd, int speed,
2293 int parity, int data_bits, int stop_bits)
2295 struct termios tty;
2296 speed_t spd;
2298 #if 0
2299 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2300 speed, parity, data_bits, stop_bits);
2301 #endif
2302 tcgetattr (fd, &tty);
2304 #define MARGIN 1.1
2305 if (speed <= 50 * MARGIN)
2306 spd = B50;
2307 else if (speed <= 75 * MARGIN)
2308 spd = B75;
2309 else if (speed <= 300 * MARGIN)
2310 spd = B300;
2311 else if (speed <= 600 * MARGIN)
2312 spd = B600;
2313 else if (speed <= 1200 * MARGIN)
2314 spd = B1200;
2315 else if (speed <= 2400 * MARGIN)
2316 spd = B2400;
2317 else if (speed <= 4800 * MARGIN)
2318 spd = B4800;
2319 else if (speed <= 9600 * MARGIN)
2320 spd = B9600;
2321 else if (speed <= 19200 * MARGIN)
2322 spd = B19200;
2323 else if (speed <= 38400 * MARGIN)
2324 spd = B38400;
2325 else if (speed <= 57600 * MARGIN)
2326 spd = B57600;
2327 else if (speed <= 115200 * MARGIN)
2328 spd = B115200;
2329 else
2330 spd = B115200;
2332 cfsetispeed(&tty, spd);
2333 cfsetospeed(&tty, spd);
2335 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2336 |INLCR|IGNCR|ICRNL|IXON);
2337 tty.c_oflag |= OPOST;
2338 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2339 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2340 switch(data_bits) {
2341 default:
2342 case 8:
2343 tty.c_cflag |= CS8;
2344 break;
2345 case 7:
2346 tty.c_cflag |= CS7;
2347 break;
2348 case 6:
2349 tty.c_cflag |= CS6;
2350 break;
2351 case 5:
2352 tty.c_cflag |= CS5;
2353 break;
2355 switch(parity) {
2356 default:
2357 case 'N':
2358 break;
2359 case 'E':
2360 tty.c_cflag |= PARENB;
2361 break;
2362 case 'O':
2363 tty.c_cflag |= PARENB | PARODD;
2364 break;
2366 if (stop_bits == 2)
2367 tty.c_cflag |= CSTOPB;
2369 tcsetattr (fd, TCSANOW, &tty);
2372 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2374 FDCharDriver *s = chr->opaque;
2376 switch(cmd) {
2377 case CHR_IOCTL_SERIAL_SET_PARAMS:
2379 QEMUSerialSetParams *ssp = arg;
2380 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2381 ssp->data_bits, ssp->stop_bits);
2383 break;
2384 case CHR_IOCTL_SERIAL_SET_BREAK:
2386 int enable = *(int *)arg;
2387 if (enable)
2388 tcsendbreak(s->fd_in, 1);
2390 break;
2391 default:
2392 return -ENOTSUP;
2394 return 0;
2397 static CharDriverState *qemu_chr_open_tty(const char *filename)
2399 CharDriverState *chr;
2400 int fd;
2402 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2403 fcntl(fd, F_SETFL, O_NONBLOCK);
2404 tty_serial_init(fd, 115200, 'N', 8, 1);
2405 chr = qemu_chr_open_fd(fd, fd);
2406 if (!chr) {
2407 close(fd);
2408 return NULL;
2410 chr->chr_ioctl = tty_serial_ioctl;
2411 qemu_chr_reset(chr);
2412 return chr;
2414 #else /* ! __linux__ && ! __sun__ */
2415 static CharDriverState *qemu_chr_open_pty(void)
2417 return NULL;
2419 #endif /* __linux__ || __sun__ */
2421 #if defined(__linux__)
2422 typedef struct {
2423 int fd;
2424 int mode;
2425 } ParallelCharDriver;
2427 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2429 if (s->mode != mode) {
2430 int m = mode;
2431 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2432 return 0;
2433 s->mode = mode;
2435 return 1;
2438 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2440 ParallelCharDriver *drv = chr->opaque;
2441 int fd = drv->fd;
2442 uint8_t b;
2444 switch(cmd) {
2445 case CHR_IOCTL_PP_READ_DATA:
2446 if (ioctl(fd, PPRDATA, &b) < 0)
2447 return -ENOTSUP;
2448 *(uint8_t *)arg = b;
2449 break;
2450 case CHR_IOCTL_PP_WRITE_DATA:
2451 b = *(uint8_t *)arg;
2452 if (ioctl(fd, PPWDATA, &b) < 0)
2453 return -ENOTSUP;
2454 break;
2455 case CHR_IOCTL_PP_READ_CONTROL:
2456 if (ioctl(fd, PPRCONTROL, &b) < 0)
2457 return -ENOTSUP;
2458 /* Linux gives only the lowest bits, and no way to know data
2459 direction! For better compatibility set the fixed upper
2460 bits. */
2461 *(uint8_t *)arg = b | 0xc0;
2462 break;
2463 case CHR_IOCTL_PP_WRITE_CONTROL:
2464 b = *(uint8_t *)arg;
2465 if (ioctl(fd, PPWCONTROL, &b) < 0)
2466 return -ENOTSUP;
2467 break;
2468 case CHR_IOCTL_PP_READ_STATUS:
2469 if (ioctl(fd, PPRSTATUS, &b) < 0)
2470 return -ENOTSUP;
2471 *(uint8_t *)arg = b;
2472 break;
2473 case CHR_IOCTL_PP_EPP_READ_ADDR:
2474 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2475 struct ParallelIOArg *parg = arg;
2476 int n = read(fd, parg->buffer, parg->count);
2477 if (n != parg->count) {
2478 return -EIO;
2481 break;
2482 case CHR_IOCTL_PP_EPP_READ:
2483 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2484 struct ParallelIOArg *parg = arg;
2485 int n = read(fd, parg->buffer, parg->count);
2486 if (n != parg->count) {
2487 return -EIO;
2490 break;
2491 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2492 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2493 struct ParallelIOArg *parg = arg;
2494 int n = write(fd, parg->buffer, parg->count);
2495 if (n != parg->count) {
2496 return -EIO;
2499 break;
2500 case CHR_IOCTL_PP_EPP_WRITE:
2501 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2502 struct ParallelIOArg *parg = arg;
2503 int n = write(fd, parg->buffer, parg->count);
2504 if (n != parg->count) {
2505 return -EIO;
2508 break;
2509 default:
2510 return -ENOTSUP;
2512 return 0;
2515 static void pp_close(CharDriverState *chr)
2517 ParallelCharDriver *drv = chr->opaque;
2518 int fd = drv->fd;
2520 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2521 ioctl(fd, PPRELEASE);
2522 close(fd);
2523 qemu_free(drv);
2526 static CharDriverState *qemu_chr_open_pp(const char *filename)
2528 CharDriverState *chr;
2529 ParallelCharDriver *drv;
2530 int fd;
2532 TFR(fd = open(filename, O_RDWR));
2533 if (fd < 0)
2534 return NULL;
2536 if (ioctl(fd, PPCLAIM) < 0) {
2537 close(fd);
2538 return NULL;
2541 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2542 if (!drv) {
2543 close(fd);
2544 return NULL;
2546 drv->fd = fd;
2547 drv->mode = IEEE1284_MODE_COMPAT;
2549 chr = qemu_mallocz(sizeof(CharDriverState));
2550 if (!chr) {
2551 qemu_free(drv);
2552 close(fd);
2553 return NULL;
2555 chr->chr_write = null_chr_write;
2556 chr->chr_ioctl = pp_ioctl;
2557 chr->chr_close = pp_close;
2558 chr->opaque = drv;
2560 qemu_chr_reset(chr);
2562 return chr;
2564 #endif /* __linux__ */
2566 #else /* _WIN32 */
2568 typedef struct {
2569 int max_size;
2570 HANDLE hcom, hrecv, hsend;
2571 OVERLAPPED orecv, osend;
2572 BOOL fpipe;
2573 DWORD len;
2574 } WinCharState;
2576 #define NSENDBUF 2048
2577 #define NRECVBUF 2048
2578 #define MAXCONNECT 1
2579 #define NTIMEOUT 5000
2581 static int win_chr_poll(void *opaque);
2582 static int win_chr_pipe_poll(void *opaque);
2584 static void win_chr_close(CharDriverState *chr)
2586 WinCharState *s = chr->opaque;
2588 if (s->hsend) {
2589 CloseHandle(s->hsend);
2590 s->hsend = NULL;
2592 if (s->hrecv) {
2593 CloseHandle(s->hrecv);
2594 s->hrecv = NULL;
2596 if (s->hcom) {
2597 CloseHandle(s->hcom);
2598 s->hcom = NULL;
2600 if (s->fpipe)
2601 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2602 else
2603 qemu_del_polling_cb(win_chr_poll, chr);
2606 static int win_chr_init(CharDriverState *chr, const char *filename)
2608 WinCharState *s = chr->opaque;
2609 COMMCONFIG comcfg;
2610 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2611 COMSTAT comstat;
2612 DWORD size;
2613 DWORD err;
2615 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2616 if (!s->hsend) {
2617 fprintf(stderr, "Failed CreateEvent\n");
2618 goto fail;
2620 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2621 if (!s->hrecv) {
2622 fprintf(stderr, "Failed CreateEvent\n");
2623 goto fail;
2626 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2627 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2628 if (s->hcom == INVALID_HANDLE_VALUE) {
2629 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2630 s->hcom = NULL;
2631 goto fail;
2634 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2635 fprintf(stderr, "Failed SetupComm\n");
2636 goto fail;
2639 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2640 size = sizeof(COMMCONFIG);
2641 GetDefaultCommConfig(filename, &comcfg, &size);
2642 comcfg.dcb.DCBlength = sizeof(DCB);
2643 CommConfigDialog(filename, NULL, &comcfg);
2645 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2646 fprintf(stderr, "Failed SetCommState\n");
2647 goto fail;
2650 if (!SetCommMask(s->hcom, EV_ERR)) {
2651 fprintf(stderr, "Failed SetCommMask\n");
2652 goto fail;
2655 cto.ReadIntervalTimeout = MAXDWORD;
2656 if (!SetCommTimeouts(s->hcom, &cto)) {
2657 fprintf(stderr, "Failed SetCommTimeouts\n");
2658 goto fail;
2661 if (!ClearCommError(s->hcom, &err, &comstat)) {
2662 fprintf(stderr, "Failed ClearCommError\n");
2663 goto fail;
2665 qemu_add_polling_cb(win_chr_poll, chr);
2666 return 0;
2668 fail:
2669 win_chr_close(chr);
2670 return -1;
2673 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2675 WinCharState *s = chr->opaque;
2676 DWORD len, ret, size, err;
2678 len = len1;
2679 ZeroMemory(&s->osend, sizeof(s->osend));
2680 s->osend.hEvent = s->hsend;
2681 while (len > 0) {
2682 if (s->hsend)
2683 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2684 else
2685 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2686 if (!ret) {
2687 err = GetLastError();
2688 if (err == ERROR_IO_PENDING) {
2689 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2690 if (ret) {
2691 buf += size;
2692 len -= size;
2693 } else {
2694 break;
2696 } else {
2697 break;
2699 } else {
2700 buf += size;
2701 len -= size;
2704 return len1 - len;
2707 static int win_chr_read_poll(CharDriverState *chr)
2709 WinCharState *s = chr->opaque;
2711 s->max_size = qemu_chr_can_read(chr);
2712 return s->max_size;
2715 static void win_chr_readfile(CharDriverState *chr)
2717 WinCharState *s = chr->opaque;
2718 int ret, err;
2719 uint8_t buf[1024];
2720 DWORD size;
2722 ZeroMemory(&s->orecv, sizeof(s->orecv));
2723 s->orecv.hEvent = s->hrecv;
2724 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2725 if (!ret) {
2726 err = GetLastError();
2727 if (err == ERROR_IO_PENDING) {
2728 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2732 if (size > 0) {
2733 qemu_chr_read(chr, buf, size);
2737 static void win_chr_read(CharDriverState *chr)
2739 WinCharState *s = chr->opaque;
2741 if (s->len > s->max_size)
2742 s->len = s->max_size;
2743 if (s->len == 0)
2744 return;
2746 win_chr_readfile(chr);
2749 static int win_chr_poll(void *opaque)
2751 CharDriverState *chr = opaque;
2752 WinCharState *s = chr->opaque;
2753 COMSTAT status;
2754 DWORD comerr;
2756 ClearCommError(s->hcom, &comerr, &status);
2757 if (status.cbInQue > 0) {
2758 s->len = status.cbInQue;
2759 win_chr_read_poll(chr);
2760 win_chr_read(chr);
2761 return 1;
2763 return 0;
2766 static CharDriverState *qemu_chr_open_win(const char *filename)
2768 CharDriverState *chr;
2769 WinCharState *s;
2771 chr = qemu_mallocz(sizeof(CharDriverState));
2772 if (!chr)
2773 return NULL;
2774 s = qemu_mallocz(sizeof(WinCharState));
2775 if (!s) {
2776 free(chr);
2777 return NULL;
2779 chr->opaque = s;
2780 chr->chr_write = win_chr_write;
2781 chr->chr_close = win_chr_close;
2783 if (win_chr_init(chr, filename) < 0) {
2784 free(s);
2785 free(chr);
2786 return NULL;
2788 qemu_chr_reset(chr);
2789 return chr;
2792 static int win_chr_pipe_poll(void *opaque)
2794 CharDriverState *chr = opaque;
2795 WinCharState *s = chr->opaque;
2796 DWORD size;
2798 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2799 if (size > 0) {
2800 s->len = size;
2801 win_chr_read_poll(chr);
2802 win_chr_read(chr);
2803 return 1;
2805 return 0;
2808 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2810 WinCharState *s = chr->opaque;
2811 OVERLAPPED ov;
2812 int ret;
2813 DWORD size;
2814 char openname[256];
2816 s->fpipe = TRUE;
2818 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2819 if (!s->hsend) {
2820 fprintf(stderr, "Failed CreateEvent\n");
2821 goto fail;
2823 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2824 if (!s->hrecv) {
2825 fprintf(stderr, "Failed CreateEvent\n");
2826 goto fail;
2829 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2830 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2831 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2832 PIPE_WAIT,
2833 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2834 if (s->hcom == INVALID_HANDLE_VALUE) {
2835 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2836 s->hcom = NULL;
2837 goto fail;
2840 ZeroMemory(&ov, sizeof(ov));
2841 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2842 ret = ConnectNamedPipe(s->hcom, &ov);
2843 if (ret) {
2844 fprintf(stderr, "Failed ConnectNamedPipe\n");
2845 goto fail;
2848 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2849 if (!ret) {
2850 fprintf(stderr, "Failed GetOverlappedResult\n");
2851 if (ov.hEvent) {
2852 CloseHandle(ov.hEvent);
2853 ov.hEvent = NULL;
2855 goto fail;
2858 if (ov.hEvent) {
2859 CloseHandle(ov.hEvent);
2860 ov.hEvent = NULL;
2862 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2863 return 0;
2865 fail:
2866 win_chr_close(chr);
2867 return -1;
2871 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2873 CharDriverState *chr;
2874 WinCharState *s;
2876 chr = qemu_mallocz(sizeof(CharDriverState));
2877 if (!chr)
2878 return NULL;
2879 s = qemu_mallocz(sizeof(WinCharState));
2880 if (!s) {
2881 free(chr);
2882 return NULL;
2884 chr->opaque = s;
2885 chr->chr_write = win_chr_write;
2886 chr->chr_close = win_chr_close;
2888 if (win_chr_pipe_init(chr, filename) < 0) {
2889 free(s);
2890 free(chr);
2891 return NULL;
2893 qemu_chr_reset(chr);
2894 return chr;
2897 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2899 CharDriverState *chr;
2900 WinCharState *s;
2902 chr = qemu_mallocz(sizeof(CharDriverState));
2903 if (!chr)
2904 return NULL;
2905 s = qemu_mallocz(sizeof(WinCharState));
2906 if (!s) {
2907 free(chr);
2908 return NULL;
2910 s->hcom = fd_out;
2911 chr->opaque = s;
2912 chr->chr_write = win_chr_write;
2913 qemu_chr_reset(chr);
2914 return chr;
2917 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2919 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2922 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2924 HANDLE fd_out;
2926 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2927 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2928 if (fd_out == INVALID_HANDLE_VALUE)
2929 return NULL;
2931 return qemu_chr_open_win_file(fd_out);
2933 #endif /* !_WIN32 */
2935 /***********************************************************/
2936 /* UDP Net console */
2938 typedef struct {
2939 int fd;
2940 struct sockaddr_in daddr;
2941 uint8_t buf[1024];
2942 int bufcnt;
2943 int bufptr;
2944 int max_size;
2945 } NetCharDriver;
2947 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2949 NetCharDriver *s = chr->opaque;
2951 return sendto(s->fd, buf, len, 0,
2952 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2955 static int udp_chr_read_poll(void *opaque)
2957 CharDriverState *chr = opaque;
2958 NetCharDriver *s = chr->opaque;
2960 s->max_size = qemu_chr_can_read(chr);
2962 /* If there were any stray characters in the queue process them
2963 * first
2965 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2966 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2967 s->bufptr++;
2968 s->max_size = qemu_chr_can_read(chr);
2970 return s->max_size;
2973 static void udp_chr_read(void *opaque)
2975 CharDriverState *chr = opaque;
2976 NetCharDriver *s = chr->opaque;
2978 if (s->max_size == 0)
2979 return;
2980 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2981 s->bufptr = s->bufcnt;
2982 if (s->bufcnt <= 0)
2983 return;
2985 s->bufptr = 0;
2986 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2987 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2988 s->bufptr++;
2989 s->max_size = qemu_chr_can_read(chr);
2993 static void udp_chr_update_read_handler(CharDriverState *chr)
2995 NetCharDriver *s = chr->opaque;
2997 if (s->fd >= 0) {
2998 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2999 udp_chr_read, NULL, chr);
3003 #ifndef _WIN32
3004 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3005 #endif
3006 int parse_host_src_port(struct sockaddr_in *haddr,
3007 struct sockaddr_in *saddr,
3008 const char *str);
3010 static CharDriverState *qemu_chr_open_udp(const char *def)
3012 CharDriverState *chr = NULL;
3013 NetCharDriver *s = NULL;
3014 int fd = -1;
3015 struct sockaddr_in saddr;
3017 chr = qemu_mallocz(sizeof(CharDriverState));
3018 if (!chr)
3019 goto return_err;
3020 s = qemu_mallocz(sizeof(NetCharDriver));
3021 if (!s)
3022 goto return_err;
3024 fd = socket(PF_INET, SOCK_DGRAM, 0);
3025 if (fd < 0) {
3026 perror("socket(PF_INET, SOCK_DGRAM)");
3027 goto return_err;
3030 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3031 printf("Could not parse: %s\n", def);
3032 goto return_err;
3035 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3037 perror("bind");
3038 goto return_err;
3041 s->fd = fd;
3042 s->bufcnt = 0;
3043 s->bufptr = 0;
3044 chr->opaque = s;
3045 chr->chr_write = udp_chr_write;
3046 chr->chr_update_read_handler = udp_chr_update_read_handler;
3047 return chr;
3049 return_err:
3050 if (chr)
3051 free(chr);
3052 if (s)
3053 free(s);
3054 if (fd >= 0)
3055 closesocket(fd);
3056 return NULL;
3059 /***********************************************************/
3060 /* TCP Net console */
3062 typedef struct {
3063 int fd, listen_fd;
3064 int connected;
3065 int max_size;
3066 int do_telnetopt;
3067 int do_nodelay;
3068 int is_unix;
3069 } TCPCharDriver;
3071 static void tcp_chr_accept(void *opaque);
3073 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3075 TCPCharDriver *s = chr->opaque;
3076 if (s->connected) {
3077 return send_all(s->fd, buf, len);
3078 } else {
3079 /* XXX: indicate an error ? */
3080 return len;
3084 static int tcp_chr_read_poll(void *opaque)
3086 CharDriverState *chr = opaque;
3087 TCPCharDriver *s = chr->opaque;
3088 if (!s->connected)
3089 return 0;
3090 s->max_size = qemu_chr_can_read(chr);
3091 return s->max_size;
3094 #define IAC 255
3095 #define IAC_BREAK 243
3096 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3097 TCPCharDriver *s,
3098 uint8_t *buf, int *size)
3100 /* Handle any telnet client's basic IAC options to satisfy char by
3101 * char mode with no echo. All IAC options will be removed from
3102 * the buf and the do_telnetopt variable will be used to track the
3103 * state of the width of the IAC information.
3105 * IAC commands come in sets of 3 bytes with the exception of the
3106 * "IAC BREAK" command and the double IAC.
3109 int i;
3110 int j = 0;
3112 for (i = 0; i < *size; i++) {
3113 if (s->do_telnetopt > 1) {
3114 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3115 /* Double IAC means send an IAC */
3116 if (j != i)
3117 buf[j] = buf[i];
3118 j++;
3119 s->do_telnetopt = 1;
3120 } else {
3121 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3122 /* Handle IAC break commands by sending a serial break */
3123 qemu_chr_event(chr, CHR_EVENT_BREAK);
3124 s->do_telnetopt++;
3126 s->do_telnetopt++;
3128 if (s->do_telnetopt >= 4) {
3129 s->do_telnetopt = 1;
3131 } else {
3132 if ((unsigned char)buf[i] == IAC) {
3133 s->do_telnetopt = 2;
3134 } else {
3135 if (j != i)
3136 buf[j] = buf[i];
3137 j++;
3141 *size = j;
3144 static void tcp_chr_read(void *opaque)
3146 CharDriverState *chr = opaque;
3147 TCPCharDriver *s = chr->opaque;
3148 uint8_t buf[1024];
3149 int len, size;
3151 if (!s->connected || s->max_size <= 0)
3152 return;
3153 len = sizeof(buf);
3154 if (len > s->max_size)
3155 len = s->max_size;
3156 size = recv(s->fd, buf, len, 0);
3157 if (size == 0) {
3158 /* connection closed */
3159 s->connected = 0;
3160 if (s->listen_fd >= 0) {
3161 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3163 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3164 closesocket(s->fd);
3165 s->fd = -1;
3166 } else if (size > 0) {
3167 if (s->do_telnetopt)
3168 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3169 if (size > 0)
3170 qemu_chr_read(chr, buf, size);
3174 static void tcp_chr_connect(void *opaque)
3176 CharDriverState *chr = opaque;
3177 TCPCharDriver *s = chr->opaque;
3179 s->connected = 1;
3180 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3181 tcp_chr_read, NULL, chr);
3182 qemu_chr_reset(chr);
3185 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3186 static void tcp_chr_telnet_init(int fd)
3188 char buf[3];
3189 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3190 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3191 send(fd, (char *)buf, 3, 0);
3192 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3193 send(fd, (char *)buf, 3, 0);
3194 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3195 send(fd, (char *)buf, 3, 0);
3196 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3197 send(fd, (char *)buf, 3, 0);
3200 static void socket_set_nodelay(int fd)
3202 int val = 1;
3203 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3206 static void tcp_chr_accept(void *opaque)
3208 CharDriverState *chr = opaque;
3209 TCPCharDriver *s = chr->opaque;
3210 struct sockaddr_in saddr;
3211 #ifndef _WIN32
3212 struct sockaddr_un uaddr;
3213 #endif
3214 struct sockaddr *addr;
3215 socklen_t len;
3216 int fd;
3218 for(;;) {
3219 #ifndef _WIN32
3220 if (s->is_unix) {
3221 len = sizeof(uaddr);
3222 addr = (struct sockaddr *)&uaddr;
3223 } else
3224 #endif
3226 len = sizeof(saddr);
3227 addr = (struct sockaddr *)&saddr;
3229 fd = accept(s->listen_fd, addr, &len);
3230 if (fd < 0 && errno != EINTR) {
3231 return;
3232 } else if (fd >= 0) {
3233 if (s->do_telnetopt)
3234 tcp_chr_telnet_init(fd);
3235 break;
3238 socket_set_nonblock(fd);
3239 if (s->do_nodelay)
3240 socket_set_nodelay(fd);
3241 s->fd = fd;
3242 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3243 tcp_chr_connect(chr);
3246 static void tcp_chr_close(CharDriverState *chr)
3248 TCPCharDriver *s = chr->opaque;
3249 if (s->fd >= 0)
3250 closesocket(s->fd);
3251 if (s->listen_fd >= 0)
3252 closesocket(s->listen_fd);
3253 qemu_free(s);
3256 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3257 int is_telnet,
3258 int is_unix)
3260 CharDriverState *chr = NULL;
3261 TCPCharDriver *s = NULL;
3262 int fd = -1, ret, err, val;
3263 int is_listen = 0;
3264 int is_waitconnect = 1;
3265 int do_nodelay = 0;
3266 const char *ptr;
3267 struct sockaddr_in saddr;
3268 #ifndef _WIN32
3269 struct sockaddr_un uaddr;
3270 #endif
3271 struct sockaddr *addr;
3272 socklen_t addrlen;
3274 #ifndef _WIN32
3275 if (is_unix) {
3276 addr = (struct sockaddr *)&uaddr;
3277 addrlen = sizeof(uaddr);
3278 if (parse_unix_path(&uaddr, host_str) < 0)
3279 goto fail;
3280 } else
3281 #endif
3283 addr = (struct sockaddr *)&saddr;
3284 addrlen = sizeof(saddr);
3285 if (parse_host_port(&saddr, host_str) < 0)
3286 goto fail;
3289 ptr = host_str;
3290 while((ptr = strchr(ptr,','))) {
3291 ptr++;
3292 if (!strncmp(ptr,"server",6)) {
3293 is_listen = 1;
3294 } else if (!strncmp(ptr,"nowait",6)) {
3295 is_waitconnect = 0;
3296 } else if (!strncmp(ptr,"nodelay",6)) {
3297 do_nodelay = 1;
3298 } else {
3299 printf("Unknown option: %s\n", ptr);
3300 goto fail;
3303 if (!is_listen)
3304 is_waitconnect = 0;
3306 chr = qemu_mallocz(sizeof(CharDriverState));
3307 if (!chr)
3308 goto fail;
3309 s = qemu_mallocz(sizeof(TCPCharDriver));
3310 if (!s)
3311 goto fail;
3313 #ifndef _WIN32
3314 if (is_unix)
3315 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3316 else
3317 #endif
3318 fd = socket(PF_INET, SOCK_STREAM, 0);
3320 if (fd < 0)
3321 goto fail;
3323 if (!is_waitconnect)
3324 socket_set_nonblock(fd);
3326 s->connected = 0;
3327 s->fd = -1;
3328 s->listen_fd = -1;
3329 s->is_unix = is_unix;
3330 s->do_nodelay = do_nodelay && !is_unix;
3332 chr->opaque = s;
3333 chr->chr_write = tcp_chr_write;
3334 chr->chr_close = tcp_chr_close;
3336 if (is_listen) {
3337 /* allow fast reuse */
3338 #ifndef _WIN32
3339 if (is_unix) {
3340 char path[109];
3341 strncpy(path, uaddr.sun_path, 108);
3342 path[108] = 0;
3343 unlink(path);
3344 } else
3345 #endif
3347 val = 1;
3348 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3351 ret = bind(fd, addr, addrlen);
3352 if (ret < 0)
3353 goto fail;
3355 ret = listen(fd, 0);
3356 if (ret < 0)
3357 goto fail;
3359 s->listen_fd = fd;
3360 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3361 if (is_telnet)
3362 s->do_telnetopt = 1;
3363 } else {
3364 for(;;) {
3365 ret = connect(fd, addr, addrlen);
3366 if (ret < 0) {
3367 err = socket_error();
3368 if (err == EINTR || err == EWOULDBLOCK) {
3369 } else if (err == EINPROGRESS) {
3370 break;
3371 #ifdef _WIN32
3372 } else if (err == WSAEALREADY) {
3373 break;
3374 #endif
3375 } else {
3376 goto fail;
3378 } else {
3379 s->connected = 1;
3380 break;
3383 s->fd = fd;
3384 socket_set_nodelay(fd);
3385 if (s->connected)
3386 tcp_chr_connect(chr);
3387 else
3388 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3391 if (is_listen && is_waitconnect) {
3392 printf("QEMU waiting for connection on: %s\n", host_str);
3393 tcp_chr_accept(chr);
3394 socket_set_nonblock(s->listen_fd);
3397 return chr;
3398 fail:
3399 if (fd >= 0)
3400 closesocket(fd);
3401 qemu_free(s);
3402 qemu_free(chr);
3403 return NULL;
3406 CharDriverState *qemu_chr_open(const char *filename)
3408 const char *p;
3410 if (!strcmp(filename, "vc")) {
3411 return text_console_init(&display_state, 0);
3412 } else if (strstart(filename, "vc:", &p)) {
3413 return text_console_init(&display_state, p);
3414 } else if (!strcmp(filename, "null")) {
3415 return qemu_chr_open_null();
3416 } else
3417 if (strstart(filename, "tcp:", &p)) {
3418 return qemu_chr_open_tcp(p, 0, 0);
3419 } else
3420 if (strstart(filename, "telnet:", &p)) {
3421 return qemu_chr_open_tcp(p, 1, 0);
3422 } else
3423 if (strstart(filename, "udp:", &p)) {
3424 return qemu_chr_open_udp(p);
3425 } else
3426 if (strstart(filename, "mon:", &p)) {
3427 CharDriverState *drv = qemu_chr_open(p);
3428 if (drv) {
3429 drv = qemu_chr_open_mux(drv);
3430 monitor_init(drv, !nographic);
3431 return drv;
3433 printf("Unable to open driver: %s\n", p);
3434 return 0;
3435 } else
3436 #ifndef _WIN32
3437 if (strstart(filename, "unix:", &p)) {
3438 return qemu_chr_open_tcp(p, 0, 1);
3439 } else if (strstart(filename, "file:", &p)) {
3440 return qemu_chr_open_file_out(p);
3441 } else if (strstart(filename, "pipe:", &p)) {
3442 return qemu_chr_open_pipe(p);
3443 } else if (!strcmp(filename, "pty")) {
3444 return qemu_chr_open_pty();
3445 } else if (!strcmp(filename, "stdio")) {
3446 return qemu_chr_open_stdio();
3447 } else
3448 #if defined(__linux__)
3449 if (strstart(filename, "/dev/parport", NULL)) {
3450 return qemu_chr_open_pp(filename);
3451 } else
3452 #endif
3453 #if defined(__linux__) || defined(__sun__)
3454 if (strstart(filename, "/dev/", NULL)) {
3455 return qemu_chr_open_tty(filename);
3456 } else
3457 #endif
3458 #else /* !_WIN32 */
3459 if (strstart(filename, "COM", NULL)) {
3460 return qemu_chr_open_win(filename);
3461 } else
3462 if (strstart(filename, "pipe:", &p)) {
3463 return qemu_chr_open_win_pipe(p);
3464 } else
3465 if (strstart(filename, "con:", NULL)) {
3466 return qemu_chr_open_win_con(filename);
3467 } else
3468 if (strstart(filename, "file:", &p)) {
3469 return qemu_chr_open_win_file_out(p);
3471 #endif
3473 return NULL;
3477 void qemu_chr_close(CharDriverState *chr)
3479 if (chr->chr_close)
3480 chr->chr_close(chr);
3481 qemu_free(chr);
3484 /***********************************************************/
3485 /* network device redirectors */
3487 __attribute__ (( unused ))
3488 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3490 int len, i, j, c;
3492 for(i=0;i<size;i+=16) {
3493 len = size - i;
3494 if (len > 16)
3495 len = 16;
3496 fprintf(f, "%08x ", i);
3497 for(j=0;j<16;j++) {
3498 if (j < len)
3499 fprintf(f, " %02x", buf[i+j]);
3500 else
3501 fprintf(f, " ");
3503 fprintf(f, " ");
3504 for(j=0;j<len;j++) {
3505 c = buf[i+j];
3506 if (c < ' ' || c > '~')
3507 c = '.';
3508 fprintf(f, "%c", c);
3510 fprintf(f, "\n");
3514 static int parse_macaddr(uint8_t *macaddr, const char *p)
3516 int i;
3517 char *last_char;
3518 long int offset;
3520 errno = 0;
3521 offset = strtol(p, &last_char, 0);
3522 if (0 == errno && '\0' == *last_char &&
3523 offset >= 0 && offset <= 0xFFFFFF) {
3524 macaddr[3] = (offset & 0xFF0000) >> 16;
3525 macaddr[4] = (offset & 0xFF00) >> 8;
3526 macaddr[5] = offset & 0xFF;
3527 return 0;
3528 } else {
3529 for(i = 0; i < 6; i++) {
3530 macaddr[i] = strtol(p, (char **)&p, 16);
3531 if (i == 5) {
3532 if (*p != '\0')
3533 return -1;
3534 } else {
3535 if (*p != ':' && *p != '-')
3536 return -1;
3537 p++;
3540 return 0;
3543 return -1;
3546 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3548 const char *p, *p1;
3549 int len;
3550 p = *pp;
3551 p1 = strchr(p, sep);
3552 if (!p1)
3553 return -1;
3554 len = p1 - p;
3555 p1++;
3556 if (buf_size > 0) {
3557 if (len > buf_size - 1)
3558 len = buf_size - 1;
3559 memcpy(buf, p, len);
3560 buf[len] = '\0';
3562 *pp = p1;
3563 return 0;
3566 int parse_host_src_port(struct sockaddr_in *haddr,
3567 struct sockaddr_in *saddr,
3568 const char *input_str)
3570 char *str = strdup(input_str);
3571 char *host_str = str;
3572 char *src_str;
3573 char *ptr;
3576 * Chop off any extra arguments at the end of the string which
3577 * would start with a comma, then fill in the src port information
3578 * if it was provided else use the "any address" and "any port".
3580 if ((ptr = strchr(str,',')))
3581 *ptr = '\0';
3583 if ((src_str = strchr(input_str,'@'))) {
3584 *src_str = '\0';
3585 src_str++;
3588 if (parse_host_port(haddr, host_str) < 0)
3589 goto fail;
3591 if (!src_str || *src_str == '\0')
3592 src_str = ":0";
3594 if (parse_host_port(saddr, src_str) < 0)
3595 goto fail;
3597 free(str);
3598 return(0);
3600 fail:
3601 free(str);
3602 return -1;
3605 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3607 char buf[512];
3608 struct hostent *he;
3609 const char *p, *r;
3610 int port;
3612 p = str;
3613 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3614 return -1;
3615 saddr->sin_family = AF_INET;
3616 if (buf[0] == '\0') {
3617 saddr->sin_addr.s_addr = 0;
3618 } else {
3619 if (isdigit(buf[0])) {
3620 if (!inet_aton(buf, &saddr->sin_addr))
3621 return -1;
3622 } else {
3623 if ((he = gethostbyname(buf)) == NULL)
3624 return - 1;
3625 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3628 port = strtol(p, (char **)&r, 0);
3629 if (r == p)
3630 return -1;
3631 saddr->sin_port = htons(port);
3632 return 0;
3635 #ifndef _WIN32
3636 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3638 const char *p;
3639 int len;
3641 len = MIN(108, strlen(str));
3642 p = strchr(str, ',');
3643 if (p)
3644 len = MIN(len, p - str);
3646 memset(uaddr, 0, sizeof(*uaddr));
3648 uaddr->sun_family = AF_UNIX;
3649 memcpy(uaddr->sun_path, str, len);
3651 return 0;
3653 #endif
3655 /* find or alloc a new VLAN */
3656 VLANState *qemu_find_vlan(int id)
3658 VLANState **pvlan, *vlan;
3659 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3660 if (vlan->id == id)
3661 return vlan;
3663 vlan = qemu_mallocz(sizeof(VLANState));
3664 if (!vlan)
3665 return NULL;
3666 vlan->id = id;
3667 vlan->next = NULL;
3668 pvlan = &first_vlan;
3669 while (*pvlan != NULL)
3670 pvlan = &(*pvlan)->next;
3671 *pvlan = vlan;
3672 return vlan;
3675 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3676 IOReadHandler *fd_read,
3677 IOCanRWHandler *fd_can_read,
3678 void *opaque)
3680 VLANClientState *vc, **pvc;
3681 vc = qemu_mallocz(sizeof(VLANClientState));
3682 if (!vc)
3683 return NULL;
3684 vc->fd_read = fd_read;
3685 vc->fd_can_read = fd_can_read;
3686 vc->opaque = opaque;
3687 vc->vlan = vlan;
3689 vc->next = NULL;
3690 pvc = &vlan->first_client;
3691 while (*pvc != NULL)
3692 pvc = &(*pvc)->next;
3693 *pvc = vc;
3694 return vc;
3697 int qemu_can_send_packet(VLANClientState *vc1)
3699 VLANState *vlan = vc1->vlan;
3700 VLANClientState *vc;
3702 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3703 if (vc != vc1) {
3704 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3705 return 1;
3708 return 0;
3711 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3713 VLANState *vlan = vc1->vlan;
3714 VLANClientState *vc;
3716 #if 0
3717 printf("vlan %d send:\n", vlan->id);
3718 hex_dump(stdout, buf, size);
3719 #endif
3720 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3721 if (vc != vc1) {
3722 vc->fd_read(vc->opaque, buf, size);
3727 #if defined(CONFIG_SLIRP)
3729 /* slirp network adapter */
3731 static int slirp_inited;
3732 static VLANClientState *slirp_vc;
3734 int slirp_can_output(void)
3736 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3739 void slirp_output(const uint8_t *pkt, int pkt_len)
3741 #if 0
3742 printf("slirp output:\n");
3743 hex_dump(stdout, pkt, pkt_len);
3744 #endif
3745 if (!slirp_vc)
3746 return;
3747 qemu_send_packet(slirp_vc, pkt, pkt_len);
3750 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3752 #if 0
3753 printf("slirp input:\n");
3754 hex_dump(stdout, buf, size);
3755 #endif
3756 slirp_input(buf, size);
3759 static int net_slirp_init(VLANState *vlan)
3761 if (!slirp_inited) {
3762 slirp_inited = 1;
3763 slirp_init();
3765 slirp_vc = qemu_new_vlan_client(vlan,
3766 slirp_receive, NULL, NULL);
3767 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3768 return 0;
3771 static void net_slirp_redir(const char *redir_str)
3773 int is_udp;
3774 char buf[256], *r;
3775 const char *p;
3776 struct in_addr guest_addr;
3777 int host_port, guest_port;
3779 if (!slirp_inited) {
3780 slirp_inited = 1;
3781 slirp_init();
3784 p = redir_str;
3785 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3786 goto fail;
3787 if (!strcmp(buf, "tcp")) {
3788 is_udp = 0;
3789 } else if (!strcmp(buf, "udp")) {
3790 is_udp = 1;
3791 } else {
3792 goto fail;
3795 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3796 goto fail;
3797 host_port = strtol(buf, &r, 0);
3798 if (r == buf)
3799 goto fail;
3801 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3802 goto fail;
3803 if (buf[0] == '\0') {
3804 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3806 if (!inet_aton(buf, &guest_addr))
3807 goto fail;
3809 guest_port = strtol(p, &r, 0);
3810 if (r == p)
3811 goto fail;
3813 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3814 fprintf(stderr, "qemu: could not set up redirection\n");
3815 exit(1);
3817 return;
3818 fail:
3819 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3820 exit(1);
3823 #ifndef _WIN32
3825 char smb_dir[1024];
3827 static void erase_dir(char *dir_name)
3829 DIR *d;
3830 struct dirent *de;
3831 char filename[1024];
3833 /* erase all the files in the directory */
3834 if ((d = opendir(dir_name)) != 0) {
3835 for(;;) {
3836 de = readdir(d);
3837 if (!de)
3838 break;
3839 if (strcmp(de->d_name, ".") != 0 &&
3840 strcmp(de->d_name, "..") != 0) {
3841 snprintf(filename, sizeof(filename), "%s/%s",
3842 smb_dir, de->d_name);
3843 if (unlink(filename) != 0) /* is it a directory? */
3844 erase_dir(filename);
3847 closedir(d);
3848 rmdir(dir_name);
3852 /* automatic user mode samba server configuration */
3853 static void smb_exit(void)
3855 erase_dir(smb_dir);
3858 /* automatic user mode samba server configuration */
3859 static void net_slirp_smb(const char *exported_dir)
3861 char smb_conf[1024];
3862 char smb_cmdline[1024];
3863 FILE *f;
3865 if (!slirp_inited) {
3866 slirp_inited = 1;
3867 slirp_init();
3870 /* XXX: better tmp dir construction */
3871 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3872 if (mkdir(smb_dir, 0700) < 0) {
3873 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3874 exit(1);
3876 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3878 f = fopen(smb_conf, "w");
3879 if (!f) {
3880 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3881 exit(1);
3883 fprintf(f,
3884 "[global]\n"
3885 "private dir=%s\n"
3886 "smb ports=0\n"
3887 "socket address=127.0.0.1\n"
3888 "pid directory=%s\n"
3889 "lock directory=%s\n"
3890 "log file=%s/log.smbd\n"
3891 "smb passwd file=%s/smbpasswd\n"
3892 "security = share\n"
3893 "[qemu]\n"
3894 "path=%s\n"
3895 "read only=no\n"
3896 "guest ok=yes\n",
3897 smb_dir,
3898 smb_dir,
3899 smb_dir,
3900 smb_dir,
3901 smb_dir,
3902 exported_dir
3904 fclose(f);
3905 atexit(smb_exit);
3907 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3908 SMBD_COMMAND, smb_conf);
3910 slirp_add_exec(0, smb_cmdline, 4, 139);
3913 #endif /* !defined(_WIN32) */
3914 void do_info_slirp(void)
3916 slirp_stats();
3919 #endif /* CONFIG_SLIRP */
3921 #if !defined(_WIN32)
3923 typedef struct TAPState {
3924 VLANClientState *vc;
3925 int fd;
3926 char down_script[1024];
3927 int no_poll;
3928 } TAPState;
3930 static int tap_read_poll(void *opaque)
3932 TAPState *s = opaque;
3933 return (!s->no_poll);
3936 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3938 TAPState *s = opaque;
3939 int ret;
3940 for(;;) {
3941 ret = write(s->fd, buf, size);
3942 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3943 } else {
3944 break;
3949 static void tap_send(void *opaque)
3951 TAPState *s = opaque;
3952 uint8_t buf[4096];
3953 int size;
3955 #ifdef __sun__
3956 struct strbuf sbuf;
3957 int f = 0;
3958 sbuf.maxlen = sizeof(buf);
3959 sbuf.buf = buf;
3960 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3961 #else
3962 size = read(s->fd, buf, sizeof(buf));
3963 #endif
3964 if (size > 0) {
3965 qemu_send_packet(s->vc, buf, size);
3969 int hack_around_tap(void *opaque)
3971 VLANClientState *vc = opaque;
3972 TAPState *ts = vc->opaque;
3974 if (vc->fd_read != tap_receive)
3975 return -1;
3977 if (ts) {
3978 ts->no_poll = 1;
3979 return ts->fd;
3982 return -1;
3985 /* fd support */
3987 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3989 TAPState *s;
3991 s = qemu_mallocz(sizeof(TAPState));
3992 if (!s)
3993 return NULL;
3994 s->fd = fd;
3995 s->no_poll = 0;
3996 enable_sigio_timer(fd);
3997 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3998 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
3999 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4000 return s;
4003 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4004 static int tap_open(char *ifname, int ifname_size)
4006 int fd;
4007 char *dev;
4008 struct stat s;
4010 TFR(fd = open("/dev/tap", O_RDWR));
4011 if (fd < 0) {
4012 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4013 return -1;
4016 fstat(fd, &s);
4017 dev = devname(s.st_rdev, S_IFCHR);
4018 pstrcpy(ifname, ifname_size, dev);
4020 fcntl(fd, F_SETFL, O_NONBLOCK);
4021 return fd;
4023 #elif defined(__sun__)
4024 #define TUNNEWPPA (('T'<<16) | 0x0001)
4026 * Allocate TAP device, returns opened fd.
4027 * Stores dev name in the first arg(must be large enough).
4029 int tap_alloc(char *dev)
4031 int tap_fd, if_fd, ppa = -1;
4032 static int ip_fd = 0;
4033 char *ptr;
4035 static int arp_fd = 0;
4036 int ip_muxid, arp_muxid;
4037 struct strioctl strioc_if, strioc_ppa;
4038 int link_type = I_PLINK;;
4039 struct lifreq ifr;
4040 char actual_name[32] = "";
4042 memset(&ifr, 0x0, sizeof(ifr));
4044 if( *dev ){
4045 ptr = dev;
4046 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4047 ppa = atoi(ptr);
4050 /* Check if IP device was opened */
4051 if( ip_fd )
4052 close(ip_fd);
4054 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4055 if (ip_fd < 0) {
4056 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4057 return -1;
4060 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4061 if (tap_fd < 0) {
4062 syslog(LOG_ERR, "Can't open /dev/tap");
4063 return -1;
4066 /* Assign a new PPA and get its unit number. */
4067 strioc_ppa.ic_cmd = TUNNEWPPA;
4068 strioc_ppa.ic_timout = 0;
4069 strioc_ppa.ic_len = sizeof(ppa);
4070 strioc_ppa.ic_dp = (char *)&ppa;
4071 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4072 syslog (LOG_ERR, "Can't assign new interface");
4074 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4075 if (if_fd < 0) {
4076 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4077 return -1;
4079 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4080 syslog(LOG_ERR, "Can't push IP module");
4081 return -1;
4084 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4085 syslog(LOG_ERR, "Can't get flags\n");
4087 snprintf (actual_name, 32, "tap%d", ppa);
4088 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4090 ifr.lifr_ppa = ppa;
4091 /* Assign ppa according to the unit number returned by tun device */
4093 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4094 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4095 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4096 syslog (LOG_ERR, "Can't get flags\n");
4097 /* Push arp module to if_fd */
4098 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4099 syslog (LOG_ERR, "Can't push ARP module (2)");
4101 /* Push arp module to ip_fd */
4102 if (ioctl (ip_fd, I_POP, NULL) < 0)
4103 syslog (LOG_ERR, "I_POP failed\n");
4104 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4105 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4106 /* Open arp_fd */
4107 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4108 if (arp_fd < 0)
4109 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4111 /* Set ifname to arp */
4112 strioc_if.ic_cmd = SIOCSLIFNAME;
4113 strioc_if.ic_timout = 0;
4114 strioc_if.ic_len = sizeof(ifr);
4115 strioc_if.ic_dp = (char *)&ifr;
4116 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4117 syslog (LOG_ERR, "Can't set ifname to arp\n");
4120 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4121 syslog(LOG_ERR, "Can't link TAP device to IP");
4122 return -1;
4125 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4126 syslog (LOG_ERR, "Can't link TAP device to ARP");
4128 close (if_fd);
4130 memset(&ifr, 0x0, sizeof(ifr));
4131 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4132 ifr.lifr_ip_muxid = ip_muxid;
4133 ifr.lifr_arp_muxid = arp_muxid;
4135 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4137 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4138 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4139 syslog (LOG_ERR, "Can't set multiplexor id");
4142 sprintf(dev, "tap%d", ppa);
4143 return tap_fd;
4146 static int tap_open(char *ifname, int ifname_size)
4148 char dev[10]="";
4149 int fd;
4150 if( (fd = tap_alloc(dev)) < 0 ){
4151 fprintf(stderr, "Cannot allocate TAP device\n");
4152 return -1;
4154 pstrcpy(ifname, ifname_size, dev);
4155 fcntl(fd, F_SETFL, O_NONBLOCK);
4156 return fd;
4158 #else
4159 static int tap_open(char *ifname, int ifname_size)
4161 struct ifreq ifr;
4162 int fd, ret;
4164 TFR(fd = open("/dev/net/tun", O_RDWR));
4165 if (fd < 0) {
4166 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4167 return -1;
4169 memset(&ifr, 0, sizeof(ifr));
4170 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4171 if (ifname[0] != '\0')
4172 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4173 else
4174 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4175 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4176 if (ret != 0) {
4177 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4178 close(fd);
4179 return -1;
4181 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4182 fcntl(fd, F_SETFL, O_NONBLOCK);
4183 return fd;
4185 #endif
4187 static int launch_script(const char *setup_script, const char *ifname, int fd)
4189 int pid, status;
4190 char *args[3];
4191 char **parg;
4193 /* try to launch network script */
4194 pid = fork();
4195 if (pid >= 0) {
4196 if (pid == 0) {
4197 int open_max = sysconf (_SC_OPEN_MAX), i;
4198 for (i = 0; i < open_max; i++)
4199 if (i != STDIN_FILENO &&
4200 i != STDOUT_FILENO &&
4201 i != STDERR_FILENO &&
4202 i != fd)
4203 close(i);
4205 parg = args;
4206 *parg++ = (char *)setup_script;
4207 *parg++ = (char *)ifname;
4208 *parg++ = NULL;
4209 execv(setup_script, args);
4210 _exit(1);
4212 while (waitpid(pid, &status, 0) != pid);
4213 if (!WIFEXITED(status) ||
4214 WEXITSTATUS(status) != 0) {
4215 fprintf(stderr, "%s: could not launch network script\n",
4216 setup_script);
4217 return -1;
4220 return 0;
4223 static int net_tap_init(VLANState *vlan, const char *ifname1,
4224 const char *setup_script, const char *down_script)
4226 TAPState *s;
4227 int fd;
4228 char ifname[128];
4230 if (ifname1 != NULL)
4231 pstrcpy(ifname, sizeof(ifname), ifname1);
4232 else
4233 ifname[0] = '\0';
4234 TFR(fd = tap_open(ifname, sizeof(ifname)));
4235 if (fd < 0)
4236 return -1;
4238 if (!setup_script || !strcmp(setup_script, "no"))
4239 setup_script = "";
4240 if (setup_script[0] != '\0') {
4241 if (launch_script(setup_script, ifname, fd))
4242 return -1;
4244 s = net_tap_fd_init(vlan, fd);
4245 if (!s)
4246 return -1;
4247 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4248 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4249 if (down_script && strcmp(down_script, "no"))
4250 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4251 return 0;
4254 #endif /* !_WIN32 */
4256 /* network connection */
4257 typedef struct NetSocketState {
4258 VLANClientState *vc;
4259 int fd;
4260 int state; /* 0 = getting length, 1 = getting data */
4261 int index;
4262 int packet_len;
4263 uint8_t buf[4096];
4264 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4265 } NetSocketState;
4267 typedef struct NetSocketListenState {
4268 VLANState *vlan;
4269 int fd;
4270 } NetSocketListenState;
4272 /* XXX: we consider we can send the whole packet without blocking */
4273 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4275 NetSocketState *s = opaque;
4276 uint32_t len;
4277 len = htonl(size);
4279 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4280 send_all(s->fd, buf, size);
4283 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4285 NetSocketState *s = opaque;
4286 sendto(s->fd, buf, size, 0,
4287 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4290 static void net_socket_send(void *opaque)
4292 NetSocketState *s = opaque;
4293 int l, size, err;
4294 uint8_t buf1[4096];
4295 const uint8_t *buf;
4297 size = recv(s->fd, buf1, sizeof(buf1), 0);
4298 if (size < 0) {
4299 err = socket_error();
4300 if (err != EWOULDBLOCK)
4301 goto eoc;
4302 } else if (size == 0) {
4303 /* end of connection */
4304 eoc:
4305 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4306 closesocket(s->fd);
4307 return;
4309 buf = buf1;
4310 while (size > 0) {
4311 /* reassemble a packet from the network */
4312 switch(s->state) {
4313 case 0:
4314 l = 4 - s->index;
4315 if (l > size)
4316 l = size;
4317 memcpy(s->buf + s->index, buf, l);
4318 buf += l;
4319 size -= l;
4320 s->index += l;
4321 if (s->index == 4) {
4322 /* got length */
4323 s->packet_len = ntohl(*(uint32_t *)s->buf);
4324 s->index = 0;
4325 s->state = 1;
4327 break;
4328 case 1:
4329 l = s->packet_len - s->index;
4330 if (l > size)
4331 l = size;
4332 memcpy(s->buf + s->index, buf, l);
4333 s->index += l;
4334 buf += l;
4335 size -= l;
4336 if (s->index >= s->packet_len) {
4337 qemu_send_packet(s->vc, s->buf, s->packet_len);
4338 s->index = 0;
4339 s->state = 0;
4341 break;
4346 static void net_socket_send_dgram(void *opaque)
4348 NetSocketState *s = opaque;
4349 int size;
4351 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4352 if (size < 0)
4353 return;
4354 if (size == 0) {
4355 /* end of connection */
4356 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4357 return;
4359 qemu_send_packet(s->vc, s->buf, size);
4362 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4364 struct ip_mreq imr;
4365 int fd;
4366 int val, ret;
4367 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4368 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4369 inet_ntoa(mcastaddr->sin_addr),
4370 (int)ntohl(mcastaddr->sin_addr.s_addr));
4371 return -1;
4374 fd = socket(PF_INET, SOCK_DGRAM, 0);
4375 if (fd < 0) {
4376 perror("socket(PF_INET, SOCK_DGRAM)");
4377 return -1;
4380 val = 1;
4381 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4382 (const char *)&val, sizeof(val));
4383 if (ret < 0) {
4384 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4385 goto fail;
4388 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4389 if (ret < 0) {
4390 perror("bind");
4391 goto fail;
4394 /* Add host to multicast group */
4395 imr.imr_multiaddr = mcastaddr->sin_addr;
4396 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4398 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4399 (const char *)&imr, sizeof(struct ip_mreq));
4400 if (ret < 0) {
4401 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4402 goto fail;
4405 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4406 val = 1;
4407 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4408 (const char *)&val, sizeof(val));
4409 if (ret < 0) {
4410 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4411 goto fail;
4414 socket_set_nonblock(fd);
4415 return fd;
4416 fail:
4417 if (fd >= 0)
4418 closesocket(fd);
4419 return -1;
4422 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4423 int is_connected)
4425 struct sockaddr_in saddr;
4426 int newfd;
4427 socklen_t saddr_len;
4428 NetSocketState *s;
4430 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4431 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4432 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4435 if (is_connected) {
4436 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4437 /* must be bound */
4438 if (saddr.sin_addr.s_addr==0) {
4439 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4440 fd);
4441 return NULL;
4443 /* clone dgram socket */
4444 newfd = net_socket_mcast_create(&saddr);
4445 if (newfd < 0) {
4446 /* error already reported by net_socket_mcast_create() */
4447 close(fd);
4448 return NULL;
4450 /* clone newfd to fd, close newfd */
4451 dup2(newfd, fd);
4452 close(newfd);
4454 } else {
4455 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4456 fd, strerror(errno));
4457 return NULL;
4461 s = qemu_mallocz(sizeof(NetSocketState));
4462 if (!s)
4463 return NULL;
4464 s->fd = fd;
4466 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4467 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4469 /* mcast: save bound address as dst */
4470 if (is_connected) s->dgram_dst=saddr;
4472 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4473 "socket: fd=%d (%s mcast=%s:%d)",
4474 fd, is_connected? "cloned" : "",
4475 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4476 return s;
4479 static void net_socket_connect(void *opaque)
4481 NetSocketState *s = opaque;
4482 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4485 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4486 int is_connected)
4488 NetSocketState *s;
4489 s = qemu_mallocz(sizeof(NetSocketState));
4490 if (!s)
4491 return NULL;
4492 s->fd = fd;
4493 s->vc = qemu_new_vlan_client(vlan,
4494 net_socket_receive, NULL, s);
4495 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4496 "socket: fd=%d", fd);
4497 if (is_connected) {
4498 net_socket_connect(s);
4499 } else {
4500 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4502 return s;
4505 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4506 int is_connected)
4508 int so_type=-1, optlen=sizeof(so_type);
4510 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4511 (socklen_t *)&optlen)< 0) {
4512 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4513 return NULL;
4515 switch(so_type) {
4516 case SOCK_DGRAM:
4517 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4518 case SOCK_STREAM:
4519 return net_socket_fd_init_stream(vlan, fd, is_connected);
4520 default:
4521 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4522 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4523 return net_socket_fd_init_stream(vlan, fd, is_connected);
4525 return NULL;
4528 static void net_socket_accept(void *opaque)
4530 NetSocketListenState *s = opaque;
4531 NetSocketState *s1;
4532 struct sockaddr_in saddr;
4533 socklen_t len;
4534 int fd;
4536 for(;;) {
4537 len = sizeof(saddr);
4538 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4539 if (fd < 0 && errno != EINTR) {
4540 return;
4541 } else if (fd >= 0) {
4542 break;
4545 s1 = net_socket_fd_init(s->vlan, fd, 1);
4546 if (!s1) {
4547 closesocket(fd);
4548 } else {
4549 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4550 "socket: connection from %s:%d",
4551 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4555 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4557 NetSocketListenState *s;
4558 int fd, val, ret;
4559 struct sockaddr_in saddr;
4561 if (parse_host_port(&saddr, host_str) < 0)
4562 return -1;
4564 s = qemu_mallocz(sizeof(NetSocketListenState));
4565 if (!s)
4566 return -1;
4568 fd = socket(PF_INET, SOCK_STREAM, 0);
4569 if (fd < 0) {
4570 perror("socket");
4571 return -1;
4573 socket_set_nonblock(fd);
4575 /* allow fast reuse */
4576 val = 1;
4577 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4579 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4580 if (ret < 0) {
4581 perror("bind");
4582 return -1;
4584 ret = listen(fd, 0);
4585 if (ret < 0) {
4586 perror("listen");
4587 return -1;
4589 s->vlan = vlan;
4590 s->fd = fd;
4591 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4592 return 0;
4595 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4597 NetSocketState *s;
4598 int fd, connected, ret, err;
4599 struct sockaddr_in saddr;
4601 if (parse_host_port(&saddr, host_str) < 0)
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 connected = 0;
4612 for(;;) {
4613 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4614 if (ret < 0) {
4615 err = socket_error();
4616 if (err == EINTR || err == EWOULDBLOCK) {
4617 } else if (err == EINPROGRESS) {
4618 break;
4619 #ifdef _WIN32
4620 } else if (err == WSAEALREADY) {
4621 break;
4622 #endif
4623 } else {
4624 perror("connect");
4625 closesocket(fd);
4626 return -1;
4628 } else {
4629 connected = 1;
4630 break;
4633 s = net_socket_fd_init(vlan, fd, connected);
4634 if (!s)
4635 return -1;
4636 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4637 "socket: connect to %s:%d",
4638 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4639 return 0;
4642 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4644 NetSocketState *s;
4645 int fd;
4646 struct sockaddr_in saddr;
4648 if (parse_host_port(&saddr, host_str) < 0)
4649 return -1;
4652 fd = net_socket_mcast_create(&saddr);
4653 if (fd < 0)
4654 return -1;
4656 s = net_socket_fd_init(vlan, fd, 0);
4657 if (!s)
4658 return -1;
4660 s->dgram_dst = saddr;
4662 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4663 "socket: mcast=%s:%d",
4664 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4665 return 0;
4669 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4671 char *q;
4673 q = buf;
4674 while (*p != '\0' && *p != '=') {
4675 if (q && (q - buf) < buf_size - 1)
4676 *q++ = *p;
4677 p++;
4679 if (q)
4680 *q = '\0';
4682 return p;
4685 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4687 char *q;
4689 q = buf;
4690 while (*p != '\0') {
4691 if (*p == ',') {
4692 if (*(p + 1) != ',')
4693 break;
4694 p++;
4696 if (q && (q - buf) < buf_size - 1)
4697 *q++ = *p;
4698 p++;
4700 if (q)
4701 *q = '\0';
4703 return p;
4706 static int get_param_value(char *buf, int buf_size,
4707 const char *tag, const char *str)
4709 const char *p;
4710 char option[128];
4712 p = str;
4713 for(;;) {
4714 p = get_opt_name(option, sizeof(option), p);
4715 if (*p != '=')
4716 break;
4717 p++;
4718 if (!strcmp(tag, option)) {
4719 (void)get_opt_value(buf, buf_size, p);
4720 return strlen(buf);
4721 } else {
4722 p = get_opt_value(NULL, 0, p);
4724 if (*p != ',')
4725 break;
4726 p++;
4728 return 0;
4731 static int check_params(char *buf, int buf_size,
4732 char **params, const char *str)
4734 const char *p;
4735 int i;
4737 p = str;
4738 for(;;) {
4739 p = get_opt_name(buf, buf_size, p);
4740 if (*p != '=')
4741 return -1;
4742 p++;
4743 for(i = 0; params[i] != NULL; i++)
4744 if (!strcmp(params[i], buf))
4745 break;
4746 if (params[i] == NULL)
4747 return -1;
4748 p = get_opt_value(NULL, 0, p);
4749 if (*p != ',')
4750 break;
4751 p++;
4753 return 0;
4757 static int net_client_init(const char *str)
4759 const char *p;
4760 char *q;
4761 char device[64];
4762 char buf[1024];
4763 int vlan_id, ret;
4764 VLANState *vlan;
4766 p = str;
4767 q = device;
4768 while (*p != '\0' && *p != ',') {
4769 if ((q - device) < sizeof(device) - 1)
4770 *q++ = *p;
4771 p++;
4773 *q = '\0';
4774 if (*p == ',')
4775 p++;
4776 vlan_id = 0;
4777 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4778 vlan_id = strtol(buf, NULL, 0);
4780 vlan = qemu_find_vlan(vlan_id);
4781 if (!vlan) {
4782 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4783 return -1;
4785 if (!strcmp(device, "nic")) {
4786 NICInfo *nd;
4787 uint8_t *macaddr;
4789 if (nb_nics >= MAX_NICS) {
4790 fprintf(stderr, "Too Many NICs\n");
4791 return -1;
4793 nd = &nd_table[nb_nics];
4794 macaddr = nd->macaddr;
4795 macaddr[0] = 0x52;
4796 macaddr[1] = 0x54;
4797 macaddr[2] = 0x00;
4798 macaddr[3] = 0x12;
4799 macaddr[4] = 0x34;
4800 macaddr[5] = 0x56 + nb_nics;
4802 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4803 if (parse_macaddr(macaddr, buf) < 0) {
4804 fprintf(stderr, "invalid syntax for ethernet address\n");
4805 return -1;
4808 if (get_param_value(buf, sizeof(buf), "model", p)) {
4809 nd->model = strdup(buf);
4811 nd->vlan = vlan;
4812 nb_nics++;
4813 vlan->nb_guest_devs++;
4814 ret = 0;
4815 } else
4816 if (!strcmp(device, "none")) {
4817 /* does nothing. It is needed to signal that no network cards
4818 are wanted */
4819 ret = 0;
4820 } else
4821 #ifdef CONFIG_SLIRP
4822 if (!strcmp(device, "user")) {
4823 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4824 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4826 vlan->nb_host_devs++;
4827 ret = net_slirp_init(vlan);
4828 } else
4829 #endif
4830 #ifdef _WIN32
4831 if (!strcmp(device, "tap")) {
4832 char ifname[64];
4833 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4834 fprintf(stderr, "tap: no interface name\n");
4835 return -1;
4837 vlan->nb_host_devs++;
4838 ret = tap_win32_init(vlan, ifname);
4839 } else
4840 #else
4841 if (!strcmp(device, "tap")) {
4842 char ifname[64];
4843 char setup_script[1024], down_script[1024];
4844 int fd;
4845 vlan->nb_host_devs++;
4846 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4847 fd = strtol(buf, NULL, 0);
4848 ret = -1;
4849 if (net_tap_fd_init(vlan, fd))
4850 ret = 0;
4851 } else {
4852 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4853 ifname[0] = '\0';
4855 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4856 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4858 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4859 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4861 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4863 } else
4864 #endif
4865 if (!strcmp(device, "socket")) {
4866 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4867 int fd;
4868 fd = strtol(buf, NULL, 0);
4869 ret = -1;
4870 if (net_socket_fd_init(vlan, fd, 1))
4871 ret = 0;
4872 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4873 ret = net_socket_listen_init(vlan, buf);
4874 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4875 ret = net_socket_connect_init(vlan, buf);
4876 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4877 ret = net_socket_mcast_init(vlan, buf);
4878 } else {
4879 fprintf(stderr, "Unknown socket options: %s\n", p);
4880 return -1;
4882 vlan->nb_host_devs++;
4883 } else
4885 fprintf(stderr, "Unknown network device: %s\n", device);
4886 return -1;
4888 if (ret < 0) {
4889 fprintf(stderr, "Could not initialize device '%s'\n", device);
4892 return ret;
4895 void do_info_network(void)
4897 VLANState *vlan;
4898 VLANClientState *vc;
4900 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4901 term_printf("VLAN %d devices:\n", vlan->id);
4902 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4903 term_printf(" %s\n", vc->info_str);
4907 #define HD_ALIAS "index=%d,media=disk"
4908 #ifdef TARGET_PPC
4909 #define CDROM_ALIAS "index=1,media=cdrom"
4910 #else
4911 #define CDROM_ALIAS "index=2,media=cdrom"
4912 #endif
4913 #define FD_ALIAS "index=%d,if=floppy"
4914 #define PFLASH_ALIAS "if=pflash"
4915 #define MTD_ALIAS "if=mtd"
4916 #define SD_ALIAS "index=0,if=sd"
4918 static int drive_add(const char *file, const char *fmt, ...)
4920 va_list ap;
4922 if (nb_drives_opt >= MAX_DRIVES) {
4923 fprintf(stderr, "qemu: too many drives\n");
4924 exit(1);
4927 drives_opt[nb_drives_opt].file = file;
4928 va_start(ap, fmt);
4929 vsnprintf(drives_opt[nb_drives_opt].opt,
4930 sizeof(drives_opt[0].opt), fmt, ap);
4931 va_end(ap);
4933 return nb_drives_opt++;
4936 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4938 int index;
4940 /* seek interface, bus and unit */
4942 for (index = 0; index < nb_drives; index++)
4943 if (drives_table[index].type == type &&
4944 drives_table[index].bus == bus &&
4945 drives_table[index].unit == unit)
4946 return index;
4948 return -1;
4951 int drive_get_max_bus(BlockInterfaceType type)
4953 int max_bus;
4954 int index;
4956 max_bus = -1;
4957 for (index = 0; index < nb_drives; index++) {
4958 if(drives_table[index].type == type &&
4959 drives_table[index].bus > max_bus)
4960 max_bus = drives_table[index].bus;
4962 return max_bus;
4965 static int drive_init(struct drive_opt *arg, int snapshot,
4966 QEMUMachine *machine)
4968 char buf[128];
4969 char file[1024];
4970 char devname[128];
4971 const char *mediastr = "";
4972 BlockInterfaceType type;
4973 enum { MEDIA_DISK, MEDIA_CDROM } media;
4974 int bus_id, unit_id;
4975 int cyls, heads, secs, translation;
4976 BlockDriverState *bdrv;
4977 int max_devs;
4978 int index;
4979 int cache;
4980 int bdrv_flags;
4981 char *str = arg->opt;
4982 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4983 "secs", "trans", "media", "snapshot", "file",
4984 "cache", "boot", NULL };
4986 if (check_params(buf, sizeof(buf), params, str) < 0) {
4987 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4988 buf, str);
4989 return -1;
4992 file[0] = 0;
4993 cyls = heads = secs = 0;
4994 bus_id = 0;
4995 unit_id = -1;
4996 translation = BIOS_ATA_TRANSLATION_AUTO;
4997 index = -1;
4998 cache = 1;
5000 if (!strcmp(machine->name, "realview") ||
5001 !strcmp(machine->name, "SS-5") ||
5002 !strcmp(machine->name, "SS-10") ||
5003 !strcmp(machine->name, "SS-600MP") ||
5004 !strcmp(machine->name, "versatilepb") ||
5005 !strcmp(machine->name, "versatileab")) {
5006 type = IF_SCSI;
5007 max_devs = MAX_SCSI_DEVS;
5008 strcpy(devname, "scsi");
5009 } else {
5010 type = IF_IDE;
5011 max_devs = MAX_IDE_DEVS;
5012 strcpy(devname, "ide");
5014 media = MEDIA_DISK;
5016 /* extract parameters */
5018 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5019 bus_id = strtol(buf, NULL, 0);
5020 if (bus_id < 0) {
5021 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5022 return -1;
5026 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5027 unit_id = strtol(buf, NULL, 0);
5028 if (unit_id < 0) {
5029 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5030 return -1;
5034 if (get_param_value(buf, sizeof(buf), "if", str)) {
5035 strncpy(devname, buf, sizeof(devname));
5036 if (!strcmp(buf, "ide")) {
5037 type = IF_IDE;
5038 max_devs = MAX_IDE_DEVS;
5039 } else if (!strcmp(buf, "scsi")) {
5040 type = IF_SCSI;
5041 max_devs = MAX_SCSI_DEVS;
5042 } else if (!strcmp(buf, "floppy")) {
5043 type = IF_FLOPPY;
5044 max_devs = 0;
5045 } else if (!strcmp(buf, "pflash")) {
5046 type = IF_PFLASH;
5047 max_devs = 0;
5048 } else if (!strcmp(buf, "mtd")) {
5049 type = IF_MTD;
5050 max_devs = 0;
5051 } else if (!strcmp(buf, "sd")) {
5052 type = IF_SD;
5053 max_devs = 0;
5054 } else if (!strcmp(buf, "virtio")) {
5055 type = IF_VIRTIO;
5056 max_devs = 0;
5057 } else {
5058 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5059 return -1;
5063 if (get_param_value(buf, sizeof(buf), "index", str)) {
5064 index = strtol(buf, NULL, 0);
5065 if (index < 0) {
5066 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5067 return -1;
5071 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5072 cyls = strtol(buf, NULL, 0);
5075 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5076 heads = strtol(buf, NULL, 0);
5079 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5080 secs = strtol(buf, NULL, 0);
5083 if (cyls || heads || secs) {
5084 if (cyls < 1 || cyls > 16383) {
5085 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5086 return -1;
5088 if (heads < 1 || heads > 16) {
5089 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5090 return -1;
5092 if (secs < 1 || secs > 63) {
5093 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5094 return -1;
5098 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5099 if (!cyls) {
5100 fprintf(stderr,
5101 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5102 str);
5103 return -1;
5105 if (!strcmp(buf, "none"))
5106 translation = BIOS_ATA_TRANSLATION_NONE;
5107 else if (!strcmp(buf, "lba"))
5108 translation = BIOS_ATA_TRANSLATION_LBA;
5109 else if (!strcmp(buf, "auto"))
5110 translation = BIOS_ATA_TRANSLATION_AUTO;
5111 else {
5112 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5113 return -1;
5117 if (get_param_value(buf, sizeof(buf), "media", str)) {
5118 if (!strcmp(buf, "disk")) {
5119 media = MEDIA_DISK;
5120 } else if (!strcmp(buf, "cdrom")) {
5121 if (cyls || secs || heads) {
5122 fprintf(stderr,
5123 "qemu: '%s' invalid physical CHS format\n", str);
5124 return -1;
5126 media = MEDIA_CDROM;
5127 } else {
5128 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5129 return -1;
5133 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5134 if (!strcmp(buf, "on"))
5135 snapshot = 1;
5136 else if (!strcmp(buf, "off"))
5137 snapshot = 0;
5138 else {
5139 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5140 return -1;
5144 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5145 if (!strcmp(buf, "off"))
5146 cache = 0;
5147 else if (!strcmp(buf, "on"))
5148 cache = 1;
5149 else {
5150 fprintf(stderr, "qemu: invalid cache option\n");
5151 return -1;
5155 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5156 if (!strcmp(buf, "on")) {
5157 if (extboot_drive != -1) {
5158 fprintf(stderr, "qemu: two bootable drives specified\n");
5159 return -1;
5161 extboot_drive = nb_drives;
5162 } else if (strcmp(buf, "off")) {
5163 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5164 return -1;
5168 if (arg->file == NULL)
5169 get_param_value(file, sizeof(file), "file", str);
5170 else
5171 pstrcpy(file, sizeof(file), arg->file);
5173 /* compute bus and unit according index */
5175 if (index != -1) {
5176 if (bus_id != 0 || unit_id != -1) {
5177 fprintf(stderr,
5178 "qemu: '%s' index cannot be used with bus and unit\n", str);
5179 return -1;
5181 if (max_devs == 0)
5183 unit_id = index;
5184 bus_id = 0;
5185 } else {
5186 unit_id = index % max_devs;
5187 bus_id = index / max_devs;
5191 /* if user doesn't specify a unit_id,
5192 * try to find the first free
5195 if (unit_id == -1) {
5196 unit_id = 0;
5197 while (drive_get_index(type, bus_id, unit_id) != -1) {
5198 unit_id++;
5199 if (max_devs && unit_id >= max_devs) {
5200 unit_id -= max_devs;
5201 bus_id++;
5206 /* check unit id */
5208 if (max_devs && unit_id >= max_devs) {
5209 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5210 str, unit_id, max_devs - 1);
5211 return -1;
5215 * ignore multiple definitions
5218 if (drive_get_index(type, bus_id, unit_id) != -1)
5219 return 0;
5221 /* init */
5223 if (type == IF_IDE || type == IF_SCSI)
5224 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5225 if (max_devs)
5226 snprintf(buf, sizeof(buf), "%s%i%s%i",
5227 devname, bus_id, mediastr, unit_id);
5228 else
5229 snprintf(buf, sizeof(buf), "%s%s%i",
5230 devname, mediastr, unit_id);
5231 bdrv = bdrv_new(buf);
5232 drives_table[nb_drives].bdrv = bdrv;
5233 drives_table[nb_drives].type = type;
5234 drives_table[nb_drives].bus = bus_id;
5235 drives_table[nb_drives].unit = unit_id;
5236 nb_drives++;
5238 switch(type) {
5239 case IF_IDE:
5240 case IF_SCSI:
5241 switch(media) {
5242 case MEDIA_DISK:
5243 if (cyls != 0) {
5244 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5245 bdrv_set_translation_hint(bdrv, translation);
5247 break;
5248 case MEDIA_CDROM:
5249 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5250 break;
5252 break;
5253 case IF_SD:
5254 /* FIXME: This isn't really a floppy, but it's a reasonable
5255 approximation. */
5256 case IF_FLOPPY:
5257 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5258 break;
5259 case IF_PFLASH:
5260 case IF_MTD:
5261 case IF_VIRTIO:
5262 break;
5264 if (!file[0])
5265 return 0;
5266 bdrv_flags = 0;
5267 if (snapshot)
5268 bdrv_flags |= BDRV_O_SNAPSHOT;
5269 if (!cache)
5270 bdrv_flags |= BDRV_O_DIRECT;
5271 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5272 fprintf(stderr, "qemu: could not open disk image %s\n",
5273 file);
5274 return -1;
5276 return 0;
5279 /***********************************************************/
5280 /* USB devices */
5282 static USBPort *used_usb_ports;
5283 static USBPort *free_usb_ports;
5285 /* ??? Maybe change this to register a hub to keep track of the topology. */
5286 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5287 usb_attachfn attach)
5289 port->opaque = opaque;
5290 port->index = index;
5291 port->attach = attach;
5292 port->next = free_usb_ports;
5293 free_usb_ports = port;
5296 static int usb_device_add(const char *devname)
5298 const char *p;
5299 USBDevice *dev;
5300 USBPort *port;
5302 if (!free_usb_ports)
5303 return -1;
5305 if (strstart(devname, "host:", &p)) {
5306 dev = usb_host_device_open(p);
5307 } else if (!strcmp(devname, "mouse")) {
5308 dev = usb_mouse_init();
5309 } else if (!strcmp(devname, "tablet")) {
5310 dev = usb_tablet_init();
5311 } else if (!strcmp(devname, "keyboard")) {
5312 dev = usb_keyboard_init();
5313 } else if (strstart(devname, "disk:", &p)) {
5314 dev = usb_msd_init(p);
5315 } else if (!strcmp(devname, "wacom-tablet")) {
5316 dev = usb_wacom_init();
5317 } else if (strstart(devname, "serial:", &p)) {
5318 dev = usb_serial_init(p);
5319 } else {
5320 return -1;
5322 if (!dev)
5323 return -1;
5325 /* Find a USB port to add the device to. */
5326 port = free_usb_ports;
5327 if (!port->next) {
5328 USBDevice *hub;
5330 /* Create a new hub and chain it on. */
5331 free_usb_ports = NULL;
5332 port->next = used_usb_ports;
5333 used_usb_ports = port;
5335 hub = usb_hub_init(VM_USB_HUB_SIZE);
5336 usb_attach(port, hub);
5337 port = free_usb_ports;
5340 free_usb_ports = port->next;
5341 port->next = used_usb_ports;
5342 used_usb_ports = port;
5343 usb_attach(port, dev);
5344 return 0;
5347 static int usb_device_del(const char *devname)
5349 USBPort *port;
5350 USBPort **lastp;
5351 USBDevice *dev;
5352 int bus_num, addr;
5353 const char *p;
5355 if (!used_usb_ports)
5356 return -1;
5358 p = strchr(devname, '.');
5359 if (!p)
5360 return -1;
5361 bus_num = strtoul(devname, NULL, 0);
5362 addr = strtoul(p + 1, NULL, 0);
5363 if (bus_num != 0)
5364 return -1;
5366 lastp = &used_usb_ports;
5367 port = used_usb_ports;
5368 while (port && port->dev->addr != addr) {
5369 lastp = &port->next;
5370 port = port->next;
5373 if (!port)
5374 return -1;
5376 dev = port->dev;
5377 *lastp = port->next;
5378 usb_attach(port, NULL);
5379 dev->handle_destroy(dev);
5380 port->next = free_usb_ports;
5381 free_usb_ports = port;
5382 return 0;
5385 void do_usb_add(const char *devname)
5387 int ret;
5388 ret = usb_device_add(devname);
5389 if (ret < 0)
5390 term_printf("Could not add USB device '%s'\n", devname);
5393 void do_usb_del(const char *devname)
5395 int ret;
5396 ret = usb_device_del(devname);
5397 if (ret < 0)
5398 term_printf("Could not remove USB device '%s'\n", devname);
5401 void usb_info(void)
5403 USBDevice *dev;
5404 USBPort *port;
5405 const char *speed_str;
5407 if (!usb_enabled) {
5408 term_printf("USB support not enabled\n");
5409 return;
5412 for (port = used_usb_ports; port; port = port->next) {
5413 dev = port->dev;
5414 if (!dev)
5415 continue;
5416 switch(dev->speed) {
5417 case USB_SPEED_LOW:
5418 speed_str = "1.5";
5419 break;
5420 case USB_SPEED_FULL:
5421 speed_str = "12";
5422 break;
5423 case USB_SPEED_HIGH:
5424 speed_str = "480";
5425 break;
5426 default:
5427 speed_str = "?";
5428 break;
5430 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5431 0, dev->addr, speed_str, dev->devname);
5435 /***********************************************************/
5436 /* PCMCIA/Cardbus */
5438 static struct pcmcia_socket_entry_s {
5439 struct pcmcia_socket_s *socket;
5440 struct pcmcia_socket_entry_s *next;
5441 } *pcmcia_sockets = 0;
5443 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5445 struct pcmcia_socket_entry_s *entry;
5447 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5448 entry->socket = socket;
5449 entry->next = pcmcia_sockets;
5450 pcmcia_sockets = entry;
5453 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5455 struct pcmcia_socket_entry_s *entry, **ptr;
5457 ptr = &pcmcia_sockets;
5458 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5459 if (entry->socket == socket) {
5460 *ptr = entry->next;
5461 qemu_free(entry);
5465 void pcmcia_info(void)
5467 struct pcmcia_socket_entry_s *iter;
5468 if (!pcmcia_sockets)
5469 term_printf("No PCMCIA sockets\n");
5471 for (iter = pcmcia_sockets; iter; iter = iter->next)
5472 term_printf("%s: %s\n", iter->socket->slot_string,
5473 iter->socket->attached ? iter->socket->card_string :
5474 "Empty");
5477 /***********************************************************/
5478 /* dumb display */
5480 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5484 static void dumb_resize(DisplayState *ds, int w, int h)
5488 static void dumb_refresh(DisplayState *ds)
5490 #if defined(CONFIG_SDL)
5491 vga_hw_update();
5492 #endif
5495 static void dumb_display_init(DisplayState *ds)
5497 ds->data = NULL;
5498 ds->linesize = 0;
5499 ds->depth = 0;
5500 ds->dpy_update = dumb_update;
5501 ds->dpy_resize = dumb_resize;
5502 ds->dpy_refresh = dumb_refresh;
5505 /***********************************************************/
5506 /* I/O handling */
5508 #define MAX_IO_HANDLERS 64
5510 typedef struct IOHandlerRecord {
5511 int fd;
5512 IOCanRWHandler *fd_read_poll;
5513 IOHandler *fd_read;
5514 IOHandler *fd_write;
5515 int deleted;
5516 void *opaque;
5517 /* temporary data */
5518 struct pollfd *ufd;
5519 struct IOHandlerRecord *next;
5520 } IOHandlerRecord;
5522 static IOHandlerRecord *first_io_handler;
5524 /* XXX: fd_read_poll should be suppressed, but an API change is
5525 necessary in the character devices to suppress fd_can_read(). */
5526 int qemu_set_fd_handler2(int fd,
5527 IOCanRWHandler *fd_read_poll,
5528 IOHandler *fd_read,
5529 IOHandler *fd_write,
5530 void *opaque)
5532 IOHandlerRecord **pioh, *ioh;
5534 if (!fd_read && !fd_write) {
5535 pioh = &first_io_handler;
5536 for(;;) {
5537 ioh = *pioh;
5538 if (ioh == NULL)
5539 break;
5540 if (ioh->fd == fd) {
5541 ioh->deleted = 1;
5542 break;
5544 pioh = &ioh->next;
5546 } else {
5547 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5548 if (ioh->fd == fd)
5549 goto found;
5551 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5552 if (!ioh)
5553 return -1;
5554 ioh->next = first_io_handler;
5555 first_io_handler = ioh;
5556 found:
5557 ioh->fd = fd;
5558 ioh->fd_read_poll = fd_read_poll;
5559 ioh->fd_read = fd_read;
5560 ioh->fd_write = fd_write;
5561 ioh->opaque = opaque;
5562 ioh->deleted = 0;
5564 return 0;
5567 int qemu_set_fd_handler(int fd,
5568 IOHandler *fd_read,
5569 IOHandler *fd_write,
5570 void *opaque)
5572 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5575 /***********************************************************/
5576 /* Polling handling */
5578 typedef struct PollingEntry {
5579 PollingFunc *func;
5580 void *opaque;
5581 struct PollingEntry *next;
5582 } PollingEntry;
5584 static PollingEntry *first_polling_entry;
5586 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5588 PollingEntry **ppe, *pe;
5589 pe = qemu_mallocz(sizeof(PollingEntry));
5590 if (!pe)
5591 return -1;
5592 pe->func = func;
5593 pe->opaque = opaque;
5594 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5595 *ppe = pe;
5596 return 0;
5599 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5601 PollingEntry **ppe, *pe;
5602 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5603 pe = *ppe;
5604 if (pe->func == func && pe->opaque == opaque) {
5605 *ppe = pe->next;
5606 qemu_free(pe);
5607 break;
5612 #ifdef _WIN32
5613 /***********************************************************/
5614 /* Wait objects support */
5615 typedef struct WaitObjects {
5616 int num;
5617 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5618 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5619 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5620 } WaitObjects;
5622 static WaitObjects wait_objects = {0};
5624 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5626 WaitObjects *w = &wait_objects;
5628 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5629 return -1;
5630 w->events[w->num] = handle;
5631 w->func[w->num] = func;
5632 w->opaque[w->num] = opaque;
5633 w->num++;
5634 return 0;
5637 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5639 int i, found;
5640 WaitObjects *w = &wait_objects;
5642 found = 0;
5643 for (i = 0; i < w->num; i++) {
5644 if (w->events[i] == handle)
5645 found = 1;
5646 if (found) {
5647 w->events[i] = w->events[i + 1];
5648 w->func[i] = w->func[i + 1];
5649 w->opaque[i] = w->opaque[i + 1];
5652 if (found)
5653 w->num--;
5655 #endif
5657 #define SELF_ANNOUNCE_ROUNDS 5
5658 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5659 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5660 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5662 static int announce_self_create(uint8_t *buf,
5663 uint8_t *mac_addr)
5665 uint32_t magic = EXPERIMENTAL_MAGIC;
5666 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5668 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5670 memset(buf, 0xff, 6); /* h_dst */
5671 memcpy(buf + 6, mac_addr, 6); /* h_src */
5672 memcpy(buf + 12, &proto, 2); /* h_proto */
5673 memcpy(buf + 14, &magic, 4); /* magic */
5675 return 18; /* len */
5678 static void qemu_announce_self(void)
5680 int i, j, len;
5681 VLANState *vlan;
5682 VLANClientState *vc;
5683 uint8_t buf[256];
5685 for (i = 0; i < nb_nics; i++) {
5686 len = announce_self_create(buf, nd_table[i].macaddr);
5687 vlan = nd_table[i].vlan;
5688 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5689 if (vc->fd_read == tap_receive) /* send only if tap */
5690 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5691 vc->fd_read(vc->opaque, buf, len);
5696 /***********************************************************/
5697 /* savevm/loadvm support */
5699 #define IO_BUF_SIZE 32768
5701 struct QEMUFile {
5702 QEMUFilePutBufferFunc *put_buffer;
5703 QEMUFileGetBufferFunc *get_buffer;
5704 QEMUFileCloseFunc *close;
5705 void *opaque;
5707 int64_t buf_offset; /* start of buffer when writing, end of buffer
5708 when reading */
5709 int buf_index;
5710 int buf_size; /* 0 when writing */
5711 uint8_t buf[IO_BUF_SIZE];
5714 typedef struct QEMUFileFD
5716 int fd;
5717 } QEMUFileFD;
5719 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5721 QEMUFileFD *s = opaque;
5722 int offset = 0;
5723 ssize_t len;
5725 again:
5726 len = read(s->fd, buf + offset, size - offset);
5727 if (len == -1) {
5728 if (errno == EINTR || errno == EAGAIN)
5729 goto again;
5732 return len;
5735 QEMUFile *qemu_fopen_fd(int fd)
5737 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5738 s->fd = fd;
5739 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5742 typedef struct QEMUFileUnix
5744 FILE *outfile;
5745 } QEMUFileUnix;
5747 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5749 QEMUFileUnix *s = opaque;
5750 fseek(s->outfile, pos, SEEK_SET);
5751 fwrite(buf, 1, size, s->outfile);
5754 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5756 QEMUFileUnix *s = opaque;
5757 fseek(s->outfile, pos, SEEK_SET);
5758 return fread(buf, 1, size, s->outfile);
5761 static void file_close(void *opaque)
5763 QEMUFileUnix *s = opaque;
5764 fclose(s->outfile);
5765 qemu_free(s);
5768 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5770 QEMUFileUnix *s;
5772 s = qemu_mallocz(sizeof(QEMUFileUnix));
5773 if (!s)
5774 return NULL;
5776 s->outfile = fopen(filename, mode);
5777 if (!s->outfile)
5778 goto fail;
5780 if (!strcmp(mode, "wb"))
5781 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5782 else if (!strcmp(mode, "rb"))
5783 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5785 fail:
5786 if (s->outfile)
5787 fclose(s->outfile);
5788 qemu_free(s);
5789 return NULL;
5792 typedef struct QEMUFileBdrv
5794 BlockDriverState *bs;
5795 int64_t base_offset;
5796 } QEMUFileBdrv;
5798 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5800 QEMUFileBdrv *s = opaque;
5801 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5804 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5806 QEMUFileBdrv *s = opaque;
5807 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
5810 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5812 QEMUFileBdrv *s;
5814 s = qemu_mallocz(sizeof(QEMUFileBdrv));
5815 if (!s)
5816 return NULL;
5818 s->bs = bs;
5819 s->base_offset = offset;
5821 if (is_writable)
5822 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
5824 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
5827 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
5828 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
5830 QEMUFile *f;
5832 f = qemu_mallocz(sizeof(QEMUFile));
5833 if (!f)
5834 return NULL;
5836 f->opaque = opaque;
5837 f->put_buffer = put_buffer;
5838 f->get_buffer = get_buffer;
5839 f->close = close;
5841 return f;
5844 void qemu_fflush(QEMUFile *f)
5846 if (!f->put_buffer)
5847 return;
5849 if (f->buf_index > 0) {
5850 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
5851 f->buf_offset += f->buf_index;
5852 f->buf_index = 0;
5856 static void qemu_fill_buffer(QEMUFile *f)
5858 int len;
5860 if (!f->get_buffer)
5861 return;
5863 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
5864 if (len < 0)
5865 len = 0;
5867 f->buf_index = 0;
5868 f->buf_size = len;
5869 f->buf_offset += len;
5872 void qemu_fclose(QEMUFile *f)
5874 qemu_fflush(f);
5875 if (f->close)
5876 f->close(f->opaque);
5877 qemu_free(f);
5880 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5882 int l;
5883 while (size > 0) {
5884 l = IO_BUF_SIZE - f->buf_index;
5885 if (l > size)
5886 l = size;
5887 memcpy(f->buf + f->buf_index, buf, l);
5888 f->buf_index += l;
5889 buf += l;
5890 size -= l;
5891 if (f->buf_index >= IO_BUF_SIZE)
5892 qemu_fflush(f);
5896 void qemu_put_byte(QEMUFile *f, int v)
5898 f->buf[f->buf_index++] = v;
5899 if (f->buf_index >= IO_BUF_SIZE)
5900 qemu_fflush(f);
5903 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5905 int size, l;
5907 size = size1;
5908 while (size > 0) {
5909 l = f->buf_size - f->buf_index;
5910 if (l == 0) {
5911 qemu_fill_buffer(f);
5912 l = f->buf_size - f->buf_index;
5913 if (l == 0)
5914 break;
5916 if (l > size)
5917 l = size;
5918 memcpy(buf, f->buf + f->buf_index, l);
5919 f->buf_index += l;
5920 buf += l;
5921 size -= l;
5923 return size1 - size;
5926 int qemu_get_byte(QEMUFile *f)
5928 if (f->buf_index >= f->buf_size) {
5929 qemu_fill_buffer(f);
5930 if (f->buf_index >= f->buf_size)
5931 return 0;
5933 return f->buf[f->buf_index++];
5936 int64_t qemu_ftell(QEMUFile *f)
5938 return f->buf_offset - f->buf_size + f->buf_index;
5941 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5943 if (whence == SEEK_SET) {
5944 /* nothing to do */
5945 } else if (whence == SEEK_CUR) {
5946 pos += qemu_ftell(f);
5947 } else {
5948 /* SEEK_END not supported */
5949 return -1;
5951 if (f->put_buffer) {
5952 qemu_fflush(f);
5953 f->buf_offset = pos;
5954 } else {
5955 f->buf_offset = pos;
5956 f->buf_index = 0;
5957 f->buf_size = 0;
5959 return pos;
5962 void qemu_put_be16(QEMUFile *f, unsigned int v)
5964 qemu_put_byte(f, v >> 8);
5965 qemu_put_byte(f, v);
5968 void qemu_put_be32(QEMUFile *f, unsigned int v)
5970 qemu_put_byte(f, v >> 24);
5971 qemu_put_byte(f, v >> 16);
5972 qemu_put_byte(f, v >> 8);
5973 qemu_put_byte(f, v);
5976 void qemu_put_be64(QEMUFile *f, uint64_t v)
5978 qemu_put_be32(f, v >> 32);
5979 qemu_put_be32(f, v);
5982 unsigned int qemu_get_be16(QEMUFile *f)
5984 unsigned int v;
5985 v = qemu_get_byte(f) << 8;
5986 v |= qemu_get_byte(f);
5987 return v;
5990 unsigned int qemu_get_be32(QEMUFile *f)
5992 unsigned int v;
5993 v = qemu_get_byte(f) << 24;
5994 v |= qemu_get_byte(f) << 16;
5995 v |= qemu_get_byte(f) << 8;
5996 v |= qemu_get_byte(f);
5997 return v;
6000 uint64_t qemu_get_be64(QEMUFile *f)
6002 uint64_t v;
6003 v = (uint64_t)qemu_get_be32(f) << 32;
6004 v |= qemu_get_be32(f);
6005 return v;
6008 typedef struct SaveStateEntry {
6009 char idstr[256];
6010 int instance_id;
6011 int version_id;
6012 SaveStateHandler *save_state;
6013 LoadStateHandler *load_state;
6014 void *opaque;
6015 struct SaveStateEntry *next;
6016 } SaveStateEntry;
6018 static SaveStateEntry *first_se;
6020 int register_savevm(const char *idstr,
6021 int instance_id,
6022 int version_id,
6023 SaveStateHandler *save_state,
6024 LoadStateHandler *load_state,
6025 void *opaque)
6027 SaveStateEntry *se, **pse;
6029 se = qemu_malloc(sizeof(SaveStateEntry));
6030 if (!se)
6031 return -1;
6032 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6033 se->instance_id = instance_id;
6034 se->version_id = version_id;
6035 se->save_state = save_state;
6036 se->load_state = load_state;
6037 se->opaque = opaque;
6038 se->next = NULL;
6040 /* add at the end of list */
6041 pse = &first_se;
6042 while (*pse != NULL)
6043 pse = &(*pse)->next;
6044 *pse = se;
6045 return 0;
6048 #define QEMU_VM_FILE_MAGIC 0x5145564d
6049 #define QEMU_VM_FILE_VERSION 0x00000002
6051 static int qemu_savevm_state(QEMUFile *f)
6053 SaveStateEntry *se;
6054 int len, ret;
6055 int64_t cur_pos, len_pos, total_len_pos;
6057 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6058 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6059 total_len_pos = qemu_ftell(f);
6060 qemu_put_be64(f, 0); /* total size */
6062 for(se = first_se; se != NULL; se = se->next) {
6063 /* ID string */
6064 len = strlen(se->idstr);
6065 qemu_put_byte(f, len);
6066 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6068 qemu_put_be32(f, se->instance_id);
6069 qemu_put_be32(f, se->version_id);
6071 /* record size: filled later */
6072 len_pos = qemu_ftell(f);
6073 qemu_put_be32(f, 0);
6074 se->save_state(f, se->opaque);
6076 /* fill record size */
6077 cur_pos = qemu_ftell(f);
6078 len = cur_pos - len_pos - 4;
6079 qemu_fseek(f, len_pos, SEEK_SET);
6080 qemu_put_be32(f, len);
6081 qemu_fseek(f, cur_pos, SEEK_SET);
6083 cur_pos = qemu_ftell(f);
6084 qemu_fseek(f, total_len_pos, SEEK_SET);
6085 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6086 qemu_fseek(f, cur_pos, SEEK_SET);
6088 ret = 0;
6089 return ret;
6092 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6094 SaveStateEntry *se;
6096 for(se = first_se; se != NULL; se = se->next) {
6097 if (!strcmp(se->idstr, idstr) &&
6098 instance_id == se->instance_id)
6099 return se;
6101 return NULL;
6104 static int qemu_loadvm_state(QEMUFile *f)
6106 SaveStateEntry *se;
6107 int len, ret, instance_id, record_len, version_id;
6108 int64_t total_len, end_pos, cur_pos;
6109 unsigned int v;
6110 char idstr[256];
6112 v = qemu_get_be32(f);
6113 if (v != QEMU_VM_FILE_MAGIC)
6114 goto fail;
6115 v = qemu_get_be32(f);
6116 if (v != QEMU_VM_FILE_VERSION) {
6117 fail:
6118 ret = -1;
6119 goto the_end;
6121 total_len = qemu_get_be64(f);
6122 end_pos = total_len + qemu_ftell(f);
6123 for(;;) {
6124 if (qemu_ftell(f) >= end_pos)
6125 break;
6126 len = qemu_get_byte(f);
6127 qemu_get_buffer(f, (uint8_t *)idstr, len);
6128 idstr[len] = '\0';
6129 instance_id = qemu_get_be32(f);
6130 version_id = qemu_get_be32(f);
6131 record_len = qemu_get_be32(f);
6132 #if 0
6133 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6134 idstr, instance_id, version_id, record_len);
6135 #endif
6136 cur_pos = qemu_ftell(f);
6137 se = find_se(idstr, instance_id);
6138 if (!se) {
6139 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6140 instance_id, idstr);
6141 } else {
6142 ret = se->load_state(f, se->opaque, version_id);
6143 if (ret < 0) {
6144 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6145 instance_id, idstr);
6146 goto the_end;
6149 /* always seek to exact end of record */
6150 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6152 ret = 0;
6153 the_end:
6154 return ret;
6157 int qemu_live_savevm_state(QEMUFile *f)
6159 SaveStateEntry *se;
6160 int len, ret;
6162 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6163 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6165 for(se = first_se; se != NULL; se = se->next) {
6166 len = strlen(se->idstr);
6168 qemu_put_byte(f, len);
6169 qemu_put_buffer(f, se->idstr, len);
6170 qemu_put_be32(f, se->instance_id);
6171 qemu_put_be32(f, se->version_id);
6173 se->save_state(f, se->opaque);
6176 qemu_put_byte(f, 0);
6178 ret = 0;
6179 return ret;
6182 int qemu_live_loadvm_state(QEMUFile *f)
6184 SaveStateEntry *se;
6185 int len, ret, instance_id, version_id;
6186 unsigned int v;
6187 char idstr[256];
6189 v = qemu_get_be32(f);
6190 if (v != QEMU_VM_FILE_MAGIC)
6191 goto fail;
6192 v = qemu_get_be32(f);
6193 if (v != QEMU_VM_FILE_VERSION) {
6194 fail:
6195 ret = -1;
6196 goto the_end;
6199 for(;;) {
6200 len = qemu_get_byte(f);
6201 if (len == 0)
6202 break;
6203 qemu_get_buffer(f, idstr, len);
6204 idstr[len] = '\0';
6205 instance_id = qemu_get_be32(f);
6206 version_id = qemu_get_be32(f);
6207 se = find_se(idstr, instance_id);
6208 if (!se) {
6209 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6210 instance_id, idstr);
6211 } else {
6212 if (version_id > se->version_id) { /* src version > dst version */
6213 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6214 idstr, version_id, se->version_id);
6215 ret = -1;
6216 goto the_end;
6218 ret = se->load_state(f, se->opaque, version_id);
6219 if (ret < 0) {
6220 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6221 instance_id, idstr);
6222 goto the_end;
6226 ret = 0;
6228 qemu_announce_self();
6230 the_end:
6231 return ret;
6234 /* device can contain snapshots */
6235 static int bdrv_can_snapshot(BlockDriverState *bs)
6237 return (bs &&
6238 !bdrv_is_removable(bs) &&
6239 !bdrv_is_read_only(bs));
6242 /* device must be snapshots in order to have a reliable snapshot */
6243 static int bdrv_has_snapshot(BlockDriverState *bs)
6245 return (bs &&
6246 !bdrv_is_removable(bs) &&
6247 !bdrv_is_read_only(bs));
6250 static BlockDriverState *get_bs_snapshots(void)
6252 BlockDriverState *bs;
6253 int i;
6255 if (bs_snapshots)
6256 return bs_snapshots;
6257 for(i = 0; i <= nb_drives; i++) {
6258 bs = drives_table[i].bdrv;
6259 if (bdrv_can_snapshot(bs))
6260 goto ok;
6262 return NULL;
6264 bs_snapshots = bs;
6265 return bs;
6268 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6269 const char *name)
6271 QEMUSnapshotInfo *sn_tab, *sn;
6272 int nb_sns, i, ret;
6274 ret = -ENOENT;
6275 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6276 if (nb_sns < 0)
6277 return ret;
6278 for(i = 0; i < nb_sns; i++) {
6279 sn = &sn_tab[i];
6280 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6281 *sn_info = *sn;
6282 ret = 0;
6283 break;
6286 qemu_free(sn_tab);
6287 return ret;
6290 void do_savevm(const char *name)
6292 BlockDriverState *bs, *bs1;
6293 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6294 int must_delete, ret, i;
6295 BlockDriverInfo bdi1, *bdi = &bdi1;
6296 QEMUFile *f;
6297 int saved_vm_running;
6298 #ifdef _WIN32
6299 struct _timeb tb;
6300 #else
6301 struct timeval tv;
6302 #endif
6304 bs = get_bs_snapshots();
6305 if (!bs) {
6306 term_printf("No block device can accept snapshots\n");
6307 return;
6310 /* ??? Should this occur after vm_stop? */
6311 qemu_aio_flush();
6313 saved_vm_running = vm_running;
6314 vm_stop(0);
6316 must_delete = 0;
6317 if (name) {
6318 ret = bdrv_snapshot_find(bs, old_sn, name);
6319 if (ret >= 0) {
6320 must_delete = 1;
6323 memset(sn, 0, sizeof(*sn));
6324 if (must_delete) {
6325 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6326 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6327 } else {
6328 if (name)
6329 pstrcpy(sn->name, sizeof(sn->name), name);
6332 /* fill auxiliary fields */
6333 #ifdef _WIN32
6334 _ftime(&tb);
6335 sn->date_sec = tb.time;
6336 sn->date_nsec = tb.millitm * 1000000;
6337 #else
6338 gettimeofday(&tv, NULL);
6339 sn->date_sec = tv.tv_sec;
6340 sn->date_nsec = tv.tv_usec * 1000;
6341 #endif
6342 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6344 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6345 term_printf("Device %s does not support VM state snapshots\n",
6346 bdrv_get_device_name(bs));
6347 goto the_end;
6350 /* save the VM state */
6351 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6352 if (!f) {
6353 term_printf("Could not open VM state file\n");
6354 goto the_end;
6356 ret = qemu_savevm_state(f);
6357 sn->vm_state_size = qemu_ftell(f);
6358 qemu_fclose(f);
6359 if (ret < 0) {
6360 term_printf("Error %d while writing VM\n", ret);
6361 goto the_end;
6364 /* create the snapshots */
6366 for(i = 0; i < nb_drives; i++) {
6367 bs1 = drives_table[i].bdrv;
6368 if (bdrv_has_snapshot(bs1)) {
6369 if (must_delete) {
6370 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6371 if (ret < 0) {
6372 term_printf("Error while deleting snapshot on '%s'\n",
6373 bdrv_get_device_name(bs1));
6376 ret = bdrv_snapshot_create(bs1, sn);
6377 if (ret < 0) {
6378 term_printf("Error while creating snapshot on '%s'\n",
6379 bdrv_get_device_name(bs1));
6384 the_end:
6385 if (saved_vm_running)
6386 vm_start();
6389 void do_loadvm(const char *name)
6391 BlockDriverState *bs, *bs1;
6392 BlockDriverInfo bdi1, *bdi = &bdi1;
6393 QEMUFile *f;
6394 int i, ret;
6395 int saved_vm_running;
6397 bs = get_bs_snapshots();
6398 if (!bs) {
6399 term_printf("No block device supports snapshots\n");
6400 return;
6403 /* Flush all IO requests so they don't interfere with the new state. */
6404 qemu_aio_flush();
6406 saved_vm_running = vm_running;
6407 vm_stop(0);
6409 for(i = 0; i <= nb_drives; i++) {
6410 bs1 = drives_table[i].bdrv;
6411 if (bdrv_has_snapshot(bs1)) {
6412 ret = bdrv_snapshot_goto(bs1, name);
6413 if (ret < 0) {
6414 if (bs != bs1)
6415 term_printf("Warning: ");
6416 switch(ret) {
6417 case -ENOTSUP:
6418 term_printf("Snapshots not supported on device '%s'\n",
6419 bdrv_get_device_name(bs1));
6420 break;
6421 case -ENOENT:
6422 term_printf("Could not find snapshot '%s' on device '%s'\n",
6423 name, bdrv_get_device_name(bs1));
6424 break;
6425 default:
6426 term_printf("Error %d while activating snapshot on '%s'\n",
6427 ret, bdrv_get_device_name(bs1));
6428 break;
6430 /* fatal on snapshot block device */
6431 if (bs == bs1)
6432 goto the_end;
6437 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6438 term_printf("Device %s does not support VM state snapshots\n",
6439 bdrv_get_device_name(bs));
6440 return;
6443 /* restore the VM state */
6444 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6445 if (!f) {
6446 term_printf("Could not open VM state file\n");
6447 goto the_end;
6449 ret = qemu_loadvm_state(f);
6450 qemu_fclose(f);
6451 if (ret < 0) {
6452 term_printf("Error %d while loading VM state\n", ret);
6454 the_end:
6455 if (saved_vm_running)
6456 vm_start();
6459 void do_delvm(const char *name)
6461 BlockDriverState *bs, *bs1;
6462 int i, ret;
6464 bs = get_bs_snapshots();
6465 if (!bs) {
6466 term_printf("No block device supports snapshots\n");
6467 return;
6470 for(i = 0; i <= nb_drives; i++) {
6471 bs1 = drives_table[i].bdrv;
6472 if (bdrv_has_snapshot(bs1)) {
6473 ret = bdrv_snapshot_delete(bs1, name);
6474 if (ret < 0) {
6475 if (ret == -ENOTSUP)
6476 term_printf("Snapshots not supported on device '%s'\n",
6477 bdrv_get_device_name(bs1));
6478 else
6479 term_printf("Error %d while deleting snapshot on '%s'\n",
6480 ret, bdrv_get_device_name(bs1));
6486 void do_info_snapshots(void)
6488 BlockDriverState *bs, *bs1;
6489 QEMUSnapshotInfo *sn_tab, *sn;
6490 int nb_sns, i;
6491 char buf[256];
6493 bs = get_bs_snapshots();
6494 if (!bs) {
6495 term_printf("No available block device supports snapshots\n");
6496 return;
6498 term_printf("Snapshot devices:");
6499 for(i = 0; i <= nb_drives; i++) {
6500 bs1 = drives_table[i].bdrv;
6501 if (bdrv_has_snapshot(bs1)) {
6502 if (bs == bs1)
6503 term_printf(" %s", bdrv_get_device_name(bs1));
6506 term_printf("\n");
6508 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6509 if (nb_sns < 0) {
6510 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6511 return;
6513 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6514 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6515 for(i = 0; i < nb_sns; i++) {
6516 sn = &sn_tab[i];
6517 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6519 qemu_free(sn_tab);
6522 /***********************************************************/
6523 /* cpu save/restore */
6525 #if defined(TARGET_I386)
6527 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6529 qemu_put_be32(f, dt->selector);
6530 qemu_put_betl(f, dt->base);
6531 qemu_put_be32(f, dt->limit);
6532 qemu_put_be32(f, dt->flags);
6535 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6537 dt->selector = qemu_get_be32(f);
6538 dt->base = qemu_get_betl(f);
6539 dt->limit = qemu_get_be32(f);
6540 dt->flags = qemu_get_be32(f);
6543 void cpu_save(QEMUFile *f, void *opaque)
6545 CPUState *env = opaque;
6546 uint16_t fptag, fpus, fpuc, fpregs_format;
6547 uint32_t hflags;
6548 int i;
6550 if (kvm_enabled())
6551 kvm_save_registers(env);
6553 for(i = 0; i < CPU_NB_REGS; i++)
6554 qemu_put_betls(f, &env->regs[i]);
6555 qemu_put_betls(f, &env->eip);
6556 qemu_put_betls(f, &env->eflags);
6557 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6558 qemu_put_be32s(f, &hflags);
6560 /* FPU */
6561 fpuc = env->fpuc;
6562 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6563 fptag = 0;
6564 for(i = 0; i < 8; i++) {
6565 fptag |= ((!env->fptags[i]) << i);
6568 qemu_put_be16s(f, &fpuc);
6569 qemu_put_be16s(f, &fpus);
6570 qemu_put_be16s(f, &fptag);
6572 #ifdef USE_X86LDOUBLE
6573 fpregs_format = 0;
6574 #else
6575 fpregs_format = 1;
6576 #endif
6577 qemu_put_be16s(f, &fpregs_format);
6579 for(i = 0; i < 8; i++) {
6580 #ifdef USE_X86LDOUBLE
6582 uint64_t mant;
6583 uint16_t exp;
6584 /* we save the real CPU data (in case of MMX usage only 'mant'
6585 contains the MMX register */
6586 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6587 qemu_put_be64(f, mant);
6588 qemu_put_be16(f, exp);
6590 #else
6591 /* if we use doubles for float emulation, we save the doubles to
6592 avoid losing information in case of MMX usage. It can give
6593 problems if the image is restored on a CPU where long
6594 doubles are used instead. */
6595 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6596 #endif
6599 for(i = 0; i < 6; i++)
6600 cpu_put_seg(f, &env->segs[i]);
6601 cpu_put_seg(f, &env->ldt);
6602 cpu_put_seg(f, &env->tr);
6603 cpu_put_seg(f, &env->gdt);
6604 cpu_put_seg(f, &env->idt);
6606 qemu_put_be32s(f, &env->sysenter_cs);
6607 qemu_put_be32s(f, &env->sysenter_esp);
6608 qemu_put_be32s(f, &env->sysenter_eip);
6610 qemu_put_betls(f, &env->cr[0]);
6611 qemu_put_betls(f, &env->cr[2]);
6612 qemu_put_betls(f, &env->cr[3]);
6613 qemu_put_betls(f, &env->cr[4]);
6615 for(i = 0; i < 8; i++)
6616 qemu_put_betls(f, &env->dr[i]);
6618 /* MMU */
6619 qemu_put_be32s(f, &env->a20_mask);
6621 /* XMM */
6622 qemu_put_be32s(f, &env->mxcsr);
6623 for(i = 0; i < CPU_NB_REGS; i++) {
6624 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6625 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6628 #ifdef TARGET_X86_64
6629 qemu_put_be64s(f, &env->efer);
6630 qemu_put_be64s(f, &env->star);
6631 qemu_put_be64s(f, &env->lstar);
6632 qemu_put_be64s(f, &env->cstar);
6633 qemu_put_be64s(f, &env->fmask);
6634 qemu_put_be64s(f, &env->kernelgsbase);
6635 #endif
6636 qemu_put_be32s(f, &env->smbase);
6638 if (kvm_enabled()) {
6639 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6640 qemu_put_be32s(f, &env->kvm_interrupt_bitmap[i]);
6642 qemu_put_be64s(f, &env->tsc);
6646 #ifdef USE_X86LDOUBLE
6647 /* XXX: add that in a FPU generic layer */
6648 union x86_longdouble {
6649 uint64_t mant;
6650 uint16_t exp;
6653 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6654 #define EXPBIAS1 1023
6655 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6656 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6658 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6660 int e;
6661 /* mantissa */
6662 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6663 /* exponent + sign */
6664 e = EXPD1(temp) - EXPBIAS1 + 16383;
6665 e |= SIGND1(temp) >> 16;
6666 p->exp = e;
6668 #endif
6670 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6672 CPUState *env = opaque;
6673 int i, guess_mmx;
6674 uint32_t hflags;
6675 uint16_t fpus, fpuc, fptag, fpregs_format;
6677 if (version_id != 3 && version_id != 4)
6678 return -EINVAL;
6679 for(i = 0; i < CPU_NB_REGS; i++)
6680 qemu_get_betls(f, &env->regs[i]);
6681 qemu_get_betls(f, &env->eip);
6682 qemu_get_betls(f, &env->eflags);
6683 qemu_get_be32s(f, &hflags);
6685 qemu_get_be16s(f, &fpuc);
6686 qemu_get_be16s(f, &fpus);
6687 qemu_get_be16s(f, &fptag);
6688 qemu_get_be16s(f, &fpregs_format);
6690 /* NOTE: we cannot always restore the FPU state if the image come
6691 from a host with a different 'USE_X86LDOUBLE' define. We guess
6692 if we are in an MMX state to restore correctly in that case. */
6693 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6694 for(i = 0; i < 8; i++) {
6695 uint64_t mant;
6696 uint16_t exp;
6698 switch(fpregs_format) {
6699 case 0:
6700 mant = qemu_get_be64(f);
6701 exp = qemu_get_be16(f);
6702 #ifdef USE_X86LDOUBLE
6703 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6704 #else
6705 /* difficult case */
6706 if (guess_mmx)
6707 env->fpregs[i].mmx.MMX_Q(0) = mant;
6708 else
6709 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6710 #endif
6711 break;
6712 case 1:
6713 mant = qemu_get_be64(f);
6714 #ifdef USE_X86LDOUBLE
6716 union x86_longdouble *p;
6717 /* difficult case */
6718 p = (void *)&env->fpregs[i];
6719 if (guess_mmx) {
6720 p->mant = mant;
6721 p->exp = 0xffff;
6722 } else {
6723 fp64_to_fp80(p, mant);
6726 #else
6727 env->fpregs[i].mmx.MMX_Q(0) = mant;
6728 #endif
6729 break;
6730 default:
6731 return -EINVAL;
6735 env->fpuc = fpuc;
6736 /* XXX: restore FPU round state */
6737 env->fpstt = (fpus >> 11) & 7;
6738 env->fpus = fpus & ~0x3800;
6739 fptag ^= 0xff;
6740 for(i = 0; i < 8; i++) {
6741 env->fptags[i] = (fptag >> i) & 1;
6744 for(i = 0; i < 6; i++)
6745 cpu_get_seg(f, &env->segs[i]);
6746 cpu_get_seg(f, &env->ldt);
6747 cpu_get_seg(f, &env->tr);
6748 cpu_get_seg(f, &env->gdt);
6749 cpu_get_seg(f, &env->idt);
6751 qemu_get_be32s(f, &env->sysenter_cs);
6752 qemu_get_be32s(f, &env->sysenter_esp);
6753 qemu_get_be32s(f, &env->sysenter_eip);
6755 qemu_get_betls(f, &env->cr[0]);
6756 qemu_get_betls(f, &env->cr[2]);
6757 qemu_get_betls(f, &env->cr[3]);
6758 qemu_get_betls(f, &env->cr[4]);
6760 for(i = 0; i < 8; i++)
6761 qemu_get_betls(f, &env->dr[i]);
6763 /* MMU */
6764 qemu_get_be32s(f, &env->a20_mask);
6766 qemu_get_be32s(f, &env->mxcsr);
6767 for(i = 0; i < CPU_NB_REGS; i++) {
6768 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6769 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6772 #ifdef TARGET_X86_64
6773 qemu_get_be64s(f, &env->efer);
6774 qemu_get_be64s(f, &env->star);
6775 qemu_get_be64s(f, &env->lstar);
6776 qemu_get_be64s(f, &env->cstar);
6777 qemu_get_be64s(f, &env->fmask);
6778 qemu_get_be64s(f, &env->kernelgsbase);
6779 #endif
6780 if (version_id >= 4)
6781 qemu_get_be32s(f, &env->smbase);
6783 /* XXX: compute hflags from scratch, except for CPL and IIF */
6784 env->hflags = hflags;
6785 tlb_flush(env, 1);
6786 if (kvm_enabled()) {
6787 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
6788 because no userspace IRQs will ever clear this flag */
6789 env->hflags &= ~HF_HALTED_MASK;
6790 for (i = 0; i < NR_IRQ_WORDS ; i++) {
6791 qemu_get_be32s(f, &env->kvm_interrupt_bitmap[i]);
6793 qemu_get_be64s(f, &env->tsc);
6794 kvm_load_registers(env);
6796 return 0;
6799 #elif defined(TARGET_PPC)
6800 void cpu_save(QEMUFile *f, void *opaque)
6804 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6806 return 0;
6809 #elif defined(TARGET_MIPS)
6810 void cpu_save(QEMUFile *f, void *opaque)
6814 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6816 return 0;
6819 #elif defined(TARGET_SPARC)
6820 void cpu_save(QEMUFile *f, void *opaque)
6822 CPUState *env = opaque;
6823 int i;
6824 uint32_t tmp;
6826 for(i = 0; i < 8; i++)
6827 qemu_put_betls(f, &env->gregs[i]);
6828 for(i = 0; i < NWINDOWS * 16; i++)
6829 qemu_put_betls(f, &env->regbase[i]);
6831 /* FPU */
6832 for(i = 0; i < TARGET_FPREGS; i++) {
6833 union {
6834 float32 f;
6835 uint32_t i;
6836 } u;
6837 u.f = env->fpr[i];
6838 qemu_put_be32(f, u.i);
6841 qemu_put_betls(f, &env->pc);
6842 qemu_put_betls(f, &env->npc);
6843 qemu_put_betls(f, &env->y);
6844 tmp = GET_PSR(env);
6845 qemu_put_be32(f, tmp);
6846 qemu_put_betls(f, &env->fsr);
6847 qemu_put_betls(f, &env->tbr);
6848 #ifndef TARGET_SPARC64
6849 qemu_put_be32s(f, &env->wim);
6850 /* MMU */
6851 for(i = 0; i < 16; i++)
6852 qemu_put_be32s(f, &env->mmuregs[i]);
6853 #endif
6856 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6858 CPUState *env = opaque;
6859 int i;
6860 uint32_t tmp;
6862 for(i = 0; i < 8; i++)
6863 qemu_get_betls(f, &env->gregs[i]);
6864 for(i = 0; i < NWINDOWS * 16; i++)
6865 qemu_get_betls(f, &env->regbase[i]);
6867 /* FPU */
6868 for(i = 0; i < TARGET_FPREGS; i++) {
6869 union {
6870 float32 f;
6871 uint32_t i;
6872 } u;
6873 u.i = qemu_get_be32(f);
6874 env->fpr[i] = u.f;
6877 qemu_get_betls(f, &env->pc);
6878 qemu_get_betls(f, &env->npc);
6879 qemu_get_betls(f, &env->y);
6880 tmp = qemu_get_be32(f);
6881 env->cwp = 0; /* needed to ensure that the wrapping registers are
6882 correctly updated */
6883 PUT_PSR(env, tmp);
6884 qemu_get_betls(f, &env->fsr);
6885 qemu_get_betls(f, &env->tbr);
6886 #ifndef TARGET_SPARC64
6887 qemu_get_be32s(f, &env->wim);
6888 /* MMU */
6889 for(i = 0; i < 16; i++)
6890 qemu_get_be32s(f, &env->mmuregs[i]);
6891 #endif
6892 tlb_flush(env, 1);
6893 return 0;
6896 #elif defined(TARGET_ARM)
6898 void cpu_save(QEMUFile *f, void *opaque)
6900 int i;
6901 CPUARMState *env = (CPUARMState *)opaque;
6903 for (i = 0; i < 16; i++) {
6904 qemu_put_be32(f, env->regs[i]);
6906 qemu_put_be32(f, cpsr_read(env));
6907 qemu_put_be32(f, env->spsr);
6908 for (i = 0; i < 6; i++) {
6909 qemu_put_be32(f, env->banked_spsr[i]);
6910 qemu_put_be32(f, env->banked_r13[i]);
6911 qemu_put_be32(f, env->banked_r14[i]);
6913 for (i = 0; i < 5; i++) {
6914 qemu_put_be32(f, env->usr_regs[i]);
6915 qemu_put_be32(f, env->fiq_regs[i]);
6917 qemu_put_be32(f, env->cp15.c0_cpuid);
6918 qemu_put_be32(f, env->cp15.c0_cachetype);
6919 qemu_put_be32(f, env->cp15.c1_sys);
6920 qemu_put_be32(f, env->cp15.c1_coproc);
6921 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6922 qemu_put_be32(f, env->cp15.c2_base0);
6923 qemu_put_be32(f, env->cp15.c2_base1);
6924 qemu_put_be32(f, env->cp15.c2_mask);
6925 qemu_put_be32(f, env->cp15.c2_data);
6926 qemu_put_be32(f, env->cp15.c2_insn);
6927 qemu_put_be32(f, env->cp15.c3);
6928 qemu_put_be32(f, env->cp15.c5_insn);
6929 qemu_put_be32(f, env->cp15.c5_data);
6930 for (i = 0; i < 8; i++) {
6931 qemu_put_be32(f, env->cp15.c6_region[i]);
6933 qemu_put_be32(f, env->cp15.c6_insn);
6934 qemu_put_be32(f, env->cp15.c6_data);
6935 qemu_put_be32(f, env->cp15.c9_insn);
6936 qemu_put_be32(f, env->cp15.c9_data);
6937 qemu_put_be32(f, env->cp15.c13_fcse);
6938 qemu_put_be32(f, env->cp15.c13_context);
6939 qemu_put_be32(f, env->cp15.c13_tls1);
6940 qemu_put_be32(f, env->cp15.c13_tls2);
6941 qemu_put_be32(f, env->cp15.c13_tls3);
6942 qemu_put_be32(f, env->cp15.c15_cpar);
6944 qemu_put_be32(f, env->features);
6946 if (arm_feature(env, ARM_FEATURE_VFP)) {
6947 for (i = 0; i < 16; i++) {
6948 CPU_DoubleU u;
6949 u.d = env->vfp.regs[i];
6950 qemu_put_be32(f, u.l.upper);
6951 qemu_put_be32(f, u.l.lower);
6953 for (i = 0; i < 16; i++) {
6954 qemu_put_be32(f, env->vfp.xregs[i]);
6957 /* TODO: Should use proper FPSCR access functions. */
6958 qemu_put_be32(f, env->vfp.vec_len);
6959 qemu_put_be32(f, env->vfp.vec_stride);
6961 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6962 for (i = 16; i < 32; i++) {
6963 CPU_DoubleU u;
6964 u.d = env->vfp.regs[i];
6965 qemu_put_be32(f, u.l.upper);
6966 qemu_put_be32(f, u.l.lower);
6971 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6972 for (i = 0; i < 16; i++) {
6973 qemu_put_be64(f, env->iwmmxt.regs[i]);
6975 for (i = 0; i < 16; i++) {
6976 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6980 if (arm_feature(env, ARM_FEATURE_M)) {
6981 qemu_put_be32(f, env->v7m.other_sp);
6982 qemu_put_be32(f, env->v7m.vecbase);
6983 qemu_put_be32(f, env->v7m.basepri);
6984 qemu_put_be32(f, env->v7m.control);
6985 qemu_put_be32(f, env->v7m.current_sp);
6986 qemu_put_be32(f, env->v7m.exception);
6990 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6992 CPUARMState *env = (CPUARMState *)opaque;
6993 int i;
6995 if (version_id != ARM_CPU_SAVE_VERSION)
6996 return -EINVAL;
6998 for (i = 0; i < 16; i++) {
6999 env->regs[i] = qemu_get_be32(f);
7001 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
7002 env->spsr = qemu_get_be32(f);
7003 for (i = 0; i < 6; i++) {
7004 env->banked_spsr[i] = qemu_get_be32(f);
7005 env->banked_r13[i] = qemu_get_be32(f);
7006 env->banked_r14[i] = qemu_get_be32(f);
7008 for (i = 0; i < 5; i++) {
7009 env->usr_regs[i] = qemu_get_be32(f);
7010 env->fiq_regs[i] = qemu_get_be32(f);
7012 env->cp15.c0_cpuid = qemu_get_be32(f);
7013 env->cp15.c0_cachetype = qemu_get_be32(f);
7014 env->cp15.c1_sys = qemu_get_be32(f);
7015 env->cp15.c1_coproc = qemu_get_be32(f);
7016 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
7017 env->cp15.c2_base0 = qemu_get_be32(f);
7018 env->cp15.c2_base1 = qemu_get_be32(f);
7019 env->cp15.c2_mask = qemu_get_be32(f);
7020 env->cp15.c2_data = qemu_get_be32(f);
7021 env->cp15.c2_insn = qemu_get_be32(f);
7022 env->cp15.c3 = qemu_get_be32(f);
7023 env->cp15.c5_insn = qemu_get_be32(f);
7024 env->cp15.c5_data = qemu_get_be32(f);
7025 for (i = 0; i < 8; i++) {
7026 env->cp15.c6_region[i] = qemu_get_be32(f);
7028 env->cp15.c6_insn = qemu_get_be32(f);
7029 env->cp15.c6_data = qemu_get_be32(f);
7030 env->cp15.c9_insn = qemu_get_be32(f);
7031 env->cp15.c9_data = qemu_get_be32(f);
7032 env->cp15.c13_fcse = qemu_get_be32(f);
7033 env->cp15.c13_context = qemu_get_be32(f);
7034 env->cp15.c13_tls1 = qemu_get_be32(f);
7035 env->cp15.c13_tls2 = qemu_get_be32(f);
7036 env->cp15.c13_tls3 = qemu_get_be32(f);
7037 env->cp15.c15_cpar = qemu_get_be32(f);
7039 env->features = qemu_get_be32(f);
7041 if (arm_feature(env, ARM_FEATURE_VFP)) {
7042 for (i = 0; i < 16; i++) {
7043 CPU_DoubleU u;
7044 u.l.upper = qemu_get_be32(f);
7045 u.l.lower = qemu_get_be32(f);
7046 env->vfp.regs[i] = u.d;
7048 for (i = 0; i < 16; i++) {
7049 env->vfp.xregs[i] = qemu_get_be32(f);
7052 /* TODO: Should use proper FPSCR access functions. */
7053 env->vfp.vec_len = qemu_get_be32(f);
7054 env->vfp.vec_stride = qemu_get_be32(f);
7056 if (arm_feature(env, ARM_FEATURE_VFP3)) {
7057 for (i = 0; i < 16; i++) {
7058 CPU_DoubleU u;
7059 u.l.upper = qemu_get_be32(f);
7060 u.l.lower = qemu_get_be32(f);
7061 env->vfp.regs[i] = u.d;
7066 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
7067 for (i = 0; i < 16; i++) {
7068 env->iwmmxt.regs[i] = qemu_get_be64(f);
7070 for (i = 0; i < 16; i++) {
7071 env->iwmmxt.cregs[i] = qemu_get_be32(f);
7075 if (arm_feature(env, ARM_FEATURE_M)) {
7076 env->v7m.other_sp = qemu_get_be32(f);
7077 env->v7m.vecbase = qemu_get_be32(f);
7078 env->v7m.basepri = qemu_get_be32(f);
7079 env->v7m.control = qemu_get_be32(f);
7080 env->v7m.current_sp = qemu_get_be32(f);
7081 env->v7m.exception = qemu_get_be32(f);
7084 return 0;
7087 #elif defined(TARGET_IA64)
7088 void cpu_save(QEMUFile *f, void *opaque)
7092 int cpu_load(QEMUFile *f, void *opaque, int version_id)
7094 return 0;
7096 #else
7098 //#warning No CPU save/restore functions
7100 #endif
7102 /***********************************************************/
7103 /* ram save/restore */
7105 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7107 int v;
7109 v = qemu_get_byte(f);
7110 switch(v) {
7111 case 0:
7112 if (qemu_get_buffer(f, buf, len) != len)
7113 return -EIO;
7114 break;
7115 case 1:
7116 v = qemu_get_byte(f);
7117 memset(buf, v, len);
7118 break;
7119 default:
7120 return -EINVAL;
7122 return 0;
7125 static int ram_load_v1(QEMUFile *f, void *opaque)
7127 int i, ret;
7129 if (qemu_get_be32(f) != phys_ram_size)
7130 return -EINVAL;
7131 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7132 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7133 continue;
7134 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7135 if (ret)
7136 return ret;
7138 return 0;
7141 #define BDRV_HASH_BLOCK_SIZE 1024
7142 #define IOBUF_SIZE 4096
7143 #define RAM_CBLOCK_MAGIC 0xfabe
7145 typedef struct RamCompressState {
7146 z_stream zstream;
7147 QEMUFile *f;
7148 uint8_t buf[IOBUF_SIZE];
7149 } RamCompressState;
7151 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7153 int ret;
7154 memset(s, 0, sizeof(*s));
7155 s->f = f;
7156 ret = deflateInit2(&s->zstream, 1,
7157 Z_DEFLATED, 15,
7158 9, Z_DEFAULT_STRATEGY);
7159 if (ret != Z_OK)
7160 return -1;
7161 s->zstream.avail_out = IOBUF_SIZE;
7162 s->zstream.next_out = s->buf;
7163 return 0;
7166 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7168 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7169 qemu_put_be16(s->f, len);
7170 qemu_put_buffer(s->f, buf, len);
7173 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7175 int ret;
7177 s->zstream.avail_in = len;
7178 s->zstream.next_in = (uint8_t *)buf;
7179 while (s->zstream.avail_in > 0) {
7180 ret = deflate(&s->zstream, Z_NO_FLUSH);
7181 if (ret != Z_OK)
7182 return -1;
7183 if (s->zstream.avail_out == 0) {
7184 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7185 s->zstream.avail_out = IOBUF_SIZE;
7186 s->zstream.next_out = s->buf;
7189 return 0;
7192 static void ram_compress_close(RamCompressState *s)
7194 int len, ret;
7196 /* compress last bytes */
7197 for(;;) {
7198 ret = deflate(&s->zstream, Z_FINISH);
7199 if (ret == Z_OK || ret == Z_STREAM_END) {
7200 len = IOBUF_SIZE - s->zstream.avail_out;
7201 if (len > 0) {
7202 ram_put_cblock(s, s->buf, len);
7204 s->zstream.avail_out = IOBUF_SIZE;
7205 s->zstream.next_out = s->buf;
7206 if (ret == Z_STREAM_END)
7207 break;
7208 } else {
7209 goto fail;
7212 fail:
7213 deflateEnd(&s->zstream);
7216 typedef struct RamDecompressState {
7217 z_stream zstream;
7218 QEMUFile *f;
7219 uint8_t buf[IOBUF_SIZE];
7220 } RamDecompressState;
7222 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7224 int ret;
7225 memset(s, 0, sizeof(*s));
7226 s->f = f;
7227 ret = inflateInit(&s->zstream);
7228 if (ret != Z_OK)
7229 return -1;
7230 return 0;
7233 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7235 int ret, clen;
7237 s->zstream.avail_out = len;
7238 s->zstream.next_out = buf;
7239 while (s->zstream.avail_out > 0) {
7240 if (s->zstream.avail_in == 0) {
7241 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7242 return -1;
7243 clen = qemu_get_be16(s->f);
7244 if (clen > IOBUF_SIZE)
7245 return -1;
7246 qemu_get_buffer(s->f, s->buf, clen);
7247 s->zstream.avail_in = clen;
7248 s->zstream.next_in = s->buf;
7250 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7251 if (ret != Z_OK && ret != Z_STREAM_END) {
7252 return -1;
7255 return 0;
7258 static void ram_decompress_close(RamDecompressState *s)
7260 inflateEnd(&s->zstream);
7263 static void ram_save_live(QEMUFile *f, void *opaque)
7265 target_ulong addr;
7267 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7268 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7269 continue;
7270 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7271 qemu_put_be32(f, addr);
7272 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7275 qemu_put_be32(f, 1);
7278 static void ram_save_static(QEMUFile *f, void *opaque)
7280 int i;
7281 RamCompressState s1, *s = &s1;
7282 uint8_t buf[10];
7284 qemu_put_be32(f, phys_ram_size);
7285 if (ram_compress_open(s, f) < 0)
7286 return;
7287 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7288 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7289 continue;
7290 #if 0
7291 if (tight_savevm_enabled) {
7292 int64_t sector_num;
7293 int j;
7295 /* find if the memory block is available on a virtual
7296 block device */
7297 sector_num = -1;
7298 for(j = 0; j < nb_drives; j++) {
7299 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7300 phys_ram_base + i,
7301 BDRV_HASH_BLOCK_SIZE);
7302 if (sector_num >= 0)
7303 break;
7305 if (j == nb_drives)
7306 goto normal_compress;
7307 buf[0] = 1;
7308 buf[1] = j;
7309 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7310 ram_compress_buf(s, buf, 10);
7311 } else
7312 #endif
7314 // normal_compress:
7315 buf[0] = 0;
7316 ram_compress_buf(s, buf, 1);
7317 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7320 ram_compress_close(s);
7323 static void ram_save(QEMUFile *f, void *opaque)
7325 int in_migration = cpu_physical_memory_get_dirty_tracking();
7327 qemu_put_byte(f, in_migration);
7329 if (in_migration)
7330 ram_save_live(f, opaque);
7331 else
7332 ram_save_static(f, opaque);
7335 static int ram_load_live(QEMUFile *f, void *opaque)
7337 target_ulong addr;
7339 do {
7340 addr = qemu_get_be32(f);
7341 if (addr == 1)
7342 break;
7344 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7345 } while (1);
7347 return 0;
7350 static int ram_load_static(QEMUFile *f, void *opaque)
7352 RamDecompressState s1, *s = &s1;
7353 uint8_t buf[10];
7354 int i;
7356 if (qemu_get_be32(f) != phys_ram_size)
7357 return -EINVAL;
7358 if (ram_decompress_open(s, f) < 0)
7359 return -EINVAL;
7360 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7361 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7362 continue;
7363 if (ram_decompress_buf(s, buf, 1) < 0) {
7364 fprintf(stderr, "Error while reading ram block header\n");
7365 goto error;
7367 if (buf[0] == 0) {
7368 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7369 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7370 goto error;
7372 } else
7373 #if 0
7374 if (buf[0] == 1) {
7375 int bs_index;
7376 int64_t sector_num;
7378 ram_decompress_buf(s, buf + 1, 9);
7379 bs_index = buf[1];
7380 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7381 if (bs_index >= nb_drives) {
7382 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7383 goto error;
7385 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7386 phys_ram_base + i,
7387 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7388 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7389 bs_index, sector_num);
7390 goto error;
7392 } else
7393 #endif
7395 error:
7396 printf("Error block header\n");
7397 return -EINVAL;
7400 ram_decompress_close(s);
7401 return 0;
7404 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7406 int ret;
7408 switch (version_id) {
7409 case 1:
7410 ret = ram_load_v1(f, opaque);
7411 break;
7412 case 3:
7413 if (qemu_get_byte(f)) {
7414 ret = ram_load_live(f, opaque);
7415 break;
7417 case 2:
7418 ret = ram_load_static(f, opaque);
7419 break;
7420 default:
7421 ret = -EINVAL;
7422 break;
7425 return ret;
7428 /***********************************************************/
7429 /* bottom halves (can be seen as timers which expire ASAP) */
7431 struct QEMUBH {
7432 QEMUBHFunc *cb;
7433 void *opaque;
7434 int scheduled;
7435 QEMUBH *next;
7438 static QEMUBH *first_bh = NULL;
7440 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7442 QEMUBH *bh;
7443 bh = qemu_mallocz(sizeof(QEMUBH));
7444 if (!bh)
7445 return NULL;
7446 bh->cb = cb;
7447 bh->opaque = opaque;
7448 return bh;
7451 int qemu_bh_poll(void)
7453 QEMUBH *bh, **pbh;
7454 int ret;
7456 ret = 0;
7457 for(;;) {
7458 pbh = &first_bh;
7459 bh = *pbh;
7460 if (!bh)
7461 break;
7462 ret = 1;
7463 *pbh = bh->next;
7464 bh->scheduled = 0;
7465 bh->cb(bh->opaque);
7467 return ret;
7470 void qemu_bh_schedule(QEMUBH *bh)
7472 CPUState *env = cpu_single_env;
7473 if (bh->scheduled)
7474 return;
7475 bh->scheduled = 1;
7476 bh->next = first_bh;
7477 first_bh = bh;
7479 /* stop the currently executing CPU to execute the BH ASAP */
7480 if (env) {
7481 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7485 void qemu_bh_cancel(QEMUBH *bh)
7487 QEMUBH **pbh;
7488 if (bh->scheduled) {
7489 pbh = &first_bh;
7490 while (*pbh != bh)
7491 pbh = &(*pbh)->next;
7492 *pbh = bh->next;
7493 bh->scheduled = 0;
7497 void qemu_bh_delete(QEMUBH *bh)
7499 qemu_bh_cancel(bh);
7500 qemu_free(bh);
7503 /***********************************************************/
7504 /* machine registration */
7506 QEMUMachine *first_machine = NULL;
7508 int qemu_register_machine(QEMUMachine *m)
7510 QEMUMachine **pm;
7511 pm = &first_machine;
7512 while (*pm != NULL)
7513 pm = &(*pm)->next;
7514 m->next = NULL;
7515 *pm = m;
7516 return 0;
7519 static QEMUMachine *find_machine(const char *name)
7521 QEMUMachine *m;
7523 for(m = first_machine; m != NULL; m = m->next) {
7524 if (!strcmp(m->name, name))
7525 return m;
7527 return NULL;
7530 /***********************************************************/
7531 /* main execution loop */
7533 static void gui_update(void *opaque)
7535 DisplayState *ds = opaque;
7536 ds->dpy_refresh(ds);
7537 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7540 struct vm_change_state_entry {
7541 VMChangeStateHandler *cb;
7542 void *opaque;
7543 LIST_ENTRY (vm_change_state_entry) entries;
7546 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7548 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7549 void *opaque)
7551 VMChangeStateEntry *e;
7553 e = qemu_mallocz(sizeof (*e));
7554 if (!e)
7555 return NULL;
7557 e->cb = cb;
7558 e->opaque = opaque;
7559 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7560 return e;
7563 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7565 LIST_REMOVE (e, entries);
7566 qemu_free (e);
7569 static void vm_state_notify(int running)
7571 VMChangeStateEntry *e;
7573 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7574 e->cb(e->opaque, running);
7578 /* XXX: support several handlers */
7579 static VMStopHandler *vm_stop_cb;
7580 static void *vm_stop_opaque;
7582 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7584 vm_stop_cb = cb;
7585 vm_stop_opaque = opaque;
7586 return 0;
7589 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7591 vm_stop_cb = NULL;
7594 void vm_start(void)
7596 if (!vm_running) {
7597 cpu_enable_ticks();
7598 vm_running = 1;
7599 vm_state_notify(1);
7600 qemu_rearm_alarm_timer(alarm_timer);
7604 void vm_stop(int reason)
7606 if (vm_running) {
7607 cpu_disable_ticks();
7608 vm_running = 0;
7609 if (reason != 0) {
7610 if (vm_stop_cb) {
7611 vm_stop_cb(vm_stop_opaque, reason);
7614 vm_state_notify(0);
7618 /* reset/shutdown handler */
7620 typedef struct QEMUResetEntry {
7621 QEMUResetHandler *func;
7622 void *opaque;
7623 struct QEMUResetEntry *next;
7624 } QEMUResetEntry;
7626 static QEMUResetEntry *first_reset_entry;
7627 static int reset_requested;
7628 static int shutdown_requested;
7629 static int powerdown_requested;
7631 int qemu_shutdown_requested(void)
7633 int r = shutdown_requested;
7634 shutdown_requested = 0;
7635 return r;
7638 int qemu_reset_requested(void)
7640 int r = reset_requested;
7641 reset_requested = 0;
7642 return r;
7645 int qemu_powerdown_requested(void)
7647 int r = powerdown_requested;
7648 powerdown_requested = 0;
7649 return r;
7652 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7654 QEMUResetEntry **pre, *re;
7656 pre = &first_reset_entry;
7657 while (*pre != NULL)
7658 pre = &(*pre)->next;
7659 re = qemu_mallocz(sizeof(QEMUResetEntry));
7660 re->func = func;
7661 re->opaque = opaque;
7662 re->next = NULL;
7663 *pre = re;
7666 void qemu_system_reset(void)
7668 QEMUResetEntry *re;
7670 /* reset all devices */
7671 for(re = first_reset_entry; re != NULL; re = re->next) {
7672 re->func(re->opaque);
7676 void qemu_system_reset_request(void)
7678 if (no_reboot) {
7679 shutdown_requested = 1;
7680 } else {
7681 reset_requested = 1;
7683 if (cpu_single_env)
7684 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7687 void qemu_system_shutdown_request(void)
7689 shutdown_requested = 1;
7690 if (cpu_single_env)
7691 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7694 void qemu_system_powerdown_request(void)
7696 powerdown_requested = 1;
7697 if (cpu_single_env)
7698 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7701 void main_loop_wait(int timeout)
7703 IOHandlerRecord *ioh;
7704 fd_set rfds, wfds, xfds;
7705 int ret, nfds;
7706 #ifdef _WIN32
7707 int ret2, i;
7708 #endif
7709 struct timeval tv;
7710 PollingEntry *pe;
7713 /* XXX: need to suppress polling by better using win32 events */
7714 ret = 0;
7715 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7716 ret |= pe->func(pe->opaque);
7718 #ifdef _WIN32
7719 if (ret == 0) {
7720 int err;
7721 WaitObjects *w = &wait_objects;
7723 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7724 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7725 if (w->func[ret - WAIT_OBJECT_0])
7726 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7728 /* Check for additional signaled events */
7729 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7731 /* Check if event is signaled */
7732 ret2 = WaitForSingleObject(w->events[i], 0);
7733 if(ret2 == WAIT_OBJECT_0) {
7734 if (w->func[i])
7735 w->func[i](w->opaque[i]);
7736 } else if (ret2 == WAIT_TIMEOUT) {
7737 } else {
7738 err = GetLastError();
7739 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7742 } else if (ret == WAIT_TIMEOUT) {
7743 } else {
7744 err = GetLastError();
7745 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7748 #endif
7749 /* poll any events */
7750 /* XXX: separate device handlers from system ones */
7751 nfds = -1;
7752 FD_ZERO(&rfds);
7753 FD_ZERO(&wfds);
7754 FD_ZERO(&xfds);
7755 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7756 if (ioh->deleted)
7757 continue;
7758 if (ioh->fd_read &&
7759 (!ioh->fd_read_poll ||
7760 ioh->fd_read_poll(ioh->opaque) != 0)) {
7761 FD_SET(ioh->fd, &rfds);
7762 if (ioh->fd > nfds)
7763 nfds = ioh->fd;
7765 if (ioh->fd_write) {
7766 FD_SET(ioh->fd, &wfds);
7767 if (ioh->fd > nfds)
7768 nfds = ioh->fd;
7772 tv.tv_sec = 0;
7773 #ifdef _WIN32
7774 tv.tv_usec = 0;
7775 #else
7776 tv.tv_usec = timeout * 1000;
7777 #endif
7778 #if defined(CONFIG_SLIRP)
7779 if (slirp_inited) {
7780 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7782 #endif
7783 moreio:
7784 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7785 if (ret > 0) {
7786 IOHandlerRecord **pioh;
7787 int more = 0;
7789 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7790 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7791 ioh->fd_read(ioh->opaque);
7792 if (!ioh->fd_read_poll || ioh->fd_read_poll(ioh->opaque))
7793 more = 1;
7794 else
7795 FD_CLR(ioh->fd, &rfds);
7797 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7798 ioh->fd_write(ioh->opaque);
7799 more = 1;
7803 /* remove deleted IO handlers */
7804 pioh = &first_io_handler;
7805 while (*pioh) {
7806 ioh = *pioh;
7807 if (ioh->deleted) {
7808 *pioh = ioh->next;
7809 qemu_free(ioh);
7810 } else
7811 pioh = &ioh->next;
7813 if (more)
7814 goto moreio;
7816 #if defined(CONFIG_SLIRP)
7817 if (slirp_inited) {
7818 if (ret < 0) {
7819 FD_ZERO(&rfds);
7820 FD_ZERO(&wfds);
7821 FD_ZERO(&xfds);
7823 slirp_select_poll(&rfds, &wfds, &xfds);
7825 #endif
7826 virtio_net_poll();
7828 qemu_aio_poll();
7830 if (vm_running) {
7831 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7832 qemu_get_clock(vm_clock));
7833 /* run dma transfers, if any */
7834 DMA_run();
7837 /* real time timers */
7838 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7839 qemu_get_clock(rt_clock));
7841 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7842 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7843 qemu_rearm_alarm_timer(alarm_timer);
7846 /* Check bottom-halves last in case any of the earlier events triggered
7847 them. */
7848 qemu_bh_poll();
7852 static int main_loop(void)
7854 int ret, timeout;
7855 #ifdef CONFIG_PROFILER
7856 int64_t ti;
7857 #endif
7858 CPUState *env;
7861 if (kvm_enabled()) {
7862 kvm_main_loop();
7863 cpu_disable_ticks();
7864 return 0;
7867 cur_cpu = first_cpu;
7868 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7869 for(;;) {
7870 if (vm_running) {
7872 for(;;) {
7873 /* get next cpu */
7874 env = next_cpu;
7875 #ifdef CONFIG_PROFILER
7876 ti = profile_getclock();
7877 #endif
7878 ret = cpu_exec(env);
7879 #ifdef CONFIG_PROFILER
7880 qemu_time += profile_getclock() - ti;
7881 #endif
7882 next_cpu = env->next_cpu ?: first_cpu;
7883 if (event_pending) {
7884 ret = EXCP_INTERRUPT;
7885 event_pending = 0;
7886 break;
7888 if (ret == EXCP_HLT) {
7889 /* Give the next CPU a chance to run. */
7890 cur_cpu = env;
7891 continue;
7893 if (ret != EXCP_HALTED)
7894 break;
7895 /* all CPUs are halted ? */
7896 if (env == cur_cpu)
7897 break;
7899 cur_cpu = env;
7901 if (shutdown_requested) {
7902 ret = EXCP_INTERRUPT;
7903 break;
7905 if (reset_requested) {
7906 reset_requested = 0;
7907 qemu_system_reset();
7908 if (kvm_enabled())
7909 kvm_load_registers(env);
7910 ret = EXCP_INTERRUPT;
7912 if (powerdown_requested) {
7913 powerdown_requested = 0;
7914 qemu_system_powerdown();
7915 ret = EXCP_INTERRUPT;
7917 if (ret == EXCP_DEBUG) {
7918 vm_stop(EXCP_DEBUG);
7920 /* If all cpus are halted then wait until the next IRQ */
7921 /* XXX: use timeout computed from timers */
7922 if (ret == EXCP_HALTED)
7923 timeout = 10;
7924 else
7925 timeout = 0;
7926 } else {
7927 timeout = 10;
7929 #ifdef CONFIG_PROFILER
7930 ti = profile_getclock();
7931 #endif
7932 main_loop_wait(timeout);
7933 #ifdef CONFIG_PROFILER
7934 dev_time += profile_getclock() - ti;
7935 #endif
7937 cpu_disable_ticks();
7938 return ret;
7941 static void help(int exitcode)
7943 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
7944 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7945 "usage: %s [options] [disk_image]\n"
7946 "\n"
7947 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7948 "\n"
7949 "Standard options:\n"
7950 "-M machine select emulated machine (-M ? for list)\n"
7951 "-cpu cpu select CPU (-cpu ? for list)\n"
7952 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7953 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7954 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7955 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7956 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7957 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7958 " [,cache=on|off][,boot=on|off]\n"
7959 " use 'file' as a drive image\n"
7960 "-mtdblock file use 'file' as on-board Flash memory image\n"
7961 "-sd file use 'file' as SecureDigital card image\n"
7962 "-pflash file use 'file' as a parallel flash image\n"
7963 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7964 "-snapshot write to temporary files instead of disk image files\n"
7965 #ifdef CONFIG_SDL
7966 "-no-frame open SDL window without a frame and window decorations\n"
7967 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7968 "-no-quit disable SDL window close capability\n"
7969 #endif
7970 #ifdef TARGET_I386
7971 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7972 #endif
7973 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7974 "-smp n set the number of CPUs to 'n' [default=1]\n"
7975 "-nographic disable graphical output and redirect serial I/Os to console\n"
7976 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7977 #ifndef _WIN32
7978 "-k language use keyboard layout (for example \"fr\" for French)\n"
7979 #endif
7980 #ifdef HAS_AUDIO
7981 "-audio-help print list of audio drivers and their options\n"
7982 "-soundhw c1,... enable audio support\n"
7983 " and only specified sound cards (comma separated list)\n"
7984 " use -soundhw ? to get the list of supported cards\n"
7985 " use -soundhw all to enable all of them\n"
7986 #endif
7987 "-localtime set the real time clock to local time [default=utc]\n"
7988 "-full-screen start in full screen\n"
7989 #ifdef TARGET_I386
7990 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7991 #endif
7992 "-usb enable the USB driver (will be the default soon)\n"
7993 "-usbdevice name add the host or guest USB device 'name'\n"
7994 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7995 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7996 #endif
7997 "-name string set the name of the guest\n"
7998 "\n"
7999 "Network options:\n"
8000 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8001 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8002 #ifdef CONFIG_SLIRP
8003 "-net user[,vlan=n][,hostname=host]\n"
8004 " connect the user mode network stack to VLAN 'n' and send\n"
8005 " hostname 'host' to DHCP clients\n"
8006 #endif
8007 #ifdef _WIN32
8008 "-net tap[,vlan=n],ifname=name\n"
8009 " connect the host TAP network interface to VLAN 'n'\n"
8010 #else
8011 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8012 " connect the host TAP network interface to VLAN 'n' and use the\n"
8013 " network scripts 'file' (default=%s)\n"
8014 " and 'dfile' (default=%s);\n"
8015 " use '[down]script=no' to disable script execution;\n"
8016 " use 'fd=h' to connect to an already opened TAP interface\n"
8017 #endif
8018 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8019 " connect the vlan 'n' to another VLAN using a socket connection\n"
8020 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8021 " connect the vlan 'n' to multicast maddr and port\n"
8022 "-net none use it alone to have zero network devices; if no -net option\n"
8023 " is provided, the default is '-net nic -net user'\n"
8024 "\n"
8025 #ifdef CONFIG_SLIRP
8026 "-tftp dir allow tftp access to files in dir [-net user]\n"
8027 "-bootp file advertise file in BOOTP replies\n"
8028 #ifndef _WIN32
8029 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8030 #endif
8031 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8032 " redirect TCP or UDP connections from host to guest [-net user]\n"
8033 #endif
8034 "\n"
8035 "Linux boot specific:\n"
8036 "-kernel bzImage use 'bzImage' as kernel image\n"
8037 "-append cmdline use 'cmdline' as kernel command line\n"
8038 "-initrd file use 'file' as initial ram disk\n"
8039 "\n"
8040 "Debug/Expert options:\n"
8041 "-monitor dev redirect the monitor to char device 'dev'\n"
8042 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
8043 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
8044 "-serial dev redirect the serial port to char device 'dev'\n"
8045 "-parallel dev redirect the parallel port to char device 'dev'\n"
8046 "-pidfile file Write PID to 'file'\n"
8047 "-S freeze CPU at startup (use 'c' to start execution)\n"
8048 "-s wait gdb connection to port\n"
8049 "-p port set gdb connection port [default=%s]\n"
8050 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8051 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8052 " translation (t=none or lba) (usually qemu can guess them)\n"
8053 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8054 #ifdef USE_KQEMU
8055 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8056 "-no-kqemu disable KQEMU kernel module usage\n"
8057 #endif
8058 #ifdef USE_KVM
8059 #ifndef NO_CPU_EMULATION
8060 "-no-kvm disable KVM hardware virtualization\n"
8061 #endif
8062 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8063 #endif
8064 #ifdef TARGET_I386
8065 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8066 " (default is CL-GD5446 PCI VGA)\n"
8067 "-no-acpi disable ACPI\n"
8068 #endif
8069 "-no-reboot exit instead of rebooting\n"
8070 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
8071 "-vnc display start a VNC server on display\n"
8072 #ifndef _WIN32
8073 "-daemonize daemonize QEMU after initializing\n"
8074 #endif
8075 "-tdf inject timer interrupts that got lost\n"
8076 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8077 "-hugetlb-path set the path to hugetlbfs mounted directory, also enables allocation of guest memory with huge pages\n"
8078 "-option-rom rom load a file, rom, into the option ROM space\n"
8079 #ifdef TARGET_SPARC
8080 "-prom-env variable=value set OpenBIOS nvram variables\n"
8081 #endif
8082 "-clock force the use of the given methods for timer alarm.\n"
8083 " To see what timers are available use -clock help\n"
8084 "-startdate select initial date of the clock\n"
8085 "\n"
8086 "During emulation, the following keys are useful:\n"
8087 "ctrl-alt-f toggle full screen\n"
8088 "ctrl-alt-n switch to virtual console 'n'\n"
8089 "ctrl-alt toggle mouse and keyboard grab\n"
8090 "\n"
8091 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8093 "qemu",
8094 DEFAULT_RAM_SIZE,
8095 #ifndef _WIN32
8096 DEFAULT_NETWORK_SCRIPT,
8097 DEFAULT_NETWORK_DOWN_SCRIPT,
8098 #endif
8099 DEFAULT_GDBSTUB_PORT,
8100 "/tmp/qemu.log");
8101 exit(exitcode);
8104 #define HAS_ARG 0x0001
8106 enum {
8107 QEMU_OPTION_h,
8109 QEMU_OPTION_M,
8110 QEMU_OPTION_cpu,
8111 QEMU_OPTION_fda,
8112 QEMU_OPTION_fdb,
8113 QEMU_OPTION_hda,
8114 QEMU_OPTION_hdb,
8115 QEMU_OPTION_hdc,
8116 QEMU_OPTION_hdd,
8117 QEMU_OPTION_drive,
8118 QEMU_OPTION_cdrom,
8119 QEMU_OPTION_mtdblock,
8120 QEMU_OPTION_sd,
8121 QEMU_OPTION_pflash,
8122 QEMU_OPTION_boot,
8123 QEMU_OPTION_snapshot,
8124 #ifdef TARGET_I386
8125 QEMU_OPTION_no_fd_bootchk,
8126 #endif
8127 QEMU_OPTION_m,
8128 QEMU_OPTION_nographic,
8129 QEMU_OPTION_portrait,
8130 #ifdef HAS_AUDIO
8131 QEMU_OPTION_audio_help,
8132 QEMU_OPTION_soundhw,
8133 #endif
8135 QEMU_OPTION_net,
8136 QEMU_OPTION_tftp,
8137 QEMU_OPTION_bootp,
8138 QEMU_OPTION_smb,
8139 QEMU_OPTION_redir,
8141 QEMU_OPTION_kernel,
8142 QEMU_OPTION_append,
8143 QEMU_OPTION_initrd,
8145 QEMU_OPTION_S,
8146 QEMU_OPTION_s,
8147 QEMU_OPTION_p,
8148 QEMU_OPTION_d,
8149 QEMU_OPTION_hdachs,
8150 QEMU_OPTION_L,
8151 QEMU_OPTION_bios,
8152 QEMU_OPTION_no_code_copy,
8153 QEMU_OPTION_k,
8154 QEMU_OPTION_localtime,
8155 QEMU_OPTION_cirrusvga,
8156 QEMU_OPTION_vmsvga,
8157 QEMU_OPTION_g,
8158 QEMU_OPTION_std_vga,
8159 QEMU_OPTION_echr,
8160 QEMU_OPTION_monitor,
8161 QEMU_OPTION_balloon,
8162 QEMU_OPTION_vmchannel,
8163 QEMU_OPTION_serial,
8164 QEMU_OPTION_parallel,
8165 QEMU_OPTION_loadvm,
8166 QEMU_OPTION_full_screen,
8167 QEMU_OPTION_no_frame,
8168 QEMU_OPTION_alt_grab,
8169 QEMU_OPTION_no_quit,
8170 QEMU_OPTION_pidfile,
8171 QEMU_OPTION_no_kqemu,
8172 QEMU_OPTION_kernel_kqemu,
8173 QEMU_OPTION_win2k_hack,
8174 QEMU_OPTION_usb,
8175 QEMU_OPTION_usbdevice,
8176 QEMU_OPTION_smp,
8177 QEMU_OPTION_vnc,
8178 QEMU_OPTION_no_acpi,
8179 QEMU_OPTION_no_kvm,
8180 QEMU_OPTION_no_kvm_irqchip,
8181 QEMU_OPTION_no_reboot,
8182 QEMU_OPTION_show_cursor,
8183 QEMU_OPTION_daemonize,
8184 QEMU_OPTION_option_rom,
8185 QEMU_OPTION_semihosting,
8186 QEMU_OPTION_cpu_vendor,
8187 QEMU_OPTION_name,
8188 QEMU_OPTION_prom_env,
8189 QEMU_OPTION_old_param,
8190 QEMU_OPTION_clock,
8191 QEMU_OPTION_startdate,
8192 QEMU_OPTION_translation,
8193 QEMU_OPTION_incoming,
8194 QEMU_OPTION_tdf,
8195 QEMU_OPTION_kvm_shadow_memory,
8196 QEMU_OPTION_hugetlbpath,
8199 typedef struct QEMUOption {
8200 const char *name;
8201 int flags;
8202 int index;
8203 } QEMUOption;
8205 const QEMUOption qemu_options[] = {
8206 { "h", 0, QEMU_OPTION_h },
8207 { "help", 0, QEMU_OPTION_h },
8209 { "M", HAS_ARG, QEMU_OPTION_M },
8210 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8211 { "fda", HAS_ARG, QEMU_OPTION_fda },
8212 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8213 { "hda", HAS_ARG, QEMU_OPTION_hda },
8214 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8215 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8216 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8217 { "drive", HAS_ARG, QEMU_OPTION_drive },
8218 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8219 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8220 { "sd", HAS_ARG, QEMU_OPTION_sd },
8221 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8222 { "boot", HAS_ARG, QEMU_OPTION_boot },
8223 { "snapshot", 0, QEMU_OPTION_snapshot },
8224 #ifdef TARGET_I386
8225 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8226 #endif
8227 { "m", HAS_ARG, QEMU_OPTION_m },
8228 { "nographic", 0, QEMU_OPTION_nographic },
8229 { "portrait", 0, QEMU_OPTION_portrait },
8230 { "k", HAS_ARG, QEMU_OPTION_k },
8231 #ifdef HAS_AUDIO
8232 { "audio-help", 0, QEMU_OPTION_audio_help },
8233 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8234 #endif
8236 { "net", HAS_ARG, QEMU_OPTION_net},
8237 #ifdef CONFIG_SLIRP
8238 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8239 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8240 #ifndef _WIN32
8241 { "smb", HAS_ARG, QEMU_OPTION_smb },
8242 #endif
8243 { "redir", HAS_ARG, QEMU_OPTION_redir },
8244 #endif
8246 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8247 { "append", HAS_ARG, QEMU_OPTION_append },
8248 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8250 { "S", 0, QEMU_OPTION_S },
8251 { "s", 0, QEMU_OPTION_s },
8252 { "p", HAS_ARG, QEMU_OPTION_p },
8253 { "d", HAS_ARG, QEMU_OPTION_d },
8254 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8255 { "L", HAS_ARG, QEMU_OPTION_L },
8256 { "bios", HAS_ARG, QEMU_OPTION_bios },
8257 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
8258 #ifdef USE_KQEMU
8259 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8260 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8261 #endif
8262 #ifdef USE_KVM
8263 #ifndef NO_CPU_EMULATION
8264 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8265 #endif
8266 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8267 #endif
8268 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8269 { "g", 1, QEMU_OPTION_g },
8270 #endif
8271 { "localtime", 0, QEMU_OPTION_localtime },
8272 { "std-vga", 0, QEMU_OPTION_std_vga },
8273 { "monitor", 1, QEMU_OPTION_monitor },
8274 { "balloon", 1, QEMU_OPTION_balloon },
8275 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8276 { "echr", HAS_ARG, QEMU_OPTION_echr },
8277 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8278 { "serial", HAS_ARG, QEMU_OPTION_serial },
8279 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8280 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8281 { "incoming", 1, QEMU_OPTION_incoming },
8282 { "full-screen", 0, QEMU_OPTION_full_screen },
8283 #ifdef CONFIG_SDL
8284 { "no-frame", 0, QEMU_OPTION_no_frame },
8285 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8286 { "no-quit", 0, QEMU_OPTION_no_quit },
8287 #endif
8288 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8289 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8290 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8291 { "smp", HAS_ARG, QEMU_OPTION_smp },
8292 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8294 /* temporary options */
8295 { "usb", 0, QEMU_OPTION_usb },
8296 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8297 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8298 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8299 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8300 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8301 { "daemonize", 0, QEMU_OPTION_daemonize },
8302 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8303 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8304 { "semihosting", 0, QEMU_OPTION_semihosting },
8305 #endif
8306 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8307 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8308 { "name", HAS_ARG, QEMU_OPTION_name },
8309 #if defined(TARGET_SPARC)
8310 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8311 #endif
8312 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8313 #if defined(TARGET_ARM)
8314 { "old-param", 0, QEMU_OPTION_old_param },
8315 #endif
8316 { "clock", HAS_ARG, QEMU_OPTION_clock },
8317 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8318 { "hugetlb-path", HAS_ARG, QEMU_OPTION_hugetlbpath },
8319 { NULL },
8322 /* password input */
8324 int qemu_key_check(BlockDriverState *bs, const char *name)
8326 char password[256];
8327 int i;
8329 if (!bdrv_is_encrypted(bs))
8330 return 0;
8332 term_printf("%s is encrypted.\n", name);
8333 for(i = 0; i < 3; i++) {
8334 monitor_readline("Password: ", 1, password, sizeof(password));
8335 if (bdrv_set_key(bs, password) == 0)
8336 return 0;
8337 term_printf("invalid password\n");
8339 return -EPERM;
8342 static BlockDriverState *get_bdrv(int index)
8344 if (index > nb_drives)
8345 return NULL;
8346 return drives_table[index].bdrv;
8349 static void read_passwords(void)
8351 BlockDriverState *bs;
8352 int i;
8354 for(i = 0; i < 6; i++) {
8355 bs = get_bdrv(i);
8356 if (bs)
8357 qemu_key_check(bs, bdrv_get_device_name(bs));
8361 /* XXX: currently we cannot use simultaneously different CPUs */
8362 static void register_machines(void)
8364 #if defined(TARGET_I386)
8365 qemu_register_machine(&pc_machine);
8366 qemu_register_machine(&isapc_machine);
8367 #elif defined(TARGET_PPC)
8368 qemu_register_machine(&heathrow_machine);
8369 qemu_register_machine(&core99_machine);
8370 qemu_register_machine(&prep_machine);
8371 qemu_register_machine(&ref405ep_machine);
8372 qemu_register_machine(&taihu_machine);
8373 qemu_register_machine(&bamboo_machine);
8374 #elif defined(TARGET_MIPS)
8375 qemu_register_machine(&mips_machine);
8376 qemu_register_machine(&mips_malta_machine);
8377 qemu_register_machine(&mips_pica61_machine);
8378 qemu_register_machine(&mips_mipssim_machine);
8379 #elif defined(TARGET_SPARC)
8380 #ifdef TARGET_SPARC64
8381 qemu_register_machine(&sun4u_machine);
8382 #else
8383 qemu_register_machine(&ss5_machine);
8384 qemu_register_machine(&ss10_machine);
8385 qemu_register_machine(&ss600mp_machine);
8386 qemu_register_machine(&ss20_machine);
8387 qemu_register_machine(&ss2_machine);
8388 qemu_register_machine(&ss1000_machine);
8389 qemu_register_machine(&ss2000_machine);
8390 #endif
8391 #elif defined(TARGET_ARM)
8392 qemu_register_machine(&integratorcp_machine);
8393 qemu_register_machine(&versatilepb_machine);
8394 qemu_register_machine(&versatileab_machine);
8395 qemu_register_machine(&realview_machine);
8396 qemu_register_machine(&akitapda_machine);
8397 qemu_register_machine(&spitzpda_machine);
8398 qemu_register_machine(&borzoipda_machine);
8399 qemu_register_machine(&terrierpda_machine);
8400 qemu_register_machine(&palmte_machine);
8401 qemu_register_machine(&lm3s811evb_machine);
8402 qemu_register_machine(&lm3s6965evb_machine);
8403 qemu_register_machine(&connex_machine);
8404 qemu_register_machine(&verdex_machine);
8405 qemu_register_machine(&mainstone2_machine);
8406 #elif defined(TARGET_SH4)
8407 qemu_register_machine(&shix_machine);
8408 qemu_register_machine(&r2d_machine);
8409 #elif defined(TARGET_ALPHA)
8410 /* XXX: TODO */
8411 #elif defined(TARGET_M68K)
8412 qemu_register_machine(&mcf5208evb_machine);
8413 qemu_register_machine(&an5206_machine);
8414 qemu_register_machine(&dummy_m68k_machine);
8415 #elif defined(TARGET_CRIS)
8416 qemu_register_machine(&bareetraxfs_machine);
8417 #elif defined(TARGET_IA64)
8418 qemu_register_machine(&ipf_machine);
8419 #else
8420 #error unsupported CPU
8421 #endif
8424 #ifdef HAS_AUDIO
8425 struct soundhw soundhw[] = {
8426 #ifdef HAS_AUDIO_CHOICE
8427 #ifdef TARGET_I386
8429 "pcspk",
8430 "PC speaker",
8433 { .init_isa = pcspk_audio_init }
8435 #endif
8437 "sb16",
8438 "Creative Sound Blaster 16",
8441 { .init_isa = SB16_init }
8444 #ifdef CONFIG_ADLIB
8446 "adlib",
8447 #ifdef HAS_YMF262
8448 "Yamaha YMF262 (OPL3)",
8449 #else
8450 "Yamaha YM3812 (OPL2)",
8451 #endif
8454 { .init_isa = Adlib_init }
8456 #endif
8458 #ifdef CONFIG_GUS
8460 "gus",
8461 "Gravis Ultrasound GF1",
8464 { .init_isa = GUS_init }
8466 #endif
8468 #ifdef CONFIG_AC97
8470 "ac97",
8471 "Intel 82801AA AC97 Audio",
8474 { .init_pci = ac97_init }
8476 #endif
8479 "es1370",
8480 "ENSONIQ AudioPCI ES1370",
8483 { .init_pci = es1370_init }
8485 #endif
8487 { NULL, NULL, 0, 0, { NULL } }
8490 static void select_soundhw (const char *optarg)
8492 struct soundhw *c;
8494 if (*optarg == '?') {
8495 show_valid_cards:
8497 printf ("Valid sound card names (comma separated):\n");
8498 for (c = soundhw; c->name; ++c) {
8499 printf ("%-11s %s\n", c->name, c->descr);
8501 printf ("\n-soundhw all will enable all of the above\n");
8502 exit (*optarg != '?');
8504 else {
8505 size_t l;
8506 const char *p;
8507 char *e;
8508 int bad_card = 0;
8510 if (!strcmp (optarg, "all")) {
8511 for (c = soundhw; c->name; ++c) {
8512 c->enabled = 1;
8514 return;
8517 p = optarg;
8518 while (*p) {
8519 e = strchr (p, ',');
8520 l = !e ? strlen (p) : (size_t) (e - p);
8522 for (c = soundhw; c->name; ++c) {
8523 if (!strncmp (c->name, p, l)) {
8524 c->enabled = 1;
8525 break;
8529 if (!c->name) {
8530 if (l > 80) {
8531 fprintf (stderr,
8532 "Unknown sound card name (too big to show)\n");
8534 else {
8535 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8536 (int) l, p);
8538 bad_card = 1;
8540 p += l + (e != NULL);
8543 if (bad_card)
8544 goto show_valid_cards;
8547 #endif
8549 #ifdef _WIN32
8550 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8552 exit(STATUS_CONTROL_C_EXIT);
8553 return TRUE;
8555 #endif
8557 #define MAX_NET_CLIENTS 32
8559 static int saved_argc;
8560 static char **saved_argv;
8562 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8564 *argc = saved_argc;
8565 *argv = saved_argv;
8566 *opt_daemonize = daemonize;
8567 *opt_incoming = incoming;
8571 static int gethugepagesize(void)
8573 int ret, fd;
8574 char buf[4096];
8575 char *needle = "Hugepagesize:";
8576 char *size;
8577 unsigned long hugepagesize;
8579 fd = open("/proc/meminfo", O_RDONLY);
8580 if (fd < 0) {
8581 perror("open");
8582 exit(0);
8585 ret = read(fd, buf, sizeof(buf));
8586 if (ret < 0) {
8587 perror("read");
8588 exit(0);
8591 size = strstr(buf, needle);
8592 if (!size)
8593 return 0;
8594 size += strlen(needle);
8595 hugepagesize = strtol(size, NULL, 0);
8596 return hugepagesize;
8599 void cleanup_hugetlb(void)
8601 if (hugetlbfile)
8602 unlink(hugetlbfile);
8605 void *alloc_huge_area(unsigned long memory, const char *path)
8607 void *area;
8608 int fd;
8609 char *filename;
8610 char *tmpfile = "/kvm.XXXXXX";
8612 filename = qemu_malloc(4096);
8613 if (!filename)
8614 return NULL;
8616 memset(filename, 0, 4096);
8617 strncpy(filename, path, 4096 - strlen(tmpfile) - 1);
8618 strcat(filename, tmpfile);
8620 hpagesize = gethugepagesize() * 1024;
8621 if (!hpagesize)
8622 return NULL;
8624 mkstemp(filename);
8625 fd = open(filename, O_RDWR);
8626 if (fd < 0) {
8627 perror("open");
8628 hpagesize = 0;
8629 exit(0);
8631 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8633 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8634 if (area == MAP_FAILED) {
8635 perror("mmap");
8636 hpagesize = 0;
8637 exit(0);
8640 hugetlbfile = filename;
8641 atexit(cleanup_hugetlb);
8643 return area;
8646 void *qemu_alloc_physram(unsigned long memory)
8648 void *area = NULL;
8650 if (hugetlbpath)
8651 area = alloc_huge_area(memory, hugetlbpath);
8652 if (!area)
8653 area = qemu_vmalloc(memory);
8655 return area;
8658 int main(int argc, char **argv)
8660 #ifdef CONFIG_GDBSTUB
8661 int use_gdbstub;
8662 const char *gdbstub_port;
8663 #endif
8664 uint32_t boot_devices_bitmap = 0;
8665 int i;
8666 int snapshot, linux_boot, net_boot;
8667 const char *initrd_filename;
8668 const char *kernel_filename, *kernel_cmdline;
8669 const char *boot_devices = "";
8670 DisplayState *ds = &display_state;
8671 int cyls, heads, secs, translation;
8672 char net_clients[MAX_NET_CLIENTS][256];
8673 int nb_net_clients;
8674 int hda_index;
8675 int optind;
8676 const char *r, *optarg;
8677 CharDriverState *monitor_hd;
8678 char monitor_device[128];
8679 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8680 int vmchannel_device_index;
8681 char serial_devices[MAX_SERIAL_PORTS][128];
8682 int serial_device_index;
8683 char parallel_devices[MAX_PARALLEL_PORTS][128];
8684 int parallel_device_index;
8685 const char *loadvm = NULL;
8686 QEMUMachine *machine;
8687 const char *cpu_model;
8688 char usb_devices[MAX_USB_CMDLINE][128];
8689 int usb_devices_index;
8690 int fds[2];
8691 const char *pid_file = NULL;
8692 VLANState *vlan;
8694 saved_argc = argc;
8695 saved_argv = argv;
8697 LIST_INIT (&vm_change_state_head);
8698 #ifndef _WIN32
8700 struct sigaction act;
8701 sigfillset(&act.sa_mask);
8702 act.sa_flags = 0;
8703 act.sa_handler = SIG_IGN;
8704 sigaction(SIGPIPE, &act, NULL);
8706 #else
8707 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8708 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8709 QEMU to run on a single CPU */
8711 HANDLE h;
8712 DWORD mask, smask;
8713 int i;
8714 h = GetCurrentProcess();
8715 if (GetProcessAffinityMask(h, &mask, &smask)) {
8716 for(i = 0; i < 32; i++) {
8717 if (mask & (1 << i))
8718 break;
8720 if (i != 32) {
8721 mask = 1 << i;
8722 SetProcessAffinityMask(h, mask);
8726 #endif
8728 register_machines();
8729 machine = first_machine;
8730 cpu_model = NULL;
8731 initrd_filename = NULL;
8732 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8733 vga_ram_size = VGA_RAM_SIZE;
8734 #ifdef CONFIG_GDBSTUB
8735 use_gdbstub = 0;
8736 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8737 #endif
8738 snapshot = 0;
8739 nographic = 0;
8740 kernel_filename = NULL;
8741 kernel_cmdline = "";
8742 cyls = heads = secs = 0;
8743 translation = BIOS_ATA_TRANSLATION_AUTO;
8744 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8746 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8747 vmchannel_devices[i][0] = '\0';
8748 vmchannel_device_index = 0;
8750 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8751 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8752 serial_devices[i][0] = '\0';
8753 serial_device_index = 0;
8755 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8756 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8757 parallel_devices[i][0] = '\0';
8758 parallel_device_index = 0;
8760 usb_devices_index = 0;
8762 nb_net_clients = 0;
8763 nb_drives = 0;
8764 nb_drives_opt = 0;
8765 hda_index = -1;
8767 nb_nics = 0;
8768 /* default mac address of the first network interface */
8770 optind = 1;
8771 for(;;) {
8772 if (optind >= argc)
8773 break;
8774 r = argv[optind];
8775 if (r[0] != '-') {
8776 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8777 } else {
8778 const QEMUOption *popt;
8780 optind++;
8781 /* Treat --foo the same as -foo. */
8782 if (r[1] == '-')
8783 r++;
8784 popt = qemu_options;
8785 for(;;) {
8786 if (!popt->name) {
8787 fprintf(stderr, "%s: invalid option -- '%s'\n",
8788 argv[0], r);
8789 exit(1);
8791 if (!strcmp(popt->name, r + 1))
8792 break;
8793 popt++;
8795 if (popt->flags & HAS_ARG) {
8796 if (optind >= argc) {
8797 fprintf(stderr, "%s: option '%s' requires an argument\n",
8798 argv[0], r);
8799 exit(1);
8801 optarg = argv[optind++];
8802 } else {
8803 optarg = NULL;
8806 switch(popt->index) {
8807 case QEMU_OPTION_M:
8808 machine = find_machine(optarg);
8809 if (!machine) {
8810 QEMUMachine *m;
8811 printf("Supported machines are:\n");
8812 for(m = first_machine; m != NULL; m = m->next) {
8813 printf("%-10s %s%s\n",
8814 m->name, m->desc,
8815 m == first_machine ? " (default)" : "");
8817 exit(*optarg != '?');
8819 break;
8820 case QEMU_OPTION_cpu:
8821 /* hw initialization will check this */
8822 if (*optarg == '?') {
8823 /* XXX: implement xxx_cpu_list for targets that still miss it */
8824 #if defined(cpu_list)
8825 cpu_list(stdout, &fprintf);
8826 #endif
8827 exit(0);
8828 } else {
8829 cpu_model = optarg;
8831 break;
8832 case QEMU_OPTION_initrd:
8833 initrd_filename = optarg;
8834 break;
8835 case QEMU_OPTION_hda:
8836 if (cyls == 0)
8837 hda_index = drive_add(optarg, HD_ALIAS, 0);
8838 else
8839 hda_index = drive_add(optarg, HD_ALIAS
8840 ",cyls=%d,heads=%d,secs=%d%s",
8841 0, cyls, heads, secs,
8842 translation == BIOS_ATA_TRANSLATION_LBA ?
8843 ",trans=lba" :
8844 translation == BIOS_ATA_TRANSLATION_NONE ?
8845 ",trans=none" : "");
8846 break;
8847 case QEMU_OPTION_hdb:
8848 case QEMU_OPTION_hdc:
8849 case QEMU_OPTION_hdd:
8850 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8851 break;
8852 case QEMU_OPTION_drive:
8853 drive_add(NULL, "%s", optarg);
8854 break;
8855 case QEMU_OPTION_mtdblock:
8856 drive_add(optarg, MTD_ALIAS);
8857 break;
8858 case QEMU_OPTION_sd:
8859 drive_add(optarg, SD_ALIAS);
8860 break;
8861 case QEMU_OPTION_pflash:
8862 drive_add(optarg, PFLASH_ALIAS);
8863 break;
8864 case QEMU_OPTION_snapshot:
8865 snapshot = 1;
8866 break;
8867 case QEMU_OPTION_hdachs:
8869 const char *p;
8870 p = optarg;
8871 cyls = strtol(p, (char **)&p, 0);
8872 if (cyls < 1 || cyls > 16383)
8873 goto chs_fail;
8874 if (*p != ',')
8875 goto chs_fail;
8876 p++;
8877 heads = strtol(p, (char **)&p, 0);
8878 if (heads < 1 || heads > 16)
8879 goto chs_fail;
8880 if (*p != ',')
8881 goto chs_fail;
8882 p++;
8883 secs = strtol(p, (char **)&p, 0);
8884 if (secs < 1 || secs > 63)
8885 goto chs_fail;
8886 if (*p == ',') {
8887 p++;
8888 if (!strcmp(p, "none"))
8889 translation = BIOS_ATA_TRANSLATION_NONE;
8890 else if (!strcmp(p, "lba"))
8891 translation = BIOS_ATA_TRANSLATION_LBA;
8892 else if (!strcmp(p, "auto"))
8893 translation = BIOS_ATA_TRANSLATION_AUTO;
8894 else
8895 goto chs_fail;
8896 } else if (*p != '\0') {
8897 chs_fail:
8898 fprintf(stderr, "qemu: invalid physical CHS format\n");
8899 exit(1);
8901 if (hda_index != -1)
8902 snprintf(drives_opt[hda_index].opt,
8903 sizeof(drives_opt[hda_index].opt),
8904 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8905 0, cyls, heads, secs,
8906 translation == BIOS_ATA_TRANSLATION_LBA ?
8907 ",trans=lba" :
8908 translation == BIOS_ATA_TRANSLATION_NONE ?
8909 ",trans=none" : "");
8911 break;
8912 case QEMU_OPTION_nographic:
8913 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8914 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8915 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8916 nographic = 1;
8917 break;
8918 case QEMU_OPTION_portrait:
8919 graphic_rotate = 1;
8920 break;
8921 case QEMU_OPTION_kernel:
8922 kernel_filename = optarg;
8923 break;
8924 case QEMU_OPTION_append:
8925 kernel_cmdline = optarg;
8926 break;
8927 case QEMU_OPTION_cdrom:
8928 drive_add(optarg, CDROM_ALIAS);
8929 break;
8930 case QEMU_OPTION_boot:
8931 boot_devices = optarg;
8932 /* We just do some generic consistency checks */
8934 /* Could easily be extended to 64 devices if needed */
8935 const char *p;
8937 boot_devices_bitmap = 0;
8938 for (p = boot_devices; *p != '\0'; p++) {
8939 /* Allowed boot devices are:
8940 * a b : floppy disk drives
8941 * c ... f : IDE disk drives
8942 * g ... m : machine implementation dependant drives
8943 * n ... p : network devices
8944 * It's up to each machine implementation to check
8945 * if the given boot devices match the actual hardware
8946 * implementation and firmware features.
8948 if (*p < 'a' || *p > 'q') {
8949 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8950 exit(1);
8952 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8953 fprintf(stderr,
8954 "Boot device '%c' was given twice\n",*p);
8955 exit(1);
8957 boot_devices_bitmap |= 1 << (*p - 'a');
8960 break;
8961 case QEMU_OPTION_fda:
8962 case QEMU_OPTION_fdb:
8963 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8964 break;
8965 #ifdef TARGET_I386
8966 case QEMU_OPTION_no_fd_bootchk:
8967 fd_bootchk = 0;
8968 break;
8969 #endif
8970 case QEMU_OPTION_no_code_copy:
8971 code_copy_enabled = 0;
8972 break;
8973 case QEMU_OPTION_net:
8974 if (nb_net_clients >= MAX_NET_CLIENTS) {
8975 fprintf(stderr, "qemu: too many network clients\n");
8976 exit(1);
8978 pstrcpy(net_clients[nb_net_clients],
8979 sizeof(net_clients[0]),
8980 optarg);
8981 nb_net_clients++;
8982 break;
8983 #ifdef CONFIG_SLIRP
8984 case QEMU_OPTION_tftp:
8985 tftp_prefix = optarg;
8986 break;
8987 case QEMU_OPTION_bootp:
8988 bootp_filename = optarg;
8989 break;
8990 #ifndef _WIN32
8991 case QEMU_OPTION_smb:
8992 net_slirp_smb(optarg);
8993 break;
8994 #endif
8995 case QEMU_OPTION_redir:
8996 net_slirp_redir(optarg);
8997 break;
8998 #endif
8999 #ifdef HAS_AUDIO
9000 case QEMU_OPTION_audio_help:
9001 AUD_help ();
9002 exit (0);
9003 break;
9004 case QEMU_OPTION_soundhw:
9005 select_soundhw (optarg);
9006 break;
9007 #endif
9008 case QEMU_OPTION_h:
9009 help(0);
9010 break;
9011 case QEMU_OPTION_m:
9012 ram_size = (int64_t)atoi(optarg) * 1024 * 1024;
9013 if (ram_size <= 0)
9014 help(1);
9015 if (ram_size > PHYS_RAM_MAX_SIZE) {
9016 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
9017 PHYS_RAM_MAX_SIZE / (1024 * 1024));
9018 exit(1);
9020 break;
9021 case QEMU_OPTION_d:
9023 int mask;
9024 CPULogItem *item;
9026 mask = cpu_str_to_log_mask(optarg);
9027 if (!mask) {
9028 printf("Log items (comma separated):\n");
9029 for(item = cpu_log_items; item->mask != 0; item++) {
9030 printf("%-10s %s\n", item->name, item->help);
9032 exit(1);
9034 cpu_set_log(mask);
9036 break;
9037 #ifdef CONFIG_GDBSTUB
9038 case QEMU_OPTION_s:
9039 use_gdbstub = 1;
9040 break;
9041 case QEMU_OPTION_p:
9042 gdbstub_port = optarg;
9043 break;
9044 #endif
9045 case QEMU_OPTION_L:
9046 bios_dir = optarg;
9047 break;
9048 case QEMU_OPTION_bios:
9049 bios_name = optarg;
9050 break;
9051 case QEMU_OPTION_S:
9052 autostart = 0;
9053 break;
9054 case QEMU_OPTION_k:
9055 keyboard_layout = optarg;
9056 break;
9057 case QEMU_OPTION_localtime:
9058 rtc_utc = 0;
9059 break;
9060 case QEMU_OPTION_cirrusvga:
9061 cirrus_vga_enabled = 1;
9062 vmsvga_enabled = 0;
9063 break;
9064 case QEMU_OPTION_vmsvga:
9065 cirrus_vga_enabled = 0;
9066 vmsvga_enabled = 1;
9067 break;
9068 case QEMU_OPTION_std_vga:
9069 cirrus_vga_enabled = 0;
9070 vmsvga_enabled = 0;
9071 break;
9072 case QEMU_OPTION_g:
9074 const char *p;
9075 int w, h, depth;
9076 p = optarg;
9077 w = strtol(p, (char **)&p, 10);
9078 if (w <= 0) {
9079 graphic_error:
9080 fprintf(stderr, "qemu: invalid resolution or depth\n");
9081 exit(1);
9083 if (*p != 'x')
9084 goto graphic_error;
9085 p++;
9086 h = strtol(p, (char **)&p, 10);
9087 if (h <= 0)
9088 goto graphic_error;
9089 if (*p == 'x') {
9090 p++;
9091 depth = strtol(p, (char **)&p, 10);
9092 if (depth != 8 && depth != 15 && depth != 16 &&
9093 depth != 24 && depth != 32)
9094 goto graphic_error;
9095 } else if (*p == '\0') {
9096 depth = graphic_depth;
9097 } else {
9098 goto graphic_error;
9101 graphic_width = w;
9102 graphic_height = h;
9103 graphic_depth = depth;
9105 break;
9106 case QEMU_OPTION_echr:
9108 char *r;
9109 term_escape_char = strtol(optarg, &r, 0);
9110 if (r == optarg)
9111 printf("Bad argument to echr\n");
9112 break;
9114 case QEMU_OPTION_monitor:
9115 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
9116 break;
9117 case QEMU_OPTION_balloon:
9118 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9119 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9120 exit(1);
9122 if (balloon_used) {
9123 fprintf(stderr, "qemu: only one balloon device can be used\n");
9124 exit(1);
9126 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
9127 vmchannel_device_index++;
9128 balloon_used = 1;
9129 break;
9130 case QEMU_OPTION_vmchannel:
9131 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
9132 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
9133 exit(1);
9135 pstrcpy(vmchannel_devices[vmchannel_device_index],
9136 sizeof(vmchannel_devices[0]), optarg);
9137 vmchannel_device_index++;
9138 break;
9139 case QEMU_OPTION_serial:
9140 if (serial_device_index >= MAX_SERIAL_PORTS) {
9141 fprintf(stderr, "qemu: too many serial ports\n");
9142 exit(1);
9144 pstrcpy(serial_devices[serial_device_index],
9145 sizeof(serial_devices[0]), optarg);
9146 serial_device_index++;
9147 break;
9148 case QEMU_OPTION_parallel:
9149 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9150 fprintf(stderr, "qemu: too many parallel ports\n");
9151 exit(1);
9153 pstrcpy(parallel_devices[parallel_device_index],
9154 sizeof(parallel_devices[0]), optarg);
9155 parallel_device_index++;
9156 break;
9157 case QEMU_OPTION_loadvm:
9158 loadvm = optarg;
9159 break;
9160 case QEMU_OPTION_incoming:
9161 incoming = optarg;
9162 break;
9163 case QEMU_OPTION_full_screen:
9164 full_screen = 1;
9165 break;
9166 #ifdef CONFIG_SDL
9167 case QEMU_OPTION_no_frame:
9168 no_frame = 1;
9169 break;
9170 case QEMU_OPTION_alt_grab:
9171 alt_grab = 1;
9172 break;
9173 case QEMU_OPTION_no_quit:
9174 no_quit = 1;
9175 break;
9176 #endif
9177 case QEMU_OPTION_pidfile:
9178 pid_file = optarg;
9179 break;
9180 #ifdef TARGET_I386
9181 case QEMU_OPTION_win2k_hack:
9182 win2k_install_hack = 1;
9183 break;
9184 #endif
9185 #ifdef USE_KQEMU
9186 case QEMU_OPTION_no_kqemu:
9187 kqemu_allowed = 0;
9188 break;
9189 case QEMU_OPTION_kernel_kqemu:
9190 kqemu_allowed = 2;
9191 break;
9192 #endif
9193 #ifdef USE_KVM
9194 case QEMU_OPTION_no_kvm:
9195 kvm_allowed = 0;
9196 break;
9197 case QEMU_OPTION_no_kvm_irqchip: {
9198 extern int kvm_irqchip;
9199 kvm_irqchip = 0;
9200 break;
9202 #endif
9203 case QEMU_OPTION_usb:
9204 usb_enabled = 1;
9205 break;
9206 case QEMU_OPTION_usbdevice:
9207 usb_enabled = 1;
9208 if (usb_devices_index >= MAX_USB_CMDLINE) {
9209 fprintf(stderr, "Too many USB devices\n");
9210 exit(1);
9212 pstrcpy(usb_devices[usb_devices_index],
9213 sizeof(usb_devices[usb_devices_index]),
9214 optarg);
9215 usb_devices_index++;
9216 break;
9217 case QEMU_OPTION_smp:
9218 smp_cpus = atoi(optarg);
9219 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9220 fprintf(stderr, "Invalid number of CPUs\n");
9221 exit(1);
9223 break;
9224 case QEMU_OPTION_vnc:
9225 vnc_display = optarg;
9226 break;
9227 case QEMU_OPTION_no_acpi:
9228 acpi_enabled = 0;
9229 break;
9230 case QEMU_OPTION_no_reboot:
9231 no_reboot = 1;
9232 break;
9233 case QEMU_OPTION_show_cursor:
9234 cursor_hide = 0;
9235 break;
9236 case QEMU_OPTION_daemonize:
9237 daemonize = 1;
9238 break;
9239 case QEMU_OPTION_option_rom:
9240 if (nb_option_roms >= MAX_OPTION_ROMS) {
9241 fprintf(stderr, "Too many option ROMs\n");
9242 exit(1);
9244 option_rom[nb_option_roms] = optarg;
9245 nb_option_roms++;
9246 break;
9247 case QEMU_OPTION_semihosting:
9248 semihosting_enabled = 1;
9249 break;
9250 case QEMU_OPTION_tdf:
9251 time_drift_fix = 1;
9252 break;
9253 case QEMU_OPTION_kvm_shadow_memory:
9254 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9255 break;
9256 case QEMU_OPTION_hugetlbpath:
9257 hugetlbpath = optarg;
9258 break;
9259 case QEMU_OPTION_name:
9260 qemu_name = optarg;
9261 break;
9262 #ifdef TARGET_SPARC
9263 case QEMU_OPTION_prom_env:
9264 if (nb_prom_envs >= MAX_PROM_ENVS) {
9265 fprintf(stderr, "Too many prom variables\n");
9266 exit(1);
9268 prom_envs[nb_prom_envs] = optarg;
9269 nb_prom_envs++;
9270 break;
9271 #endif
9272 case QEMU_OPTION_cpu_vendor:
9273 cpu_vendor_string = optarg;
9274 break;
9275 #ifdef TARGET_ARM
9276 case QEMU_OPTION_old_param:
9277 old_param = 1;
9278 break;
9279 #endif
9280 case QEMU_OPTION_clock:
9281 configure_alarms(optarg);
9282 break;
9283 case QEMU_OPTION_startdate:
9285 struct tm tm;
9286 if (!strcmp(optarg, "now")) {
9287 rtc_start_date = -1;
9288 } else {
9289 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9290 &tm.tm_year,
9291 &tm.tm_mon,
9292 &tm.tm_mday,
9293 &tm.tm_hour,
9294 &tm.tm_min,
9295 &tm.tm_sec) == 6) {
9296 /* OK */
9297 } else if (sscanf(optarg, "%d-%d-%d",
9298 &tm.tm_year,
9299 &tm.tm_mon,
9300 &tm.tm_mday) == 3) {
9301 tm.tm_hour = 0;
9302 tm.tm_min = 0;
9303 tm.tm_sec = 0;
9304 } else {
9305 goto date_fail;
9307 tm.tm_year -= 1900;
9308 tm.tm_mon--;
9309 rtc_start_date = mktimegm(&tm);
9310 if (rtc_start_date == -1) {
9311 date_fail:
9312 fprintf(stderr, "Invalid date format. Valid format are:\n"
9313 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9314 exit(1);
9318 break;
9323 #ifndef _WIN32
9324 if (daemonize) {
9325 pid_t pid;
9327 if (pipe(fds) == -1)
9328 exit(1);
9330 pid = fork();
9331 if (pid > 0) {
9332 uint8_t status;
9333 ssize_t len;
9335 close(fds[1]);
9337 again:
9338 len = read(fds[0], &status, 1);
9339 if (len == -1 && (errno == EINTR))
9340 goto again;
9342 if (len != 1)
9343 exit(1);
9344 else if (status == 1) {
9345 fprintf(stderr, "Could not acquire pidfile\n");
9346 exit(1);
9347 } else
9348 exit(0);
9349 } else if (pid < 0)
9350 exit(1);
9352 setsid();
9354 pid = fork();
9355 if (pid > 0)
9356 exit(0);
9357 else if (pid < 0)
9358 exit(1);
9360 umask(027);
9362 signal(SIGTSTP, SIG_IGN);
9363 signal(SIGTTOU, SIG_IGN);
9364 signal(SIGTTIN, SIG_IGN);
9366 #endif
9368 #if USE_KVM
9369 if (kvm_enabled()) {
9370 if (kvm_qemu_init() < 0) {
9371 extern int kvm_allowed;
9372 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9373 #ifdef NO_CPU_EMULATION
9374 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9375 exit(1);
9376 #endif
9377 kvm_allowed = 0;
9380 #endif
9382 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9383 if (daemonize) {
9384 uint8_t status = 1;
9385 write(fds[1], &status, 1);
9386 } else
9387 fprintf(stderr, "Could not acquire pid file\n");
9388 exit(1);
9391 #ifdef USE_KQEMU
9392 if (smp_cpus > 1)
9393 kqemu_allowed = 0;
9394 #endif
9395 linux_boot = (kernel_filename != NULL);
9396 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9398 /* XXX: this should not be: some embedded targets just have flash */
9399 if (!linux_boot && net_boot == 0 &&
9400 nb_drives_opt == 0)
9401 help(1);
9403 /* boot to floppy or the default cd if no hard disk defined yet */
9404 if (!boot_devices[0]) {
9405 boot_devices = "cad";
9407 setvbuf(stdout, NULL, _IOLBF, 0);
9409 init_timers();
9410 init_timer_alarm();
9411 qemu_aio_init();
9413 #ifdef _WIN32
9414 socket_init();
9415 #endif
9417 /* init network clients */
9418 if (nb_net_clients == 0) {
9419 /* if no clients, we use a default config */
9420 pstrcpy(net_clients[0], sizeof(net_clients[0]),
9421 "nic");
9422 pstrcpy(net_clients[1], sizeof(net_clients[0]),
9423 "user");
9424 nb_net_clients = 2;
9427 for(i = 0;i < nb_net_clients; i++) {
9428 if (net_client_init(net_clients[i]) < 0)
9429 exit(1);
9431 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9432 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9433 continue;
9434 if (vlan->nb_guest_devs == 0) {
9435 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9436 exit(1);
9438 if (vlan->nb_host_devs == 0)
9439 fprintf(stderr,
9440 "Warning: vlan %d is not connected to host network\n",
9441 vlan->id);
9444 #ifdef TARGET_I386
9445 /* XXX: this should be moved in the PC machine instantiation code */
9446 if (net_boot != 0) {
9447 int netroms = 0;
9448 for (i = 0; i < nb_nics && i < 4; i++) {
9449 const char *model = nd_table[i].model;
9450 char buf[1024];
9451 if (net_boot & (1 << i)) {
9452 if (model == NULL)
9453 model = "rtl8139";
9454 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9455 if (get_image_size(buf) > 0) {
9456 if (nb_option_roms >= MAX_OPTION_ROMS) {
9457 fprintf(stderr, "Too many option ROMs\n");
9458 exit(1);
9460 option_rom[nb_option_roms] = strdup(buf);
9461 nb_option_roms++;
9462 netroms++;
9466 if (netroms == 0) {
9467 fprintf(stderr, "No valid PXE rom found for network device\n");
9468 exit(1);
9471 #endif
9473 /* init the memory */
9474 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9476 /* Initialize kvm */
9477 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9478 #define KVM_EXTRA_PAGES 3
9479 #else
9480 #define KVM_EXTRA_PAGES 0
9481 #endif
9482 if (kvm_enabled()) {
9483 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9484 if (kvm_qemu_create_context() < 0) {
9485 fprintf(stderr, "Could not create KVM context\n");
9486 exit(1);
9488 #ifdef KVM_CAP_USER_MEMORY
9490 int ret;
9492 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9493 if (ret) {
9494 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9495 if (!phys_ram_base) {
9496 fprintf(stderr, "Could not allocate physical memory\n");
9497 exit(1);
9501 #endif
9502 } else {
9503 phys_ram_base = qemu_vmalloc(phys_ram_size);
9504 if (!phys_ram_base) {
9505 fprintf(stderr, "Could not allocate physical memory\n");
9506 exit(1);
9510 bdrv_init();
9512 /* we always create the cdrom drive, even if no disk is there */
9514 if (nb_drives_opt < MAX_DRIVES)
9515 drive_add(NULL, CDROM_ALIAS);
9517 /* we always create at least one floppy */
9519 if (nb_drives_opt < MAX_DRIVES)
9520 drive_add(NULL, FD_ALIAS, 0);
9522 /* we always create one sd slot, even if no card is in it */
9524 if (nb_drives_opt < MAX_DRIVES)
9525 drive_add(NULL, SD_ALIAS);
9527 /* open the virtual block devices */
9529 for(i = 0; i < nb_drives_opt; i++)
9530 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9531 exit(1);
9533 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9534 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9536 init_ioports();
9538 /* terminal init */
9539 memset(&display_state, 0, sizeof(display_state));
9540 if (nographic) {
9541 /* nearly nothing to do */
9542 dumb_display_init(ds);
9543 } else if (vnc_display != NULL) {
9544 vnc_display_init(ds);
9545 if (vnc_display_open(ds, vnc_display) < 0)
9546 exit(1);
9547 } else {
9548 #if defined(CONFIG_SDL)
9549 sdl_display_init(ds, full_screen, no_frame);
9550 #elif defined(CONFIG_COCOA)
9551 cocoa_display_init(ds, full_screen);
9552 #else
9553 dumb_display_init(ds);
9554 #endif
9557 /* Maintain compatibility with multiple stdio monitors */
9558 if (!strcmp(monitor_device,"stdio")) {
9559 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9560 if (!strcmp(serial_devices[i],"mon:stdio")) {
9561 monitor_device[0] = '\0';
9562 break;
9563 } else if (!strcmp(serial_devices[i],"stdio")) {
9564 monitor_device[0] = '\0';
9565 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
9566 break;
9570 if (monitor_device[0] != '\0') {
9571 monitor_hd = qemu_chr_open(monitor_device);
9572 if (!monitor_hd) {
9573 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9574 exit(1);
9576 monitor_init(monitor_hd, !nographic);
9579 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9580 const char *devname = vmchannel_devices[i];
9581 if (devname[0] != '\0' && strcmp(devname, "none")) {
9582 int devid;
9583 char *termn;
9585 if (strstart(devname, "di:", &devname)) {
9586 devid = strtol(devname, &termn, 16);
9587 devname = termn + 1;
9589 else {
9590 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9591 devname);
9592 exit(1);
9594 vmchannel_hds[i] = qemu_chr_open(devname);
9595 if (!vmchannel_hds[i]) {
9596 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9597 devname);
9598 exit(1);
9600 vmchannel_init(vmchannel_hds[i], devid, i);
9604 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9605 const char *devname = serial_devices[i];
9606 if (devname[0] != '\0' && strcmp(devname, "none")) {
9607 serial_hds[i] = qemu_chr_open(devname);
9608 if (!serial_hds[i]) {
9609 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9610 devname);
9611 exit(1);
9613 if (strstart(devname, "vc", 0))
9614 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9618 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9619 const char *devname = parallel_devices[i];
9620 if (devname[0] != '\0' && strcmp(devname, "none")) {
9621 parallel_hds[i] = qemu_chr_open(devname);
9622 if (!parallel_hds[i]) {
9623 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9624 devname);
9625 exit(1);
9627 if (strstart(devname, "vc", 0))
9628 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9632 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9633 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9635 /* init USB devices */
9636 if (usb_enabled) {
9637 for(i = 0; i < usb_devices_index; i++) {
9638 if (usb_device_add(usb_devices[i]) < 0) {
9639 fprintf(stderr, "Warning: could not add USB device %s\n",
9640 usb_devices[i]);
9645 if (display_state.dpy_refresh) {
9646 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9647 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9650 if (kvm_enabled())
9651 kvm_init_ap();
9653 #ifdef CONFIG_GDBSTUB
9654 if (use_gdbstub) {
9655 /* XXX: use standard host:port notation and modify options
9656 accordingly. */
9657 if (gdbserver_start(gdbstub_port) < 0) {
9658 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9659 gdbstub_port);
9660 exit(1);
9663 #endif
9664 if (loadvm)
9665 do_loadvm(loadvm);
9667 if (incoming) {
9668 int rc;
9670 rc = migrate_incoming(incoming);
9671 if (rc != 0) {
9672 fprintf(stderr, "Migration failed rc=%d\n", rc);
9673 exit(rc);
9678 /* XXX: simplify init */
9679 read_passwords();
9680 if (autostart) {
9681 vm_start();
9685 if (daemonize) {
9686 uint8_t status = 0;
9687 ssize_t len;
9688 int fd;
9690 again1:
9691 len = write(fds[1], &status, 1);
9692 if (len == -1 && (errno == EINTR))
9693 goto again1;
9695 if (len != 1)
9696 exit(1);
9698 chdir("/");
9699 TFR(fd = open("/dev/null", O_RDWR));
9700 if (fd == -1)
9701 exit(1);
9703 dup2(fd, 0);
9704 dup2(fd, 1);
9705 dup2(fd, 2);
9707 close(fd);
9710 main_loop();
9711 quit_timers();
9713 #if !defined(_WIN32)
9714 /* close network clients */
9715 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9716 VLANClientState *vc;
9718 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9719 if (vc->fd_read == tap_receive) {
9720 char ifname[64];
9721 TAPState *s = vc->opaque;
9723 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9724 s->down_script[0])
9725 launch_script(s->down_script, ifname, s->fd);
9729 #endif
9730 return 0;