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