kvm: bios: detect vapic calls to uninitialized vapic
[qemu-kvm/fedora.git] / vl.c
blob2dc131120f12f2dd32685f395eb2f4278e625d8c
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.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 #if defined(CONFIG_VDE)
112 #include <libvdeplug.h>
113 #endif
115 #ifdef _WIN32
116 #include <malloc.h>
117 #include <sys/timeb.h>
118 #include <mmsystem.h>
119 #define getopt_long_only getopt_long
120 #define memalign(align, size) malloc(size)
121 #endif
123 #include "qemu_socket.h"
125 #ifdef CONFIG_SDL
126 #ifdef __APPLE__
127 #include <SDL/SDL.h>
128 #endif
129 #endif /* CONFIG_SDL */
131 #ifdef CONFIG_COCOA
132 #undef main
133 #define main qemu_main
134 #endif /* CONFIG_COCOA */
136 #include "disas.h"
138 #include "exec-all.h"
140 #include "qemu-kvm.h"
142 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
143 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
144 #ifdef __sun__
145 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
146 #else
147 #define SMBD_COMMAND "/usr/sbin/smbd"
148 #endif
150 //#define DEBUG_UNUSED_IOPORT
151 //#define DEBUG_IOPORT
153 #ifdef TARGET_PPC
154 #define DEFAULT_RAM_SIZE 144
155 #else
156 #define DEFAULT_RAM_SIZE 128
157 #endif
158 /* in ms */
159 #define GUI_REFRESH_INTERVAL 30
161 /* Max number of USB devices that can be specified on the commandline. */
162 #define MAX_USB_CMDLINE 8
164 /* XXX: use a two level table to limit memory usage */
165 #define MAX_IOPORTS 65536
167 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
168 const char *bios_name = NULL;
169 void *ioport_opaque[MAX_IOPORTS];
170 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
171 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
172 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
173 to store the VM snapshots */
174 DriveInfo drives_table[MAX_DRIVES+1];
175 int nb_drives;
176 int extboot_drive = -1;
177 /* point to the block driver where the snapshots are managed */
178 BlockDriverState *bs_snapshots;
179 int vga_ram_size;
180 static DisplayState display_state;
181 int nographic;
182 int curses;
183 const char* keyboard_layout = NULL;
184 int64_t ticks_per_sec;
185 ram_addr_t ram_size;
186 int pit_min_timer_count = 0;
187 int nb_nics;
188 NICInfo nd_table[MAX_NICS];
189 int vm_running;
190 static int rtc_utc = 1;
191 static int rtc_date_offset = -1; /* -1 means no change */
192 int cirrus_vga_enabled = 1;
193 int vmsvga_enabled = 0;
194 #ifdef TARGET_SPARC
195 int graphic_width = 1024;
196 int graphic_height = 768;
197 int graphic_depth = 8;
198 #else
199 int graphic_width = 800;
200 int graphic_height = 600;
201 int graphic_depth = 15;
202 #endif
203 int full_screen = 0;
204 int no_frame = 0;
205 int no_quit = 0;
206 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
207 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
208 #ifdef TARGET_I386
209 int win2k_install_hack = 0;
210 #endif
211 int usb_enabled = 0;
212 static VLANState *first_vlan;
213 int smp_cpus = 1;
214 const char *vnc_display;
215 #if defined(TARGET_SPARC)
216 #define MAX_CPUS 16
217 #elif defined(TARGET_I386)
218 #define MAX_CPUS 255
219 #elif defined(TARGET_IA64)
220 #define MAX_CPUS 4
221 #else
222 #define MAX_CPUS 1
223 #endif
224 int acpi_enabled = 1;
225 int fd_bootchk = 1;
226 int no_reboot = 0;
227 int no_shutdown = 0;
228 int cursor_hide = 1;
229 int graphic_rotate = 0;
230 int daemonize = 0;
231 const char *incoming;
232 const char *option_rom[MAX_OPTION_ROMS];
233 int nb_option_roms;
234 int semihosting_enabled = 0;
235 int autostart = 1;
236 int time_drift_fix = 0;
237 unsigned int kvm_shadow_memory = 0;
238 const char *mem_path = NULL;
239 int hpagesize = 0;
240 const char *cpu_vendor_string;
241 #ifdef TARGET_ARM
242 int old_param = 0;
243 #endif
244 const char *qemu_name;
245 int alt_grab = 0;
246 #ifdef TARGET_SPARC
247 unsigned int nb_prom_envs = 0;
248 const char *prom_envs[MAX_PROM_ENVS];
249 #endif
250 int nb_drives_opt;
251 struct drive_opt drives_opt[MAX_DRIVES];
253 static CPUState *cur_cpu;
254 static CPUState *next_cpu;
255 static int event_pending = 1;
256 /* Conversion factor from emulated instructions to virtual clock ticks. */
257 static int icount_time_shift;
258 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
259 #define MAX_ICOUNT_SHIFT 10
260 /* Compensate for varying guest execution speed. */
261 static int64_t qemu_icount_bias;
262 QEMUTimer *icount_rt_timer;
263 QEMUTimer *icount_vm_timer;
265 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
267 /* KVM runs the main loop in a separate thread. If we update one of the lists
268 * that are polled before or after select(), we need to make sure to break out
269 * of the select() to ensure the new item is serviced.
271 static void main_loop_break(void)
273 if (kvm_enabled())
274 qemu_kvm_notify_work();
277 /***********************************************************/
278 /* x86 ISA bus support */
280 target_phys_addr_t isa_mem_base = 0;
281 PicState2 *isa_pic;
283 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
284 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
286 static uint32_t ioport_read(int index, uint32_t address)
288 static IOPortReadFunc *default_func[3] = {
289 default_ioport_readb,
290 default_ioport_readw,
291 default_ioport_readl
293 IOPortReadFunc *func = ioport_read_table[index][address];
294 if (!func)
295 func = default_func[index];
296 return func(ioport_opaque[address], address);
299 static void ioport_write(int index, uint32_t address, uint32_t data)
301 static IOPortWriteFunc *default_func[3] = {
302 default_ioport_writeb,
303 default_ioport_writew,
304 default_ioport_writel
306 IOPortWriteFunc *func = ioport_write_table[index][address];
307 if (!func)
308 func = default_func[index];
309 func(ioport_opaque[address], address, data);
312 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
314 #ifdef DEBUG_UNUSED_IOPORT
315 fprintf(stderr, "unused inb: port=0x%04x\n", address);
316 #endif
317 return 0xff;
320 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
322 #ifdef DEBUG_UNUSED_IOPORT
323 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
324 #endif
327 /* default is to make two byte accesses */
328 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
330 uint32_t data;
331 data = ioport_read(0, address);
332 address = (address + 1) & (MAX_IOPORTS - 1);
333 data |= ioport_read(0, address) << 8;
334 return data;
337 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
339 ioport_write(0, address, data & 0xff);
340 address = (address + 1) & (MAX_IOPORTS - 1);
341 ioport_write(0, address, (data >> 8) & 0xff);
344 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
346 #ifdef DEBUG_UNUSED_IOPORT
347 fprintf(stderr, "unused inl: port=0x%04x\n", address);
348 #endif
349 return 0xffffffff;
352 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
354 #ifdef DEBUG_UNUSED_IOPORT
355 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
356 #endif
359 /* size is the word size in byte */
360 int register_ioport_read(int start, int length, int size,
361 IOPortReadFunc *func, void *opaque)
363 int i, bsize;
365 if (size == 1) {
366 bsize = 0;
367 } else if (size == 2) {
368 bsize = 1;
369 } else if (size == 4) {
370 bsize = 2;
371 } else {
372 hw_error("register_ioport_read: invalid size");
373 return -1;
375 for(i = start; i < start + length; i += size) {
376 ioport_read_table[bsize][i] = func;
377 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
378 hw_error("register_ioport_read: invalid opaque");
379 ioport_opaque[i] = opaque;
381 return 0;
384 /* size is the word size in byte */
385 int register_ioport_write(int start, int length, int size,
386 IOPortWriteFunc *func, void *opaque)
388 int i, bsize;
390 if (size == 1) {
391 bsize = 0;
392 } else if (size == 2) {
393 bsize = 1;
394 } else if (size == 4) {
395 bsize = 2;
396 } else {
397 hw_error("register_ioport_write: invalid size");
398 return -1;
400 for(i = start; i < start + length; i += size) {
401 ioport_write_table[bsize][i] = func;
402 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
403 hw_error("register_ioport_write: invalid opaque");
404 ioport_opaque[i] = opaque;
406 return 0;
409 void isa_unassign_ioport(int start, int length)
411 int i;
413 for(i = start; i < start + length; i++) {
414 ioport_read_table[0][i] = default_ioport_readb;
415 ioport_read_table[1][i] = default_ioport_readw;
416 ioport_read_table[2][i] = default_ioport_readl;
418 ioport_write_table[0][i] = default_ioport_writeb;
419 ioport_write_table[1][i] = default_ioport_writew;
420 ioport_write_table[2][i] = default_ioport_writel;
422 ioport_opaque[i] = NULL;
426 /***********************************************************/
428 void cpu_outb(CPUState *env, int addr, int val)
430 #ifdef DEBUG_IOPORT
431 if (loglevel & CPU_LOG_IOPORT)
432 fprintf(logfile, "outb: %04x %02x\n", addr, val);
433 #endif
434 ioport_write(0, addr, val);
435 #ifdef USE_KQEMU
436 if (env)
437 env->last_io_time = cpu_get_time_fast();
438 #endif
441 void cpu_outw(CPUState *env, int addr, int val)
443 #ifdef DEBUG_IOPORT
444 if (loglevel & CPU_LOG_IOPORT)
445 fprintf(logfile, "outw: %04x %04x\n", addr, val);
446 #endif
447 ioport_write(1, addr, val);
448 #ifdef USE_KQEMU
449 if (env)
450 env->last_io_time = cpu_get_time_fast();
451 #endif
454 void cpu_outl(CPUState *env, int addr, int val)
456 #ifdef DEBUG_IOPORT
457 if (loglevel & CPU_LOG_IOPORT)
458 fprintf(logfile, "outl: %04x %08x\n", addr, val);
459 #endif
460 ioport_write(2, addr, val);
461 #ifdef USE_KQEMU
462 if (env)
463 env->last_io_time = cpu_get_time_fast();
464 #endif
467 int cpu_inb(CPUState *env, int addr)
469 int val;
470 val = ioport_read(0, addr);
471 #ifdef DEBUG_IOPORT
472 if (loglevel & CPU_LOG_IOPORT)
473 fprintf(logfile, "inb : %04x %02x\n", addr, val);
474 #endif
475 #ifdef USE_KQEMU
476 if (env)
477 env->last_io_time = cpu_get_time_fast();
478 #endif
479 return val;
482 int cpu_inw(CPUState *env, int addr)
484 int val;
485 val = ioport_read(1, addr);
486 #ifdef DEBUG_IOPORT
487 if (loglevel & CPU_LOG_IOPORT)
488 fprintf(logfile, "inw : %04x %04x\n", addr, val);
489 #endif
490 #ifdef USE_KQEMU
491 if (env)
492 env->last_io_time = cpu_get_time_fast();
493 #endif
494 return val;
497 int cpu_inl(CPUState *env, int addr)
499 int val;
500 val = ioport_read(2, addr);
501 #ifdef DEBUG_IOPORT
502 if (loglevel & CPU_LOG_IOPORT)
503 fprintf(logfile, "inl : %04x %08x\n", addr, val);
504 #endif
505 #ifdef USE_KQEMU
506 if (env)
507 env->last_io_time = cpu_get_time_fast();
508 #endif
509 return val;
512 /***********************************************************/
513 void hw_error(const char *fmt, ...)
515 va_list ap;
516 CPUState *env;
518 va_start(ap, fmt);
519 fprintf(stderr, "qemu: hardware error: ");
520 vfprintf(stderr, fmt, ap);
521 fprintf(stderr, "\n");
522 for(env = first_cpu; env != NULL; env = env->next_cpu) {
523 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
524 #ifdef TARGET_I386
525 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
526 #else
527 cpu_dump_state(env, stderr, fprintf, 0);
528 #endif
530 va_end(ap);
531 abort();
534 /***********************************************************/
535 /* keyboard/mouse */
537 static QEMUPutKBDEvent *qemu_put_kbd_event;
538 static void *qemu_put_kbd_event_opaque;
539 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
540 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
542 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
544 qemu_put_kbd_event_opaque = opaque;
545 qemu_put_kbd_event = func;
548 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
549 void *opaque, int absolute,
550 const char *name)
552 QEMUPutMouseEntry *s, *cursor;
554 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
555 if (!s)
556 return NULL;
558 s->qemu_put_mouse_event = func;
559 s->qemu_put_mouse_event_opaque = opaque;
560 s->qemu_put_mouse_event_absolute = absolute;
561 s->qemu_put_mouse_event_name = qemu_strdup(name);
562 s->next = NULL;
564 if (!qemu_put_mouse_event_head) {
565 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
566 return s;
569 cursor = qemu_put_mouse_event_head;
570 while (cursor->next != NULL)
571 cursor = cursor->next;
573 cursor->next = s;
574 qemu_put_mouse_event_current = s;
576 return s;
579 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
581 QEMUPutMouseEntry *prev = NULL, *cursor;
583 if (!qemu_put_mouse_event_head || entry == NULL)
584 return;
586 cursor = qemu_put_mouse_event_head;
587 while (cursor != NULL && cursor != entry) {
588 prev = cursor;
589 cursor = cursor->next;
592 if (cursor == NULL) // does not exist or list empty
593 return;
594 else if (prev == NULL) { // entry is head
595 qemu_put_mouse_event_head = cursor->next;
596 if (qemu_put_mouse_event_current == entry)
597 qemu_put_mouse_event_current = cursor->next;
598 qemu_free(entry->qemu_put_mouse_event_name);
599 qemu_free(entry);
600 return;
603 prev->next = entry->next;
605 if (qemu_put_mouse_event_current == entry)
606 qemu_put_mouse_event_current = prev;
608 qemu_free(entry->qemu_put_mouse_event_name);
609 qemu_free(entry);
612 void kbd_put_keycode(int keycode)
614 if (qemu_put_kbd_event) {
615 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
619 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
621 QEMUPutMouseEvent *mouse_event;
622 void *mouse_event_opaque;
623 int width;
625 if (!qemu_put_mouse_event_current) {
626 return;
629 mouse_event =
630 qemu_put_mouse_event_current->qemu_put_mouse_event;
631 mouse_event_opaque =
632 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
634 if (mouse_event) {
635 if (graphic_rotate) {
636 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
637 width = 0x7fff;
638 else
639 width = graphic_width - 1;
640 mouse_event(mouse_event_opaque,
641 width - dy, dx, dz, buttons_state);
642 } else
643 mouse_event(mouse_event_opaque,
644 dx, dy, dz, buttons_state);
648 int kbd_mouse_is_absolute(void)
650 if (!qemu_put_mouse_event_current)
651 return 0;
653 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
656 void do_info_mice(void)
658 QEMUPutMouseEntry *cursor;
659 int index = 0;
661 if (!qemu_put_mouse_event_head) {
662 term_printf("No mouse devices connected\n");
663 return;
666 term_printf("Mouse devices available:\n");
667 cursor = qemu_put_mouse_event_head;
668 while (cursor != NULL) {
669 term_printf("%c Mouse #%d: %s\n",
670 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
671 index, cursor->qemu_put_mouse_event_name);
672 index++;
673 cursor = cursor->next;
677 void do_mouse_set(int index)
679 QEMUPutMouseEntry *cursor;
680 int i = 0;
682 if (!qemu_put_mouse_event_head) {
683 term_printf("No mouse devices connected\n");
684 return;
687 cursor = qemu_put_mouse_event_head;
688 while (cursor != NULL && index != i) {
689 i++;
690 cursor = cursor->next;
693 if (cursor != NULL)
694 qemu_put_mouse_event_current = cursor;
695 else
696 term_printf("Mouse at given index not found\n");
699 /* compute with 96 bit intermediate result: (a*b)/c */
700 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
702 union {
703 uint64_t ll;
704 struct {
705 #ifdef WORDS_BIGENDIAN
706 uint32_t high, low;
707 #else
708 uint32_t low, high;
709 #endif
710 } l;
711 } u, res;
712 uint64_t rl, rh;
714 u.ll = a;
715 rl = (uint64_t)u.l.low * (uint64_t)b;
716 rh = (uint64_t)u.l.high * (uint64_t)b;
717 rh += (rl >> 32);
718 res.l.high = rh / c;
719 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
720 return res.ll;
723 /***********************************************************/
724 /* real time host monotonic timer */
726 #define QEMU_TIMER_BASE 1000000000LL
728 #ifdef WIN32
730 static int64_t clock_freq;
732 static void init_get_clock(void)
734 LARGE_INTEGER freq;
735 int ret;
736 ret = QueryPerformanceFrequency(&freq);
737 if (ret == 0) {
738 fprintf(stderr, "Could not calibrate ticks\n");
739 exit(1);
741 clock_freq = freq.QuadPart;
744 static int64_t get_clock(void)
746 LARGE_INTEGER ti;
747 QueryPerformanceCounter(&ti);
748 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
751 #else
753 static int use_rt_clock;
755 static void init_get_clock(void)
757 use_rt_clock = 0;
758 #if defined(__linux__)
760 struct timespec ts;
761 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
762 use_rt_clock = 1;
765 #endif
768 static int64_t get_clock(void)
770 #if defined(__linux__)
771 if (use_rt_clock) {
772 struct timespec ts;
773 clock_gettime(CLOCK_MONOTONIC, &ts);
774 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
775 } else
776 #endif
778 /* XXX: using gettimeofday leads to problems if the date
779 changes, so it should be avoided. */
780 struct timeval tv;
781 gettimeofday(&tv, NULL);
782 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
785 #endif
787 /* Return the virtual CPU time, based on the instruction counter. */
788 static int64_t cpu_get_icount(void)
790 int64_t icount;
791 CPUState *env = cpu_single_env;;
792 icount = qemu_icount;
793 if (env) {
794 if (!can_do_io(env))
795 fprintf(stderr, "Bad clock read\n");
796 icount -= (env->icount_decr.u16.low + env->icount_extra);
798 return qemu_icount_bias + (icount << icount_time_shift);
801 /***********************************************************/
802 /* guest cycle counter */
804 static int64_t cpu_ticks_prev;
805 static int64_t cpu_ticks_offset;
806 static int64_t cpu_clock_offset;
807 static int cpu_ticks_enabled;
809 /* return the host CPU cycle counter and handle stop/restart */
810 int64_t cpu_get_ticks(void)
812 if (use_icount) {
813 return cpu_get_icount();
815 if (!cpu_ticks_enabled) {
816 return cpu_ticks_offset;
817 } else {
818 int64_t ticks;
819 ticks = cpu_get_real_ticks();
820 if (cpu_ticks_prev > ticks) {
821 /* Note: non increasing ticks may happen if the host uses
822 software suspend */
823 cpu_ticks_offset += cpu_ticks_prev - ticks;
825 cpu_ticks_prev = ticks;
826 return ticks + cpu_ticks_offset;
830 /* return the host CPU monotonic timer and handle stop/restart */
831 static int64_t cpu_get_clock(void)
833 int64_t ti;
834 if (!cpu_ticks_enabled) {
835 return cpu_clock_offset;
836 } else {
837 ti = get_clock();
838 return ti + cpu_clock_offset;
842 /* enable cpu_get_ticks() */
843 void cpu_enable_ticks(void)
845 if (!cpu_ticks_enabled) {
846 cpu_ticks_offset -= cpu_get_real_ticks();
847 cpu_clock_offset -= get_clock();
848 cpu_ticks_enabled = 1;
852 /* disable cpu_get_ticks() : the clock is stopped. You must not call
853 cpu_get_ticks() after that. */
854 void cpu_disable_ticks(void)
856 if (cpu_ticks_enabled) {
857 cpu_ticks_offset = cpu_get_ticks();
858 cpu_clock_offset = cpu_get_clock();
859 cpu_ticks_enabled = 0;
863 /***********************************************************/
864 /* timers */
866 #define QEMU_TIMER_REALTIME 0
867 #define QEMU_TIMER_VIRTUAL 1
869 struct QEMUClock {
870 int type;
871 /* XXX: add frequency */
874 struct QEMUTimer {
875 QEMUClock *clock;
876 int64_t expire_time;
877 QEMUTimerCB *cb;
878 void *opaque;
879 struct QEMUTimer *next;
882 struct qemu_alarm_timer {
883 char const *name;
884 unsigned int flags;
886 int (*start)(struct qemu_alarm_timer *t);
887 void (*stop)(struct qemu_alarm_timer *t);
888 void (*rearm)(struct qemu_alarm_timer *t);
889 void *priv;
892 #define ALARM_FLAG_DYNTICKS 0x1
893 #define ALARM_FLAG_EXPIRED 0x2
895 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
897 return t->flags & ALARM_FLAG_DYNTICKS;
900 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
902 if (!alarm_has_dynticks(t))
903 return;
905 t->rearm(t);
908 /* TODO: MIN_TIMER_REARM_US should be optimized */
909 #define MIN_TIMER_REARM_US 250
911 static struct qemu_alarm_timer *alarm_timer;
913 #ifdef _WIN32
915 struct qemu_alarm_win32 {
916 MMRESULT timerId;
917 HANDLE host_alarm;
918 unsigned int period;
919 } alarm_win32_data = {0, NULL, -1};
921 static int win32_start_timer(struct qemu_alarm_timer *t);
922 static void win32_stop_timer(struct qemu_alarm_timer *t);
923 static void win32_rearm_timer(struct qemu_alarm_timer *t);
925 #else
927 static int unix_start_timer(struct qemu_alarm_timer *t);
928 static void unix_stop_timer(struct qemu_alarm_timer *t);
930 #ifdef __linux__
932 static int dynticks_start_timer(struct qemu_alarm_timer *t);
933 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
934 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
936 static int hpet_start_timer(struct qemu_alarm_timer *t);
937 static void hpet_stop_timer(struct qemu_alarm_timer *t);
939 static int rtc_start_timer(struct qemu_alarm_timer *t);
940 static void rtc_stop_timer(struct qemu_alarm_timer *t);
942 #endif /* __linux__ */
944 #endif /* _WIN32 */
946 /* Correlation between real and virtual time is always going to be
947 fairly approximate, so ignore small variation.
948 When the guest is idle real and virtual time will be aligned in
949 the IO wait loop. */
950 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
952 static void icount_adjust(void)
954 int64_t cur_time;
955 int64_t cur_icount;
956 int64_t delta;
957 static int64_t last_delta;
958 /* If the VM is not running, then do nothing. */
959 if (!vm_running)
960 return;
962 cur_time = cpu_get_clock();
963 cur_icount = qemu_get_clock(vm_clock);
964 delta = cur_icount - cur_time;
965 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
966 if (delta > 0
967 && last_delta + ICOUNT_WOBBLE < delta * 2
968 && icount_time_shift > 0) {
969 /* The guest is getting too far ahead. Slow time down. */
970 icount_time_shift--;
972 if (delta < 0
973 && last_delta - ICOUNT_WOBBLE > delta * 2
974 && icount_time_shift < MAX_ICOUNT_SHIFT) {
975 /* The guest is getting too far behind. Speed time up. */
976 icount_time_shift++;
978 last_delta = delta;
979 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
982 static void icount_adjust_rt(void * opaque)
984 qemu_mod_timer(icount_rt_timer,
985 qemu_get_clock(rt_clock) + 1000);
986 icount_adjust();
989 static void icount_adjust_vm(void * opaque)
991 qemu_mod_timer(icount_vm_timer,
992 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
993 icount_adjust();
996 static void init_icount_adjust(void)
998 /* Have both realtime and virtual time triggers for speed adjustment.
999 The realtime trigger catches emulated time passing too slowly,
1000 the virtual time trigger catches emulated time passing too fast.
1001 Realtime triggers occur even when idle, so use them less frequently
1002 than VM triggers. */
1003 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1004 qemu_mod_timer(icount_rt_timer,
1005 qemu_get_clock(rt_clock) + 1000);
1006 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1007 qemu_mod_timer(icount_vm_timer,
1008 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1011 static struct qemu_alarm_timer alarm_timers[] = {
1012 #ifndef _WIN32
1013 #ifdef __linux__
1014 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1015 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1016 /* HPET - if available - is preferred */
1017 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1018 /* ...otherwise try RTC */
1019 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1020 #endif
1021 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1022 #else
1023 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1024 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1025 {"win32", 0, win32_start_timer,
1026 win32_stop_timer, NULL, &alarm_win32_data},
1027 #endif
1028 {NULL, }
1031 static void show_available_alarms(void)
1033 int i;
1035 printf("Available alarm timers, in order of precedence:\n");
1036 for (i = 0; alarm_timers[i].name; i++)
1037 printf("%s\n", alarm_timers[i].name);
1040 static void configure_alarms(char const *opt)
1042 int i;
1043 int cur = 0;
1044 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1045 char *arg;
1046 char *name;
1047 struct qemu_alarm_timer tmp;
1049 if (!strcmp(opt, "?")) {
1050 show_available_alarms();
1051 exit(0);
1054 arg = strdup(opt);
1056 /* Reorder the array */
1057 name = strtok(arg, ",");
1058 while (name) {
1059 for (i = 0; i < count && alarm_timers[i].name; i++) {
1060 if (!strcmp(alarm_timers[i].name, name))
1061 break;
1064 if (i == count) {
1065 fprintf(stderr, "Unknown clock %s\n", name);
1066 goto next;
1069 if (i < cur)
1070 /* Ignore */
1071 goto next;
1073 /* Swap */
1074 tmp = alarm_timers[i];
1075 alarm_timers[i] = alarm_timers[cur];
1076 alarm_timers[cur] = tmp;
1078 cur++;
1079 next:
1080 name = strtok(NULL, ",");
1083 free(arg);
1085 if (cur) {
1086 /* Disable remaining timers */
1087 for (i = cur; i < count; i++)
1088 alarm_timers[i].name = NULL;
1089 } else {
1090 show_available_alarms();
1091 exit(1);
1095 QEMUClock *rt_clock;
1096 QEMUClock *vm_clock;
1098 static QEMUTimer *active_timers[2];
1100 static QEMUClock *qemu_new_clock(int type)
1102 QEMUClock *clock;
1103 clock = qemu_mallocz(sizeof(QEMUClock));
1104 if (!clock)
1105 return NULL;
1106 clock->type = type;
1107 return clock;
1110 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1112 QEMUTimer *ts;
1114 ts = qemu_mallocz(sizeof(QEMUTimer));
1115 ts->clock = clock;
1116 ts->cb = cb;
1117 ts->opaque = opaque;
1118 return ts;
1121 void qemu_free_timer(QEMUTimer *ts)
1123 qemu_free(ts);
1126 /* stop a timer, but do not dealloc it */
1127 void qemu_del_timer(QEMUTimer *ts)
1129 QEMUTimer **pt, *t;
1131 /* NOTE: this code must be signal safe because
1132 qemu_timer_expired() can be called from a signal. */
1133 pt = &active_timers[ts->clock->type];
1134 for(;;) {
1135 t = *pt;
1136 if (!t)
1137 break;
1138 if (t == ts) {
1139 *pt = t->next;
1140 break;
1142 pt = &t->next;
1146 /* modify the current timer so that it will be fired when current_time
1147 >= expire_time. The corresponding callback will be called. */
1148 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1150 QEMUTimer **pt, *t;
1152 qemu_del_timer(ts);
1154 /* add the timer in the sorted list */
1155 /* NOTE: this code must be signal safe because
1156 qemu_timer_expired() can be called from a signal. */
1157 pt = &active_timers[ts->clock->type];
1158 for(;;) {
1159 t = *pt;
1160 if (!t)
1161 break;
1162 if (t->expire_time > expire_time)
1163 break;
1164 pt = &t->next;
1166 ts->expire_time = expire_time;
1167 ts->next = *pt;
1168 *pt = ts;
1170 /* Rearm if necessary */
1171 if (pt == &active_timers[ts->clock->type]) {
1172 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1173 qemu_rearm_alarm_timer(alarm_timer);
1175 /* Interrupt execution to force deadline recalculation. */
1176 if (use_icount && cpu_single_env) {
1177 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1182 int qemu_timer_pending(QEMUTimer *ts)
1184 QEMUTimer *t;
1185 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1186 if (t == ts)
1187 return 1;
1189 return 0;
1192 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1194 if (!timer_head)
1195 return 0;
1196 return (timer_head->expire_time <= current_time);
1199 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1201 QEMUTimer *ts;
1203 for(;;) {
1204 ts = *ptimer_head;
1205 if (!ts || ts->expire_time > current_time)
1206 break;
1207 /* remove timer from the list before calling the callback */
1208 *ptimer_head = ts->next;
1209 ts->next = NULL;
1211 /* run the callback (the timer list can be modified) */
1212 ts->cb(ts->opaque);
1216 int64_t qemu_get_clock(QEMUClock *clock)
1218 switch(clock->type) {
1219 case QEMU_TIMER_REALTIME:
1220 return get_clock() / 1000000;
1221 default:
1222 case QEMU_TIMER_VIRTUAL:
1223 if (use_icount) {
1224 return cpu_get_icount();
1225 } else {
1226 return cpu_get_clock();
1231 static void init_timers(void)
1233 init_get_clock();
1234 ticks_per_sec = QEMU_TIMER_BASE;
1235 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1236 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1239 /* save a timer */
1240 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1242 uint64_t expire_time;
1244 if (qemu_timer_pending(ts)) {
1245 expire_time = ts->expire_time;
1246 } else {
1247 expire_time = -1;
1249 qemu_put_be64(f, expire_time);
1252 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1254 uint64_t expire_time;
1256 expire_time = qemu_get_be64(f);
1257 if (expire_time != -1) {
1258 qemu_mod_timer(ts, expire_time);
1259 } else {
1260 qemu_del_timer(ts);
1264 static void timer_save(QEMUFile *f, void *opaque)
1266 if (cpu_ticks_enabled) {
1267 hw_error("cannot save state if virtual timers are running");
1269 qemu_put_be64(f, cpu_ticks_offset);
1270 qemu_put_be64(f, ticks_per_sec);
1271 qemu_put_be64(f, cpu_clock_offset);
1274 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1276 if (version_id != 1 && version_id != 2)
1277 return -EINVAL;
1278 if (cpu_ticks_enabled) {
1279 return -EINVAL;
1281 cpu_ticks_offset=qemu_get_be64(f);
1282 ticks_per_sec=qemu_get_be64(f);
1283 if (version_id == 2) {
1284 cpu_clock_offset=qemu_get_be64(f);
1286 return 0;
1289 #ifdef _WIN32
1290 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1291 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1292 #else
1293 static void host_alarm_handler(int host_signum)
1294 #endif
1296 #if 0
1297 #define DISP_FREQ 1000
1299 static int64_t delta_min = INT64_MAX;
1300 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1301 static int count;
1302 ti = qemu_get_clock(vm_clock);
1303 if (last_clock != 0) {
1304 delta = ti - last_clock;
1305 if (delta < delta_min)
1306 delta_min = delta;
1307 if (delta > delta_max)
1308 delta_max = delta;
1309 delta_cum += delta;
1310 if (++count == DISP_FREQ) {
1311 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1312 muldiv64(delta_min, 1000000, ticks_per_sec),
1313 muldiv64(delta_max, 1000000, ticks_per_sec),
1314 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1315 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1316 count = 0;
1317 delta_min = INT64_MAX;
1318 delta_max = 0;
1319 delta_cum = 0;
1322 last_clock = ti;
1324 #endif
1325 if (1 ||
1326 alarm_has_dynticks(alarm_timer) ||
1327 (!use_icount &&
1328 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1329 qemu_get_clock(vm_clock))) ||
1330 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1331 qemu_get_clock(rt_clock))) {
1332 #ifdef _WIN32
1333 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1334 SetEvent(data->host_alarm);
1335 #endif
1336 CPUState *env = next_cpu;
1338 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1340 if (env) {
1341 /* stop the currently executing cpu because a timer occured */
1342 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1343 #ifdef USE_KQEMU
1344 if (env->kqemu_enabled) {
1345 kqemu_cpu_interrupt(env);
1347 #endif
1349 event_pending = 1;
1353 static int64_t qemu_next_deadline(void)
1355 int64_t delta;
1357 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1358 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1359 qemu_get_clock(vm_clock);
1360 } else {
1361 /* To avoid problems with overflow limit this to 2^32. */
1362 delta = INT32_MAX;
1365 if (delta < 0)
1366 delta = 0;
1368 return delta;
1371 static uint64_t qemu_next_deadline_dyntick(void)
1373 int64_t delta;
1374 int64_t rtdelta;
1376 if (use_icount)
1377 delta = INT32_MAX;
1378 else
1379 delta = (qemu_next_deadline() + 999) / 1000;
1381 if (active_timers[QEMU_TIMER_REALTIME]) {
1382 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1383 qemu_get_clock(rt_clock))*1000;
1384 if (rtdelta < delta)
1385 delta = rtdelta;
1388 if (delta < MIN_TIMER_REARM_US)
1389 delta = MIN_TIMER_REARM_US;
1391 return delta;
1394 #ifndef _WIN32
1396 #if defined(__linux__)
1398 #define RTC_FREQ 1024
1400 static void enable_sigio_timer(int fd)
1402 struct sigaction act;
1404 /* timer signal */
1405 sigfillset(&act.sa_mask);
1406 act.sa_flags = 0;
1407 act.sa_handler = host_alarm_handler;
1409 sigaction(SIGIO, &act, NULL);
1410 fcntl(fd, F_SETFL, O_ASYNC);
1411 fcntl(fd, F_SETOWN, getpid());
1414 static int hpet_start_timer(struct qemu_alarm_timer *t)
1416 struct hpet_info info;
1417 int r, fd;
1419 fd = open("/dev/hpet", O_RDONLY);
1420 if (fd < 0)
1421 return -1;
1423 /* Set frequency */
1424 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1425 if (r < 0) {
1426 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1427 "error, but for better emulation accuracy type:\n"
1428 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1429 goto fail;
1432 /* Check capabilities */
1433 r = ioctl(fd, HPET_INFO, &info);
1434 if (r < 0)
1435 goto fail;
1437 /* Enable periodic mode */
1438 r = ioctl(fd, HPET_EPI, 0);
1439 if (info.hi_flags && (r < 0))
1440 goto fail;
1442 /* Enable interrupt */
1443 r = ioctl(fd, HPET_IE_ON, 0);
1444 if (r < 0)
1445 goto fail;
1447 enable_sigio_timer(fd);
1448 t->priv = (void *)(long)fd;
1450 return 0;
1451 fail:
1452 close(fd);
1453 return -1;
1456 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1458 int fd = (long)t->priv;
1460 close(fd);
1463 static int rtc_start_timer(struct qemu_alarm_timer *t)
1465 int rtc_fd;
1466 unsigned long current_rtc_freq = 0;
1468 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1469 if (rtc_fd < 0)
1470 return -1;
1471 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1472 if (current_rtc_freq != RTC_FREQ &&
1473 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1474 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1475 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1476 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1477 goto fail;
1479 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1480 fail:
1481 close(rtc_fd);
1482 return -1;
1485 enable_sigio_timer(rtc_fd);
1487 t->priv = (void *)(long)rtc_fd;
1489 return 0;
1492 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1494 int rtc_fd = (long)t->priv;
1496 close(rtc_fd);
1499 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1501 struct sigevent ev;
1502 timer_t host_timer;
1503 struct sigaction act;
1505 sigfillset(&act.sa_mask);
1506 act.sa_flags = 0;
1507 act.sa_handler = host_alarm_handler;
1509 sigaction(SIGALRM, &act, NULL);
1511 ev.sigev_value.sival_int = 0;
1512 ev.sigev_notify = SIGEV_SIGNAL;
1513 ev.sigev_signo = SIGALRM;
1515 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1516 perror("timer_create");
1518 /* disable dynticks */
1519 fprintf(stderr, "Dynamic Ticks disabled\n");
1521 return -1;
1524 t->priv = (void *)host_timer;
1526 return 0;
1529 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1531 timer_t host_timer = (timer_t)t->priv;
1533 timer_delete(host_timer);
1536 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1538 timer_t host_timer = (timer_t)t->priv;
1539 struct itimerspec timeout;
1540 int64_t nearest_delta_us = INT64_MAX;
1541 int64_t current_us;
1543 if (!active_timers[QEMU_TIMER_REALTIME] &&
1544 !active_timers[QEMU_TIMER_VIRTUAL])
1545 return;
1547 nearest_delta_us = qemu_next_deadline_dyntick();
1549 /* check whether a timer is already running */
1550 if (timer_gettime(host_timer, &timeout)) {
1551 perror("gettime");
1552 fprintf(stderr, "Internal timer error: aborting\n");
1553 exit(1);
1555 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1556 if (current_us && current_us <= nearest_delta_us)
1557 return;
1559 timeout.it_interval.tv_sec = 0;
1560 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1561 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1562 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1563 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1564 perror("settime");
1565 fprintf(stderr, "Internal timer error: aborting\n");
1566 exit(1);
1570 #endif /* defined(__linux__) */
1572 static int unix_start_timer(struct qemu_alarm_timer *t)
1574 struct sigaction act;
1575 struct itimerval itv;
1576 int err;
1578 /* timer signal */
1579 sigfillset(&act.sa_mask);
1580 act.sa_flags = 0;
1581 act.sa_handler = host_alarm_handler;
1583 sigaction(SIGALRM, &act, NULL);
1585 itv.it_interval.tv_sec = 0;
1586 /* for i386 kernel 2.6 to get 1 ms */
1587 itv.it_interval.tv_usec = 999;
1588 itv.it_value.tv_sec = 0;
1589 itv.it_value.tv_usec = 10 * 1000;
1591 err = setitimer(ITIMER_REAL, &itv, NULL);
1592 if (err)
1593 return -1;
1595 return 0;
1598 static void unix_stop_timer(struct qemu_alarm_timer *t)
1600 struct itimerval itv;
1602 memset(&itv, 0, sizeof(itv));
1603 setitimer(ITIMER_REAL, &itv, NULL);
1606 #endif /* !defined(_WIN32) */
1608 #ifdef _WIN32
1610 static int win32_start_timer(struct qemu_alarm_timer *t)
1612 TIMECAPS tc;
1613 struct qemu_alarm_win32 *data = t->priv;
1614 UINT flags;
1616 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1617 if (!data->host_alarm) {
1618 perror("Failed CreateEvent");
1619 return -1;
1622 memset(&tc, 0, sizeof(tc));
1623 timeGetDevCaps(&tc, sizeof(tc));
1625 if (data->period < tc.wPeriodMin)
1626 data->period = tc.wPeriodMin;
1628 timeBeginPeriod(data->period);
1630 flags = TIME_CALLBACK_FUNCTION;
1631 if (alarm_has_dynticks(t))
1632 flags |= TIME_ONESHOT;
1633 else
1634 flags |= TIME_PERIODIC;
1636 data->timerId = timeSetEvent(1, // interval (ms)
1637 data->period, // resolution
1638 host_alarm_handler, // function
1639 (DWORD)t, // parameter
1640 flags);
1642 if (!data->timerId) {
1643 perror("Failed to initialize win32 alarm timer");
1645 timeEndPeriod(data->period);
1646 CloseHandle(data->host_alarm);
1647 return -1;
1650 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1652 return 0;
1655 static void win32_stop_timer(struct qemu_alarm_timer *t)
1657 struct qemu_alarm_win32 *data = t->priv;
1659 timeKillEvent(data->timerId);
1660 timeEndPeriod(data->period);
1662 CloseHandle(data->host_alarm);
1665 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1667 struct qemu_alarm_win32 *data = t->priv;
1668 uint64_t nearest_delta_us;
1670 if (!active_timers[QEMU_TIMER_REALTIME] &&
1671 !active_timers[QEMU_TIMER_VIRTUAL])
1672 return;
1674 nearest_delta_us = qemu_next_deadline_dyntick();
1675 nearest_delta_us /= 1000;
1677 timeKillEvent(data->timerId);
1679 data->timerId = timeSetEvent(1,
1680 data->period,
1681 host_alarm_handler,
1682 (DWORD)t,
1683 TIME_ONESHOT | TIME_PERIODIC);
1685 if (!data->timerId) {
1686 perror("Failed to re-arm win32 alarm timer");
1688 timeEndPeriod(data->period);
1689 CloseHandle(data->host_alarm);
1690 exit(1);
1694 #endif /* _WIN32 */
1696 static void init_timer_alarm(void)
1698 struct qemu_alarm_timer *t;
1699 int i, err = -1;
1701 for (i = 0; alarm_timers[i].name; i++) {
1702 t = &alarm_timers[i];
1704 err = t->start(t);
1705 if (!err)
1706 break;
1709 if (err) {
1710 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1711 fprintf(stderr, "Terminating\n");
1712 exit(1);
1715 alarm_timer = t;
1718 static void quit_timers(void)
1720 alarm_timer->stop(alarm_timer);
1721 alarm_timer = NULL;
1724 /***********************************************************/
1725 /* host time/date access */
1726 void qemu_get_timedate(struct tm *tm, int offset)
1728 time_t ti;
1729 struct tm *ret;
1731 time(&ti);
1732 ti += offset;
1733 if (rtc_date_offset == -1) {
1734 if (rtc_utc)
1735 ret = gmtime(&ti);
1736 else
1737 ret = localtime(&ti);
1738 } else {
1739 ti -= rtc_date_offset;
1740 ret = gmtime(&ti);
1743 memcpy(tm, ret, sizeof(struct tm));
1746 int qemu_timedate_diff(struct tm *tm)
1748 time_t seconds;
1750 if (rtc_date_offset == -1)
1751 if (rtc_utc)
1752 seconds = mktimegm(tm);
1753 else
1754 seconds = mktime(tm);
1755 else
1756 seconds = mktimegm(tm) + rtc_date_offset;
1758 return seconds - time(NULL);
1761 /***********************************************************/
1762 /* character device */
1764 static void qemu_chr_event(CharDriverState *s, int event)
1766 if (!s->chr_event)
1767 return;
1768 s->chr_event(s->handler_opaque, event);
1771 static void qemu_chr_reset_bh(void *opaque)
1773 CharDriverState *s = opaque;
1774 qemu_chr_event(s, CHR_EVENT_RESET);
1775 qemu_bh_delete(s->bh);
1776 s->bh = NULL;
1779 void qemu_chr_reset(CharDriverState *s)
1781 if (s->bh == NULL) {
1782 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1783 qemu_bh_schedule(s->bh);
1787 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1789 return s->chr_write(s, buf, len);
1792 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1794 if (!s->chr_ioctl)
1795 return -ENOTSUP;
1796 return s->chr_ioctl(s, cmd, arg);
1799 int qemu_chr_can_read(CharDriverState *s)
1801 if (!s->chr_can_read)
1802 return 0;
1803 return s->chr_can_read(s->handler_opaque);
1806 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1808 s->chr_read(s->handler_opaque, buf, len);
1811 void qemu_chr_accept_input(CharDriverState *s)
1813 if (s->chr_accept_input)
1814 s->chr_accept_input(s);
1817 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1819 char buf[4096];
1820 va_list ap;
1821 va_start(ap, fmt);
1822 vsnprintf(buf, sizeof(buf), fmt, ap);
1823 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1824 va_end(ap);
1827 void qemu_chr_send_event(CharDriverState *s, int event)
1829 if (s->chr_send_event)
1830 s->chr_send_event(s, event);
1833 void qemu_chr_add_handlers(CharDriverState *s,
1834 IOCanRWHandler *fd_can_read,
1835 IOReadHandler *fd_read,
1836 IOEventHandler *fd_event,
1837 void *opaque)
1839 s->chr_can_read = fd_can_read;
1840 s->chr_read = fd_read;
1841 s->chr_event = fd_event;
1842 s->handler_opaque = opaque;
1843 if (s->chr_update_read_handler)
1844 s->chr_update_read_handler(s);
1847 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1849 return len;
1852 static CharDriverState *qemu_chr_open_null(void)
1854 CharDriverState *chr;
1856 chr = qemu_mallocz(sizeof(CharDriverState));
1857 if (!chr)
1858 return NULL;
1859 chr->chr_write = null_chr_write;
1860 return chr;
1863 /* MUX driver for serial I/O splitting */
1864 static int term_timestamps;
1865 static int64_t term_timestamps_start;
1866 #define MAX_MUX 4
1867 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1868 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1869 typedef struct {
1870 IOCanRWHandler *chr_can_read[MAX_MUX];
1871 IOReadHandler *chr_read[MAX_MUX];
1872 IOEventHandler *chr_event[MAX_MUX];
1873 void *ext_opaque[MAX_MUX];
1874 CharDriverState *drv;
1875 unsigned char buffer[MUX_BUFFER_SIZE];
1876 int prod;
1877 int cons;
1878 int mux_cnt;
1879 int term_got_escape;
1880 int max_size;
1881 } MuxDriver;
1884 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1886 MuxDriver *d = chr->opaque;
1887 int ret;
1888 if (!term_timestamps) {
1889 ret = d->drv->chr_write(d->drv, buf, len);
1890 } else {
1891 int i;
1893 ret = 0;
1894 for(i = 0; i < len; i++) {
1895 ret += d->drv->chr_write(d->drv, buf+i, 1);
1896 if (buf[i] == '\n') {
1897 char buf1[64];
1898 int64_t ti;
1899 int secs;
1901 ti = get_clock();
1902 if (term_timestamps_start == -1)
1903 term_timestamps_start = ti;
1904 ti -= term_timestamps_start;
1905 secs = ti / 1000000000;
1906 snprintf(buf1, sizeof(buf1),
1907 "[%02d:%02d:%02d.%03d] ",
1908 secs / 3600,
1909 (secs / 60) % 60,
1910 secs % 60,
1911 (int)((ti / 1000000) % 1000));
1912 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1916 return ret;
1919 static char *mux_help[] = {
1920 "% h print this help\n\r",
1921 "% x exit emulator\n\r",
1922 "% s save disk data back to file (if -snapshot)\n\r",
1923 "% t toggle console timestamps\n\r"
1924 "% b send break (magic sysrq)\n\r",
1925 "% c switch between console and monitor\n\r",
1926 "% % sends %\n\r",
1927 NULL
1930 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1931 static void mux_print_help(CharDriverState *chr)
1933 int i, j;
1934 char ebuf[15] = "Escape-Char";
1935 char cbuf[50] = "\n\r";
1937 if (term_escape_char > 0 && term_escape_char < 26) {
1938 sprintf(cbuf,"\n\r");
1939 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1940 } else {
1941 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1942 term_escape_char);
1944 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1945 for (i = 0; mux_help[i] != NULL; i++) {
1946 for (j=0; mux_help[i][j] != '\0'; j++) {
1947 if (mux_help[i][j] == '%')
1948 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1949 else
1950 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1955 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1957 if (d->term_got_escape) {
1958 d->term_got_escape = 0;
1959 if (ch == term_escape_char)
1960 goto send_char;
1961 switch(ch) {
1962 case '?':
1963 case 'h':
1964 mux_print_help(chr);
1965 break;
1966 case 'x':
1968 char *term = "QEMU: Terminated\n\r";
1969 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1970 exit(0);
1971 break;
1973 case 's':
1975 int i;
1976 for (i = 0; i < nb_drives; i++) {
1977 bdrv_commit(drives_table[i].bdrv);
1980 break;
1981 case 'b':
1982 qemu_chr_event(chr, CHR_EVENT_BREAK);
1983 break;
1984 case 'c':
1985 /* Switch to the next registered device */
1986 chr->focus++;
1987 if (chr->focus >= d->mux_cnt)
1988 chr->focus = 0;
1989 break;
1990 case 't':
1991 term_timestamps = !term_timestamps;
1992 term_timestamps_start = -1;
1993 break;
1995 } else if (ch == term_escape_char) {
1996 d->term_got_escape = 1;
1997 } else {
1998 send_char:
1999 return 1;
2001 return 0;
2004 static void mux_chr_accept_input(CharDriverState *chr)
2006 int m = chr->focus;
2007 MuxDriver *d = chr->opaque;
2009 while (d->prod != d->cons &&
2010 d->chr_can_read[m] &&
2011 d->chr_can_read[m](d->ext_opaque[m])) {
2012 d->chr_read[m](d->ext_opaque[m],
2013 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
2017 static int mux_chr_can_read(void *opaque)
2019 CharDriverState *chr = opaque;
2020 MuxDriver *d = chr->opaque;
2022 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2023 return 1;
2024 if (d->chr_can_read[chr->focus])
2025 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2026 return 0;
2029 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2031 CharDriverState *chr = opaque;
2032 MuxDriver *d = chr->opaque;
2033 int m = chr->focus;
2034 int i;
2036 mux_chr_accept_input (opaque);
2038 for(i = 0; i < size; i++)
2039 if (mux_proc_byte(chr, d, buf[i])) {
2040 if (d->prod == d->cons &&
2041 d->chr_can_read[m] &&
2042 d->chr_can_read[m](d->ext_opaque[m]))
2043 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2044 else
2045 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2049 static void mux_chr_event(void *opaque, int event)
2051 CharDriverState *chr = opaque;
2052 MuxDriver *d = chr->opaque;
2053 int i;
2055 /* Send the event to all registered listeners */
2056 for (i = 0; i < d->mux_cnt; i++)
2057 if (d->chr_event[i])
2058 d->chr_event[i](d->ext_opaque[i], event);
2061 static void mux_chr_update_read_handler(CharDriverState *chr)
2063 MuxDriver *d = chr->opaque;
2065 if (d->mux_cnt >= MAX_MUX) {
2066 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2067 return;
2069 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2070 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2071 d->chr_read[d->mux_cnt] = chr->chr_read;
2072 d->chr_event[d->mux_cnt] = chr->chr_event;
2073 /* Fix up the real driver with mux routines */
2074 if (d->mux_cnt == 0) {
2075 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2076 mux_chr_event, chr);
2078 chr->focus = d->mux_cnt;
2079 d->mux_cnt++;
2082 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2084 CharDriverState *chr;
2085 MuxDriver *d;
2087 chr = qemu_mallocz(sizeof(CharDriverState));
2088 if (!chr)
2089 return NULL;
2090 d = qemu_mallocz(sizeof(MuxDriver));
2091 if (!d) {
2092 free(chr);
2093 return NULL;
2096 chr->opaque = d;
2097 d->drv = drv;
2098 chr->focus = -1;
2099 chr->chr_write = mux_chr_write;
2100 chr->chr_update_read_handler = mux_chr_update_read_handler;
2101 chr->chr_accept_input = mux_chr_accept_input;
2102 return chr;
2106 #ifdef _WIN32
2108 static void socket_cleanup(void)
2110 WSACleanup();
2113 static int socket_init(void)
2115 WSADATA Data;
2116 int ret, err;
2118 ret = WSAStartup(MAKEWORD(2,2), &Data);
2119 if (ret != 0) {
2120 err = WSAGetLastError();
2121 fprintf(stderr, "WSAStartup: %d\n", err);
2122 return -1;
2124 atexit(socket_cleanup);
2125 return 0;
2128 static int send_all(int fd, const uint8_t *buf, int len1)
2130 int ret, len;
2132 len = len1;
2133 while (len > 0) {
2134 ret = send(fd, buf, len, 0);
2135 if (ret < 0) {
2136 int errno;
2137 errno = WSAGetLastError();
2138 if (errno != WSAEWOULDBLOCK) {
2139 return -1;
2141 } else if (ret == 0) {
2142 break;
2143 } else {
2144 buf += ret;
2145 len -= ret;
2148 return len1 - len;
2151 void socket_set_nonblock(int fd)
2153 unsigned long opt = 1;
2154 ioctlsocket(fd, FIONBIO, &opt);
2157 #else
2159 static int unix_write(int fd, const uint8_t *buf, int len1)
2161 int ret, len;
2163 len = len1;
2164 while (len > 0) {
2165 ret = write(fd, buf, len);
2166 if (ret < 0) {
2167 if (errno != EINTR && errno != EAGAIN)
2168 return -1;
2169 } else if (ret == 0) {
2170 break;
2171 } else {
2172 buf += ret;
2173 len -= ret;
2176 return len1 - len;
2179 static inline int send_all(int fd, const uint8_t *buf, int len1)
2181 return unix_write(fd, buf, len1);
2184 void socket_set_nonblock(int fd)
2186 int f;
2187 f = fcntl(fd, F_GETFL);
2188 fcntl(fd, F_SETFL, f | O_NONBLOCK);
2190 #endif /* !_WIN32 */
2192 #ifndef _WIN32
2194 typedef struct {
2195 int fd_in, fd_out;
2196 int max_size;
2197 } FDCharDriver;
2199 #define STDIO_MAX_CLIENTS 1
2200 static int stdio_nb_clients = 0;
2202 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2204 FDCharDriver *s = chr->opaque;
2205 return unix_write(s->fd_out, buf, len);
2208 static int fd_chr_read_poll(void *opaque)
2210 CharDriverState *chr = opaque;
2211 FDCharDriver *s = chr->opaque;
2213 s->max_size = qemu_chr_can_read(chr);
2214 return s->max_size;
2217 static void fd_chr_read(void *opaque)
2219 CharDriverState *chr = opaque;
2220 FDCharDriver *s = chr->opaque;
2221 int size, len;
2222 uint8_t buf[1024];
2224 len = sizeof(buf);
2225 if (len > s->max_size)
2226 len = s->max_size;
2227 if (len == 0)
2228 return;
2229 size = read(s->fd_in, buf, len);
2230 if (size == 0) {
2231 /* FD has been closed. Remove it from the active list. */
2232 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2233 return;
2235 if (size > 0) {
2236 qemu_chr_read(chr, buf, size);
2240 static void fd_chr_update_read_handler(CharDriverState *chr)
2242 FDCharDriver *s = chr->opaque;
2244 if (s->fd_in >= 0) {
2245 if (nographic && s->fd_in == 0) {
2246 } else {
2247 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2248 fd_chr_read, NULL, chr);
2253 static void fd_chr_close(struct CharDriverState *chr)
2255 FDCharDriver *s = chr->opaque;
2257 if (s->fd_in >= 0) {
2258 if (nographic && s->fd_in == 0) {
2259 } else {
2260 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2264 qemu_free(s);
2267 /* open a character device to a unix fd */
2268 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2270 CharDriverState *chr;
2271 FDCharDriver *s;
2273 chr = qemu_mallocz(sizeof(CharDriverState));
2274 if (!chr)
2275 return NULL;
2276 s = qemu_mallocz(sizeof(FDCharDriver));
2277 if (!s) {
2278 free(chr);
2279 return NULL;
2281 s->fd_in = fd_in;
2282 s->fd_out = fd_out;
2283 chr->opaque = s;
2284 chr->chr_write = fd_chr_write;
2285 chr->chr_update_read_handler = fd_chr_update_read_handler;
2286 chr->chr_close = fd_chr_close;
2288 qemu_chr_reset(chr);
2290 return chr;
2293 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2295 int fd_out;
2297 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2298 if (fd_out < 0)
2299 return NULL;
2300 return qemu_chr_open_fd(-1, fd_out);
2303 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2305 int fd_in, fd_out;
2306 char filename_in[256], filename_out[256];
2308 snprintf(filename_in, 256, "%s.in", filename);
2309 snprintf(filename_out, 256, "%s.out", filename);
2310 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2311 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2312 if (fd_in < 0 || fd_out < 0) {
2313 if (fd_in >= 0)
2314 close(fd_in);
2315 if (fd_out >= 0)
2316 close(fd_out);
2317 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2318 if (fd_in < 0)
2319 return NULL;
2321 return qemu_chr_open_fd(fd_in, fd_out);
2325 /* for STDIO, we handle the case where several clients use it
2326 (nographic mode) */
2328 #define TERM_FIFO_MAX_SIZE 1
2330 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2331 static int term_fifo_size;
2333 static int stdio_read_poll(void *opaque)
2335 CharDriverState *chr = opaque;
2337 /* try to flush the queue if needed */
2338 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2339 qemu_chr_read(chr, term_fifo, 1);
2340 term_fifo_size = 0;
2342 /* see if we can absorb more chars */
2343 if (term_fifo_size == 0)
2344 return 1;
2345 else
2346 return 0;
2349 static void stdio_read(void *opaque)
2351 int size;
2352 uint8_t buf[1];
2353 CharDriverState *chr = opaque;
2355 size = read(0, buf, 1);
2356 if (size == 0) {
2357 /* stdin has been closed. Remove it from the active list. */
2358 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2359 return;
2361 if (size > 0) {
2362 if (qemu_chr_can_read(chr) > 0) {
2363 qemu_chr_read(chr, buf, 1);
2364 } else if (term_fifo_size == 0) {
2365 term_fifo[term_fifo_size++] = buf[0];
2370 /* init terminal so that we can grab keys */
2371 static struct termios oldtty;
2372 static int old_fd0_flags;
2373 static int term_atexit_done;
2375 static void term_exit(void)
2377 tcsetattr (0, TCSANOW, &oldtty);
2378 fcntl(0, F_SETFL, old_fd0_flags);
2381 static void term_init(void)
2383 struct termios tty;
2385 tcgetattr (0, &tty);
2386 oldtty = tty;
2387 old_fd0_flags = fcntl(0, F_GETFL);
2389 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2390 |INLCR|IGNCR|ICRNL|IXON);
2391 tty.c_oflag |= OPOST;
2392 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2393 /* if graphical mode, we allow Ctrl-C handling */
2394 if (nographic)
2395 tty.c_lflag &= ~ISIG;
2396 tty.c_cflag &= ~(CSIZE|PARENB);
2397 tty.c_cflag |= CS8;
2398 tty.c_cc[VMIN] = 1;
2399 tty.c_cc[VTIME] = 0;
2401 tcsetattr (0, TCSANOW, &tty);
2403 if (!term_atexit_done++)
2404 atexit(term_exit);
2406 fcntl(0, F_SETFL, O_NONBLOCK);
2409 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2411 term_exit();
2412 stdio_nb_clients--;
2413 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2414 fd_chr_close(chr);
2417 static CharDriverState *qemu_chr_open_stdio(void)
2419 CharDriverState *chr;
2421 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2422 return NULL;
2423 chr = qemu_chr_open_fd(0, 1);
2424 chr->chr_close = qemu_chr_close_stdio;
2425 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2426 stdio_nb_clients++;
2427 term_init();
2429 return chr;
2432 #ifdef __sun__
2433 /* Once Solaris has openpty(), this is going to be removed. */
2434 int openpty(int *amaster, int *aslave, char *name,
2435 struct termios *termp, struct winsize *winp)
2437 const char *slave;
2438 int mfd = -1, sfd = -1;
2440 *amaster = *aslave = -1;
2442 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2443 if (mfd < 0)
2444 goto err;
2446 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2447 goto err;
2449 if ((slave = ptsname(mfd)) == NULL)
2450 goto err;
2452 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2453 goto err;
2455 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2456 (termp != NULL && tcgetattr(sfd, termp) < 0))
2457 goto err;
2459 if (amaster)
2460 *amaster = mfd;
2461 if (aslave)
2462 *aslave = sfd;
2463 if (winp)
2464 ioctl(sfd, TIOCSWINSZ, winp);
2466 return 0;
2468 err:
2469 if (sfd != -1)
2470 close(sfd);
2471 close(mfd);
2472 return -1;
2475 void cfmakeraw (struct termios *termios_p)
2477 termios_p->c_iflag &=
2478 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2479 termios_p->c_oflag &= ~OPOST;
2480 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2481 termios_p->c_cflag &= ~(CSIZE|PARENB);
2482 termios_p->c_cflag |= CS8;
2484 termios_p->c_cc[VMIN] = 0;
2485 termios_p->c_cc[VTIME] = 0;
2487 #endif
2489 #if defined(__linux__) || defined(__sun__)
2491 typedef struct {
2492 int fd;
2493 int connected;
2494 int polling;
2495 int read_bytes;
2496 QEMUTimer *timer;
2497 } PtyCharDriver;
2499 static void pty_chr_update_read_handler(CharDriverState *chr);
2500 static void pty_chr_state(CharDriverState *chr, int connected);
2502 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2504 PtyCharDriver *s = chr->opaque;
2506 if (!s->connected) {
2507 /* guest sends data, check for (re-)connect */
2508 pty_chr_update_read_handler(chr);
2509 return 0;
2511 return unix_write(s->fd, buf, len);
2514 static int pty_chr_read_poll(void *opaque)
2516 CharDriverState *chr = opaque;
2517 PtyCharDriver *s = chr->opaque;
2519 s->read_bytes = qemu_chr_can_read(chr);
2520 return s->read_bytes;
2523 static void pty_chr_read(void *opaque)
2525 CharDriverState *chr = opaque;
2526 PtyCharDriver *s = chr->opaque;
2527 int size, len;
2528 uint8_t buf[1024];
2530 len = sizeof(buf);
2531 if (len > s->read_bytes)
2532 len = s->read_bytes;
2533 if (len == 0)
2534 return;
2535 size = read(s->fd, buf, len);
2536 if ((size == -1 && errno == EIO) ||
2537 (size == 0)) {
2538 pty_chr_state(chr, 0);
2539 return;
2541 if (size > 0) {
2542 pty_chr_state(chr, 1);
2543 qemu_chr_read(chr, buf, size);
2547 static void pty_chr_update_read_handler(CharDriverState *chr)
2549 PtyCharDriver *s = chr->opaque;
2551 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2552 pty_chr_read, NULL, chr);
2553 s->polling = 1;
2555 * Short timeout here: just need wait long enougth that qemu makes
2556 * it through the poll loop once. When reconnected we want a
2557 * short timeout so we notice it almost instantly. Otherwise
2558 * read() gives us -EIO instantly, making pty_chr_state() reset the
2559 * timeout to the normal (much longer) poll interval before the
2560 * timer triggers.
2562 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2565 static void pty_chr_state(CharDriverState *chr, int connected)
2567 PtyCharDriver *s = chr->opaque;
2569 if (!connected) {
2570 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2571 s->connected = 0;
2572 s->polling = 0;
2573 /* (re-)connect poll interval for idle guests: once per second.
2574 * We check more frequently in case the guests sends data to
2575 * the virtual device linked to our pty. */
2576 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2577 } else {
2578 if (!s->connected)
2579 qemu_chr_reset(chr);
2580 s->connected = 1;
2584 void pty_chr_timer(void *opaque)
2586 struct CharDriverState *chr = opaque;
2587 PtyCharDriver *s = chr->opaque;
2589 if (s->connected)
2590 return;
2591 if (s->polling) {
2592 /* If we arrive here without polling being cleared due
2593 * read returning -EIO, then we are (re-)connected */
2594 pty_chr_state(chr, 1);
2595 return;
2598 /* Next poll ... */
2599 pty_chr_update_read_handler(chr);
2602 static void pty_chr_close(struct CharDriverState *chr)
2604 PtyCharDriver *s = chr->opaque;
2606 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2607 close(s->fd);
2608 qemu_free(s);
2611 static CharDriverState *qemu_chr_open_pty(void)
2613 CharDriverState *chr;
2614 PtyCharDriver *s;
2615 struct termios tty;
2616 int slave_fd;
2618 chr = qemu_mallocz(sizeof(CharDriverState));
2619 if (!chr)
2620 return NULL;
2621 s = qemu_mallocz(sizeof(PtyCharDriver));
2622 if (!s) {
2623 qemu_free(chr);
2624 return NULL;
2627 if (openpty(&s->fd, &slave_fd, NULL, NULL, NULL) < 0) {
2628 return NULL;
2631 /* Set raw attributes on the pty. */
2632 cfmakeraw(&tty);
2633 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2634 close(slave_fd);
2636 fprintf(stderr, "char device redirected to %s\n", ptsname(s->fd));
2638 chr->opaque = s;
2639 chr->chr_write = pty_chr_write;
2640 chr->chr_update_read_handler = pty_chr_update_read_handler;
2641 chr->chr_close = pty_chr_close;
2643 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2645 return chr;
2648 static void tty_serial_init(int fd, int speed,
2649 int parity, int data_bits, int stop_bits)
2651 struct termios tty;
2652 speed_t spd;
2654 #if 0
2655 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2656 speed, parity, data_bits, stop_bits);
2657 #endif
2658 tcgetattr (fd, &tty);
2660 #define MARGIN 1.1
2661 if (speed <= 50 * MARGIN)
2662 spd = B50;
2663 else if (speed <= 75 * MARGIN)
2664 spd = B75;
2665 else if (speed <= 300 * MARGIN)
2666 spd = B300;
2667 else if (speed <= 600 * MARGIN)
2668 spd = B600;
2669 else if (speed <= 1200 * MARGIN)
2670 spd = B1200;
2671 else if (speed <= 2400 * MARGIN)
2672 spd = B2400;
2673 else if (speed <= 4800 * MARGIN)
2674 spd = B4800;
2675 else if (speed <= 9600 * MARGIN)
2676 spd = B9600;
2677 else if (speed <= 19200 * MARGIN)
2678 spd = B19200;
2679 else if (speed <= 38400 * MARGIN)
2680 spd = B38400;
2681 else if (speed <= 57600 * MARGIN)
2682 spd = B57600;
2683 else if (speed <= 115200 * MARGIN)
2684 spd = B115200;
2685 else
2686 spd = B115200;
2688 cfsetispeed(&tty, spd);
2689 cfsetospeed(&tty, spd);
2691 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2692 |INLCR|IGNCR|ICRNL|IXON);
2693 tty.c_oflag |= OPOST;
2694 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2695 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2696 switch(data_bits) {
2697 default:
2698 case 8:
2699 tty.c_cflag |= CS8;
2700 break;
2701 case 7:
2702 tty.c_cflag |= CS7;
2703 break;
2704 case 6:
2705 tty.c_cflag |= CS6;
2706 break;
2707 case 5:
2708 tty.c_cflag |= CS5;
2709 break;
2711 switch(parity) {
2712 default:
2713 case 'N':
2714 break;
2715 case 'E':
2716 tty.c_cflag |= PARENB;
2717 break;
2718 case 'O':
2719 tty.c_cflag |= PARENB | PARODD;
2720 break;
2722 if (stop_bits == 2)
2723 tty.c_cflag |= CSTOPB;
2725 tcsetattr (fd, TCSANOW, &tty);
2728 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2730 FDCharDriver *s = chr->opaque;
2732 switch(cmd) {
2733 case CHR_IOCTL_SERIAL_SET_PARAMS:
2735 QEMUSerialSetParams *ssp = arg;
2736 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2737 ssp->data_bits, ssp->stop_bits);
2739 break;
2740 case CHR_IOCTL_SERIAL_SET_BREAK:
2742 int enable = *(int *)arg;
2743 if (enable)
2744 tcsendbreak(s->fd_in, 1);
2746 break;
2747 default:
2748 return -ENOTSUP;
2750 return 0;
2753 static CharDriverState *qemu_chr_open_tty(const char *filename)
2755 CharDriverState *chr;
2756 int fd;
2758 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2759 tty_serial_init(fd, 115200, 'N', 8, 1);
2760 chr = qemu_chr_open_fd(fd, fd);
2761 if (!chr) {
2762 close(fd);
2763 return NULL;
2765 chr->chr_ioctl = tty_serial_ioctl;
2766 qemu_chr_reset(chr);
2767 return chr;
2769 #else /* ! __linux__ && ! __sun__ */
2770 static CharDriverState *qemu_chr_open_pty(void)
2772 return NULL;
2774 #endif /* __linux__ || __sun__ */
2776 #if defined(__linux__)
2777 typedef struct {
2778 int fd;
2779 int mode;
2780 } ParallelCharDriver;
2782 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2784 if (s->mode != mode) {
2785 int m = mode;
2786 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2787 return 0;
2788 s->mode = mode;
2790 return 1;
2793 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2795 ParallelCharDriver *drv = chr->opaque;
2796 int fd = drv->fd;
2797 uint8_t b;
2799 switch(cmd) {
2800 case CHR_IOCTL_PP_READ_DATA:
2801 if (ioctl(fd, PPRDATA, &b) < 0)
2802 return -ENOTSUP;
2803 *(uint8_t *)arg = b;
2804 break;
2805 case CHR_IOCTL_PP_WRITE_DATA:
2806 b = *(uint8_t *)arg;
2807 if (ioctl(fd, PPWDATA, &b) < 0)
2808 return -ENOTSUP;
2809 break;
2810 case CHR_IOCTL_PP_READ_CONTROL:
2811 if (ioctl(fd, PPRCONTROL, &b) < 0)
2812 return -ENOTSUP;
2813 /* Linux gives only the lowest bits, and no way to know data
2814 direction! For better compatibility set the fixed upper
2815 bits. */
2816 *(uint8_t *)arg = b | 0xc0;
2817 break;
2818 case CHR_IOCTL_PP_WRITE_CONTROL:
2819 b = *(uint8_t *)arg;
2820 if (ioctl(fd, PPWCONTROL, &b) < 0)
2821 return -ENOTSUP;
2822 break;
2823 case CHR_IOCTL_PP_READ_STATUS:
2824 if (ioctl(fd, PPRSTATUS, &b) < 0)
2825 return -ENOTSUP;
2826 *(uint8_t *)arg = b;
2827 break;
2828 case CHR_IOCTL_PP_EPP_READ_ADDR:
2829 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2830 struct ParallelIOArg *parg = arg;
2831 int n = read(fd, parg->buffer, parg->count);
2832 if (n != parg->count) {
2833 return -EIO;
2836 break;
2837 case CHR_IOCTL_PP_EPP_READ:
2838 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2839 struct ParallelIOArg *parg = arg;
2840 int n = read(fd, parg->buffer, parg->count);
2841 if (n != parg->count) {
2842 return -EIO;
2845 break;
2846 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2847 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2848 struct ParallelIOArg *parg = arg;
2849 int n = write(fd, parg->buffer, parg->count);
2850 if (n != parg->count) {
2851 return -EIO;
2854 break;
2855 case CHR_IOCTL_PP_EPP_WRITE:
2856 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2857 struct ParallelIOArg *parg = arg;
2858 int n = write(fd, parg->buffer, parg->count);
2859 if (n != parg->count) {
2860 return -EIO;
2863 break;
2864 default:
2865 return -ENOTSUP;
2867 return 0;
2870 static void pp_close(CharDriverState *chr)
2872 ParallelCharDriver *drv = chr->opaque;
2873 int fd = drv->fd;
2875 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2876 ioctl(fd, PPRELEASE);
2877 close(fd);
2878 qemu_free(drv);
2881 static CharDriverState *qemu_chr_open_pp(const char *filename)
2883 CharDriverState *chr;
2884 ParallelCharDriver *drv;
2885 int fd;
2887 TFR(fd = open(filename, O_RDWR));
2888 if (fd < 0)
2889 return NULL;
2891 if (ioctl(fd, PPCLAIM) < 0) {
2892 close(fd);
2893 return NULL;
2896 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2897 if (!drv) {
2898 close(fd);
2899 return NULL;
2901 drv->fd = fd;
2902 drv->mode = IEEE1284_MODE_COMPAT;
2904 chr = qemu_mallocz(sizeof(CharDriverState));
2905 if (!chr) {
2906 qemu_free(drv);
2907 close(fd);
2908 return NULL;
2910 chr->chr_write = null_chr_write;
2911 chr->chr_ioctl = pp_ioctl;
2912 chr->chr_close = pp_close;
2913 chr->opaque = drv;
2915 qemu_chr_reset(chr);
2917 return chr;
2919 #endif /* __linux__ */
2921 #else /* _WIN32 */
2923 typedef struct {
2924 int max_size;
2925 HANDLE hcom, hrecv, hsend;
2926 OVERLAPPED orecv, osend;
2927 BOOL fpipe;
2928 DWORD len;
2929 } WinCharState;
2931 #define NSENDBUF 2048
2932 #define NRECVBUF 2048
2933 #define MAXCONNECT 1
2934 #define NTIMEOUT 5000
2936 static int win_chr_poll(void *opaque);
2937 static int win_chr_pipe_poll(void *opaque);
2939 static void win_chr_close(CharDriverState *chr)
2941 WinCharState *s = chr->opaque;
2943 if (s->hsend) {
2944 CloseHandle(s->hsend);
2945 s->hsend = NULL;
2947 if (s->hrecv) {
2948 CloseHandle(s->hrecv);
2949 s->hrecv = NULL;
2951 if (s->hcom) {
2952 CloseHandle(s->hcom);
2953 s->hcom = NULL;
2955 if (s->fpipe)
2956 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2957 else
2958 qemu_del_polling_cb(win_chr_poll, chr);
2961 static int win_chr_init(CharDriverState *chr, const char *filename)
2963 WinCharState *s = chr->opaque;
2964 COMMCONFIG comcfg;
2965 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2966 COMSTAT comstat;
2967 DWORD size;
2968 DWORD err;
2970 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2971 if (!s->hsend) {
2972 fprintf(stderr, "Failed CreateEvent\n");
2973 goto fail;
2975 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2976 if (!s->hrecv) {
2977 fprintf(stderr, "Failed CreateEvent\n");
2978 goto fail;
2981 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2982 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2983 if (s->hcom == INVALID_HANDLE_VALUE) {
2984 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2985 s->hcom = NULL;
2986 goto fail;
2989 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2990 fprintf(stderr, "Failed SetupComm\n");
2991 goto fail;
2994 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2995 size = sizeof(COMMCONFIG);
2996 GetDefaultCommConfig(filename, &comcfg, &size);
2997 comcfg.dcb.DCBlength = sizeof(DCB);
2998 CommConfigDialog(filename, NULL, &comcfg);
3000 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3001 fprintf(stderr, "Failed SetCommState\n");
3002 goto fail;
3005 if (!SetCommMask(s->hcom, EV_ERR)) {
3006 fprintf(stderr, "Failed SetCommMask\n");
3007 goto fail;
3010 cto.ReadIntervalTimeout = MAXDWORD;
3011 if (!SetCommTimeouts(s->hcom, &cto)) {
3012 fprintf(stderr, "Failed SetCommTimeouts\n");
3013 goto fail;
3016 if (!ClearCommError(s->hcom, &err, &comstat)) {
3017 fprintf(stderr, "Failed ClearCommError\n");
3018 goto fail;
3020 qemu_add_polling_cb(win_chr_poll, chr);
3021 return 0;
3023 fail:
3024 win_chr_close(chr);
3025 return -1;
3028 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3030 WinCharState *s = chr->opaque;
3031 DWORD len, ret, size, err;
3033 len = len1;
3034 ZeroMemory(&s->osend, sizeof(s->osend));
3035 s->osend.hEvent = s->hsend;
3036 while (len > 0) {
3037 if (s->hsend)
3038 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3039 else
3040 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3041 if (!ret) {
3042 err = GetLastError();
3043 if (err == ERROR_IO_PENDING) {
3044 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3045 if (ret) {
3046 buf += size;
3047 len -= size;
3048 } else {
3049 break;
3051 } else {
3052 break;
3054 } else {
3055 buf += size;
3056 len -= size;
3059 return len1 - len;
3062 static int win_chr_read_poll(CharDriverState *chr)
3064 WinCharState *s = chr->opaque;
3066 s->max_size = qemu_chr_can_read(chr);
3067 return s->max_size;
3070 static void win_chr_readfile(CharDriverState *chr)
3072 WinCharState *s = chr->opaque;
3073 int ret, err;
3074 uint8_t buf[1024];
3075 DWORD size;
3077 ZeroMemory(&s->orecv, sizeof(s->orecv));
3078 s->orecv.hEvent = s->hrecv;
3079 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3080 if (!ret) {
3081 err = GetLastError();
3082 if (err == ERROR_IO_PENDING) {
3083 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3087 if (size > 0) {
3088 qemu_chr_read(chr, buf, size);
3092 static void win_chr_read(CharDriverState *chr)
3094 WinCharState *s = chr->opaque;
3096 if (s->len > s->max_size)
3097 s->len = s->max_size;
3098 if (s->len == 0)
3099 return;
3101 win_chr_readfile(chr);
3104 static int win_chr_poll(void *opaque)
3106 CharDriverState *chr = opaque;
3107 WinCharState *s = chr->opaque;
3108 COMSTAT status;
3109 DWORD comerr;
3111 ClearCommError(s->hcom, &comerr, &status);
3112 if (status.cbInQue > 0) {
3113 s->len = status.cbInQue;
3114 win_chr_read_poll(chr);
3115 win_chr_read(chr);
3116 return 1;
3118 return 0;
3121 static CharDriverState *qemu_chr_open_win(const char *filename)
3123 CharDriverState *chr;
3124 WinCharState *s;
3126 chr = qemu_mallocz(sizeof(CharDriverState));
3127 if (!chr)
3128 return NULL;
3129 s = qemu_mallocz(sizeof(WinCharState));
3130 if (!s) {
3131 free(chr);
3132 return NULL;
3134 chr->opaque = s;
3135 chr->chr_write = win_chr_write;
3136 chr->chr_close = win_chr_close;
3138 if (win_chr_init(chr, filename) < 0) {
3139 free(s);
3140 free(chr);
3141 return NULL;
3143 qemu_chr_reset(chr);
3144 return chr;
3147 static int win_chr_pipe_poll(void *opaque)
3149 CharDriverState *chr = opaque;
3150 WinCharState *s = chr->opaque;
3151 DWORD size;
3153 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3154 if (size > 0) {
3155 s->len = size;
3156 win_chr_read_poll(chr);
3157 win_chr_read(chr);
3158 return 1;
3160 return 0;
3163 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3165 WinCharState *s = chr->opaque;
3166 OVERLAPPED ov;
3167 int ret;
3168 DWORD size;
3169 char openname[256];
3171 s->fpipe = TRUE;
3173 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3174 if (!s->hsend) {
3175 fprintf(stderr, "Failed CreateEvent\n");
3176 goto fail;
3178 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3179 if (!s->hrecv) {
3180 fprintf(stderr, "Failed CreateEvent\n");
3181 goto fail;
3184 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3185 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3186 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3187 PIPE_WAIT,
3188 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3189 if (s->hcom == INVALID_HANDLE_VALUE) {
3190 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3191 s->hcom = NULL;
3192 goto fail;
3195 ZeroMemory(&ov, sizeof(ov));
3196 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3197 ret = ConnectNamedPipe(s->hcom, &ov);
3198 if (ret) {
3199 fprintf(stderr, "Failed ConnectNamedPipe\n");
3200 goto fail;
3203 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3204 if (!ret) {
3205 fprintf(stderr, "Failed GetOverlappedResult\n");
3206 if (ov.hEvent) {
3207 CloseHandle(ov.hEvent);
3208 ov.hEvent = NULL;
3210 goto fail;
3213 if (ov.hEvent) {
3214 CloseHandle(ov.hEvent);
3215 ov.hEvent = NULL;
3217 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3218 return 0;
3220 fail:
3221 win_chr_close(chr);
3222 return -1;
3226 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3228 CharDriverState *chr;
3229 WinCharState *s;
3231 chr = qemu_mallocz(sizeof(CharDriverState));
3232 if (!chr)
3233 return NULL;
3234 s = qemu_mallocz(sizeof(WinCharState));
3235 if (!s) {
3236 free(chr);
3237 return NULL;
3239 chr->opaque = s;
3240 chr->chr_write = win_chr_write;
3241 chr->chr_close = win_chr_close;
3243 if (win_chr_pipe_init(chr, filename) < 0) {
3244 free(s);
3245 free(chr);
3246 return NULL;
3248 qemu_chr_reset(chr);
3249 return chr;
3252 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3254 CharDriverState *chr;
3255 WinCharState *s;
3257 chr = qemu_mallocz(sizeof(CharDriverState));
3258 if (!chr)
3259 return NULL;
3260 s = qemu_mallocz(sizeof(WinCharState));
3261 if (!s) {
3262 free(chr);
3263 return NULL;
3265 s->hcom = fd_out;
3266 chr->opaque = s;
3267 chr->chr_write = win_chr_write;
3268 qemu_chr_reset(chr);
3269 return chr;
3272 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3274 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3277 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3279 HANDLE fd_out;
3281 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3282 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3283 if (fd_out == INVALID_HANDLE_VALUE)
3284 return NULL;
3286 return qemu_chr_open_win_file(fd_out);
3288 #endif /* !_WIN32 */
3290 /***********************************************************/
3291 /* UDP Net console */
3293 typedef struct {
3294 int fd;
3295 struct sockaddr_in daddr;
3296 uint8_t buf[1024];
3297 int bufcnt;
3298 int bufptr;
3299 int max_size;
3300 } NetCharDriver;
3302 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3304 NetCharDriver *s = chr->opaque;
3306 return sendto(s->fd, buf, len, 0,
3307 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3310 static int udp_chr_read_poll(void *opaque)
3312 CharDriverState *chr = opaque;
3313 NetCharDriver *s = chr->opaque;
3315 s->max_size = qemu_chr_can_read(chr);
3317 /* If there were any stray characters in the queue process them
3318 * first
3320 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3321 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3322 s->bufptr++;
3323 s->max_size = qemu_chr_can_read(chr);
3325 return s->max_size;
3328 static void udp_chr_read(void *opaque)
3330 CharDriverState *chr = opaque;
3331 NetCharDriver *s = chr->opaque;
3333 if (s->max_size == 0)
3334 return;
3335 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3336 s->bufptr = s->bufcnt;
3337 if (s->bufcnt <= 0)
3338 return;
3340 s->bufptr = 0;
3341 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3342 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3343 s->bufptr++;
3344 s->max_size = qemu_chr_can_read(chr);
3348 static void udp_chr_update_read_handler(CharDriverState *chr)
3350 NetCharDriver *s = chr->opaque;
3352 if (s->fd >= 0) {
3353 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3354 udp_chr_read, NULL, chr);
3358 #ifndef _WIN32
3359 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3360 #endif
3361 int parse_host_src_port(struct sockaddr_in *haddr,
3362 struct sockaddr_in *saddr,
3363 const char *str);
3365 static CharDriverState *qemu_chr_open_udp(const char *def)
3367 CharDriverState *chr = NULL;
3368 NetCharDriver *s = NULL;
3369 int fd = -1;
3370 struct sockaddr_in saddr;
3372 chr = qemu_mallocz(sizeof(CharDriverState));
3373 if (!chr)
3374 goto return_err;
3375 s = qemu_mallocz(sizeof(NetCharDriver));
3376 if (!s)
3377 goto return_err;
3379 fd = socket(PF_INET, SOCK_DGRAM, 0);
3380 if (fd < 0) {
3381 perror("socket(PF_INET, SOCK_DGRAM)");
3382 goto return_err;
3385 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3386 printf("Could not parse: %s\n", def);
3387 goto return_err;
3390 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3392 perror("bind");
3393 goto return_err;
3396 s->fd = fd;
3397 s->bufcnt = 0;
3398 s->bufptr = 0;
3399 chr->opaque = s;
3400 chr->chr_write = udp_chr_write;
3401 chr->chr_update_read_handler = udp_chr_update_read_handler;
3402 return chr;
3404 return_err:
3405 if (chr)
3406 free(chr);
3407 if (s)
3408 free(s);
3409 if (fd >= 0)
3410 closesocket(fd);
3411 return NULL;
3414 /***********************************************************/
3415 /* TCP Net console */
3417 typedef struct {
3418 int fd, listen_fd;
3419 int connected;
3420 int max_size;
3421 int do_telnetopt;
3422 int do_nodelay;
3423 int is_unix;
3424 } TCPCharDriver;
3426 static void tcp_chr_accept(void *opaque);
3428 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3430 TCPCharDriver *s = chr->opaque;
3431 if (s->connected) {
3432 return send_all(s->fd, buf, len);
3433 } else {
3434 /* XXX: indicate an error ? */
3435 return len;
3439 static int tcp_chr_read_poll(void *opaque)
3441 CharDriverState *chr = opaque;
3442 TCPCharDriver *s = chr->opaque;
3443 if (!s->connected)
3444 return 0;
3445 s->max_size = qemu_chr_can_read(chr);
3446 return s->max_size;
3449 #define IAC 255
3450 #define IAC_BREAK 243
3451 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3452 TCPCharDriver *s,
3453 uint8_t *buf, int *size)
3455 /* Handle any telnet client's basic IAC options to satisfy char by
3456 * char mode with no echo. All IAC options will be removed from
3457 * the buf and the do_telnetopt variable will be used to track the
3458 * state of the width of the IAC information.
3460 * IAC commands come in sets of 3 bytes with the exception of the
3461 * "IAC BREAK" command and the double IAC.
3464 int i;
3465 int j = 0;
3467 for (i = 0; i < *size; i++) {
3468 if (s->do_telnetopt > 1) {
3469 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3470 /* Double IAC means send an IAC */
3471 if (j != i)
3472 buf[j] = buf[i];
3473 j++;
3474 s->do_telnetopt = 1;
3475 } else {
3476 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3477 /* Handle IAC break commands by sending a serial break */
3478 qemu_chr_event(chr, CHR_EVENT_BREAK);
3479 s->do_telnetopt++;
3481 s->do_telnetopt++;
3483 if (s->do_telnetopt >= 4) {
3484 s->do_telnetopt = 1;
3486 } else {
3487 if ((unsigned char)buf[i] == IAC) {
3488 s->do_telnetopt = 2;
3489 } else {
3490 if (j != i)
3491 buf[j] = buf[i];
3492 j++;
3496 *size = j;
3499 static void tcp_chr_read(void *opaque)
3501 CharDriverState *chr = opaque;
3502 TCPCharDriver *s = chr->opaque;
3503 uint8_t buf[1024];
3504 int len, size;
3506 if (!s->connected || s->max_size <= 0)
3507 return;
3508 len = sizeof(buf);
3509 if (len > s->max_size)
3510 len = s->max_size;
3511 size = recv(s->fd, buf, len, 0);
3512 if (size == 0) {
3513 /* connection closed */
3514 s->connected = 0;
3515 if (s->listen_fd >= 0) {
3516 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3518 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3519 closesocket(s->fd);
3520 s->fd = -1;
3521 } else if (size > 0) {
3522 if (s->do_telnetopt)
3523 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3524 if (size > 0)
3525 qemu_chr_read(chr, buf, size);
3529 static void tcp_chr_connect(void *opaque)
3531 CharDriverState *chr = opaque;
3532 TCPCharDriver *s = chr->opaque;
3534 s->connected = 1;
3535 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3536 tcp_chr_read, NULL, chr);
3537 qemu_chr_reset(chr);
3540 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3541 static void tcp_chr_telnet_init(int fd)
3543 char buf[3];
3544 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3545 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3546 send(fd, (char *)buf, 3, 0);
3547 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3548 send(fd, (char *)buf, 3, 0);
3549 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3550 send(fd, (char *)buf, 3, 0);
3551 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3552 send(fd, (char *)buf, 3, 0);
3555 static void socket_set_nodelay(int fd)
3557 int val = 1;
3558 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3561 static void tcp_chr_accept(void *opaque)
3563 CharDriverState *chr = opaque;
3564 TCPCharDriver *s = chr->opaque;
3565 struct sockaddr_in saddr;
3566 #ifndef _WIN32
3567 struct sockaddr_un uaddr;
3568 #endif
3569 struct sockaddr *addr;
3570 socklen_t len;
3571 int fd;
3573 for(;;) {
3574 #ifndef _WIN32
3575 if (s->is_unix) {
3576 len = sizeof(uaddr);
3577 addr = (struct sockaddr *)&uaddr;
3578 } else
3579 #endif
3581 len = sizeof(saddr);
3582 addr = (struct sockaddr *)&saddr;
3584 fd = accept(s->listen_fd, addr, &len);
3585 if (fd < 0 && errno != EINTR) {
3586 return;
3587 } else if (fd >= 0) {
3588 if (s->do_telnetopt)
3589 tcp_chr_telnet_init(fd);
3590 break;
3593 socket_set_nonblock(fd);
3594 if (s->do_nodelay)
3595 socket_set_nodelay(fd);
3596 s->fd = fd;
3597 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3598 tcp_chr_connect(chr);
3601 static void tcp_chr_close(CharDriverState *chr)
3603 TCPCharDriver *s = chr->opaque;
3604 if (s->fd >= 0)
3605 closesocket(s->fd);
3606 if (s->listen_fd >= 0)
3607 closesocket(s->listen_fd);
3608 qemu_free(s);
3611 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3612 int is_telnet,
3613 int is_unix)
3615 CharDriverState *chr = NULL;
3616 TCPCharDriver *s = NULL;
3617 int fd = -1, ret, err, val;
3618 int is_listen = 0;
3619 int is_waitconnect = 1;
3620 int do_nodelay = 0;
3621 const char *ptr;
3622 struct sockaddr_in saddr;
3623 #ifndef _WIN32
3624 struct sockaddr_un uaddr;
3625 #endif
3626 struct sockaddr *addr;
3627 socklen_t addrlen;
3629 #ifndef _WIN32
3630 if (is_unix) {
3631 addr = (struct sockaddr *)&uaddr;
3632 addrlen = sizeof(uaddr);
3633 if (parse_unix_path(&uaddr, host_str) < 0)
3634 goto fail;
3635 } else
3636 #endif
3638 addr = (struct sockaddr *)&saddr;
3639 addrlen = sizeof(saddr);
3640 if (parse_host_port(&saddr, host_str) < 0)
3641 goto fail;
3644 ptr = host_str;
3645 while((ptr = strchr(ptr,','))) {
3646 ptr++;
3647 if (!strncmp(ptr,"server",6)) {
3648 is_listen = 1;
3649 } else if (!strncmp(ptr,"nowait",6)) {
3650 is_waitconnect = 0;
3651 } else if (!strncmp(ptr,"nodelay",6)) {
3652 do_nodelay = 1;
3653 } else {
3654 printf("Unknown option: %s\n", ptr);
3655 goto fail;
3658 if (!is_listen)
3659 is_waitconnect = 0;
3661 chr = qemu_mallocz(sizeof(CharDriverState));
3662 if (!chr)
3663 goto fail;
3664 s = qemu_mallocz(sizeof(TCPCharDriver));
3665 if (!s)
3666 goto fail;
3668 #ifndef _WIN32
3669 if (is_unix)
3670 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3671 else
3672 #endif
3673 fd = socket(PF_INET, SOCK_STREAM, 0);
3675 if (fd < 0)
3676 goto fail;
3678 if (!is_waitconnect)
3679 socket_set_nonblock(fd);
3681 s->connected = 0;
3682 s->fd = -1;
3683 s->listen_fd = -1;
3684 s->is_unix = is_unix;
3685 s->do_nodelay = do_nodelay && !is_unix;
3687 chr->opaque = s;
3688 chr->chr_write = tcp_chr_write;
3689 chr->chr_close = tcp_chr_close;
3691 if (is_listen) {
3692 /* allow fast reuse */
3693 #ifndef _WIN32
3694 if (is_unix) {
3695 char path[109];
3696 pstrcpy(path, sizeof(path), uaddr.sun_path);
3697 unlink(path);
3698 } else
3699 #endif
3701 val = 1;
3702 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3705 ret = bind(fd, addr, addrlen);
3706 if (ret < 0)
3707 goto fail;
3709 ret = listen(fd, 0);
3710 if (ret < 0)
3711 goto fail;
3713 s->listen_fd = fd;
3714 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3715 if (is_telnet)
3716 s->do_telnetopt = 1;
3717 } else {
3718 for(;;) {
3719 ret = connect(fd, addr, addrlen);
3720 if (ret < 0) {
3721 err = socket_error();
3722 if (err == EINTR || err == EWOULDBLOCK) {
3723 } else if (err == EINPROGRESS) {
3724 break;
3725 #ifdef _WIN32
3726 } else if (err == WSAEALREADY) {
3727 break;
3728 #endif
3729 } else {
3730 goto fail;
3732 } else {
3733 s->connected = 1;
3734 break;
3737 s->fd = fd;
3738 socket_set_nodelay(fd);
3739 if (s->connected)
3740 tcp_chr_connect(chr);
3741 else
3742 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3745 if (is_listen && is_waitconnect) {
3746 printf("QEMU waiting for connection on: %s\n", host_str);
3747 tcp_chr_accept(chr);
3748 socket_set_nonblock(s->listen_fd);
3751 return chr;
3752 fail:
3753 if (fd >= 0)
3754 closesocket(fd);
3755 qemu_free(s);
3756 qemu_free(chr);
3757 return NULL;
3760 CharDriverState *qemu_chr_open(const char *filename)
3762 const char *p;
3764 if (!strcmp(filename, "vc")) {
3765 return text_console_init(&display_state, 0);
3766 } else if (strstart(filename, "vc:", &p)) {
3767 return text_console_init(&display_state, p);
3768 } else if (!strcmp(filename, "null")) {
3769 return qemu_chr_open_null();
3770 } else
3771 if (strstart(filename, "tcp:", &p)) {
3772 return qemu_chr_open_tcp(p, 0, 0);
3773 } else
3774 if (strstart(filename, "telnet:", &p)) {
3775 return qemu_chr_open_tcp(p, 1, 0);
3776 } else
3777 if (strstart(filename, "udp:", &p)) {
3778 return qemu_chr_open_udp(p);
3779 } else
3780 if (strstart(filename, "mon:", &p)) {
3781 CharDriverState *drv = qemu_chr_open(p);
3782 if (drv) {
3783 drv = qemu_chr_open_mux(drv);
3784 monitor_init(drv, !nographic);
3785 return drv;
3787 printf("Unable to open driver: %s\n", p);
3788 return 0;
3789 } else
3790 #ifndef _WIN32
3791 if (strstart(filename, "unix:", &p)) {
3792 return qemu_chr_open_tcp(p, 0, 1);
3793 } else if (strstart(filename, "file:", &p)) {
3794 return qemu_chr_open_file_out(p);
3795 } else if (strstart(filename, "pipe:", &p)) {
3796 return qemu_chr_open_pipe(p);
3797 } else if (!strcmp(filename, "pty")) {
3798 return qemu_chr_open_pty();
3799 } else if (!strcmp(filename, "stdio")) {
3800 return qemu_chr_open_stdio();
3801 } else
3802 #if defined(__linux__)
3803 if (strstart(filename, "/dev/parport", NULL)) {
3804 return qemu_chr_open_pp(filename);
3805 } else
3806 #endif
3807 #if defined(__linux__) || defined(__sun__)
3808 if (strstart(filename, "/dev/", NULL)) {
3809 return qemu_chr_open_tty(filename);
3810 } else
3811 #endif
3812 #else /* !_WIN32 */
3813 if (strstart(filename, "COM", NULL)) {
3814 return qemu_chr_open_win(filename);
3815 } else
3816 if (strstart(filename, "pipe:", &p)) {
3817 return qemu_chr_open_win_pipe(p);
3818 } else
3819 if (strstart(filename, "con:", NULL)) {
3820 return qemu_chr_open_win_con(filename);
3821 } else
3822 if (strstart(filename, "file:", &p)) {
3823 return qemu_chr_open_win_file_out(p);
3824 } else
3825 #endif
3826 #ifdef CONFIG_BRLAPI
3827 if (!strcmp(filename, "braille")) {
3828 return chr_baum_init();
3829 } else
3830 #endif
3832 return NULL;
3836 void qemu_chr_close(CharDriverState *chr)
3838 if (chr->chr_close)
3839 chr->chr_close(chr);
3840 qemu_free(chr);
3843 /***********************************************************/
3844 /* network device redirectors */
3846 __attribute__ (( unused ))
3847 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3849 int len, i, j, c;
3851 for(i=0;i<size;i+=16) {
3852 len = size - i;
3853 if (len > 16)
3854 len = 16;
3855 fprintf(f, "%08x ", i);
3856 for(j=0;j<16;j++) {
3857 if (j < len)
3858 fprintf(f, " %02x", buf[i+j]);
3859 else
3860 fprintf(f, " ");
3862 fprintf(f, " ");
3863 for(j=0;j<len;j++) {
3864 c = buf[i+j];
3865 if (c < ' ' || c > '~')
3866 c = '.';
3867 fprintf(f, "%c", c);
3869 fprintf(f, "\n");
3873 static int parse_macaddr(uint8_t *macaddr, const char *p)
3875 int i;
3876 char *last_char;
3877 long int offset;
3879 errno = 0;
3880 offset = strtol(p, &last_char, 0);
3881 if (0 == errno && '\0' == *last_char &&
3882 offset >= 0 && offset <= 0xFFFFFF) {
3883 macaddr[3] = (offset & 0xFF0000) >> 16;
3884 macaddr[4] = (offset & 0xFF00) >> 8;
3885 macaddr[5] = offset & 0xFF;
3886 return 0;
3887 } else {
3888 for(i = 0; i < 6; i++) {
3889 macaddr[i] = strtol(p, (char **)&p, 16);
3890 if (i == 5) {
3891 if (*p != '\0')
3892 return -1;
3893 } else {
3894 if (*p != ':' && *p != '-')
3895 return -1;
3896 p++;
3899 return 0;
3902 return -1;
3905 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3907 const char *p, *p1;
3908 int len;
3909 p = *pp;
3910 p1 = strchr(p, sep);
3911 if (!p1)
3912 return -1;
3913 len = p1 - p;
3914 p1++;
3915 if (buf_size > 0) {
3916 if (len > buf_size - 1)
3917 len = buf_size - 1;
3918 memcpy(buf, p, len);
3919 buf[len] = '\0';
3921 *pp = p1;
3922 return 0;
3925 int parse_host_src_port(struct sockaddr_in *haddr,
3926 struct sockaddr_in *saddr,
3927 const char *input_str)
3929 char *str = strdup(input_str);
3930 char *host_str = str;
3931 char *src_str;
3932 char *ptr;
3935 * Chop off any extra arguments at the end of the string which
3936 * would start with a comma, then fill in the src port information
3937 * if it was provided else use the "any address" and "any port".
3939 if ((ptr = strchr(str,',')))
3940 *ptr = '\0';
3942 if ((src_str = strchr(input_str,'@'))) {
3943 *src_str = '\0';
3944 src_str++;
3947 if (parse_host_port(haddr, host_str) < 0)
3948 goto fail;
3950 if (!src_str || *src_str == '\0')
3951 src_str = ":0";
3953 if (parse_host_port(saddr, src_str) < 0)
3954 goto fail;
3956 free(str);
3957 return(0);
3959 fail:
3960 free(str);
3961 return -1;
3964 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3966 char buf[512];
3967 struct hostent *he;
3968 const char *p, *r;
3969 int port;
3971 p = str;
3972 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3973 return -1;
3974 saddr->sin_family = AF_INET;
3975 if (buf[0] == '\0') {
3976 saddr->sin_addr.s_addr = 0;
3977 } else {
3978 if (isdigit(buf[0])) {
3979 if (!inet_aton(buf, &saddr->sin_addr))
3980 return -1;
3981 } else {
3982 if ((he = gethostbyname(buf)) == NULL)
3983 return - 1;
3984 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3987 port = strtol(p, (char **)&r, 0);
3988 if (r == p)
3989 return -1;
3990 saddr->sin_port = htons(port);
3991 return 0;
3994 #ifndef _WIN32
3995 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3997 const char *p;
3998 int len;
4000 len = MIN(108, strlen(str));
4001 p = strchr(str, ',');
4002 if (p)
4003 len = MIN(len, p - str);
4005 memset(uaddr, 0, sizeof(*uaddr));
4007 uaddr->sun_family = AF_UNIX;
4008 memcpy(uaddr->sun_path, str, len);
4010 return 0;
4012 #endif
4014 /* find or alloc a new VLAN */
4015 VLANState *qemu_find_vlan(int id)
4017 VLANState **pvlan, *vlan;
4018 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4019 if (vlan->id == id)
4020 return vlan;
4022 vlan = qemu_mallocz(sizeof(VLANState));
4023 if (!vlan)
4024 return NULL;
4025 vlan->id = id;
4026 vlan->next = NULL;
4027 pvlan = &first_vlan;
4028 while (*pvlan != NULL)
4029 pvlan = &(*pvlan)->next;
4030 *pvlan = vlan;
4031 return vlan;
4034 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4035 IOReadHandler *fd_read,
4036 IOCanRWHandler *fd_can_read,
4037 void *opaque)
4039 VLANClientState *vc, **pvc;
4040 vc = qemu_mallocz(sizeof(VLANClientState));
4041 if (!vc)
4042 return NULL;
4043 vc->fd_read = fd_read;
4044 vc->fd_can_read = fd_can_read;
4045 vc->opaque = opaque;
4046 vc->vlan = vlan;
4048 vc->next = NULL;
4049 pvc = &vlan->first_client;
4050 while (*pvc != NULL)
4051 pvc = &(*pvc)->next;
4052 *pvc = vc;
4053 return vc;
4056 void qemu_del_vlan_client(VLANClientState *vc)
4058 VLANClientState **pvc = &vc->vlan->first_client;
4060 while (*pvc != NULL)
4061 if (*pvc == vc) {
4062 *pvc = vc->next;
4063 free(vc);
4064 break;
4065 } else
4066 pvc = &(*pvc)->next;
4069 int qemu_can_send_packet(VLANClientState *vc1)
4071 VLANState *vlan = vc1->vlan;
4072 VLANClientState *vc;
4074 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4075 if (vc != vc1) {
4076 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4077 return 1;
4080 return 0;
4083 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4085 VLANState *vlan = vc1->vlan;
4086 VLANClientState *vc;
4087 int ret = -EAGAIN;
4089 #if 0
4090 printf("vlan %d send:\n", vlan->id);
4091 hex_dump(stdout, buf, size);
4092 #endif
4093 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4094 if (vc != vc1) {
4095 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
4096 vc->fd_read(vc->opaque, buf, size);
4097 ret = 0;
4102 return ret;
4105 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
4106 int iovcnt)
4108 char buffer[4096];
4109 size_t offset = 0;
4110 int i;
4112 for (i = 0; i < iovcnt; i++) {
4113 size_t len;
4115 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
4116 memcpy(buffer + offset, iov[i].iov_base, len);
4117 offset += len;
4120 vc->fd_read(vc->opaque, buffer, offset);
4122 return offset;
4125 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
4126 int iovcnt)
4128 VLANState *vlan = vc1->vlan;
4129 VLANClientState *vc;
4130 ssize_t max_len = 0;
4132 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
4133 ssize_t len = 0;
4135 if (vc == vc1)
4136 continue;
4138 if (vc->fd_readv)
4139 len = vc->fd_readv(vc->opaque, iov, iovcnt);
4140 else if (vc->fd_read)
4141 len = vc_sendv_compat(vc, iov, iovcnt);
4143 max_len = MAX(max_len, len);
4146 return max_len;
4149 #if defined(CONFIG_SLIRP)
4151 /* slirp network adapter */
4153 static int slirp_inited;
4154 static VLANClientState *slirp_vc;
4156 int slirp_can_output(void)
4158 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4161 void slirp_output(const uint8_t *pkt, int pkt_len)
4163 #if 0
4164 printf("slirp output:\n");
4165 hex_dump(stdout, pkt, pkt_len);
4166 #endif
4167 if (!slirp_vc)
4168 return;
4169 qemu_send_packet(slirp_vc, pkt, pkt_len);
4172 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4174 #if 0
4175 printf("slirp input:\n");
4176 hex_dump(stdout, buf, size);
4177 #endif
4178 slirp_input(buf, size);
4181 static int net_slirp_init(VLANState *vlan)
4183 if (!slirp_inited) {
4184 slirp_inited = 1;
4185 slirp_init();
4187 slirp_vc = qemu_new_vlan_client(vlan,
4188 slirp_receive, NULL, NULL);
4189 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4190 return 0;
4193 static void net_slirp_redir(const char *redir_str)
4195 int is_udp;
4196 char buf[256], *r;
4197 const char *p;
4198 struct in_addr guest_addr;
4199 int host_port, guest_port;
4201 if (!slirp_inited) {
4202 slirp_inited = 1;
4203 slirp_init();
4206 p = redir_str;
4207 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4208 goto fail;
4209 if (!strcmp(buf, "tcp")) {
4210 is_udp = 0;
4211 } else if (!strcmp(buf, "udp")) {
4212 is_udp = 1;
4213 } else {
4214 goto fail;
4217 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4218 goto fail;
4219 host_port = strtol(buf, &r, 0);
4220 if (r == buf)
4221 goto fail;
4223 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4224 goto fail;
4225 if (buf[0] == '\0') {
4226 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4228 if (!inet_aton(buf, &guest_addr))
4229 goto fail;
4231 guest_port = strtol(p, &r, 0);
4232 if (r == p)
4233 goto fail;
4235 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4236 fprintf(stderr, "qemu: could not set up redirection\n");
4237 exit(1);
4239 return;
4240 fail:
4241 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4242 exit(1);
4245 #ifndef _WIN32
4247 char smb_dir[1024];
4249 static void erase_dir(char *dir_name)
4251 DIR *d;
4252 struct dirent *de;
4253 char filename[1024];
4255 /* erase all the files in the directory */
4256 if ((d = opendir(dir_name)) != 0) {
4257 for(;;) {
4258 de = readdir(d);
4259 if (!de)
4260 break;
4261 if (strcmp(de->d_name, ".") != 0 &&
4262 strcmp(de->d_name, "..") != 0) {
4263 snprintf(filename, sizeof(filename), "%s/%s",
4264 smb_dir, de->d_name);
4265 if (unlink(filename) != 0) /* is it a directory? */
4266 erase_dir(filename);
4269 closedir(d);
4270 rmdir(dir_name);
4274 /* automatic user mode samba server configuration */
4275 static void smb_exit(void)
4277 erase_dir(smb_dir);
4280 /* automatic user mode samba server configuration */
4281 static void net_slirp_smb(const char *exported_dir)
4283 char smb_conf[1024];
4284 char smb_cmdline[1024];
4285 FILE *f;
4287 if (!slirp_inited) {
4288 slirp_inited = 1;
4289 slirp_init();
4292 /* XXX: better tmp dir construction */
4293 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4294 if (mkdir(smb_dir, 0700) < 0) {
4295 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4296 exit(1);
4298 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4300 f = fopen(smb_conf, "w");
4301 if (!f) {
4302 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4303 exit(1);
4305 fprintf(f,
4306 "[global]\n"
4307 "private dir=%s\n"
4308 "smb ports=0\n"
4309 "socket address=127.0.0.1\n"
4310 "pid directory=%s\n"
4311 "lock directory=%s\n"
4312 "log file=%s/log.smbd\n"
4313 "smb passwd file=%s/smbpasswd\n"
4314 "security = share\n"
4315 "[qemu]\n"
4316 "path=%s\n"
4317 "read only=no\n"
4318 "guest ok=yes\n",
4319 smb_dir,
4320 smb_dir,
4321 smb_dir,
4322 smb_dir,
4323 smb_dir,
4324 exported_dir
4326 fclose(f);
4327 atexit(smb_exit);
4329 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4330 SMBD_COMMAND, smb_conf);
4332 slirp_add_exec(0, smb_cmdline, 4, 139);
4335 #endif /* !defined(_WIN32) */
4336 void do_info_slirp(void)
4338 slirp_stats();
4341 #endif /* CONFIG_SLIRP */
4343 #ifdef _WIN32
4345 int tap_has_vnet_hdr(void *opaque)
4347 return 0;
4350 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
4354 #else /* !defined(_WIN32) */
4356 #ifndef IFF_VNET_HDR
4357 #define TAP_BUFSIZE 4096
4358 #else
4359 #include <linux/virtio_net.h>
4360 #define ETH_HLEN 14
4361 #define ETH_DATA_LEN 1500
4362 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4363 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4364 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4365 #endif
4367 typedef struct TAPState {
4368 VLANClientState *vc;
4369 int fd;
4370 char down_script[1024];
4371 char buf[TAP_BUFSIZE];
4372 int size;
4373 unsigned int has_vnet_hdr : 1;
4374 unsigned int using_vnet_hdr : 1;
4375 } TAPState;
4377 static ssize_t tap_writev(void *opaque, const struct iovec *iov,
4378 int iovcnt)
4380 TAPState *s = opaque;
4381 ssize_t len;
4383 do {
4384 len = writev(s->fd, iov, iovcnt);
4385 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
4387 return len;
4390 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
4391 int iovcnt)
4393 #ifdef IFF_VNET_HDR
4394 TAPState *s = opaque;
4396 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4397 struct iovec *iov_copy;
4398 struct virtio_net_hdr hdr = { 0, };
4400 iov_copy = alloca(sizeof(struct iovec) * (iovcnt + 1));
4402 iov_copy[0].iov_base = &hdr;
4403 iov_copy[0].iov_len = sizeof(hdr);
4405 memcpy(&iov_copy[1], iov, sizeof(struct iovec) * iovcnt);
4407 return tap_writev(opaque, iov_copy, iovcnt + 1);
4409 #endif
4411 return tap_writev(opaque, iov, iovcnt);
4414 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4416 struct iovec iov[2];
4417 int i = 0;
4419 #ifdef IFF_VNET_HDR
4420 TAPState *s = opaque;
4421 struct virtio_net_hdr hdr = { 0, };
4423 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4424 iov[i].iov_base = &hdr;
4425 iov[i].iov_len = sizeof(hdr);
4426 i++;
4428 #endif
4430 iov[i].iov_base = (char *) buf;
4431 iov[i].iov_len = size;
4432 i++;
4434 tap_writev(opaque, iov, i);
4437 static int tap_can_send(void *opaque)
4439 TAPState *s = opaque;
4440 VLANClientState *vc;
4441 int can_receive = 0;
4443 /* Check to see if any of our clients can receive a packet */
4444 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
4445 /* Skip ourselves */
4446 if (vc == s->vc)
4447 continue;
4449 if (!vc->fd_can_read) {
4450 /* no fd_can_read handler, they always can receive */
4451 can_receive = 1;
4452 } else
4453 can_receive = vc->fd_can_read(vc->opaque);
4455 /* Once someone can receive, we try to send a packet */
4456 if (can_receive)
4457 break;
4460 return can_receive;
4463 static int tap_send_packet(TAPState *s)
4465 uint8_t *buf = s->buf;
4466 int size = s->size;
4468 #ifdef IFF_VNET_HDR
4469 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4470 buf += sizeof(struct virtio_net_hdr);
4471 size -= sizeof(struct virtio_net_hdr);
4473 #endif
4475 return qemu_send_packet(s->vc, buf, size);
4478 static void tap_send(void *opaque)
4480 TAPState *s = opaque;
4482 /* First try to send any buffered packet */
4483 if (s->size > 0) {
4484 int err;
4486 /* If noone can receive the packet, buffer it */
4487 err = tap_send_packet(s);
4488 if (err == -EAGAIN)
4489 return;
4492 /* Read packets until we hit EAGAIN */
4493 do {
4494 #ifdef __sun__
4495 struct strbuf sbuf;
4496 int f = 0;
4497 sbuf.maxlen = sizeof(s->buf);
4498 sbuf.buf = s->buf;
4499 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4500 #else
4501 kvm_sleep_begin();
4502 s->size = read(s->fd, s->buf, sizeof(s->buf));
4503 kvm_sleep_end();
4504 #endif
4506 if (s->size == -1 && errno == EINTR)
4507 continue;
4509 if (s->size > 0) {
4510 int err;
4512 /* If noone can receive the packet, buffer it */
4513 err = tap_send_packet(s);
4514 if (err == -EAGAIN)
4515 break;
4517 } while (s->size > 0);
4520 int tap_has_vnet_hdr(void *opaque)
4522 VLANClientState *vc = opaque;
4523 TAPState *s = vc->opaque;
4525 return s ? s->has_vnet_hdr : 0;
4528 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
4530 VLANClientState *vc = opaque;
4531 TAPState *s = vc->opaque;
4533 if (!s || !s->has_vnet_hdr)
4534 return;
4536 s->using_vnet_hdr = using_vnet_hdr != 0;
4539 #ifdef TUNSETOFFLOAD
4540 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
4541 int ecn)
4543 TAPState *s = vc->opaque;
4544 unsigned int offload = 0;
4546 if (csum) {
4547 offload |= TUN_F_CSUM;
4548 if (tso4)
4549 offload |= TUN_F_TSO4;
4550 if (tso6)
4551 offload |= TUN_F_TSO6;
4552 if ((tso4 || tso6) && ecn)
4553 offload |= TUN_F_TSO_ECN;
4556 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
4557 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
4558 strerror(errno));
4560 #endif /* TUNSETOFFLOAD */
4562 /* fd support */
4564 static TAPState *net_tap_fd_init(VLANState *vlan, int fd, int vnet_hdr)
4566 TAPState *s;
4568 s = qemu_mallocz(sizeof(TAPState));
4569 if (!s)
4570 return NULL;
4571 s->fd = fd;
4572 s->has_vnet_hdr = vnet_hdr != 0;
4573 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4574 s->vc->fd_readv = tap_receive_iov;
4575 #ifdef TUNSETOFFLOAD
4576 s->vc->set_offload = tap_set_offload;
4577 #endif
4578 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
4579 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4580 return s;
4583 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4584 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4586 int fd;
4587 char *dev;
4588 struct stat s;
4590 TFR(fd = open("/dev/tap", O_RDWR));
4591 if (fd < 0) {
4592 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4593 return -1;
4596 fstat(fd, &s);
4597 dev = devname(s.st_rdev, S_IFCHR);
4598 pstrcpy(ifname, ifname_size, dev);
4600 fcntl(fd, F_SETFL, O_NONBLOCK);
4601 return fd;
4603 #elif defined(__sun__)
4604 #define TUNNEWPPA (('T'<<16) | 0x0001)
4606 * Allocate TAP device, returns opened fd.
4607 * Stores dev name in the first arg(must be large enough).
4609 int tap_alloc(char *dev)
4611 int tap_fd, if_fd, ppa = -1;
4612 static int ip_fd = 0;
4613 char *ptr;
4615 static int arp_fd = 0;
4616 int ip_muxid, arp_muxid;
4617 struct strioctl strioc_if, strioc_ppa;
4618 int link_type = I_PLINK;;
4619 struct lifreq ifr;
4620 char actual_name[32] = "";
4622 memset(&ifr, 0x0, sizeof(ifr));
4624 if( *dev ){
4625 ptr = dev;
4626 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4627 ppa = atoi(ptr);
4630 /* Check if IP device was opened */
4631 if( ip_fd )
4632 close(ip_fd);
4634 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4635 if (ip_fd < 0) {
4636 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4637 return -1;
4640 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4641 if (tap_fd < 0) {
4642 syslog(LOG_ERR, "Can't open /dev/tap");
4643 return -1;
4646 /* Assign a new PPA and get its unit number. */
4647 strioc_ppa.ic_cmd = TUNNEWPPA;
4648 strioc_ppa.ic_timout = 0;
4649 strioc_ppa.ic_len = sizeof(ppa);
4650 strioc_ppa.ic_dp = (char *)&ppa;
4651 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4652 syslog (LOG_ERR, "Can't assign new interface");
4654 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4655 if (if_fd < 0) {
4656 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4657 return -1;
4659 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4660 syslog(LOG_ERR, "Can't push IP module");
4661 return -1;
4664 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4665 syslog(LOG_ERR, "Can't get flags\n");
4667 snprintf (actual_name, 32, "tap%d", ppa);
4668 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4670 ifr.lifr_ppa = ppa;
4671 /* Assign ppa according to the unit number returned by tun device */
4673 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4674 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4675 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4676 syslog (LOG_ERR, "Can't get flags\n");
4677 /* Push arp module to if_fd */
4678 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4679 syslog (LOG_ERR, "Can't push ARP module (2)");
4681 /* Push arp module to ip_fd */
4682 if (ioctl (ip_fd, I_POP, NULL) < 0)
4683 syslog (LOG_ERR, "I_POP failed\n");
4684 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4685 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4686 /* Open arp_fd */
4687 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4688 if (arp_fd < 0)
4689 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4691 /* Set ifname to arp */
4692 strioc_if.ic_cmd = SIOCSLIFNAME;
4693 strioc_if.ic_timout = 0;
4694 strioc_if.ic_len = sizeof(ifr);
4695 strioc_if.ic_dp = (char *)&ifr;
4696 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4697 syslog (LOG_ERR, "Can't set ifname to arp\n");
4700 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4701 syslog(LOG_ERR, "Can't link TAP device to IP");
4702 return -1;
4705 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4706 syslog (LOG_ERR, "Can't link TAP device to ARP");
4708 close (if_fd);
4710 memset(&ifr, 0x0, sizeof(ifr));
4711 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4712 ifr.lifr_ip_muxid = ip_muxid;
4713 ifr.lifr_arp_muxid = arp_muxid;
4715 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4717 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4718 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4719 syslog (LOG_ERR, "Can't set multiplexor id");
4722 sprintf(dev, "tap%d", ppa);
4723 return tap_fd;
4726 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4728 char dev[10]="";
4729 int fd;
4730 if( (fd = tap_alloc(dev)) < 0 ){
4731 fprintf(stderr, "Cannot allocate TAP device\n");
4732 return -1;
4734 pstrcpy(ifname, ifname_size, dev);
4735 fcntl(fd, F_SETFL, O_NONBLOCK);
4736 return fd;
4738 #else
4739 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4741 struct ifreq ifr;
4742 int fd, ret;
4744 TFR(fd = open("/dev/net/tun", O_RDWR));
4745 if (fd < 0) {
4746 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4747 return -1;
4749 memset(&ifr, 0, sizeof(ifr));
4750 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4752 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4754 unsigned int features;
4756 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
4757 features & IFF_VNET_HDR) {
4758 *vnet_hdr = 1;
4759 ifr.ifr_flags |= IFF_VNET_HDR;
4762 #endif
4764 if (ifname[0] != '\0')
4765 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4766 else
4767 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4768 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4769 if (ret != 0) {
4770 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4771 close(fd);
4772 return -1;
4774 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4775 fcntl(fd, F_SETFL, O_NONBLOCK);
4776 return fd;
4778 #endif
4780 static int launch_script(const char *setup_script, const char *ifname, int fd)
4782 int pid, status;
4783 char *args[3];
4784 char **parg;
4786 /* try to launch network script */
4787 pid = fork();
4788 if (pid >= 0) {
4789 if (pid == 0) {
4790 int open_max = sysconf (_SC_OPEN_MAX), i;
4791 for (i = 0; i < open_max; i++)
4792 if (i != STDIN_FILENO &&
4793 i != STDOUT_FILENO &&
4794 i != STDERR_FILENO &&
4795 i != fd)
4796 close(i);
4798 parg = args;
4799 *parg++ = (char *)setup_script;
4800 *parg++ = (char *)ifname;
4801 *parg++ = NULL;
4802 execv(setup_script, args);
4803 _exit(1);
4805 while (waitpid(pid, &status, 0) != pid);
4806 if (!WIFEXITED(status) ||
4807 WEXITSTATUS(status) != 0) {
4808 fprintf(stderr, "%s: could not launch network script\n",
4809 setup_script);
4810 return -1;
4813 return 0;
4816 static int net_tap_init(VLANState *vlan, const char *ifname1,
4817 const char *setup_script, const char *down_script)
4819 TAPState *s;
4820 int fd;
4821 int vnet_hdr;
4822 char ifname[128];
4824 if (ifname1 != NULL)
4825 pstrcpy(ifname, sizeof(ifname), ifname1);
4826 else
4827 ifname[0] = '\0';
4828 vnet_hdr = 0;
4829 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
4830 if (fd < 0)
4831 return -1;
4833 if (!setup_script || !strcmp(setup_script, "no"))
4834 setup_script = "";
4835 if (setup_script[0] != '\0') {
4836 if (launch_script(setup_script, ifname, fd))
4837 return -1;
4839 s = net_tap_fd_init(vlan, fd, vnet_hdr);
4840 if (!s)
4841 return -1;
4843 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4844 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4845 if (down_script && strcmp(down_script, "no"))
4846 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4847 return 0;
4850 #endif /* !_WIN32 */
4852 #if defined(CONFIG_VDE)
4853 typedef struct VDEState {
4854 VLANClientState *vc;
4855 VDECONN *vde;
4856 } VDEState;
4858 static void vde_to_qemu(void *opaque)
4860 VDEState *s = opaque;
4861 uint8_t buf[4096];
4862 int size;
4864 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4865 if (size > 0) {
4866 qemu_send_packet(s->vc, buf, size);
4870 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4872 VDEState *s = opaque;
4873 int ret;
4874 for(;;) {
4875 ret = vde_send(s->vde, buf, size, 0);
4876 if (ret < 0 && errno == EINTR) {
4877 } else {
4878 break;
4883 static int net_vde_init(VLANState *vlan, const char *sock, int port,
4884 const char *group, int mode)
4886 VDEState *s;
4887 char *init_group = strlen(group) ? (char *)group : NULL;
4888 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4890 struct vde_open_args args = {
4891 .port = port,
4892 .group = init_group,
4893 .mode = mode,
4896 s = qemu_mallocz(sizeof(VDEState));
4897 if (!s)
4898 return -1;
4899 s->vde = vde_open(init_sock, "QEMU", &args);
4900 if (!s->vde){
4901 free(s);
4902 return -1;
4904 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4905 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4906 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4907 sock, vde_datafd(s->vde));
4908 return 0;
4910 #endif
4912 /* network connection */
4913 typedef struct NetSocketState {
4914 VLANClientState *vc;
4915 int fd;
4916 int state; /* 0 = getting length, 1 = getting data */
4917 int index;
4918 int packet_len;
4919 uint8_t buf[4096];
4920 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4921 } NetSocketState;
4923 typedef struct NetSocketListenState {
4924 VLANState *vlan;
4925 int fd;
4926 } NetSocketListenState;
4928 /* XXX: we consider we can send the whole packet without blocking */
4929 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4931 NetSocketState *s = opaque;
4932 uint32_t len;
4933 len = htonl(size);
4935 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4936 send_all(s->fd, buf, size);
4939 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4941 NetSocketState *s = opaque;
4942 sendto(s->fd, buf, size, 0,
4943 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4946 static void net_socket_send(void *opaque)
4948 NetSocketState *s = opaque;
4949 int l, size, err;
4950 uint8_t buf1[4096];
4951 const uint8_t *buf;
4953 size = recv(s->fd, buf1, sizeof(buf1), 0);
4954 if (size < 0) {
4955 err = socket_error();
4956 if (err != EWOULDBLOCK)
4957 goto eoc;
4958 } else if (size == 0) {
4959 /* end of connection */
4960 eoc:
4961 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4962 closesocket(s->fd);
4963 return;
4965 buf = buf1;
4966 while (size > 0) {
4967 /* reassemble a packet from the network */
4968 switch(s->state) {
4969 case 0:
4970 l = 4 - s->index;
4971 if (l > size)
4972 l = size;
4973 memcpy(s->buf + s->index, buf, l);
4974 buf += l;
4975 size -= l;
4976 s->index += l;
4977 if (s->index == 4) {
4978 /* got length */
4979 s->packet_len = ntohl(*(uint32_t *)s->buf);
4980 s->index = 0;
4981 s->state = 1;
4983 break;
4984 case 1:
4985 l = s->packet_len - s->index;
4986 if (l > size)
4987 l = size;
4988 memcpy(s->buf + s->index, buf, l);
4989 s->index += l;
4990 buf += l;
4991 size -= l;
4992 if (s->index >= s->packet_len) {
4993 qemu_send_packet(s->vc, s->buf, s->packet_len);
4994 s->index = 0;
4995 s->state = 0;
4997 break;
5002 static void net_socket_send_dgram(void *opaque)
5004 NetSocketState *s = opaque;
5005 int size;
5007 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
5008 if (size < 0)
5009 return;
5010 if (size == 0) {
5011 /* end of connection */
5012 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
5013 return;
5015 qemu_send_packet(s->vc, s->buf, size);
5018 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
5020 struct ip_mreq imr;
5021 int fd;
5022 int val, ret;
5023 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
5024 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5025 inet_ntoa(mcastaddr->sin_addr),
5026 (int)ntohl(mcastaddr->sin_addr.s_addr));
5027 return -1;
5030 fd = socket(PF_INET, SOCK_DGRAM, 0);
5031 if (fd < 0) {
5032 perror("socket(PF_INET, SOCK_DGRAM)");
5033 return -1;
5036 val = 1;
5037 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
5038 (const char *)&val, sizeof(val));
5039 if (ret < 0) {
5040 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5041 goto fail;
5044 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
5045 if (ret < 0) {
5046 perror("bind");
5047 goto fail;
5050 /* Add host to multicast group */
5051 imr.imr_multiaddr = mcastaddr->sin_addr;
5052 imr.imr_interface.s_addr = htonl(INADDR_ANY);
5054 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5055 (const char *)&imr, sizeof(struct ip_mreq));
5056 if (ret < 0) {
5057 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5058 goto fail;
5061 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5062 val = 1;
5063 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
5064 (const char *)&val, sizeof(val));
5065 if (ret < 0) {
5066 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5067 goto fail;
5070 socket_set_nonblock(fd);
5071 return fd;
5072 fail:
5073 if (fd >= 0)
5074 closesocket(fd);
5075 return -1;
5078 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
5079 int is_connected)
5081 struct sockaddr_in saddr;
5082 int newfd;
5083 socklen_t saddr_len;
5084 NetSocketState *s;
5086 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5087 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5088 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5091 if (is_connected) {
5092 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
5093 /* must be bound */
5094 if (saddr.sin_addr.s_addr==0) {
5095 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5096 fd);
5097 return NULL;
5099 /* clone dgram socket */
5100 newfd = net_socket_mcast_create(&saddr);
5101 if (newfd < 0) {
5102 /* error already reported by net_socket_mcast_create() */
5103 close(fd);
5104 return NULL;
5106 /* clone newfd to fd, close newfd */
5107 dup2(newfd, fd);
5108 close(newfd);
5110 } else {
5111 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5112 fd, strerror(errno));
5113 return NULL;
5117 s = qemu_mallocz(sizeof(NetSocketState));
5118 if (!s)
5119 return NULL;
5120 s->fd = fd;
5122 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
5123 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
5125 /* mcast: save bound address as dst */
5126 if (is_connected) s->dgram_dst=saddr;
5128 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5129 "socket: fd=%d (%s mcast=%s:%d)",
5130 fd, is_connected? "cloned" : "",
5131 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5132 return s;
5135 static void net_socket_connect(void *opaque)
5137 NetSocketState *s = opaque;
5138 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
5141 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
5142 int is_connected)
5144 NetSocketState *s;
5145 s = qemu_mallocz(sizeof(NetSocketState));
5146 if (!s)
5147 return NULL;
5148 s->fd = fd;
5149 s->vc = qemu_new_vlan_client(vlan,
5150 net_socket_receive, NULL, s);
5151 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5152 "socket: fd=%d", fd);
5153 if (is_connected) {
5154 net_socket_connect(s);
5155 } else {
5156 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
5158 return s;
5161 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
5162 int is_connected)
5164 int so_type=-1, optlen=sizeof(so_type);
5166 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
5167 (socklen_t *)&optlen)< 0) {
5168 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
5169 return NULL;
5171 switch(so_type) {
5172 case SOCK_DGRAM:
5173 return net_socket_fd_init_dgram(vlan, fd, is_connected);
5174 case SOCK_STREAM:
5175 return net_socket_fd_init_stream(vlan, fd, is_connected);
5176 default:
5177 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5178 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
5179 return net_socket_fd_init_stream(vlan, fd, is_connected);
5181 return NULL;
5184 static void net_socket_accept(void *opaque)
5186 NetSocketListenState *s = opaque;
5187 NetSocketState *s1;
5188 struct sockaddr_in saddr;
5189 socklen_t len;
5190 int fd;
5192 for(;;) {
5193 len = sizeof(saddr);
5194 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
5195 if (fd < 0 && errno != EINTR) {
5196 return;
5197 } else if (fd >= 0) {
5198 break;
5201 s1 = net_socket_fd_init(s->vlan, fd, 1);
5202 if (!s1) {
5203 closesocket(fd);
5204 } else {
5205 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
5206 "socket: connection from %s:%d",
5207 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5211 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
5213 NetSocketListenState *s;
5214 int fd, val, ret;
5215 struct sockaddr_in saddr;
5217 if (parse_host_port(&saddr, host_str) < 0)
5218 return -1;
5220 s = qemu_mallocz(sizeof(NetSocketListenState));
5221 if (!s)
5222 return -1;
5224 fd = socket(PF_INET, SOCK_STREAM, 0);
5225 if (fd < 0) {
5226 perror("socket");
5227 return -1;
5229 socket_set_nonblock(fd);
5231 /* allow fast reuse */
5232 val = 1;
5233 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5235 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5236 if (ret < 0) {
5237 perror("bind");
5238 return -1;
5240 ret = listen(fd, 0);
5241 if (ret < 0) {
5242 perror("listen");
5243 return -1;
5245 s->vlan = vlan;
5246 s->fd = fd;
5247 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5248 return 0;
5251 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5253 NetSocketState *s;
5254 int fd, connected, ret, err;
5255 struct sockaddr_in saddr;
5257 if (parse_host_port(&saddr, host_str) < 0)
5258 return -1;
5260 fd = socket(PF_INET, SOCK_STREAM, 0);
5261 if (fd < 0) {
5262 perror("socket");
5263 return -1;
5265 socket_set_nonblock(fd);
5267 connected = 0;
5268 for(;;) {
5269 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5270 if (ret < 0) {
5271 err = socket_error();
5272 if (err == EINTR || err == EWOULDBLOCK) {
5273 } else if (err == EINPROGRESS) {
5274 break;
5275 #ifdef _WIN32
5276 } else if (err == WSAEALREADY) {
5277 break;
5278 #endif
5279 } else {
5280 perror("connect");
5281 closesocket(fd);
5282 return -1;
5284 } else {
5285 connected = 1;
5286 break;
5289 s = net_socket_fd_init(vlan, fd, connected);
5290 if (!s)
5291 return -1;
5292 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5293 "socket: connect to %s:%d",
5294 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5295 return 0;
5298 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5300 NetSocketState *s;
5301 int fd;
5302 struct sockaddr_in saddr;
5304 if (parse_host_port(&saddr, host_str) < 0)
5305 return -1;
5308 fd = net_socket_mcast_create(&saddr);
5309 if (fd < 0)
5310 return -1;
5312 s = net_socket_fd_init(vlan, fd, 0);
5313 if (!s)
5314 return -1;
5316 s->dgram_dst = saddr;
5318 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5319 "socket: mcast=%s:%d",
5320 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5321 return 0;
5325 static const char *get_opt_name(char *buf, int buf_size, const char *p)
5327 char *q;
5329 q = buf;
5330 while (*p != '\0' && *p != '=') {
5331 if (q && (q - buf) < buf_size - 1)
5332 *q++ = *p;
5333 p++;
5335 if (q)
5336 *q = '\0';
5338 return p;
5341 static const char *get_opt_value(char *buf, int buf_size, const char *p)
5343 char *q;
5345 q = buf;
5346 while (*p != '\0') {
5347 if (*p == ',') {
5348 if (*(p + 1) != ',')
5349 break;
5350 p++;
5352 if (q && (q - buf) < buf_size - 1)
5353 *q++ = *p;
5354 p++;
5356 if (q)
5357 *q = '\0';
5359 return p;
5362 int get_param_value(char *buf, int buf_size,
5363 const char *tag, const char *str)
5365 const char *p;
5366 char option[128];
5368 p = str;
5369 for(;;) {
5370 p = get_opt_name(option, sizeof(option), p);
5371 if (*p != '=')
5372 break;
5373 p++;
5374 if (!strcmp(tag, option)) {
5375 (void)get_opt_value(buf, buf_size, p);
5376 return strlen(buf);
5377 } else {
5378 p = get_opt_value(NULL, 0, p);
5380 if (*p != ',')
5381 break;
5382 p++;
5384 return 0;
5387 int check_params(char *buf, int buf_size,
5388 char **params, const char *str)
5390 const char *p;
5391 int i;
5393 p = str;
5394 for(;;) {
5395 p = get_opt_name(buf, buf_size, p);
5396 if (*p != '=')
5397 return -1;
5398 p++;
5399 for(i = 0; params[i] != NULL; i++)
5400 if (!strcmp(params[i], buf))
5401 break;
5402 if (params[i] == NULL)
5403 return -1;
5404 p = get_opt_value(NULL, 0, p);
5405 if (*p != ',')
5406 break;
5407 p++;
5409 return 0;
5412 static int nic_get_free_idx(void)
5414 int index;
5416 for (index = 0; index < MAX_NICS; index++)
5417 if (!nd_table[index].used)
5418 return index;
5419 return -1;
5422 int net_client_init(const char *device, const char *p)
5424 char buf[1024];
5425 int vlan_id, ret;
5426 VLANState *vlan;
5428 vlan_id = 0;
5429 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5430 vlan_id = strtol(buf, NULL, 0);
5432 vlan = qemu_find_vlan(vlan_id);
5433 if (!vlan) {
5434 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5435 return -1;
5437 if (!strcmp(device, "nic")) {
5438 NICInfo *nd;
5439 uint8_t *macaddr;
5440 int idx = nic_get_free_idx();
5442 if (idx == -1 || nb_nics >= MAX_NICS) {
5443 fprintf(stderr, "Too Many NICs\n");
5444 return -1;
5446 nd = &nd_table[idx];
5447 macaddr = nd->macaddr;
5448 macaddr[0] = 0x52;
5449 macaddr[1] = 0x54;
5450 macaddr[2] = 0x00;
5451 macaddr[3] = 0x12;
5452 macaddr[4] = 0x34;
5453 macaddr[5] = 0x56 + idx;
5455 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5456 if (parse_macaddr(macaddr, buf) < 0) {
5457 fprintf(stderr, "invalid syntax for ethernet address\n");
5458 return -1;
5461 if (get_param_value(buf, sizeof(buf), "model", p)) {
5462 nd->model = strdup(buf);
5464 nd->vlan = vlan;
5465 nd->used = 1;
5466 nb_nics++;
5467 vlan->nb_guest_devs++;
5468 ret = idx;
5469 } else
5470 if (!strcmp(device, "none")) {
5471 /* does nothing. It is needed to signal that no network cards
5472 are wanted */
5473 ret = 0;
5474 } else
5475 #ifdef CONFIG_SLIRP
5476 if (!strcmp(device, "user")) {
5477 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5478 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5480 vlan->nb_host_devs++;
5481 ret = net_slirp_init(vlan);
5482 } else
5483 #endif
5484 #ifdef _WIN32
5485 if (!strcmp(device, "tap")) {
5486 char ifname[64];
5487 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5488 fprintf(stderr, "tap: no interface name\n");
5489 return -1;
5491 vlan->nb_host_devs++;
5492 ret = tap_win32_init(vlan, ifname);
5493 } else
5494 #else
5495 if (!strcmp(device, "tap")) {
5496 char ifname[64];
5497 char setup_script[1024], down_script[1024];
5498 int fd;
5499 vlan->nb_host_devs++;
5500 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5501 fd = strtol(buf, NULL, 0);
5502 fcntl(fd, F_SETFL, O_NONBLOCK);
5503 ret = -1;
5504 if (net_tap_fd_init(vlan, fd, 0))
5505 ret = 0;
5506 } else {
5507 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5508 ifname[0] = '\0';
5510 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5511 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5513 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5514 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5516 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5518 } else
5519 #endif
5520 if (!strcmp(device, "socket")) {
5521 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5522 int fd;
5523 fd = strtol(buf, NULL, 0);
5524 ret = -1;
5525 if (net_socket_fd_init(vlan, fd, 1))
5526 ret = 0;
5527 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5528 ret = net_socket_listen_init(vlan, buf);
5529 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5530 ret = net_socket_connect_init(vlan, buf);
5531 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5532 ret = net_socket_mcast_init(vlan, buf);
5533 } else {
5534 fprintf(stderr, "Unknown socket options: %s\n", p);
5535 return -1;
5537 vlan->nb_host_devs++;
5538 } else
5539 #ifdef CONFIG_VDE
5540 if (!strcmp(device, "vde")) {
5541 char vde_sock[1024], vde_group[512];
5542 int vde_port, vde_mode;
5543 vlan->nb_host_devs++;
5544 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5545 vde_sock[0] = '\0';
5547 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5548 vde_port = strtol(buf, NULL, 10);
5549 } else {
5550 vde_port = 0;
5552 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5553 vde_group[0] = '\0';
5555 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5556 vde_mode = strtol(buf, NULL, 8);
5557 } else {
5558 vde_mode = 0700;
5560 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5561 } else
5562 #endif
5564 fprintf(stderr, "Unknown network device: %s\n", device);
5565 return -1;
5567 if (ret < 0) {
5568 fprintf(stderr, "Could not initialize device '%s'\n", device);
5571 return ret;
5574 void net_client_uninit(NICInfo *nd)
5576 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
5577 nb_nics--;
5578 nd->used = 0;
5579 free((void *)nd->model);
5582 static int net_client_parse(const char *str)
5584 const char *p;
5585 char *q;
5586 char device[64];
5588 p = str;
5589 q = device;
5590 while (*p != '\0' && *p != ',') {
5591 if ((q - device) < sizeof(device) - 1)
5592 *q++ = *p;
5593 p++;
5595 *q = '\0';
5596 if (*p == ',')
5597 p++;
5599 return net_client_init(device, p);
5602 void do_info_network(void)
5604 VLANState *vlan;
5605 VLANClientState *vc;
5607 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5608 term_printf("VLAN %d devices:\n", vlan->id);
5609 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5610 term_printf(" %s\n", vc->info_str);
5614 #define HD_ALIAS "index=%d,media=disk"
5615 #ifdef TARGET_PPC
5616 #define CDROM_ALIAS "index=1,media=cdrom"
5617 #else
5618 #define CDROM_ALIAS "index=2,media=cdrom"
5619 #endif
5620 #define FD_ALIAS "index=%d,if=floppy"
5621 #define PFLASH_ALIAS "if=pflash"
5622 #define MTD_ALIAS "if=mtd"
5623 #define SD_ALIAS "index=0,if=sd"
5625 static int drive_opt_get_free_idx(void)
5627 int index;
5629 for (index = 0; index < MAX_DRIVES; index++)
5630 if (!drives_opt[index].used) {
5631 drives_opt[index].used = 1;
5632 return index;
5635 return -1;
5638 static int drive_get_free_idx(void)
5640 int index;
5642 for (index = 0; index < MAX_DRIVES; index++)
5643 if (!drives_table[index].used) {
5644 drives_table[index].used = 1;
5645 return index;
5648 return -1;
5651 int drive_add(const char *file, const char *fmt, ...)
5653 va_list ap;
5654 int index = drive_opt_get_free_idx();
5656 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5657 fprintf(stderr, "qemu: too many drives\n");
5658 return -1;
5661 drives_opt[index].file = file;
5662 va_start(ap, fmt);
5663 vsnprintf(drives_opt[index].opt,
5664 sizeof(drives_opt[0].opt), fmt, ap);
5665 va_end(ap);
5667 nb_drives_opt++;
5668 return index;
5671 void drive_remove(int index)
5673 drives_opt[index].used = 0;
5674 nb_drives_opt--;
5677 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5679 int index;
5681 /* seek interface, bus and unit */
5683 for (index = 0; index < MAX_DRIVES; index++)
5684 if (drives_table[index].type == type &&
5685 drives_table[index].bus == bus &&
5686 drives_table[index].unit == unit &&
5687 drives_table[index].used)
5688 return index;
5690 return -1;
5693 int drive_get_max_bus(BlockInterfaceType type)
5695 int max_bus;
5696 int index;
5698 max_bus = -1;
5699 for (index = 0; index < nb_drives; index++) {
5700 if(drives_table[index].type == type &&
5701 drives_table[index].bus > max_bus)
5702 max_bus = drives_table[index].bus;
5704 return max_bus;
5707 static void bdrv_format_print(void *opaque, const char *name)
5709 fprintf(stderr, " %s", name);
5712 void drive_uninit(BlockDriverState *bdrv)
5714 int i;
5716 for (i = 0; i < MAX_DRIVES; i++)
5717 if (drives_table[i].bdrv == bdrv) {
5718 drives_table[i].bdrv = NULL;
5719 drives_table[i].used = 0;
5720 drive_remove(drives_table[i].drive_opt_idx);
5721 nb_drives--;
5722 break;
5726 int drive_init(struct drive_opt *arg, int snapshot,
5727 QEMUMachine *machine)
5729 char buf[128];
5730 char file[1024];
5731 char devname[128];
5732 const char *mediastr = "";
5733 BlockInterfaceType type;
5734 enum { MEDIA_DISK, MEDIA_CDROM } media;
5735 int bus_id, unit_id;
5736 int cyls, heads, secs, translation;
5737 BlockDriverState *bdrv;
5738 BlockDriver *drv = NULL;
5739 int max_devs;
5740 int index;
5741 int cache;
5742 int bdrv_flags;
5743 int drives_table_idx;
5744 char *str = arg->opt;
5745 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5746 "secs", "trans", "media", "snapshot", "file",
5747 "cache", "format", "boot", NULL };
5749 if (check_params(buf, sizeof(buf), params, str) < 0) {
5750 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5751 buf, str);
5752 return -1;
5755 file[0] = 0;
5756 cyls = heads = secs = 0;
5757 bus_id = 0;
5758 unit_id = -1;
5759 translation = BIOS_ATA_TRANSLATION_AUTO;
5760 index = -1;
5761 cache = 1;
5763 if (!strcmp(machine->name, "realview") ||
5764 !strcmp(machine->name, "SS-5") ||
5765 !strcmp(machine->name, "SS-10") ||
5766 !strcmp(machine->name, "SS-600MP") ||
5767 !strcmp(machine->name, "versatilepb") ||
5768 !strcmp(machine->name, "versatileab")) {
5769 type = IF_SCSI;
5770 max_devs = MAX_SCSI_DEVS;
5771 strcpy(devname, "scsi");
5772 } else {
5773 type = IF_IDE;
5774 max_devs = MAX_IDE_DEVS;
5775 strcpy(devname, "ide");
5777 media = MEDIA_DISK;
5779 /* extract parameters */
5781 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5782 bus_id = strtol(buf, NULL, 0);
5783 if (bus_id < 0) {
5784 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5785 return -1;
5789 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5790 unit_id = strtol(buf, NULL, 0);
5791 if (unit_id < 0) {
5792 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5793 return -1;
5797 if (get_param_value(buf, sizeof(buf), "if", str)) {
5798 pstrcpy(devname, sizeof(devname), buf);
5799 if (!strcmp(buf, "ide")) {
5800 type = IF_IDE;
5801 max_devs = MAX_IDE_DEVS;
5802 } else if (!strcmp(buf, "scsi")) {
5803 type = IF_SCSI;
5804 max_devs = MAX_SCSI_DEVS;
5805 } else if (!strcmp(buf, "floppy")) {
5806 type = IF_FLOPPY;
5807 max_devs = 0;
5808 } else if (!strcmp(buf, "pflash")) {
5809 type = IF_PFLASH;
5810 max_devs = 0;
5811 } else if (!strcmp(buf, "mtd")) {
5812 type = IF_MTD;
5813 max_devs = 0;
5814 } else if (!strcmp(buf, "sd")) {
5815 type = IF_SD;
5816 max_devs = 0;
5817 } else if (!strcmp(buf, "virtio")) {
5818 type = IF_VIRTIO;
5819 max_devs = 0;
5820 } else {
5821 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5822 return -1;
5826 if (get_param_value(buf, sizeof(buf), "index", str)) {
5827 index = strtol(buf, NULL, 0);
5828 if (index < 0) {
5829 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5830 return -1;
5834 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5835 cyls = strtol(buf, NULL, 0);
5838 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5839 heads = strtol(buf, NULL, 0);
5842 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5843 secs = strtol(buf, NULL, 0);
5846 if (cyls || heads || secs) {
5847 if (cyls < 1 || cyls > 16383) {
5848 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5849 return -1;
5851 if (heads < 1 || heads > 16) {
5852 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5853 return -1;
5855 if (secs < 1 || secs > 63) {
5856 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5857 return -1;
5861 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5862 if (!cyls) {
5863 fprintf(stderr,
5864 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5865 str);
5866 return -1;
5868 if (!strcmp(buf, "none"))
5869 translation = BIOS_ATA_TRANSLATION_NONE;
5870 else if (!strcmp(buf, "lba"))
5871 translation = BIOS_ATA_TRANSLATION_LBA;
5872 else if (!strcmp(buf, "auto"))
5873 translation = BIOS_ATA_TRANSLATION_AUTO;
5874 else {
5875 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5876 return -1;
5880 if (get_param_value(buf, sizeof(buf), "media", str)) {
5881 if (!strcmp(buf, "disk")) {
5882 media = MEDIA_DISK;
5883 } else if (!strcmp(buf, "cdrom")) {
5884 if (cyls || secs || heads) {
5885 fprintf(stderr,
5886 "qemu: '%s' invalid physical CHS format\n", str);
5887 return -1;
5889 media = MEDIA_CDROM;
5890 } else {
5891 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5892 return -1;
5896 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5897 if (!strcmp(buf, "on"))
5898 snapshot = 1;
5899 else if (!strcmp(buf, "off"))
5900 snapshot = 0;
5901 else {
5902 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5903 return -1;
5907 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5908 if (!strcmp(buf, "off"))
5909 cache = 0;
5910 else if (!strcmp(buf, "on"))
5911 cache = 1;
5912 else {
5913 fprintf(stderr, "qemu: invalid cache option\n");
5914 return -1;
5918 if (get_param_value(buf, sizeof(buf), "format", str)) {
5919 if (strcmp(buf, "?") == 0) {
5920 fprintf(stderr, "qemu: Supported formats:");
5921 bdrv_iterate_format(bdrv_format_print, NULL);
5922 fprintf(stderr, "\n");
5923 return -1;
5925 drv = bdrv_find_format(buf);
5926 if (!drv) {
5927 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5928 return -1;
5932 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5933 if (!strcmp(buf, "on")) {
5934 if (extboot_drive != -1) {
5935 fprintf(stderr, "qemu: two bootable drives specified\n");
5936 return -1;
5938 extboot_drive = nb_drives;
5939 } else if (strcmp(buf, "off")) {
5940 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5941 return -1;
5945 if (arg->file == NULL)
5946 get_param_value(file, sizeof(file), "file", str);
5947 else
5948 pstrcpy(file, sizeof(file), arg->file);
5950 /* compute bus and unit according index */
5952 if (index != -1) {
5953 if (bus_id != 0 || unit_id != -1) {
5954 fprintf(stderr,
5955 "qemu: '%s' index cannot be used with bus and unit\n", str);
5956 return -1;
5958 if (max_devs == 0)
5960 unit_id = index;
5961 bus_id = 0;
5962 } else {
5963 unit_id = index % max_devs;
5964 bus_id = index / max_devs;
5968 /* if user doesn't specify a unit_id,
5969 * try to find the first free
5972 if (unit_id == -1) {
5973 unit_id = 0;
5974 while (drive_get_index(type, bus_id, unit_id) != -1) {
5975 unit_id++;
5976 if (max_devs && unit_id >= max_devs) {
5977 unit_id -= max_devs;
5978 bus_id++;
5983 /* check unit id */
5985 if (max_devs && unit_id >= max_devs) {
5986 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5987 str, unit_id, max_devs - 1);
5988 return -1;
5992 * ignore multiple definitions
5995 if (drive_get_index(type, bus_id, unit_id) != -1)
5996 return -2;
5998 /* init */
6000 if (type == IF_IDE || type == IF_SCSI)
6001 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
6002 if (max_devs)
6003 snprintf(buf, sizeof(buf), "%s%i%s%i",
6004 devname, bus_id, mediastr, unit_id);
6005 else
6006 snprintf(buf, sizeof(buf), "%s%s%i",
6007 devname, mediastr, unit_id);
6008 bdrv = bdrv_new(buf);
6009 drives_table_idx = drive_get_free_idx();
6010 drives_table[drives_table_idx].bdrv = bdrv;
6011 drives_table[drives_table_idx].type = type;
6012 drives_table[drives_table_idx].bus = bus_id;
6013 drives_table[drives_table_idx].unit = unit_id;
6014 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
6015 nb_drives++;
6017 switch(type) {
6018 case IF_IDE:
6019 case IF_SCSI:
6020 switch(media) {
6021 case MEDIA_DISK:
6022 if (cyls != 0) {
6023 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
6024 bdrv_set_translation_hint(bdrv, translation);
6026 break;
6027 case MEDIA_CDROM:
6028 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
6029 break;
6031 break;
6032 case IF_SD:
6033 /* FIXME: This isn't really a floppy, but it's a reasonable
6034 approximation. */
6035 case IF_FLOPPY:
6036 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
6037 break;
6038 case IF_PFLASH:
6039 case IF_MTD:
6040 case IF_VIRTIO:
6041 break;
6043 if (!file[0])
6044 return -2;
6045 bdrv_flags = 0;
6046 if (snapshot)
6047 bdrv_flags |= BDRV_O_SNAPSHOT;
6048 if (!cache)
6049 bdrv_flags |= BDRV_O_DIRECT;
6050 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
6051 fprintf(stderr, "qemu: could not open disk image %s\n",
6052 file);
6053 return -1;
6055 return drives_table_idx;
6058 /***********************************************************/
6059 /* USB devices */
6061 static USBPort *used_usb_ports;
6062 static USBPort *free_usb_ports;
6064 /* ??? Maybe change this to register a hub to keep track of the topology. */
6065 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
6066 usb_attachfn attach)
6068 port->opaque = opaque;
6069 port->index = index;
6070 port->attach = attach;
6071 port->next = free_usb_ports;
6072 free_usb_ports = port;
6075 static int usb_device_add(const char *devname)
6077 const char *p;
6078 USBDevice *dev;
6079 USBPort *port;
6081 if (!free_usb_ports)
6082 return -1;
6084 if (strstart(devname, "host:", &p)) {
6085 dev = usb_host_device_open(p);
6086 } else if (!strcmp(devname, "mouse")) {
6087 dev = usb_mouse_init();
6088 } else if (!strcmp(devname, "tablet")) {
6089 dev = usb_tablet_init();
6090 } else if (!strcmp(devname, "keyboard")) {
6091 dev = usb_keyboard_init();
6092 } else if (strstart(devname, "disk:", &p)) {
6093 dev = usb_msd_init(p);
6094 } else if (!strcmp(devname, "wacom-tablet")) {
6095 dev = usb_wacom_init();
6096 } else if (strstart(devname, "serial:", &p)) {
6097 dev = usb_serial_init(p);
6098 #ifdef CONFIG_BRLAPI
6099 } else if (!strcmp(devname, "braille")) {
6100 dev = usb_baum_init();
6101 #endif
6102 } else if (strstart(devname, "net:", &p)) {
6103 int nic = nb_nics;
6105 if (net_client_init("nic", p) < 0)
6106 return -1;
6107 nd_table[nic].model = "usb";
6108 dev = usb_net_init(&nd_table[nic]);
6109 } else {
6110 return -1;
6112 if (!dev)
6113 return -1;
6115 /* Find a USB port to add the device to. */
6116 port = free_usb_ports;
6117 if (!port->next) {
6118 USBDevice *hub;
6120 /* Create a new hub and chain it on. */
6121 free_usb_ports = NULL;
6122 port->next = used_usb_ports;
6123 used_usb_ports = port;
6125 hub = usb_hub_init(VM_USB_HUB_SIZE);
6126 usb_attach(port, hub);
6127 port = free_usb_ports;
6130 free_usb_ports = port->next;
6131 port->next = used_usb_ports;
6132 used_usb_ports = port;
6133 usb_attach(port, dev);
6134 return 0;
6137 static int usb_device_del(const char *devname)
6139 USBPort *port;
6140 USBPort **lastp;
6141 USBDevice *dev;
6142 int bus_num, addr;
6143 const char *p;
6145 if (!used_usb_ports)
6146 return -1;
6148 p = strchr(devname, '.');
6149 if (!p)
6150 return -1;
6151 bus_num = strtoul(devname, NULL, 0);
6152 addr = strtoul(p + 1, NULL, 0);
6153 if (bus_num != 0)
6154 return -1;
6156 lastp = &used_usb_ports;
6157 port = used_usb_ports;
6158 while (port && port->dev->addr != addr) {
6159 lastp = &port->next;
6160 port = port->next;
6163 if (!port)
6164 return -1;
6166 dev = port->dev;
6167 *lastp = port->next;
6168 usb_attach(port, NULL);
6169 dev->handle_destroy(dev);
6170 port->next = free_usb_ports;
6171 free_usb_ports = port;
6172 return 0;
6175 void do_usb_add(const char *devname)
6177 int ret;
6178 ret = usb_device_add(devname);
6179 if (ret < 0)
6180 term_printf("Could not add USB device '%s'\n", devname);
6183 void do_usb_del(const char *devname)
6185 int ret;
6186 ret = usb_device_del(devname);
6187 if (ret < 0)
6188 term_printf("Could not remove USB device '%s'\n", devname);
6191 void usb_info(void)
6193 USBDevice *dev;
6194 USBPort *port;
6195 const char *speed_str;
6197 if (!usb_enabled) {
6198 term_printf("USB support not enabled\n");
6199 return;
6202 for (port = used_usb_ports; port; port = port->next) {
6203 dev = port->dev;
6204 if (!dev)
6205 continue;
6206 switch(dev->speed) {
6207 case USB_SPEED_LOW:
6208 speed_str = "1.5";
6209 break;
6210 case USB_SPEED_FULL:
6211 speed_str = "12";
6212 break;
6213 case USB_SPEED_HIGH:
6214 speed_str = "480";
6215 break;
6216 default:
6217 speed_str = "?";
6218 break;
6220 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6221 0, dev->addr, speed_str, dev->devname);
6225 /***********************************************************/
6226 /* PCMCIA/Cardbus */
6228 static struct pcmcia_socket_entry_s {
6229 struct pcmcia_socket_s *socket;
6230 struct pcmcia_socket_entry_s *next;
6231 } *pcmcia_sockets = 0;
6233 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
6235 struct pcmcia_socket_entry_s *entry;
6237 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
6238 entry->socket = socket;
6239 entry->next = pcmcia_sockets;
6240 pcmcia_sockets = entry;
6243 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
6245 struct pcmcia_socket_entry_s *entry, **ptr;
6247 ptr = &pcmcia_sockets;
6248 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
6249 if (entry->socket == socket) {
6250 *ptr = entry->next;
6251 qemu_free(entry);
6255 void pcmcia_info(void)
6257 struct pcmcia_socket_entry_s *iter;
6258 if (!pcmcia_sockets)
6259 term_printf("No PCMCIA sockets\n");
6261 for (iter = pcmcia_sockets; iter; iter = iter->next)
6262 term_printf("%s: %s\n", iter->socket->slot_string,
6263 iter->socket->attached ? iter->socket->card_string :
6264 "Empty");
6267 /***********************************************************/
6268 /* dumb display */
6270 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
6274 static void dumb_resize(DisplayState *ds, int w, int h)
6278 static void dumb_refresh(DisplayState *ds)
6280 #if defined(CONFIG_SDL)
6281 vga_hw_update();
6282 #endif
6285 static void dumb_display_init(DisplayState *ds)
6287 ds->data = NULL;
6288 ds->linesize = 0;
6289 ds->depth = 0;
6290 ds->dpy_update = dumb_update;
6291 ds->dpy_resize = dumb_resize;
6292 ds->dpy_refresh = dumb_refresh;
6295 /***********************************************************/
6296 /* I/O handling */
6298 #define MAX_IO_HANDLERS 64
6300 typedef struct IOHandlerRecord {
6301 int fd;
6302 IOCanRWHandler *fd_read_poll;
6303 IOHandler *fd_read;
6304 IOHandler *fd_write;
6305 int deleted;
6306 void *opaque;
6307 /* temporary data */
6308 struct pollfd *ufd;
6309 struct IOHandlerRecord *next;
6310 } IOHandlerRecord;
6312 static IOHandlerRecord *first_io_handler;
6314 /* XXX: fd_read_poll should be suppressed, but an API change is
6315 necessary in the character devices to suppress fd_can_read(). */
6316 int qemu_set_fd_handler2(int fd,
6317 IOCanRWHandler *fd_read_poll,
6318 IOHandler *fd_read,
6319 IOHandler *fd_write,
6320 void *opaque)
6322 IOHandlerRecord **pioh, *ioh;
6324 if (!fd_read && !fd_write) {
6325 pioh = &first_io_handler;
6326 for(;;) {
6327 ioh = *pioh;
6328 if (ioh == NULL)
6329 break;
6330 if (ioh->fd == fd) {
6331 ioh->deleted = 1;
6332 break;
6334 pioh = &ioh->next;
6336 } else {
6337 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6338 if (ioh->fd == fd)
6339 goto found;
6341 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6342 if (!ioh)
6343 return -1;
6344 ioh->next = first_io_handler;
6345 first_io_handler = ioh;
6346 found:
6347 ioh->fd = fd;
6348 ioh->fd_read_poll = fd_read_poll;
6349 ioh->fd_read = fd_read;
6350 ioh->fd_write = fd_write;
6351 ioh->opaque = opaque;
6352 ioh->deleted = 0;
6354 main_loop_break();
6355 return 0;
6358 int qemu_set_fd_handler(int fd,
6359 IOHandler *fd_read,
6360 IOHandler *fd_write,
6361 void *opaque)
6363 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6366 /***********************************************************/
6367 /* Polling handling */
6369 typedef struct PollingEntry {
6370 PollingFunc *func;
6371 void *opaque;
6372 struct PollingEntry *next;
6373 } PollingEntry;
6375 static PollingEntry *first_polling_entry;
6377 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6379 PollingEntry **ppe, *pe;
6380 pe = qemu_mallocz(sizeof(PollingEntry));
6381 if (!pe)
6382 return -1;
6383 pe->func = func;
6384 pe->opaque = opaque;
6385 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6386 *ppe = pe;
6387 return 0;
6390 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6392 PollingEntry **ppe, *pe;
6393 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6394 pe = *ppe;
6395 if (pe->func == func && pe->opaque == opaque) {
6396 *ppe = pe->next;
6397 qemu_free(pe);
6398 break;
6403 #ifdef _WIN32
6404 /***********************************************************/
6405 /* Wait objects support */
6406 typedef struct WaitObjects {
6407 int num;
6408 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6409 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6410 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6411 } WaitObjects;
6413 static WaitObjects wait_objects = {0};
6415 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6417 WaitObjects *w = &wait_objects;
6419 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6420 return -1;
6421 w->events[w->num] = handle;
6422 w->func[w->num] = func;
6423 w->opaque[w->num] = opaque;
6424 w->num++;
6425 return 0;
6428 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6430 int i, found;
6431 WaitObjects *w = &wait_objects;
6433 found = 0;
6434 for (i = 0; i < w->num; i++) {
6435 if (w->events[i] == handle)
6436 found = 1;
6437 if (found) {
6438 w->events[i] = w->events[i + 1];
6439 w->func[i] = w->func[i + 1];
6440 w->opaque[i] = w->opaque[i + 1];
6443 if (found)
6444 w->num--;
6446 #endif
6448 #define SELF_ANNOUNCE_ROUNDS 5
6449 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6450 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6451 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6453 static int announce_self_create(uint8_t *buf,
6454 uint8_t *mac_addr)
6456 uint32_t magic = EXPERIMENTAL_MAGIC;
6457 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
6459 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6461 memset(buf, 0xff, 6); /* h_dst */
6462 memcpy(buf + 6, mac_addr, 6); /* h_src */
6463 memcpy(buf + 12, &proto, 2); /* h_proto */
6464 memcpy(buf + 14, &magic, 4); /* magic */
6466 return 18; /* len */
6469 static void qemu_announce_self(void)
6471 int i, j, len;
6472 VLANState *vlan;
6473 VLANClientState *vc;
6474 uint8_t buf[256];
6476 for (i = 0; i < nb_nics; i++) {
6477 len = announce_self_create(buf, nd_table[i].macaddr);
6478 vlan = nd_table[i].vlan;
6479 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
6480 if (vc->fd_read == tap_receive) /* send only if tap */
6481 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
6482 vc->fd_read(vc->opaque, buf, len);
6487 /***********************************************************/
6488 /* savevm/loadvm support */
6490 #define IO_BUF_SIZE 32768
6492 struct QEMUFile {
6493 QEMUFilePutBufferFunc *put_buffer;
6494 QEMUFileGetBufferFunc *get_buffer;
6495 QEMUFileCloseFunc *close;
6496 void *opaque;
6498 int64_t buf_offset; /* start of buffer when writing, end of buffer
6499 when reading */
6500 int buf_index;
6501 int buf_size; /* 0 when writing */
6502 uint8_t buf[IO_BUF_SIZE];
6505 typedef struct QEMUFileFD
6507 int fd;
6508 } QEMUFileFD;
6510 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6512 QEMUFileFD *s = opaque;
6513 int offset = 0;
6514 ssize_t len;
6516 again:
6517 len = read(s->fd, buf + offset, size - offset);
6518 if (len == -1) {
6519 if (errno == EINTR || errno == EAGAIN)
6520 goto again;
6523 return len;
6526 QEMUFile *qemu_fopen_fd(int fd)
6528 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
6529 s->fd = fd;
6530 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
6533 typedef struct QEMUFileUnix
6535 FILE *outfile;
6536 } QEMUFileUnix;
6538 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6540 QEMUFileUnix *s = opaque;
6541 fseek(s->outfile, pos, SEEK_SET);
6542 fwrite(buf, 1, size, s->outfile);
6545 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6547 QEMUFileUnix *s = opaque;
6548 fseek(s->outfile, pos, SEEK_SET);
6549 return fread(buf, 1, size, s->outfile);
6552 static void file_close(void *opaque)
6554 QEMUFileUnix *s = opaque;
6555 fclose(s->outfile);
6556 qemu_free(s);
6559 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
6561 QEMUFileUnix *s;
6563 s = qemu_mallocz(sizeof(QEMUFileUnix));
6564 if (!s)
6565 return NULL;
6567 s->outfile = fopen(filename, mode);
6568 if (!s->outfile)
6569 goto fail;
6571 if (!strcmp(mode, "wb"))
6572 return qemu_fopen(s, file_put_buffer, NULL, file_close);
6573 else if (!strcmp(mode, "rb"))
6574 return qemu_fopen(s, NULL, file_get_buffer, file_close);
6576 fail:
6577 if (s->outfile)
6578 fclose(s->outfile);
6579 qemu_free(s);
6580 return NULL;
6583 typedef struct QEMUFileBdrv
6585 BlockDriverState *bs;
6586 int64_t base_offset;
6587 } QEMUFileBdrv;
6589 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6591 QEMUFileBdrv *s = opaque;
6592 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
6595 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6597 QEMUFileBdrv *s = opaque;
6598 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6601 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6603 QEMUFileBdrv *s;
6605 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6606 if (!s)
6607 return NULL;
6609 s->bs = bs;
6610 s->base_offset = offset;
6612 if (is_writable)
6613 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
6615 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
6618 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6619 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
6621 QEMUFile *f;
6623 f = qemu_mallocz(sizeof(QEMUFile));
6624 if (!f)
6625 return NULL;
6627 f->opaque = opaque;
6628 f->put_buffer = put_buffer;
6629 f->get_buffer = get_buffer;
6630 f->close = close;
6632 return f;
6635 void qemu_fflush(QEMUFile *f)
6637 if (!f->put_buffer)
6638 return;
6640 if (f->buf_index > 0) {
6641 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
6642 f->buf_offset += f->buf_index;
6643 f->buf_index = 0;
6647 static void qemu_fill_buffer(QEMUFile *f)
6649 int len;
6651 if (!f->get_buffer)
6652 return;
6654 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6655 if (len < 0)
6656 len = 0;
6658 f->buf_index = 0;
6659 f->buf_size = len;
6660 f->buf_offset += len;
6663 void qemu_fclose(QEMUFile *f)
6665 qemu_fflush(f);
6666 if (f->close)
6667 f->close(f->opaque);
6668 qemu_free(f);
6671 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6673 int l;
6674 while (size > 0) {
6675 l = IO_BUF_SIZE - f->buf_index;
6676 if (l > size)
6677 l = size;
6678 memcpy(f->buf + f->buf_index, buf, l);
6679 f->buf_index += l;
6680 buf += l;
6681 size -= l;
6682 if (f->buf_index >= IO_BUF_SIZE)
6683 qemu_fflush(f);
6687 void qemu_put_byte(QEMUFile *f, int v)
6689 f->buf[f->buf_index++] = v;
6690 if (f->buf_index >= IO_BUF_SIZE)
6691 qemu_fflush(f);
6694 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6696 int size, l;
6698 size = size1;
6699 while (size > 0) {
6700 l = f->buf_size - f->buf_index;
6701 if (l == 0) {
6702 qemu_fill_buffer(f);
6703 l = f->buf_size - f->buf_index;
6704 if (l == 0)
6705 break;
6707 if (l > size)
6708 l = size;
6709 memcpy(buf, f->buf + f->buf_index, l);
6710 f->buf_index += l;
6711 buf += l;
6712 size -= l;
6714 return size1 - size;
6717 int qemu_get_byte(QEMUFile *f)
6719 if (f->buf_index >= f->buf_size) {
6720 qemu_fill_buffer(f);
6721 if (f->buf_index >= f->buf_size)
6722 return 0;
6724 return f->buf[f->buf_index++];
6727 int64_t qemu_ftell(QEMUFile *f)
6729 return f->buf_offset - f->buf_size + f->buf_index;
6732 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6734 if (whence == SEEK_SET) {
6735 /* nothing to do */
6736 } else if (whence == SEEK_CUR) {
6737 pos += qemu_ftell(f);
6738 } else {
6739 /* SEEK_END not supported */
6740 return -1;
6742 if (f->put_buffer) {
6743 qemu_fflush(f);
6744 f->buf_offset = pos;
6745 } else {
6746 f->buf_offset = pos;
6747 f->buf_index = 0;
6748 f->buf_size = 0;
6750 return pos;
6753 void qemu_put_be16(QEMUFile *f, unsigned int v)
6755 qemu_put_byte(f, v >> 8);
6756 qemu_put_byte(f, v);
6759 void qemu_put_be32(QEMUFile *f, unsigned int v)
6761 qemu_put_byte(f, v >> 24);
6762 qemu_put_byte(f, v >> 16);
6763 qemu_put_byte(f, v >> 8);
6764 qemu_put_byte(f, v);
6767 void qemu_put_be64(QEMUFile *f, uint64_t v)
6769 qemu_put_be32(f, v >> 32);
6770 qemu_put_be32(f, v);
6773 unsigned int qemu_get_be16(QEMUFile *f)
6775 unsigned int v;
6776 v = qemu_get_byte(f) << 8;
6777 v |= qemu_get_byte(f);
6778 return v;
6781 unsigned int qemu_get_be32(QEMUFile *f)
6783 unsigned int v;
6784 v = qemu_get_byte(f) << 24;
6785 v |= qemu_get_byte(f) << 16;
6786 v |= qemu_get_byte(f) << 8;
6787 v |= qemu_get_byte(f);
6788 return v;
6791 uint64_t qemu_get_be64(QEMUFile *f)
6793 uint64_t v;
6794 v = (uint64_t)qemu_get_be32(f) << 32;
6795 v |= qemu_get_be32(f);
6796 return v;
6799 typedef struct SaveStateEntry {
6800 char idstr[256];
6801 int instance_id;
6802 int version_id;
6803 SaveStateHandler *save_state;
6804 LoadStateHandler *load_state;
6805 void *opaque;
6806 struct SaveStateEntry *next;
6807 } SaveStateEntry;
6809 static SaveStateEntry *first_se;
6811 /* TODO: Individual devices generally have very little idea about the rest
6812 of the system, so instance_id should be removed/replaced.
6813 Meanwhile pass -1 as instance_id if you do not already have a clearly
6814 distinguishing id for all instances of your device class. */
6815 int register_savevm(const char *idstr,
6816 int instance_id,
6817 int version_id,
6818 SaveStateHandler *save_state,
6819 LoadStateHandler *load_state,
6820 void *opaque)
6822 SaveStateEntry *se, **pse;
6824 se = qemu_malloc(sizeof(SaveStateEntry));
6825 if (!se)
6826 return -1;
6827 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6828 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6829 se->version_id = version_id;
6830 se->save_state = save_state;
6831 se->load_state = load_state;
6832 se->opaque = opaque;
6833 se->next = NULL;
6835 /* add at the end of list */
6836 pse = &first_se;
6837 while (*pse != NULL) {
6838 if (instance_id == -1
6839 && strcmp(se->idstr, (*pse)->idstr) == 0
6840 && se->instance_id <= (*pse)->instance_id)
6841 se->instance_id = (*pse)->instance_id + 1;
6842 pse = &(*pse)->next;
6844 *pse = se;
6845 return 0;
6848 #define QEMU_VM_FILE_MAGIC 0x5145564d
6849 #define QEMU_VM_FILE_VERSION 0x00000002
6851 static int qemu_savevm_state(QEMUFile *f)
6853 SaveStateEntry *se;
6854 int len, ret;
6855 int64_t cur_pos, len_pos, total_len_pos;
6857 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6858 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6859 total_len_pos = qemu_ftell(f);
6860 qemu_put_be64(f, 0); /* total size */
6862 for(se = first_se; se != NULL; se = se->next) {
6863 if (se->save_state == NULL)
6864 /* this one has a loader only, for backwards compatibility */
6865 continue;
6867 /* ID string */
6868 len = strlen(se->idstr);
6869 qemu_put_byte(f, len);
6870 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6872 qemu_put_be32(f, se->instance_id);
6873 qemu_put_be32(f, se->version_id);
6875 /* record size: filled later */
6876 len_pos = qemu_ftell(f);
6877 qemu_put_be32(f, 0);
6878 se->save_state(f, se->opaque);
6880 /* fill record size */
6881 cur_pos = qemu_ftell(f);
6882 len = cur_pos - len_pos - 4;
6883 qemu_fseek(f, len_pos, SEEK_SET);
6884 qemu_put_be32(f, len);
6885 qemu_fseek(f, cur_pos, SEEK_SET);
6887 cur_pos = qemu_ftell(f);
6888 qemu_fseek(f, total_len_pos, SEEK_SET);
6889 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6890 qemu_fseek(f, cur_pos, SEEK_SET);
6892 ret = 0;
6893 return ret;
6896 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6898 SaveStateEntry *se;
6900 for(se = first_se; se != NULL; se = se->next) {
6901 if (!strcmp(se->idstr, idstr) &&
6902 instance_id == se->instance_id)
6903 return se;
6905 return NULL;
6908 static int qemu_loadvm_state(QEMUFile *f)
6910 SaveStateEntry *se;
6911 int len, ret, instance_id, record_len, version_id;
6912 int64_t total_len, end_pos, cur_pos;
6913 unsigned int v;
6914 char idstr[256];
6916 v = qemu_get_be32(f);
6917 if (v != QEMU_VM_FILE_MAGIC)
6918 goto fail;
6919 v = qemu_get_be32(f);
6920 if (v != QEMU_VM_FILE_VERSION) {
6921 fail:
6922 ret = -1;
6923 goto the_end;
6925 total_len = qemu_get_be64(f);
6926 end_pos = total_len + qemu_ftell(f);
6927 for(;;) {
6928 if (qemu_ftell(f) >= end_pos)
6929 break;
6930 len = qemu_get_byte(f);
6931 qemu_get_buffer(f, (uint8_t *)idstr, len);
6932 idstr[len] = '\0';
6933 instance_id = qemu_get_be32(f);
6934 version_id = qemu_get_be32(f);
6935 record_len = qemu_get_be32(f);
6936 #if 0
6937 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6938 idstr, instance_id, version_id, record_len);
6939 #endif
6940 cur_pos = qemu_ftell(f);
6941 se = find_se(idstr, instance_id);
6942 if (!se) {
6943 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6944 instance_id, idstr);
6945 } else {
6946 ret = se->load_state(f, se->opaque, version_id);
6947 if (ret < 0) {
6948 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6949 instance_id, idstr);
6950 goto the_end;
6953 /* always seek to exact end of record */
6954 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6956 ret = 0;
6957 the_end:
6958 return ret;
6961 int qemu_live_savevm_state(QEMUFile *f)
6963 SaveStateEntry *se;
6964 int len, ret;
6966 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6967 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6969 for(se = first_se; se != NULL; se = se->next) {
6970 len = strlen(se->idstr);
6972 qemu_put_byte(f, len);
6973 qemu_put_buffer(f, se->idstr, len);
6974 qemu_put_be32(f, se->instance_id);
6975 qemu_put_be32(f, se->version_id);
6977 se->save_state(f, se->opaque);
6980 qemu_put_byte(f, 0);
6982 ret = 0;
6983 return ret;
6986 int qemu_live_loadvm_state(QEMUFile *f)
6988 SaveStateEntry *se;
6989 int len, ret, instance_id, version_id;
6990 unsigned int v;
6991 char idstr[256];
6993 v = qemu_get_be32(f);
6994 if (v != QEMU_VM_FILE_MAGIC)
6995 goto fail;
6996 v = qemu_get_be32(f);
6997 if (v != QEMU_VM_FILE_VERSION) {
6998 fail:
6999 ret = -1;
7000 goto the_end;
7003 for(;;) {
7004 len = qemu_get_byte(f);
7005 if (len == 0)
7006 break;
7007 qemu_get_buffer(f, idstr, len);
7008 idstr[len] = '\0';
7009 instance_id = qemu_get_be32(f);
7010 version_id = qemu_get_be32(f);
7011 se = find_se(idstr, instance_id);
7012 if (!se) {
7013 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7014 instance_id, idstr);
7015 } else {
7016 if (version_id > se->version_id) { /* src version > dst version */
7017 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7018 idstr, version_id, se->version_id);
7019 ret = -1;
7020 goto the_end;
7022 ret = se->load_state(f, se->opaque, version_id);
7023 if (ret < 0) {
7024 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7025 instance_id, idstr);
7026 goto the_end;
7030 ret = 0;
7032 qemu_announce_self();
7034 the_end:
7035 return ret;
7038 /* device can contain snapshots */
7039 static int bdrv_can_snapshot(BlockDriverState *bs)
7041 return (bs &&
7042 !bdrv_is_removable(bs) &&
7043 !bdrv_is_read_only(bs));
7046 /* device must be snapshots in order to have a reliable snapshot */
7047 static int bdrv_has_snapshot(BlockDriverState *bs)
7049 return (bs &&
7050 !bdrv_is_removable(bs) &&
7051 !bdrv_is_read_only(bs));
7054 static BlockDriverState *get_bs_snapshots(void)
7056 BlockDriverState *bs;
7057 int i;
7059 if (bs_snapshots)
7060 return bs_snapshots;
7061 for(i = 0; i <= nb_drives; i++) {
7062 bs = drives_table[i].bdrv;
7063 if (bdrv_can_snapshot(bs))
7064 goto ok;
7066 return NULL;
7068 bs_snapshots = bs;
7069 return bs;
7072 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
7073 const char *name)
7075 QEMUSnapshotInfo *sn_tab, *sn;
7076 int nb_sns, i, ret;
7078 ret = -ENOENT;
7079 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7080 if (nb_sns < 0)
7081 return ret;
7082 for(i = 0; i < nb_sns; i++) {
7083 sn = &sn_tab[i];
7084 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
7085 *sn_info = *sn;
7086 ret = 0;
7087 break;
7090 qemu_free(sn_tab);
7091 return ret;
7094 void do_savevm(const char *name)
7096 BlockDriverState *bs, *bs1;
7097 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
7098 int must_delete, ret, i;
7099 BlockDriverInfo bdi1, *bdi = &bdi1;
7100 QEMUFile *f;
7101 int saved_vm_running;
7102 #ifdef _WIN32
7103 struct _timeb tb;
7104 #else
7105 struct timeval tv;
7106 #endif
7108 bs = get_bs_snapshots();
7109 if (!bs) {
7110 term_printf("No block device can accept snapshots\n");
7111 return;
7114 /* ??? Should this occur after vm_stop? */
7115 qemu_aio_flush();
7117 saved_vm_running = vm_running;
7118 vm_stop(0);
7120 must_delete = 0;
7121 if (name) {
7122 ret = bdrv_snapshot_find(bs, old_sn, name);
7123 if (ret >= 0) {
7124 must_delete = 1;
7127 memset(sn, 0, sizeof(*sn));
7128 if (must_delete) {
7129 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
7130 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
7131 } else {
7132 if (name)
7133 pstrcpy(sn->name, sizeof(sn->name), name);
7136 /* fill auxiliary fields */
7137 #ifdef _WIN32
7138 _ftime(&tb);
7139 sn->date_sec = tb.time;
7140 sn->date_nsec = tb.millitm * 1000000;
7141 #else
7142 gettimeofday(&tv, NULL);
7143 sn->date_sec = tv.tv_sec;
7144 sn->date_nsec = tv.tv_usec * 1000;
7145 #endif
7146 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
7148 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7149 term_printf("Device %s does not support VM state snapshots\n",
7150 bdrv_get_device_name(bs));
7151 goto the_end;
7154 /* save the VM state */
7155 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
7156 if (!f) {
7157 term_printf("Could not open VM state file\n");
7158 goto the_end;
7160 ret = qemu_savevm_state(f);
7161 sn->vm_state_size = qemu_ftell(f);
7162 qemu_fclose(f);
7163 if (ret < 0) {
7164 term_printf("Error %d while writing VM\n", ret);
7165 goto the_end;
7168 /* create the snapshots */
7170 for(i = 0; i < nb_drives; i++) {
7171 bs1 = drives_table[i].bdrv;
7172 if (bdrv_has_snapshot(bs1)) {
7173 if (must_delete) {
7174 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
7175 if (ret < 0) {
7176 term_printf("Error while deleting snapshot on '%s'\n",
7177 bdrv_get_device_name(bs1));
7180 ret = bdrv_snapshot_create(bs1, sn);
7181 if (ret < 0) {
7182 term_printf("Error while creating snapshot on '%s'\n",
7183 bdrv_get_device_name(bs1));
7188 the_end:
7189 if (saved_vm_running)
7190 vm_start();
7193 void do_loadvm(const char *name)
7195 BlockDriverState *bs, *bs1;
7196 BlockDriverInfo bdi1, *bdi = &bdi1;
7197 QEMUFile *f;
7198 int i, ret;
7199 int saved_vm_running;
7201 bs = get_bs_snapshots();
7202 if (!bs) {
7203 term_printf("No block device supports snapshots\n");
7204 return;
7207 /* Flush all IO requests so they don't interfere with the new state. */
7208 qemu_aio_flush();
7210 saved_vm_running = vm_running;
7211 vm_stop(0);
7213 for(i = 0; i <= nb_drives; i++) {
7214 bs1 = drives_table[i].bdrv;
7215 if (bdrv_has_snapshot(bs1)) {
7216 ret = bdrv_snapshot_goto(bs1, name);
7217 if (ret < 0) {
7218 if (bs != bs1)
7219 term_printf("Warning: ");
7220 switch(ret) {
7221 case -ENOTSUP:
7222 term_printf("Snapshots not supported on device '%s'\n",
7223 bdrv_get_device_name(bs1));
7224 break;
7225 case -ENOENT:
7226 term_printf("Could not find snapshot '%s' on device '%s'\n",
7227 name, bdrv_get_device_name(bs1));
7228 break;
7229 default:
7230 term_printf("Error %d while activating snapshot on '%s'\n",
7231 ret, bdrv_get_device_name(bs1));
7232 break;
7234 /* fatal on snapshot block device */
7235 if (bs == bs1)
7236 goto the_end;
7241 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7242 term_printf("Device %s does not support VM state snapshots\n",
7243 bdrv_get_device_name(bs));
7244 return;
7247 /* restore the VM state */
7248 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
7249 if (!f) {
7250 term_printf("Could not open VM state file\n");
7251 goto the_end;
7253 ret = qemu_loadvm_state(f);
7254 qemu_fclose(f);
7255 if (ret < 0) {
7256 term_printf("Error %d while loading VM state\n", ret);
7258 the_end:
7259 if (saved_vm_running)
7260 vm_start();
7263 void do_delvm(const char *name)
7265 BlockDriverState *bs, *bs1;
7266 int i, ret;
7268 bs = get_bs_snapshots();
7269 if (!bs) {
7270 term_printf("No block device supports snapshots\n");
7271 return;
7274 for(i = 0; i <= nb_drives; i++) {
7275 bs1 = drives_table[i].bdrv;
7276 if (bdrv_has_snapshot(bs1)) {
7277 ret = bdrv_snapshot_delete(bs1, name);
7278 if (ret < 0) {
7279 if (ret == -ENOTSUP)
7280 term_printf("Snapshots not supported on device '%s'\n",
7281 bdrv_get_device_name(bs1));
7282 else
7283 term_printf("Error %d while deleting snapshot on '%s'\n",
7284 ret, bdrv_get_device_name(bs1));
7290 void do_info_snapshots(void)
7292 BlockDriverState *bs, *bs1;
7293 QEMUSnapshotInfo *sn_tab, *sn;
7294 int nb_sns, i;
7295 char buf[256];
7297 bs = get_bs_snapshots();
7298 if (!bs) {
7299 term_printf("No available block device supports snapshots\n");
7300 return;
7302 term_printf("Snapshot devices:");
7303 for(i = 0; i <= nb_drives; i++) {
7304 bs1 = drives_table[i].bdrv;
7305 if (bdrv_has_snapshot(bs1)) {
7306 if (bs == bs1)
7307 term_printf(" %s", bdrv_get_device_name(bs1));
7310 term_printf("\n");
7312 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7313 if (nb_sns < 0) {
7314 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
7315 return;
7317 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
7318 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
7319 for(i = 0; i < nb_sns; i++) {
7320 sn = &sn_tab[i];
7321 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
7323 qemu_free(sn_tab);
7326 /***********************************************************/
7327 /* ram save/restore */
7329 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7331 int v;
7333 v = qemu_get_byte(f);
7334 switch(v) {
7335 case 0:
7336 if (qemu_get_buffer(f, buf, len) != len)
7337 return -EIO;
7338 break;
7339 case 1:
7340 v = qemu_get_byte(f);
7341 memset(buf, v, len);
7342 break;
7343 default:
7344 return -EINVAL;
7346 return 0;
7349 static int ram_load_v1(QEMUFile *f, void *opaque)
7351 int ret;
7352 ram_addr_t i;
7354 if (qemu_get_be32(f) != phys_ram_size)
7355 return -EINVAL;
7356 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7357 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7358 continue;
7359 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7360 if (ret)
7361 return ret;
7363 return 0;
7366 #define BDRV_HASH_BLOCK_SIZE 1024
7367 #define IOBUF_SIZE 4096
7368 #define RAM_CBLOCK_MAGIC 0xfabe
7370 typedef struct RamCompressState {
7371 z_stream zstream;
7372 QEMUFile *f;
7373 uint8_t buf[IOBUF_SIZE];
7374 } RamCompressState;
7376 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7378 int ret;
7379 memset(s, 0, sizeof(*s));
7380 s->f = f;
7381 ret = deflateInit2(&s->zstream, 1,
7382 Z_DEFLATED, 15,
7383 9, Z_DEFAULT_STRATEGY);
7384 if (ret != Z_OK)
7385 return -1;
7386 s->zstream.avail_out = IOBUF_SIZE;
7387 s->zstream.next_out = s->buf;
7388 return 0;
7391 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7393 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7394 qemu_put_be16(s->f, len);
7395 qemu_put_buffer(s->f, buf, len);
7398 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7400 int ret;
7402 s->zstream.avail_in = len;
7403 s->zstream.next_in = (uint8_t *)buf;
7404 while (s->zstream.avail_in > 0) {
7405 ret = deflate(&s->zstream, Z_NO_FLUSH);
7406 if (ret != Z_OK)
7407 return -1;
7408 if (s->zstream.avail_out == 0) {
7409 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7410 s->zstream.avail_out = IOBUF_SIZE;
7411 s->zstream.next_out = s->buf;
7414 return 0;
7417 static void ram_compress_close(RamCompressState *s)
7419 int len, ret;
7421 /* compress last bytes */
7422 for(;;) {
7423 ret = deflate(&s->zstream, Z_FINISH);
7424 if (ret == Z_OK || ret == Z_STREAM_END) {
7425 len = IOBUF_SIZE - s->zstream.avail_out;
7426 if (len > 0) {
7427 ram_put_cblock(s, s->buf, len);
7429 s->zstream.avail_out = IOBUF_SIZE;
7430 s->zstream.next_out = s->buf;
7431 if (ret == Z_STREAM_END)
7432 break;
7433 } else {
7434 goto fail;
7437 fail:
7438 deflateEnd(&s->zstream);
7441 typedef struct RamDecompressState {
7442 z_stream zstream;
7443 QEMUFile *f;
7444 uint8_t buf[IOBUF_SIZE];
7445 } RamDecompressState;
7447 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7449 int ret;
7450 memset(s, 0, sizeof(*s));
7451 s->f = f;
7452 ret = inflateInit(&s->zstream);
7453 if (ret != Z_OK)
7454 return -1;
7455 return 0;
7458 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7460 int ret, clen;
7462 s->zstream.avail_out = len;
7463 s->zstream.next_out = buf;
7464 while (s->zstream.avail_out > 0) {
7465 if (s->zstream.avail_in == 0) {
7466 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7467 return -1;
7468 clen = qemu_get_be16(s->f);
7469 if (clen > IOBUF_SIZE)
7470 return -1;
7471 qemu_get_buffer(s->f, s->buf, clen);
7472 s->zstream.avail_in = clen;
7473 s->zstream.next_in = s->buf;
7475 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7476 if (ret != Z_OK && ret != Z_STREAM_END) {
7477 return -1;
7480 return 0;
7483 static void ram_decompress_close(RamDecompressState *s)
7485 inflateEnd(&s->zstream);
7488 static void ram_save_live(QEMUFile *f, void *opaque)
7490 target_ulong addr;
7492 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7493 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7494 continue;
7495 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7496 qemu_put_be32(f, addr);
7497 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7500 qemu_put_be32(f, 1);
7503 static void ram_save_static(QEMUFile *f, void *opaque)
7505 ram_addr_t i;
7506 RamCompressState s1, *s = &s1;
7507 uint8_t buf[10];
7509 qemu_put_be32(f, phys_ram_size);
7510 if (ram_compress_open(s, f) < 0)
7511 return;
7512 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7513 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7514 continue;
7515 #if 0
7516 if (tight_savevm_enabled) {
7517 int64_t sector_num;
7518 int j;
7520 /* find if the memory block is available on a virtual
7521 block device */
7522 sector_num = -1;
7523 for(j = 0; j < nb_drives; j++) {
7524 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7525 phys_ram_base + i,
7526 BDRV_HASH_BLOCK_SIZE);
7527 if (sector_num >= 0)
7528 break;
7530 if (j == nb_drives)
7531 goto normal_compress;
7532 buf[0] = 1;
7533 buf[1] = j;
7534 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7535 ram_compress_buf(s, buf, 10);
7536 } else
7537 #endif
7539 // normal_compress:
7540 buf[0] = 0;
7541 ram_compress_buf(s, buf, 1);
7542 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7545 ram_compress_close(s);
7548 static void ram_save(QEMUFile *f, void *opaque)
7550 int in_migration = cpu_physical_memory_get_dirty_tracking();
7552 qemu_put_byte(f, in_migration);
7554 if (in_migration)
7555 ram_save_live(f, opaque);
7556 else
7557 ram_save_static(f, opaque);
7560 static int ram_load_live(QEMUFile *f, void *opaque)
7562 target_ulong addr;
7564 do {
7565 addr = qemu_get_be32(f);
7566 if (addr == 1)
7567 break;
7569 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7570 } while (1);
7572 return 0;
7575 static int ram_load_static(QEMUFile *f, void *opaque)
7577 RamDecompressState s1, *s = &s1;
7578 uint8_t buf[10];
7579 ram_addr_t i;
7581 if (qemu_get_be32(f) != phys_ram_size)
7582 return -EINVAL;
7583 if (ram_decompress_open(s, f) < 0)
7584 return -EINVAL;
7585 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7586 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7587 continue;
7588 if (ram_decompress_buf(s, buf, 1) < 0) {
7589 fprintf(stderr, "Error while reading ram block header\n");
7590 goto error;
7592 if (buf[0] == 0) {
7593 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7594 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7595 goto error;
7597 } else
7598 #if 0
7599 if (buf[0] == 1) {
7600 int bs_index;
7601 int64_t sector_num;
7603 ram_decompress_buf(s, buf + 1, 9);
7604 bs_index = buf[1];
7605 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7606 if (bs_index >= nb_drives) {
7607 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7608 goto error;
7610 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7611 phys_ram_base + i,
7612 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7613 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7614 bs_index, sector_num);
7615 goto error;
7617 } else
7618 #endif
7620 error:
7621 printf("Error block header\n");
7622 return -EINVAL;
7625 ram_decompress_close(s);
7626 return 0;
7629 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7631 int ret;
7633 switch (version_id) {
7634 case 1:
7635 ret = ram_load_v1(f, opaque);
7636 break;
7637 case 3:
7638 if (qemu_get_byte(f)) {
7639 ret = ram_load_live(f, opaque);
7640 break;
7642 case 2:
7643 ret = ram_load_static(f, opaque);
7644 break;
7645 default:
7646 ret = -EINVAL;
7647 break;
7650 return ret;
7653 /***********************************************************/
7654 /* bottom halves (can be seen as timers which expire ASAP) */
7656 struct QEMUBH {
7657 QEMUBHFunc *cb;
7658 void *opaque;
7659 int scheduled;
7660 QEMUBH *next;
7663 static QEMUBH *first_bh = NULL;
7665 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7667 QEMUBH *bh;
7668 bh = qemu_mallocz(sizeof(QEMUBH));
7669 if (!bh)
7670 return NULL;
7671 bh->cb = cb;
7672 bh->opaque = opaque;
7673 return bh;
7676 int qemu_bh_poll(void)
7678 QEMUBH *bh, **pbh;
7679 int ret;
7681 ret = 0;
7682 for(;;) {
7683 pbh = &first_bh;
7684 bh = *pbh;
7685 if (!bh)
7686 break;
7687 ret = 1;
7688 *pbh = bh->next;
7689 bh->scheduled = 0;
7690 bh->cb(bh->opaque);
7692 return ret;
7695 void qemu_bh_schedule(QEMUBH *bh)
7697 CPUState *env = cpu_single_env;
7698 if (bh->scheduled)
7699 return;
7700 bh->scheduled = 1;
7701 bh->next = first_bh;
7702 first_bh = bh;
7704 /* stop the currently executing CPU to execute the BH ASAP */
7705 if (env) {
7706 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7708 main_loop_break();
7711 void qemu_bh_cancel(QEMUBH *bh)
7713 QEMUBH **pbh;
7714 if (bh->scheduled) {
7715 pbh = &first_bh;
7716 while (*pbh != bh)
7717 pbh = &(*pbh)->next;
7718 *pbh = bh->next;
7719 bh->scheduled = 0;
7723 void qemu_bh_delete(QEMUBH *bh)
7725 qemu_bh_cancel(bh);
7726 qemu_free(bh);
7729 /***********************************************************/
7730 /* machine registration */
7732 QEMUMachine *first_machine = NULL;
7733 QEMUMachine *current_machine = NULL;
7735 int qemu_register_machine(QEMUMachine *m)
7737 QEMUMachine **pm;
7738 pm = &first_machine;
7739 while (*pm != NULL)
7740 pm = &(*pm)->next;
7741 m->next = NULL;
7742 *pm = m;
7743 return 0;
7746 static QEMUMachine *find_machine(const char *name)
7748 QEMUMachine *m;
7750 for(m = first_machine; m != NULL; m = m->next) {
7751 if (!strcmp(m->name, name))
7752 return m;
7754 return NULL;
7757 /***********************************************************/
7758 /* main execution loop */
7760 static void gui_update(void *opaque)
7762 DisplayState *ds = opaque;
7763 ds->dpy_refresh(ds);
7764 qemu_mod_timer(ds->gui_timer,
7765 (ds->gui_timer_interval ?
7766 ds->gui_timer_interval :
7767 GUI_REFRESH_INTERVAL)
7768 + qemu_get_clock(rt_clock));
7771 struct vm_change_state_entry {
7772 VMChangeStateHandler *cb;
7773 void *opaque;
7774 LIST_ENTRY (vm_change_state_entry) entries;
7777 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7779 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7780 void *opaque)
7782 VMChangeStateEntry *e;
7784 e = qemu_mallocz(sizeof (*e));
7785 if (!e)
7786 return NULL;
7788 e->cb = cb;
7789 e->opaque = opaque;
7790 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7791 return e;
7794 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7796 LIST_REMOVE (e, entries);
7797 qemu_free (e);
7800 static void vm_state_notify(int running)
7802 VMChangeStateEntry *e;
7804 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7805 e->cb(e->opaque, running);
7809 /* XXX: support several handlers */
7810 static VMStopHandler *vm_stop_cb;
7811 static void *vm_stop_opaque;
7813 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7815 vm_stop_cb = cb;
7816 vm_stop_opaque = opaque;
7817 return 0;
7820 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7822 vm_stop_cb = NULL;
7825 void vm_start(void)
7827 if (!vm_running) {
7828 cpu_enable_ticks();
7829 vm_running = 1;
7830 vm_state_notify(1);
7831 qemu_rearm_alarm_timer(alarm_timer);
7835 void vm_stop(int reason)
7837 if (vm_running) {
7838 cpu_disable_ticks();
7839 vm_running = 0;
7840 if (reason != 0) {
7841 if (vm_stop_cb) {
7842 vm_stop_cb(vm_stop_opaque, reason);
7845 vm_state_notify(0);
7849 /* reset/shutdown handler */
7851 typedef struct QEMUResetEntry {
7852 QEMUResetHandler *func;
7853 void *opaque;
7854 struct QEMUResetEntry *next;
7855 } QEMUResetEntry;
7857 static QEMUResetEntry *first_reset_entry;
7858 static int reset_requested;
7859 static int shutdown_requested;
7860 static int powerdown_requested;
7862 int qemu_shutdown_requested(void)
7864 int r = shutdown_requested;
7865 shutdown_requested = 0;
7866 return r;
7869 int qemu_reset_requested(void)
7871 int r = reset_requested;
7872 reset_requested = 0;
7873 return r;
7876 int qemu_powerdown_requested(void)
7878 int r = powerdown_requested;
7879 powerdown_requested = 0;
7880 return r;
7883 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7885 QEMUResetEntry **pre, *re;
7887 pre = &first_reset_entry;
7888 while (*pre != NULL)
7889 pre = &(*pre)->next;
7890 re = qemu_mallocz(sizeof(QEMUResetEntry));
7891 re->func = func;
7892 re->opaque = opaque;
7893 re->next = NULL;
7894 *pre = re;
7897 void qemu_system_reset(void)
7899 QEMUResetEntry *re;
7901 /* reset all devices */
7902 for(re = first_reset_entry; re != NULL; re = re->next) {
7903 re->func(re->opaque);
7907 void qemu_system_reset_request(void)
7909 if (no_reboot) {
7910 shutdown_requested = 1;
7911 } else {
7912 reset_requested = 1;
7914 if (cpu_single_env)
7915 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7916 main_loop_break();
7919 void qemu_system_shutdown_request(void)
7921 shutdown_requested = 1;
7922 if (cpu_single_env)
7923 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7926 void qemu_system_powerdown_request(void)
7928 powerdown_requested = 1;
7929 if (cpu_single_env)
7930 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7933 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
7934 struct timeval *tv)
7936 int ret;
7938 /* KVM holds a mutex while QEMU code is running, we need hooks to
7939 release the mutex whenever QEMU code sleeps. */
7941 kvm_sleep_begin();
7943 ret = select(max_fd, rfds, wfds, xfds, tv);
7945 kvm_sleep_end();
7947 return ret;
7950 void main_loop_wait(int timeout)
7952 IOHandlerRecord *ioh;
7953 fd_set rfds, wfds, xfds;
7954 int ret, nfds;
7955 #ifdef _WIN32
7956 int ret2, i;
7957 #endif
7958 struct timeval tv;
7959 PollingEntry *pe;
7962 /* XXX: need to suppress polling by better using win32 events */
7963 ret = 0;
7964 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7965 ret |= pe->func(pe->opaque);
7967 #ifdef _WIN32
7968 if (ret == 0) {
7969 int err;
7970 WaitObjects *w = &wait_objects;
7972 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7973 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7974 if (w->func[ret - WAIT_OBJECT_0])
7975 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7977 /* Check for additional signaled events */
7978 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7980 /* Check if event is signaled */
7981 ret2 = WaitForSingleObject(w->events[i], 0);
7982 if(ret2 == WAIT_OBJECT_0) {
7983 if (w->func[i])
7984 w->func[i](w->opaque[i]);
7985 } else if (ret2 == WAIT_TIMEOUT) {
7986 } else {
7987 err = GetLastError();
7988 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7991 } else if (ret == WAIT_TIMEOUT) {
7992 } else {
7993 err = GetLastError();
7994 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7997 #endif
7998 /* poll any events */
7999 /* XXX: separate device handlers from system ones */
8000 nfds = -1;
8001 FD_ZERO(&rfds);
8002 FD_ZERO(&wfds);
8003 FD_ZERO(&xfds);
8004 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
8005 if (ioh->deleted)
8006 continue;
8007 if (ioh->fd_read &&
8008 (!ioh->fd_read_poll ||
8009 ioh->fd_read_poll(ioh->opaque) != 0)) {
8010 FD_SET(ioh->fd, &rfds);
8011 if (ioh->fd > nfds)
8012 nfds = ioh->fd;
8014 if (ioh->fd_write) {
8015 FD_SET(ioh->fd, &wfds);
8016 if (ioh->fd > nfds)
8017 nfds = ioh->fd;
8021 #ifdef _WIN32
8022 tv.tv_sec = 0;
8023 tv.tv_usec = 0;
8024 #else
8025 tv.tv_sec = timeout / 1000;
8026 tv.tv_usec = (timeout % 1000) * 1000;
8027 #endif
8028 #if defined(CONFIG_SLIRP)
8029 if (slirp_inited) {
8030 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
8032 #endif
8033 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
8034 if (ret > 0) {
8035 IOHandlerRecord **pioh;
8037 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
8038 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
8039 ioh->fd_read(ioh->opaque);
8040 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
8041 FD_CLR(ioh->fd, &rfds);
8043 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
8044 ioh->fd_write(ioh->opaque);
8048 /* remove deleted IO handlers */
8049 pioh = &first_io_handler;
8050 while (*pioh) {
8051 ioh = *pioh;
8052 if (ioh->deleted) {
8053 *pioh = ioh->next;
8054 qemu_free(ioh);
8055 } else
8056 pioh = &ioh->next;
8059 #if defined(CONFIG_SLIRP)
8060 if (slirp_inited) {
8061 if (ret < 0) {
8062 FD_ZERO(&rfds);
8063 FD_ZERO(&wfds);
8064 FD_ZERO(&xfds);
8066 slirp_select_poll(&rfds, &wfds, &xfds);
8068 #endif
8069 qemu_aio_poll();
8070 if (vm_running) {
8071 if (likely(!cur_cpu || !(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
8072 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
8073 qemu_get_clock(vm_clock));
8074 /* run dma transfers, if any */
8075 DMA_run();
8078 /* real time timers */
8079 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
8080 qemu_get_clock(rt_clock));
8082 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
8083 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
8084 qemu_rearm_alarm_timer(alarm_timer);
8087 /* Check bottom-halves last in case any of the earlier events triggered
8088 them. */
8089 qemu_bh_poll();
8093 static int main_loop(void)
8095 int ret, timeout;
8096 #ifdef CONFIG_PROFILER
8097 int64_t ti;
8098 #endif
8099 CPUState *env;
8102 if (kvm_enabled()) {
8103 kvm_main_loop();
8104 cpu_disable_ticks();
8105 return 0;
8108 cur_cpu = first_cpu;
8109 next_cpu = cur_cpu->next_cpu ?: first_cpu;
8110 for(;;) {
8111 if (vm_running) {
8113 for(;;) {
8114 /* get next cpu */
8115 env = next_cpu;
8116 #ifdef CONFIG_PROFILER
8117 ti = profile_getclock();
8118 #endif
8119 if (use_icount) {
8120 int64_t count;
8121 int decr;
8122 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
8123 env->icount_decr.u16.low = 0;
8124 env->icount_extra = 0;
8125 count = qemu_next_deadline();
8126 count = (count + (1 << icount_time_shift) - 1)
8127 >> icount_time_shift;
8128 qemu_icount += count;
8129 decr = (count > 0xffff) ? 0xffff : count;
8130 count -= decr;
8131 env->icount_decr.u16.low = decr;
8132 env->icount_extra = count;
8134 ret = cpu_exec(env);
8135 #ifdef CONFIG_PROFILER
8136 qemu_time += profile_getclock() - ti;
8137 #endif
8138 if (use_icount) {
8139 /* Fold pending instructions back into the
8140 instruction counter, and clear the interrupt flag. */
8141 qemu_icount -= (env->icount_decr.u16.low
8142 + env->icount_extra);
8143 env->icount_decr.u32 = 0;
8144 env->icount_extra = 0;
8146 next_cpu = env->next_cpu ?: first_cpu;
8147 if (event_pending && likely(ret != EXCP_DEBUG)) {
8148 ret = EXCP_INTERRUPT;
8149 event_pending = 0;
8150 break;
8152 if (ret == EXCP_HLT) {
8153 /* Give the next CPU a chance to run. */
8154 cur_cpu = env;
8155 continue;
8157 if (ret != EXCP_HALTED)
8158 break;
8159 /* all CPUs are halted ? */
8160 if (env == cur_cpu)
8161 break;
8163 cur_cpu = env;
8165 if (shutdown_requested) {
8166 ret = EXCP_INTERRUPT;
8167 if (no_shutdown) {
8168 vm_stop(0);
8169 no_shutdown = 0;
8171 else
8172 break;
8174 if (reset_requested) {
8175 reset_requested = 0;
8176 qemu_system_reset();
8177 if (kvm_enabled())
8178 kvm_load_registers(env);
8179 ret = EXCP_INTERRUPT;
8181 if (powerdown_requested) {
8182 powerdown_requested = 0;
8183 qemu_system_powerdown();
8184 ret = EXCP_INTERRUPT;
8186 if (unlikely(ret == EXCP_DEBUG)) {
8187 vm_stop(EXCP_DEBUG);
8189 /* If all cpus are halted then wait until the next IRQ */
8190 /* XXX: use timeout computed from timers */
8191 if (ret == EXCP_HALTED) {
8192 if (use_icount) {
8193 int64_t add;
8194 int64_t delta;
8195 /* Advance virtual time to the next event. */
8196 if (use_icount == 1) {
8197 /* When not using an adaptive execution frequency
8198 we tend to get badly out of sync with real time,
8199 so just delay for a reasonable amount of time. */
8200 delta = 0;
8201 } else {
8202 delta = cpu_get_icount() - cpu_get_clock();
8204 if (delta > 0) {
8205 /* If virtual time is ahead of real time then just
8206 wait for IO. */
8207 timeout = (delta / 1000000) + 1;
8208 } else {
8209 /* Wait for either IO to occur or the next
8210 timer event. */
8211 add = qemu_next_deadline();
8212 /* We advance the timer before checking for IO.
8213 Limit the amount we advance so that early IO
8214 activity won't get the guest too far ahead. */
8215 if (add > 10000000)
8216 add = 10000000;
8217 delta += add;
8218 add = (add + (1 << icount_time_shift) - 1)
8219 >> icount_time_shift;
8220 qemu_icount += add;
8221 timeout = delta / 1000000;
8222 if (timeout < 0)
8223 timeout = 0;
8225 } else {
8226 timeout = 10;
8228 } else {
8229 timeout = 0;
8231 } else {
8232 timeout = 10;
8234 #ifdef CONFIG_PROFILER
8235 ti = profile_getclock();
8236 #endif
8237 main_loop_wait(timeout);
8238 #ifdef CONFIG_PROFILER
8239 dev_time += profile_getclock() - ti;
8240 #endif
8242 cpu_disable_ticks();
8243 return ret;
8246 static void help(int exitcode)
8248 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
8249 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8250 "usage: %s [options] [disk_image]\n"
8251 "\n"
8252 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8253 "\n"
8254 "Standard options:\n"
8255 "-M machine select emulated machine (-M ? for list)\n"
8256 "-cpu cpu select CPU (-cpu ? for list)\n"
8257 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8258 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8259 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8260 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8261 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8262 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8263 " [,cache=on|off][,format=f][,boot=on|off]\n"
8264 " use 'file' as a drive image\n"
8265 "-mtdblock file use 'file' as on-board Flash memory image\n"
8266 "-sd file use 'file' as SecureDigital card image\n"
8267 "-pflash file use 'file' as a parallel flash image\n"
8268 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8269 "-snapshot write to temporary files instead of disk image files\n"
8270 #ifdef CONFIG_SDL
8271 "-no-frame open SDL window without a frame and window decorations\n"
8272 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8273 "-no-quit disable SDL window close capability\n"
8274 #endif
8275 #ifdef TARGET_I386
8276 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8277 #endif
8278 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8279 "-smp n set the number of CPUs to 'n' [default=1]\n"
8280 "-nographic disable graphical output and redirect serial I/Os to console\n"
8281 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8282 #ifndef _WIN32
8283 "-k language use keyboard layout (for example \"fr\" for French)\n"
8284 #endif
8285 #ifdef HAS_AUDIO
8286 "-audio-help print list of audio drivers and their options\n"
8287 "-soundhw c1,... enable audio support\n"
8288 " and only specified sound cards (comma separated list)\n"
8289 " use -soundhw ? to get the list of supported cards\n"
8290 " use -soundhw all to enable all of them\n"
8291 #endif
8292 "-localtime set the real time clock to local time [default=utc]\n"
8293 "-full-screen start in full screen\n"
8294 #ifdef TARGET_I386
8295 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8296 #endif
8297 "-usb enable the USB driver (will be the default soon)\n"
8298 "-usbdevice name add the host or guest USB device 'name'\n"
8299 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8300 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8301 #endif
8302 "-name string set the name of the guest\n"
8303 "\n"
8304 "Network options:\n"
8305 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8306 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8307 #ifdef CONFIG_SLIRP
8308 "-net user[,vlan=n][,hostname=host]\n"
8309 " connect the user mode network stack to VLAN 'n' and send\n"
8310 " hostname 'host' to DHCP clients\n"
8311 #endif
8312 #ifdef _WIN32
8313 "-net tap[,vlan=n],ifname=name\n"
8314 " connect the host TAP network interface to VLAN 'n'\n"
8315 #else
8316 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8317 " connect the host TAP network interface to VLAN 'n' and use the\n"
8318 " network scripts 'file' (default=%s)\n"
8319 " and 'dfile' (default=%s);\n"
8320 " use '[down]script=no' to disable script execution;\n"
8321 " use 'fd=h' to connect to an already opened TAP interface\n"
8322 #endif
8323 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8324 " connect the vlan 'n' to another VLAN using a socket connection\n"
8325 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8326 " connect the vlan 'n' to multicast maddr and port\n"
8327 #ifdef CONFIG_VDE
8328 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8329 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8330 " on host and listening for incoming connections on 'socketpath'.\n"
8331 " Use group 'groupname' and mode 'octalmode' to change default\n"
8332 " ownership and permissions for communication port.\n"
8333 #endif
8334 "-net none use it alone to have zero network devices; if no -net option\n"
8335 " is provided, the default is '-net nic -net user'\n"
8336 "\n"
8337 #ifdef CONFIG_SLIRP
8338 "-tftp dir allow tftp access to files in dir [-net user]\n"
8339 "-bootp file advertise file in BOOTP replies\n"
8340 #ifndef _WIN32
8341 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8342 #endif
8343 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8344 " redirect TCP or UDP connections from host to guest [-net user]\n"
8345 #endif
8346 "\n"
8347 "Linux boot specific:\n"
8348 "-kernel bzImage use 'bzImage' as kernel image\n"
8349 "-append cmdline use 'cmdline' as kernel command line\n"
8350 "-initrd file use 'file' as initial ram disk\n"
8351 "\n"
8352 "Debug/Expert options:\n"
8353 "-monitor dev redirect the monitor to char device 'dev'\n"
8354 "-serial dev redirect the serial port to char device 'dev'\n"
8355 "-parallel dev redirect the parallel port to char device 'dev'\n"
8356 "-pidfile file Write PID to 'file'\n"
8357 "-S freeze CPU at startup (use 'c' to start execution)\n"
8358 "-s wait gdb connection to port\n"
8359 "-p port set gdb connection port [default=%s]\n"
8360 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8361 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8362 " translation (t=none or lba) (usually qemu can guess them)\n"
8363 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8364 #ifdef USE_KQEMU
8365 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8366 "-no-kqemu disable KQEMU kernel module usage\n"
8367 #endif
8368 #ifdef USE_KVM
8369 #ifndef NO_CPU_EMULATION
8370 "-no-kvm disable KVM hardware virtualization\n"
8371 #endif
8372 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8373 "-no-kvm-pit disable KVM kernel mode PIT\n"
8374 #endif
8375 #ifdef TARGET_I386
8376 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8377 " (default is CL-GD5446 PCI VGA)\n"
8378 "-no-acpi disable ACPI\n"
8379 #endif
8380 #ifdef CONFIG_CURSES
8381 "-curses use a curses/ncurses interface instead of SDL\n"
8382 #endif
8383 "-no-reboot exit instead of rebooting\n"
8384 "-no-shutdown stop before shutdown\n"
8385 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8386 "-vnc display start a VNC server on display\n"
8387 #ifndef _WIN32
8388 "-daemonize daemonize QEMU after initializing\n"
8389 #endif
8390 "-tdf inject timer interrupts that got lost\n"
8391 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8392 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8393 "-option-rom rom load a file, rom, into the option ROM space\n"
8394 #ifdef TARGET_SPARC
8395 "-prom-env variable=value set OpenBIOS nvram variables\n"
8396 #endif
8397 "-clock force the use of the given methods for timer alarm.\n"
8398 " To see what timers are available use -clock ?\n"
8399 "-startdate select initial date of the clock\n"
8400 "-icount [N|auto]\n"
8401 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8402 "\n"
8403 "During emulation, the following keys are useful:\n"
8404 "ctrl-alt-f toggle full screen\n"
8405 "ctrl-alt-n switch to virtual console 'n'\n"
8406 "ctrl-alt toggle mouse and keyboard grab\n"
8407 "\n"
8408 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8410 "qemu",
8411 DEFAULT_RAM_SIZE,
8412 #ifndef _WIN32
8413 DEFAULT_NETWORK_SCRIPT,
8414 DEFAULT_NETWORK_DOWN_SCRIPT,
8415 #endif
8416 DEFAULT_GDBSTUB_PORT,
8417 "/tmp/qemu.log");
8418 exit(exitcode);
8421 #define HAS_ARG 0x0001
8423 enum {
8424 QEMU_OPTION_h,
8426 QEMU_OPTION_M,
8427 QEMU_OPTION_cpu,
8428 QEMU_OPTION_fda,
8429 QEMU_OPTION_fdb,
8430 QEMU_OPTION_hda,
8431 QEMU_OPTION_hdb,
8432 QEMU_OPTION_hdc,
8433 QEMU_OPTION_hdd,
8434 QEMU_OPTION_drive,
8435 QEMU_OPTION_cdrom,
8436 QEMU_OPTION_mtdblock,
8437 QEMU_OPTION_sd,
8438 QEMU_OPTION_pflash,
8439 QEMU_OPTION_boot,
8440 QEMU_OPTION_snapshot,
8441 #ifdef TARGET_I386
8442 QEMU_OPTION_no_fd_bootchk,
8443 #endif
8444 QEMU_OPTION_m,
8445 QEMU_OPTION_nographic,
8446 QEMU_OPTION_portrait,
8447 #ifdef HAS_AUDIO
8448 QEMU_OPTION_audio_help,
8449 QEMU_OPTION_soundhw,
8450 #endif
8452 QEMU_OPTION_net,
8453 QEMU_OPTION_tftp,
8454 QEMU_OPTION_bootp,
8455 QEMU_OPTION_smb,
8456 QEMU_OPTION_redir,
8458 QEMU_OPTION_kernel,
8459 QEMU_OPTION_append,
8460 QEMU_OPTION_initrd,
8462 QEMU_OPTION_S,
8463 QEMU_OPTION_s,
8464 QEMU_OPTION_p,
8465 QEMU_OPTION_d,
8466 QEMU_OPTION_hdachs,
8467 QEMU_OPTION_L,
8468 QEMU_OPTION_bios,
8469 QEMU_OPTION_k,
8470 QEMU_OPTION_localtime,
8471 QEMU_OPTION_cirrusvga,
8472 QEMU_OPTION_vmsvga,
8473 QEMU_OPTION_g,
8474 QEMU_OPTION_std_vga,
8475 QEMU_OPTION_echr,
8476 QEMU_OPTION_monitor,
8477 QEMU_OPTION_serial,
8478 QEMU_OPTION_parallel,
8479 QEMU_OPTION_loadvm,
8480 QEMU_OPTION_full_screen,
8481 QEMU_OPTION_no_frame,
8482 QEMU_OPTION_alt_grab,
8483 QEMU_OPTION_no_quit,
8484 QEMU_OPTION_pidfile,
8485 QEMU_OPTION_no_kqemu,
8486 QEMU_OPTION_kernel_kqemu,
8487 QEMU_OPTION_win2k_hack,
8488 QEMU_OPTION_usb,
8489 QEMU_OPTION_usbdevice,
8490 QEMU_OPTION_smp,
8491 QEMU_OPTION_vnc,
8492 QEMU_OPTION_no_acpi,
8493 QEMU_OPTION_curses,
8494 QEMU_OPTION_no_kvm,
8495 QEMU_OPTION_no_kvm_irqchip,
8496 QEMU_OPTION_no_kvm_pit,
8497 QEMU_OPTION_no_reboot,
8498 QEMU_OPTION_no_shutdown,
8499 QEMU_OPTION_show_cursor,
8500 QEMU_OPTION_daemonize,
8501 QEMU_OPTION_option_rom,
8502 QEMU_OPTION_semihosting,
8503 QEMU_OPTION_cpu_vendor,
8504 QEMU_OPTION_name,
8505 QEMU_OPTION_prom_env,
8506 QEMU_OPTION_old_param,
8507 QEMU_OPTION_clock,
8508 QEMU_OPTION_startdate,
8509 QEMU_OPTION_tb_size,
8510 QEMU_OPTION_icount,
8511 QEMU_OPTION_incoming,
8512 QEMU_OPTION_tdf,
8513 QEMU_OPTION_kvm_shadow_memory,
8514 QEMU_OPTION_mempath,
8517 typedef struct QEMUOption {
8518 const char *name;
8519 int flags;
8520 int index;
8521 } QEMUOption;
8523 const QEMUOption qemu_options[] = {
8524 { "h", 0, QEMU_OPTION_h },
8525 { "help", 0, QEMU_OPTION_h },
8527 { "M", HAS_ARG, QEMU_OPTION_M },
8528 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8529 { "fda", HAS_ARG, QEMU_OPTION_fda },
8530 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8531 { "hda", HAS_ARG, QEMU_OPTION_hda },
8532 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8533 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8534 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8535 { "drive", HAS_ARG, QEMU_OPTION_drive },
8536 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8537 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8538 { "sd", HAS_ARG, QEMU_OPTION_sd },
8539 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8540 { "boot", HAS_ARG, QEMU_OPTION_boot },
8541 { "snapshot", 0, QEMU_OPTION_snapshot },
8542 #ifdef TARGET_I386
8543 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8544 #endif
8545 { "m", HAS_ARG, QEMU_OPTION_m },
8546 { "nographic", 0, QEMU_OPTION_nographic },
8547 { "portrait", 0, QEMU_OPTION_portrait },
8548 { "k", HAS_ARG, QEMU_OPTION_k },
8549 #ifdef HAS_AUDIO
8550 { "audio-help", 0, QEMU_OPTION_audio_help },
8551 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8552 #endif
8554 { "net", HAS_ARG, QEMU_OPTION_net},
8555 #ifdef CONFIG_SLIRP
8556 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8557 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8558 #ifndef _WIN32
8559 { "smb", HAS_ARG, QEMU_OPTION_smb },
8560 #endif
8561 { "redir", HAS_ARG, QEMU_OPTION_redir },
8562 #endif
8564 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8565 { "append", HAS_ARG, QEMU_OPTION_append },
8566 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8568 { "S", 0, QEMU_OPTION_S },
8569 { "s", 0, QEMU_OPTION_s },
8570 { "p", HAS_ARG, QEMU_OPTION_p },
8571 { "d", HAS_ARG, QEMU_OPTION_d },
8572 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8573 { "L", HAS_ARG, QEMU_OPTION_L },
8574 { "bios", HAS_ARG, QEMU_OPTION_bios },
8575 #ifdef USE_KQEMU
8576 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8577 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8578 #endif
8579 #ifdef USE_KVM
8580 #ifndef NO_CPU_EMULATION
8581 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8582 #endif
8583 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8584 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8585 #endif
8586 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8587 { "g", 1, QEMU_OPTION_g },
8588 #endif
8589 { "localtime", 0, QEMU_OPTION_localtime },
8590 { "std-vga", 0, QEMU_OPTION_std_vga },
8591 { "echr", HAS_ARG, QEMU_OPTION_echr },
8592 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8593 { "serial", HAS_ARG, QEMU_OPTION_serial },
8594 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8595 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8596 { "incoming", 1, QEMU_OPTION_incoming },
8597 { "full-screen", 0, QEMU_OPTION_full_screen },
8598 #ifdef CONFIG_SDL
8599 { "no-frame", 0, QEMU_OPTION_no_frame },
8600 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8601 { "no-quit", 0, QEMU_OPTION_no_quit },
8602 #endif
8603 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8604 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8605 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8606 { "smp", HAS_ARG, QEMU_OPTION_smp },
8607 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8608 #ifdef CONFIG_CURSES
8609 { "curses", 0, QEMU_OPTION_curses },
8610 #endif
8612 /* temporary options */
8613 { "usb", 0, QEMU_OPTION_usb },
8614 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8615 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8616 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8617 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8618 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8619 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8620 { "daemonize", 0, QEMU_OPTION_daemonize },
8621 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8622 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8623 { "semihosting", 0, QEMU_OPTION_semihosting },
8624 #endif
8625 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8626 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8627 { "name", HAS_ARG, QEMU_OPTION_name },
8628 #if defined(TARGET_SPARC)
8629 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8630 #endif
8631 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8632 #if defined(TARGET_ARM)
8633 { "old-param", 0, QEMU_OPTION_old_param },
8634 #endif
8635 { "clock", HAS_ARG, QEMU_OPTION_clock },
8636 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8637 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8638 { "icount", HAS_ARG, QEMU_OPTION_icount },
8639 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8640 { NULL },
8643 /* password input */
8645 int qemu_key_check(BlockDriverState *bs, const char *name)
8647 char password[256];
8648 int i;
8650 if (!bdrv_is_encrypted(bs))
8651 return 0;
8653 term_printf("%s is encrypted.\n", name);
8654 for(i = 0; i < 3; i++) {
8655 monitor_readline("Password: ", 1, password, sizeof(password));
8656 if (bdrv_set_key(bs, password) == 0)
8657 return 0;
8658 term_printf("invalid password\n");
8660 return -EPERM;
8663 static void read_passwords(void)
8665 BlockDriverState *bs;
8666 int i;
8668 for(i = 0; i < nb_drives; i++) {
8669 bs = drives_table[i].bdrv;
8670 qemu_key_check(bs, bdrv_get_device_name(bs));
8674 #ifdef HAS_AUDIO
8675 struct soundhw soundhw[] = {
8676 #ifdef HAS_AUDIO_CHOICE
8677 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8679 "pcspk",
8680 "PC speaker",
8683 { .init_isa = pcspk_audio_init }
8685 #endif
8687 "sb16",
8688 "Creative Sound Blaster 16",
8691 { .init_isa = SB16_init }
8694 #ifdef CONFIG_CS4231A
8696 "cs4231a",
8697 "CS4231A",
8700 { .init_isa = cs4231a_init }
8702 #endif
8704 #ifdef CONFIG_ADLIB
8706 "adlib",
8707 #ifdef HAS_YMF262
8708 "Yamaha YMF262 (OPL3)",
8709 #else
8710 "Yamaha YM3812 (OPL2)",
8711 #endif
8714 { .init_isa = Adlib_init }
8716 #endif
8718 #ifdef CONFIG_GUS
8720 "gus",
8721 "Gravis Ultrasound GF1",
8724 { .init_isa = GUS_init }
8726 #endif
8728 #ifdef CONFIG_AC97
8730 "ac97",
8731 "Intel 82801AA AC97 Audio",
8734 { .init_pci = ac97_init }
8736 #endif
8739 "es1370",
8740 "ENSONIQ AudioPCI ES1370",
8743 { .init_pci = es1370_init }
8745 #endif
8747 { NULL, NULL, 0, 0, { NULL } }
8750 static void select_soundhw (const char *optarg)
8752 struct soundhw *c;
8754 if (*optarg == '?') {
8755 show_valid_cards:
8757 printf ("Valid sound card names (comma separated):\n");
8758 for (c = soundhw; c->name; ++c) {
8759 printf ("%-11s %s\n", c->name, c->descr);
8761 printf ("\n-soundhw all will enable all of the above\n");
8762 exit (*optarg != '?');
8764 else {
8765 size_t l;
8766 const char *p;
8767 char *e;
8768 int bad_card = 0;
8770 if (!strcmp (optarg, "all")) {
8771 for (c = soundhw; c->name; ++c) {
8772 c->enabled = 1;
8774 return;
8777 p = optarg;
8778 while (*p) {
8779 e = strchr (p, ',');
8780 l = !e ? strlen (p) : (size_t) (e - p);
8782 for (c = soundhw; c->name; ++c) {
8783 if (!strncmp (c->name, p, l)) {
8784 c->enabled = 1;
8785 break;
8789 if (!c->name) {
8790 if (l > 80) {
8791 fprintf (stderr,
8792 "Unknown sound card name (too big to show)\n");
8794 else {
8795 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8796 (int) l, p);
8798 bad_card = 1;
8800 p += l + (e != NULL);
8803 if (bad_card)
8804 goto show_valid_cards;
8807 #endif
8809 #ifdef _WIN32
8810 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8812 exit(STATUS_CONTROL_C_EXIT);
8813 return TRUE;
8815 #endif
8817 #define MAX_NET_CLIENTS 32
8819 static int saved_argc;
8820 static char **saved_argv;
8822 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8824 *argc = saved_argc;
8825 *argv = saved_argv;
8826 *opt_daemonize = daemonize;
8827 *opt_incoming = incoming;
8831 static int gethugepagesize(void)
8833 int ret, fd;
8834 char buf[4096];
8835 char *needle = "Hugepagesize:";
8836 char *size;
8837 unsigned long hugepagesize;
8839 fd = open("/proc/meminfo", O_RDONLY);
8840 if (fd < 0) {
8841 perror("open");
8842 exit(0);
8845 ret = read(fd, buf, sizeof(buf));
8846 if (ret < 0) {
8847 perror("read");
8848 exit(0);
8851 size = strstr(buf, needle);
8852 if (!size)
8853 return 0;
8854 size += strlen(needle);
8855 hugepagesize = strtol(size, NULL, 0);
8856 return hugepagesize;
8859 void *alloc_mem_area(unsigned long memory, const char *path)
8861 char *filename;
8862 void *area;
8863 int fd;
8865 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8866 return NULL;
8868 hpagesize = gethugepagesize() * 1024;
8869 if (!hpagesize)
8870 return NULL;
8872 fd = mkstemp(filename);
8873 if (fd < 0) {
8874 perror("mkstemp");
8875 free(filename);
8876 return NULL;
8878 unlink(filename);
8879 free(filename);
8881 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8884 * ftruncate is not supported by hugetlbfs in older
8885 * hosts, so don't bother checking for errors.
8886 * If anything goes wrong with it under other filesystems,
8887 * mmap will fail.
8889 ftruncate(fd, memory);
8891 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8892 if (area == MAP_FAILED) {
8893 perror("mmap");
8894 close(fd);
8895 return NULL;
8898 return area;
8901 void *qemu_alloc_physram(unsigned long memory)
8903 void *area = NULL;
8905 if (mem_path)
8906 area = alloc_mem_area(memory, mem_path);
8907 if (!area)
8908 area = qemu_vmalloc(memory);
8910 return area;
8913 int main(int argc, char **argv)
8915 #ifdef CONFIG_GDBSTUB
8916 int use_gdbstub;
8917 const char *gdbstub_port;
8918 #endif
8919 uint32_t boot_devices_bitmap = 0;
8920 int i;
8921 int snapshot, linux_boot, net_boot;
8922 const char *initrd_filename;
8923 const char *kernel_filename, *kernel_cmdline;
8924 const char *boot_devices = "";
8925 DisplayState *ds = &display_state;
8926 int cyls, heads, secs, translation;
8927 const char *net_clients[MAX_NET_CLIENTS];
8928 int nb_net_clients;
8929 int hda_index;
8930 int optind;
8931 const char *r, *optarg;
8932 CharDriverState *monitor_hd;
8933 int has_monitor;
8934 const char *monitor_device;
8935 const char *serial_devices[MAX_SERIAL_PORTS];
8936 int serial_device_index;
8937 const char *parallel_devices[MAX_PARALLEL_PORTS];
8938 int parallel_device_index;
8939 const char *loadvm = NULL;
8940 QEMUMachine *machine;
8941 const char *cpu_model;
8942 const char *usb_devices[MAX_USB_CMDLINE];
8943 int usb_devices_index;
8944 int fds[2];
8945 int tb_size;
8946 const char *pid_file = NULL;
8947 VLANState *vlan;
8949 saved_argc = argc;
8950 saved_argv = argv;
8952 LIST_INIT (&vm_change_state_head);
8953 #ifndef _WIN32
8955 struct sigaction act;
8956 sigfillset(&act.sa_mask);
8957 act.sa_flags = 0;
8958 act.sa_handler = SIG_IGN;
8959 sigaction(SIGPIPE, &act, NULL);
8961 #else
8962 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8963 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8964 QEMU to run on a single CPU */
8966 HANDLE h;
8967 DWORD mask, smask;
8968 int i;
8969 h = GetCurrentProcess();
8970 if (GetProcessAffinityMask(h, &mask, &smask)) {
8971 for(i = 0; i < 32; i++) {
8972 if (mask & (1 << i))
8973 break;
8975 if (i != 32) {
8976 mask = 1 << i;
8977 SetProcessAffinityMask(h, mask);
8981 #endif
8983 register_machines();
8984 machine = first_machine;
8985 cpu_model = NULL;
8986 initrd_filename = NULL;
8987 ram_size = 0;
8988 vga_ram_size = VGA_RAM_SIZE;
8989 #ifdef CONFIG_GDBSTUB
8990 use_gdbstub = 0;
8991 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8992 #endif
8993 snapshot = 0;
8994 nographic = 0;
8995 curses = 0;
8996 kernel_filename = NULL;
8997 kernel_cmdline = "";
8998 cyls = heads = secs = 0;
8999 translation = BIOS_ATA_TRANSLATION_AUTO;
9000 monitor_device = "vc";
9002 serial_devices[0] = "vc:80Cx24C";
9003 for(i = 1; i < MAX_SERIAL_PORTS; i++)
9004 serial_devices[i] = NULL;
9005 serial_device_index = 0;
9007 parallel_devices[0] = "vc:640x480";
9008 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
9009 parallel_devices[i] = NULL;
9010 parallel_device_index = 0;
9012 usb_devices_index = 0;
9014 nb_net_clients = 0;
9015 nb_drives = 0;
9016 nb_drives_opt = 0;
9017 hda_index = -1;
9019 nb_nics = 0;
9021 tb_size = 0;
9023 optind = 1;
9024 for(;;) {
9025 if (optind >= argc)
9026 break;
9027 r = argv[optind];
9028 if (r[0] != '-') {
9029 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
9030 } else {
9031 const QEMUOption *popt;
9033 optind++;
9034 /* Treat --foo the same as -foo. */
9035 if (r[1] == '-')
9036 r++;
9037 popt = qemu_options;
9038 for(;;) {
9039 if (!popt->name) {
9040 fprintf(stderr, "%s: invalid option -- '%s'\n",
9041 argv[0], r);
9042 exit(1);
9044 if (!strcmp(popt->name, r + 1))
9045 break;
9046 popt++;
9048 if (popt->flags & HAS_ARG) {
9049 if (optind >= argc) {
9050 fprintf(stderr, "%s: option '%s' requires an argument\n",
9051 argv[0], r);
9052 exit(1);
9054 optarg = argv[optind++];
9055 } else {
9056 optarg = NULL;
9059 switch(popt->index) {
9060 case QEMU_OPTION_M:
9061 machine = find_machine(optarg);
9062 if (!machine) {
9063 QEMUMachine *m;
9064 printf("Supported machines are:\n");
9065 for(m = first_machine; m != NULL; m = m->next) {
9066 printf("%-10s %s%s\n",
9067 m->name, m->desc,
9068 m == first_machine ? " (default)" : "");
9070 exit(*optarg != '?');
9072 break;
9073 case QEMU_OPTION_cpu:
9074 /* hw initialization will check this */
9075 if (*optarg == '?') {
9076 /* XXX: implement xxx_cpu_list for targets that still miss it */
9077 #if defined(cpu_list)
9078 cpu_list(stdout, &fprintf);
9079 #endif
9080 exit(0);
9081 } else {
9082 cpu_model = optarg;
9084 break;
9085 case QEMU_OPTION_initrd:
9086 initrd_filename = optarg;
9087 break;
9088 case QEMU_OPTION_hda:
9089 if (cyls == 0)
9090 hda_index = drive_add(optarg, HD_ALIAS, 0);
9091 else
9092 hda_index = drive_add(optarg, HD_ALIAS
9093 ",cyls=%d,heads=%d,secs=%d%s",
9094 0, cyls, heads, secs,
9095 translation == BIOS_ATA_TRANSLATION_LBA ?
9096 ",trans=lba" :
9097 translation == BIOS_ATA_TRANSLATION_NONE ?
9098 ",trans=none" : "");
9099 break;
9100 case QEMU_OPTION_hdb:
9101 case QEMU_OPTION_hdc:
9102 case QEMU_OPTION_hdd:
9103 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
9104 break;
9105 case QEMU_OPTION_drive:
9106 drive_add(NULL, "%s", optarg);
9107 break;
9108 case QEMU_OPTION_mtdblock:
9109 drive_add(optarg, MTD_ALIAS);
9110 break;
9111 case QEMU_OPTION_sd:
9112 drive_add(optarg, SD_ALIAS);
9113 break;
9114 case QEMU_OPTION_pflash:
9115 drive_add(optarg, PFLASH_ALIAS);
9116 break;
9117 case QEMU_OPTION_snapshot:
9118 snapshot = 1;
9119 break;
9120 case QEMU_OPTION_hdachs:
9122 const char *p;
9123 p = optarg;
9124 cyls = strtol(p, (char **)&p, 0);
9125 if (cyls < 1 || cyls > 16383)
9126 goto chs_fail;
9127 if (*p != ',')
9128 goto chs_fail;
9129 p++;
9130 heads = strtol(p, (char **)&p, 0);
9131 if (heads < 1 || heads > 16)
9132 goto chs_fail;
9133 if (*p != ',')
9134 goto chs_fail;
9135 p++;
9136 secs = strtol(p, (char **)&p, 0);
9137 if (secs < 1 || secs > 63)
9138 goto chs_fail;
9139 if (*p == ',') {
9140 p++;
9141 if (!strcmp(p, "none"))
9142 translation = BIOS_ATA_TRANSLATION_NONE;
9143 else if (!strcmp(p, "lba"))
9144 translation = BIOS_ATA_TRANSLATION_LBA;
9145 else if (!strcmp(p, "auto"))
9146 translation = BIOS_ATA_TRANSLATION_AUTO;
9147 else
9148 goto chs_fail;
9149 } else if (*p != '\0') {
9150 chs_fail:
9151 fprintf(stderr, "qemu: invalid physical CHS format\n");
9152 exit(1);
9154 if (hda_index != -1)
9155 snprintf(drives_opt[hda_index].opt,
9156 sizeof(drives_opt[hda_index].opt),
9157 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
9158 0, cyls, heads, secs,
9159 translation == BIOS_ATA_TRANSLATION_LBA ?
9160 ",trans=lba" :
9161 translation == BIOS_ATA_TRANSLATION_NONE ?
9162 ",trans=none" : "");
9164 break;
9165 case QEMU_OPTION_nographic:
9166 nographic = 1;
9167 break;
9168 #ifdef CONFIG_CURSES
9169 case QEMU_OPTION_curses:
9170 curses = 1;
9171 break;
9172 #endif
9173 case QEMU_OPTION_portrait:
9174 graphic_rotate = 1;
9175 break;
9176 case QEMU_OPTION_kernel:
9177 kernel_filename = optarg;
9178 break;
9179 case QEMU_OPTION_append:
9180 kernel_cmdline = optarg;
9181 break;
9182 case QEMU_OPTION_cdrom:
9183 drive_add(optarg, CDROM_ALIAS);
9184 break;
9185 case QEMU_OPTION_boot:
9186 boot_devices = optarg;
9187 /* We just do some generic consistency checks */
9189 /* Could easily be extended to 64 devices if needed */
9190 const char *p;
9192 boot_devices_bitmap = 0;
9193 for (p = boot_devices; *p != '\0'; p++) {
9194 /* Allowed boot devices are:
9195 * a b : floppy disk drives
9196 * c ... f : IDE disk drives
9197 * g ... m : machine implementation dependant drives
9198 * n ... p : network devices
9199 * It's up to each machine implementation to check
9200 * if the given boot devices match the actual hardware
9201 * implementation and firmware features.
9203 if (*p < 'a' || *p > 'q') {
9204 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9205 exit(1);
9207 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9208 fprintf(stderr,
9209 "Boot device '%c' was given twice\n",*p);
9210 exit(1);
9212 boot_devices_bitmap |= 1 << (*p - 'a');
9215 break;
9216 case QEMU_OPTION_fda:
9217 case QEMU_OPTION_fdb:
9218 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9219 break;
9220 #ifdef TARGET_I386
9221 case QEMU_OPTION_no_fd_bootchk:
9222 fd_bootchk = 0;
9223 break;
9224 #endif
9225 case QEMU_OPTION_net:
9226 if (nb_net_clients >= MAX_NET_CLIENTS) {
9227 fprintf(stderr, "qemu: too many network clients\n");
9228 exit(1);
9230 net_clients[nb_net_clients] = optarg;
9231 nb_net_clients++;
9232 break;
9233 #ifdef CONFIG_SLIRP
9234 case QEMU_OPTION_tftp:
9235 tftp_prefix = optarg;
9236 break;
9237 case QEMU_OPTION_bootp:
9238 bootp_filename = optarg;
9239 break;
9240 #ifndef _WIN32
9241 case QEMU_OPTION_smb:
9242 net_slirp_smb(optarg);
9243 break;
9244 #endif
9245 case QEMU_OPTION_redir:
9246 net_slirp_redir(optarg);
9247 break;
9248 #endif
9249 #ifdef HAS_AUDIO
9250 case QEMU_OPTION_audio_help:
9251 AUD_help ();
9252 exit (0);
9253 break;
9254 case QEMU_OPTION_soundhw:
9255 select_soundhw (optarg);
9256 break;
9257 #endif
9258 case QEMU_OPTION_h:
9259 help(0);
9260 break;
9261 case QEMU_OPTION_m: {
9262 uint64_t value;
9263 char *ptr;
9265 value = strtoul(optarg, &ptr, 10);
9266 switch (*ptr) {
9267 case 0: case 'M': case 'm':
9268 value <<= 20;
9269 break;
9270 case 'G': case 'g':
9271 value <<= 30;
9272 break;
9273 default:
9274 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
9275 exit(1);
9278 /* On 32-bit hosts, QEMU is limited by virtual address space */
9279 if (value > (2047 << 20)
9280 #ifndef USE_KQEMU
9281 && HOST_LONG_BITS == 32
9282 #endif
9284 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
9285 exit(1);
9287 if (value != (uint64_t)(ram_addr_t)value) {
9288 fprintf(stderr, "qemu: ram size too large\n");
9289 exit(1);
9291 ram_size = value;
9292 break;
9294 case QEMU_OPTION_d:
9296 int mask;
9297 CPULogItem *item;
9299 mask = cpu_str_to_log_mask(optarg);
9300 if (!mask) {
9301 printf("Log items (comma separated):\n");
9302 for(item = cpu_log_items; item->mask != 0; item++) {
9303 printf("%-10s %s\n", item->name, item->help);
9305 exit(1);
9307 cpu_set_log(mask);
9309 break;
9310 #ifdef CONFIG_GDBSTUB
9311 case QEMU_OPTION_s:
9312 use_gdbstub = 1;
9313 break;
9314 case QEMU_OPTION_p:
9315 gdbstub_port = optarg;
9316 break;
9317 #endif
9318 case QEMU_OPTION_L:
9319 bios_dir = optarg;
9320 break;
9321 case QEMU_OPTION_bios:
9322 bios_name = optarg;
9323 break;
9324 case QEMU_OPTION_S:
9325 autostart = 0;
9326 break;
9327 case QEMU_OPTION_k:
9328 keyboard_layout = optarg;
9329 break;
9330 case QEMU_OPTION_localtime:
9331 rtc_utc = 0;
9332 break;
9333 case QEMU_OPTION_cirrusvga:
9334 cirrus_vga_enabled = 1;
9335 vmsvga_enabled = 0;
9336 break;
9337 case QEMU_OPTION_vmsvga:
9338 cirrus_vga_enabled = 0;
9339 vmsvga_enabled = 1;
9340 break;
9341 case QEMU_OPTION_std_vga:
9342 cirrus_vga_enabled = 0;
9343 vmsvga_enabled = 0;
9344 break;
9345 case QEMU_OPTION_g:
9347 const char *p;
9348 int w, h, depth;
9349 p = optarg;
9350 w = strtol(p, (char **)&p, 10);
9351 if (w <= 0) {
9352 graphic_error:
9353 fprintf(stderr, "qemu: invalid resolution or depth\n");
9354 exit(1);
9356 if (*p != 'x')
9357 goto graphic_error;
9358 p++;
9359 h = strtol(p, (char **)&p, 10);
9360 if (h <= 0)
9361 goto graphic_error;
9362 if (*p == 'x') {
9363 p++;
9364 depth = strtol(p, (char **)&p, 10);
9365 if (depth != 8 && depth != 15 && depth != 16 &&
9366 depth != 24 && depth != 32)
9367 goto graphic_error;
9368 } else if (*p == '\0') {
9369 depth = graphic_depth;
9370 } else {
9371 goto graphic_error;
9374 graphic_width = w;
9375 graphic_height = h;
9376 graphic_depth = depth;
9378 break;
9379 case QEMU_OPTION_echr:
9381 char *r;
9382 term_escape_char = strtol(optarg, &r, 0);
9383 if (r == optarg)
9384 printf("Bad argument to echr\n");
9385 break;
9387 case QEMU_OPTION_monitor:
9388 monitor_device = optarg;
9389 break;
9390 case QEMU_OPTION_serial:
9391 if (serial_device_index >= MAX_SERIAL_PORTS) {
9392 fprintf(stderr, "qemu: too many serial ports\n");
9393 exit(1);
9395 serial_devices[serial_device_index] = optarg;
9396 serial_device_index++;
9397 break;
9398 case QEMU_OPTION_parallel:
9399 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9400 fprintf(stderr, "qemu: too many parallel ports\n");
9401 exit(1);
9403 parallel_devices[parallel_device_index] = optarg;
9404 parallel_device_index++;
9405 break;
9406 case QEMU_OPTION_loadvm:
9407 loadvm = optarg;
9408 break;
9409 case QEMU_OPTION_incoming:
9410 incoming = optarg;
9411 break;
9412 case QEMU_OPTION_full_screen:
9413 full_screen = 1;
9414 break;
9415 #ifdef CONFIG_SDL
9416 case QEMU_OPTION_no_frame:
9417 no_frame = 1;
9418 break;
9419 case QEMU_OPTION_alt_grab:
9420 alt_grab = 1;
9421 break;
9422 case QEMU_OPTION_no_quit:
9423 no_quit = 1;
9424 break;
9425 #endif
9426 case QEMU_OPTION_pidfile:
9427 pid_file = optarg;
9428 break;
9429 #ifdef TARGET_I386
9430 case QEMU_OPTION_win2k_hack:
9431 win2k_install_hack = 1;
9432 break;
9433 #endif
9434 #ifdef USE_KQEMU
9435 case QEMU_OPTION_no_kqemu:
9436 kqemu_allowed = 0;
9437 break;
9438 case QEMU_OPTION_kernel_kqemu:
9439 kqemu_allowed = 2;
9440 break;
9441 #endif
9442 #ifdef USE_KVM
9443 case QEMU_OPTION_no_kvm:
9444 kvm_allowed = 0;
9445 break;
9446 case QEMU_OPTION_no_kvm_irqchip: {
9447 extern int kvm_irqchip, kvm_pit;
9448 kvm_irqchip = 0;
9449 kvm_pit = 0;
9450 break;
9452 case QEMU_OPTION_no_kvm_pit: {
9453 extern int kvm_pit;
9454 kvm_pit = 0;
9455 break;
9457 #endif
9458 case QEMU_OPTION_usb:
9459 usb_enabled = 1;
9460 break;
9461 case QEMU_OPTION_usbdevice:
9462 usb_enabled = 1;
9463 if (usb_devices_index >= MAX_USB_CMDLINE) {
9464 fprintf(stderr, "Too many USB devices\n");
9465 exit(1);
9467 usb_devices[usb_devices_index] = optarg;
9468 usb_devices_index++;
9469 break;
9470 case QEMU_OPTION_smp:
9471 smp_cpus = atoi(optarg);
9472 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9473 fprintf(stderr, "Invalid number of CPUs\n");
9474 exit(1);
9476 break;
9477 case QEMU_OPTION_vnc:
9478 vnc_display = optarg;
9479 break;
9480 case QEMU_OPTION_no_acpi:
9481 acpi_enabled = 0;
9482 break;
9483 case QEMU_OPTION_no_reboot:
9484 no_reboot = 1;
9485 break;
9486 case QEMU_OPTION_no_shutdown:
9487 no_shutdown = 1;
9488 break;
9489 case QEMU_OPTION_show_cursor:
9490 cursor_hide = 0;
9491 break;
9492 case QEMU_OPTION_daemonize:
9493 daemonize = 1;
9494 break;
9495 case QEMU_OPTION_option_rom:
9496 if (nb_option_roms >= MAX_OPTION_ROMS) {
9497 fprintf(stderr, "Too many option ROMs\n");
9498 exit(1);
9500 option_rom[nb_option_roms] = optarg;
9501 nb_option_roms++;
9502 break;
9503 case QEMU_OPTION_semihosting:
9504 semihosting_enabled = 1;
9505 break;
9506 case QEMU_OPTION_tdf:
9507 time_drift_fix = 1;
9508 break;
9509 case QEMU_OPTION_kvm_shadow_memory:
9510 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9511 break;
9512 case QEMU_OPTION_mempath:
9513 mem_path = optarg;
9514 break;
9515 case QEMU_OPTION_name:
9516 qemu_name = optarg;
9517 break;
9518 #ifdef TARGET_SPARC
9519 case QEMU_OPTION_prom_env:
9520 if (nb_prom_envs >= MAX_PROM_ENVS) {
9521 fprintf(stderr, "Too many prom variables\n");
9522 exit(1);
9524 prom_envs[nb_prom_envs] = optarg;
9525 nb_prom_envs++;
9526 break;
9527 #endif
9528 case QEMU_OPTION_cpu_vendor:
9529 cpu_vendor_string = optarg;
9530 break;
9531 #ifdef TARGET_ARM
9532 case QEMU_OPTION_old_param:
9533 old_param = 1;
9534 break;
9535 #endif
9536 case QEMU_OPTION_clock:
9537 configure_alarms(optarg);
9538 break;
9539 case QEMU_OPTION_startdate:
9541 struct tm tm;
9542 time_t rtc_start_date;
9543 if (!strcmp(optarg, "now")) {
9544 rtc_date_offset = -1;
9545 } else {
9546 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9547 &tm.tm_year,
9548 &tm.tm_mon,
9549 &tm.tm_mday,
9550 &tm.tm_hour,
9551 &tm.tm_min,
9552 &tm.tm_sec) == 6) {
9553 /* OK */
9554 } else if (sscanf(optarg, "%d-%d-%d",
9555 &tm.tm_year,
9556 &tm.tm_mon,
9557 &tm.tm_mday) == 3) {
9558 tm.tm_hour = 0;
9559 tm.tm_min = 0;
9560 tm.tm_sec = 0;
9561 } else {
9562 goto date_fail;
9564 tm.tm_year -= 1900;
9565 tm.tm_mon--;
9566 rtc_start_date = mktimegm(&tm);
9567 if (rtc_start_date == -1) {
9568 date_fail:
9569 fprintf(stderr, "Invalid date format. Valid format are:\n"
9570 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9571 exit(1);
9573 rtc_date_offset = time(NULL) - rtc_start_date;
9576 break;
9577 case QEMU_OPTION_tb_size:
9578 tb_size = strtol(optarg, NULL, 0);
9579 if (tb_size < 0)
9580 tb_size = 0;
9581 break;
9582 case QEMU_OPTION_icount:
9583 use_icount = 1;
9584 if (strcmp(optarg, "auto") == 0) {
9585 icount_time_shift = -1;
9586 } else {
9587 icount_time_shift = strtol(optarg, NULL, 0);
9589 break;
9594 if (nographic) {
9595 if (serial_device_index == 0)
9596 serial_devices[0] = "stdio";
9597 if (parallel_device_index == 0)
9598 parallel_devices[0] = "null";
9599 if (strncmp(monitor_device, "vc", 2) == 0)
9600 monitor_device = "stdio";
9603 #ifndef _WIN32
9604 if (daemonize) {
9605 pid_t pid;
9607 if (pipe(fds) == -1)
9608 exit(1);
9610 pid = fork();
9611 if (pid > 0) {
9612 uint8_t status;
9613 ssize_t len;
9615 close(fds[1]);
9617 again:
9618 len = read(fds[0], &status, 1);
9619 if (len == -1 && (errno == EINTR))
9620 goto again;
9622 if (len != 1)
9623 exit(1);
9624 else if (status == 1) {
9625 fprintf(stderr, "Could not acquire pidfile\n");
9626 exit(1);
9627 } else
9628 exit(0);
9629 } else if (pid < 0)
9630 exit(1);
9632 setsid();
9634 pid = fork();
9635 if (pid > 0)
9636 exit(0);
9637 else if (pid < 0)
9638 exit(1);
9640 umask(027);
9642 signal(SIGTSTP, SIG_IGN);
9643 signal(SIGTTOU, SIG_IGN);
9644 signal(SIGTTIN, SIG_IGN);
9646 #endif
9648 #if USE_KVM
9649 if (kvm_enabled()) {
9650 if (kvm_qemu_init() < 0) {
9651 extern int kvm_allowed;
9652 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9653 #ifdef NO_CPU_EMULATION
9654 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9655 exit(1);
9656 #endif
9657 kvm_allowed = 0;
9660 #endif
9662 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9663 if (daemonize) {
9664 uint8_t status = 1;
9665 write(fds[1], &status, 1);
9666 } else
9667 fprintf(stderr, "Could not acquire pid file\n");
9668 exit(1);
9671 #ifdef USE_KQEMU
9672 if (smp_cpus > 1)
9673 kqemu_allowed = 0;
9674 #endif
9675 linux_boot = (kernel_filename != NULL);
9676 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9678 /* XXX: this should not be: some embedded targets just have flash */
9679 if (!linux_boot && net_boot == 0 &&
9680 nb_drives_opt == 0)
9681 help(1);
9683 if (!linux_boot && *kernel_cmdline != '\0') {
9684 fprintf(stderr, "-append only allowed with -kernel option\n");
9685 exit(1);
9688 if (!linux_boot && initrd_filename != NULL) {
9689 fprintf(stderr, "-initrd only allowed with -kernel option\n");
9690 exit(1);
9693 /* boot to floppy or the default cd if no hard disk defined yet */
9694 if (!boot_devices[0]) {
9695 boot_devices = "cad";
9697 setvbuf(stdout, NULL, _IOLBF, 0);
9699 init_timers();
9700 init_timer_alarm();
9701 qemu_aio_init();
9702 if (use_icount && icount_time_shift < 0) {
9703 use_icount = 2;
9704 /* 125MIPS seems a reasonable initial guess at the guest speed.
9705 It will be corrected fairly quickly anyway. */
9706 icount_time_shift = 3;
9707 init_icount_adjust();
9710 #ifdef _WIN32
9711 socket_init();
9712 #endif
9714 /* init network clients */
9715 if (nb_net_clients == 0) {
9716 /* if no clients, we use a default config */
9717 net_clients[0] = "nic";
9718 net_clients[1] = "user";
9719 nb_net_clients = 2;
9722 for(i = 0;i < nb_net_clients; i++) {
9723 if (net_client_parse(net_clients[i]) < 0)
9724 exit(1);
9726 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9727 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9728 continue;
9729 if (vlan->nb_guest_devs == 0)
9730 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9731 if (vlan->nb_host_devs == 0)
9732 fprintf(stderr,
9733 "Warning: vlan %d is not connected to host network\n",
9734 vlan->id);
9737 #ifdef TARGET_I386
9738 /* XXX: this should be moved in the PC machine instantiation code */
9739 if (net_boot != 0) {
9740 int netroms = 0;
9741 for (i = 0; i < nb_nics && i < 4; i++) {
9742 const char *model = nd_table[i].model;
9743 char buf[1024];
9744 if (net_boot & (1 << i)) {
9745 if (model == NULL)
9746 model = "rtl8139";
9747 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9748 if (get_image_size(buf) > 0) {
9749 if (nb_option_roms >= MAX_OPTION_ROMS) {
9750 fprintf(stderr, "Too many option ROMs\n");
9751 exit(1);
9753 option_rom[nb_option_roms] = strdup(buf);
9754 nb_option_roms++;
9755 netroms++;
9759 if (netroms == 0) {
9760 fprintf(stderr, "No valid PXE rom found for network device\n");
9761 exit(1);
9764 #endif
9766 /* init the memory */
9767 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9769 if (machine->ram_require & RAMSIZE_FIXED) {
9770 if (ram_size > 0) {
9771 if (ram_size < phys_ram_size) {
9772 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9773 machine->name, (unsigned long long) phys_ram_size);
9774 exit(-1);
9777 phys_ram_size = ram_size;
9778 } else
9779 ram_size = phys_ram_size;
9780 } else {
9781 if (ram_size == 0)
9782 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9784 phys_ram_size += ram_size;
9787 /* Initialize kvm */
9788 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9789 #define KVM_EXTRA_PAGES 3
9790 #else
9791 #define KVM_EXTRA_PAGES 0
9792 #endif
9793 if (kvm_enabled()) {
9794 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9795 if (kvm_qemu_create_context() < 0) {
9796 fprintf(stderr, "Could not create KVM context\n");
9797 exit(1);
9799 #ifdef KVM_CAP_USER_MEMORY
9801 int ret;
9803 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9804 if (ret) {
9805 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9806 if (!phys_ram_base) {
9807 fprintf(stderr, "Could not allocate physical memory\n");
9808 exit(1);
9812 #endif
9813 } else {
9814 phys_ram_base = qemu_vmalloc(phys_ram_size);
9815 if (!phys_ram_base) {
9816 fprintf(stderr, "Could not allocate physical memory\n");
9817 exit(1);
9821 /* init the dynamic translator */
9822 cpu_exec_init_all(tb_size * 1024 * 1024);
9824 bdrv_init();
9826 /* we always create the cdrom drive, even if no disk is there */
9828 if (nb_drives_opt < MAX_DRIVES)
9829 drive_add(NULL, CDROM_ALIAS);
9831 /* we always create at least one floppy */
9833 if (nb_drives_opt < MAX_DRIVES)
9834 drive_add(NULL, FD_ALIAS, 0);
9836 /* we always create one sd slot, even if no card is in it */
9838 if (nb_drives_opt < MAX_DRIVES)
9839 drive_add(NULL, SD_ALIAS);
9841 /* open the virtual block devices
9842 * note that migration with device
9843 * hot add/remove is broken.
9845 for(i = 0; i < nb_drives_opt; i++)
9846 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9847 exit(1);
9849 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9850 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9852 /* terminal init */
9853 memset(&display_state, 0, sizeof(display_state));
9854 if (nographic) {
9855 if (curses) {
9856 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9857 exit(1);
9859 /* nearly nothing to do */
9860 dumb_display_init(ds);
9861 } else if (vnc_display != NULL) {
9862 vnc_display_init(ds);
9863 if (vnc_display_open(ds, vnc_display) < 0)
9864 exit(1);
9865 } else
9866 #if defined(CONFIG_CURSES)
9867 if (curses) {
9868 curses_display_init(ds, full_screen);
9869 } else
9870 #endif
9872 #if defined(CONFIG_SDL)
9873 sdl_display_init(ds, full_screen, no_frame);
9874 #elif defined(CONFIG_COCOA)
9875 cocoa_display_init(ds, full_screen);
9876 #else
9877 dumb_display_init(ds);
9878 #endif
9881 /* Maintain compatibility with multiple stdio monitors */
9883 has_monitor = 0;
9884 if (!strcmp(monitor_device,"stdio")) {
9885 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9886 const char *devname = serial_devices[i];
9887 if (devname && !strcmp(devname,"mon:stdio")) {
9888 monitor_device = NULL;
9889 break;
9890 } else if (devname && !strcmp(devname,"stdio")) {
9891 monitor_device = NULL;
9892 serial_devices[i] = "mon:stdio";
9893 break;
9896 has_monitor = 1;
9898 if (monitor_device) {
9899 monitor_hd = qemu_chr_open(monitor_device);
9900 if (!monitor_hd) {
9901 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9902 exit(1);
9904 monitor_init(monitor_hd, !nographic);
9905 has_monitor = 1;
9908 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9909 const char *devname = serial_devices[i];
9910 if (devname && strcmp(devname, "none")) {
9911 serial_hds[i] = qemu_chr_open(devname);
9912 if (!serial_hds[i]) {
9913 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9914 devname);
9915 exit(1);
9917 if (strstart(devname, "vc", 0))
9918 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9922 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9923 const char *devname = parallel_devices[i];
9924 if (devname && strcmp(devname, "none")) {
9925 parallel_hds[i] = qemu_chr_open(devname);
9926 if (!parallel_hds[i]) {
9927 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9928 devname);
9929 exit(1);
9931 if (strstart(devname, "vc", 0))
9932 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9936 if (kvm_enabled())
9937 kvm_init_ap();
9939 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9940 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9942 current_machine = machine;
9944 /* init USB devices */
9945 if (usb_enabled) {
9946 for(i = 0; i < usb_devices_index; i++) {
9947 if (usb_device_add(usb_devices[i]) < 0) {
9948 fprintf(stderr, "Warning: could not add USB device %s\n",
9949 usb_devices[i]);
9954 if (display_state.dpy_refresh) {
9955 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9956 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9959 #ifdef CONFIG_GDBSTUB
9960 if (use_gdbstub) {
9961 /* XXX: use standard host:port notation and modify options
9962 accordingly. */
9963 if (gdbserver_start(gdbstub_port) < 0) {
9964 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9965 gdbstub_port);
9966 exit(1);
9969 #endif
9971 read_passwords();
9973 if (has_monitor)
9974 monitor_start_input();
9976 if (loadvm)
9977 do_loadvm(loadvm);
9979 if (incoming) {
9980 int rc;
9982 rc = migrate_incoming(incoming);
9983 if (rc != 0) {
9984 fprintf(stderr, "Migration failed rc=%d\n", rc);
9985 exit(rc);
9990 /* XXX: simplify init */
9991 if (autostart) {
9992 vm_start();
9996 if (daemonize) {
9997 uint8_t status = 0;
9998 ssize_t len;
9999 int fd;
10001 again1:
10002 len = write(fds[1], &status, 1);
10003 if (len == -1 && (errno == EINTR))
10004 goto again1;
10006 if (len != 1)
10007 exit(1);
10009 chdir("/");
10010 TFR(fd = open("/dev/null", O_RDWR));
10011 if (fd == -1)
10012 exit(1);
10014 dup2(fd, 0);
10015 dup2(fd, 1);
10016 dup2(fd, 2);
10018 close(fd);
10021 main_loop();
10022 quit_timers();
10024 #if !defined(_WIN32)
10025 /* close network clients */
10026 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
10027 VLANClientState *vc;
10029 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
10030 if (vc->fd_read == tap_receive) {
10031 char ifname[64];
10032 TAPState *s = vc->opaque;
10034 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
10035 s->down_script[0])
10036 launch_script(s->down_script, ifname, s->fd);
10038 #if defined(CONFIG_VDE)
10039 if (vc->fd_read == vde_from_qemu) {
10040 VDEState *s = vc->opaque;
10041 vde_close(s->vde);
10043 #endif
10046 #endif
10047 return 0;