kvm: libkvm: fix indentation
[qemu-kvm/fedora.git] / vl.c
blobfbf647545098a8479244b21f8a2868d1067d1721
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 #if !defined(__APPLE__) && !defined(__OpenBSD__)
67 #include <libutil.h>
68 #endif
69 #ifdef __OpenBSD__
70 #include <net/if.h>
71 #endif
72 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
73 #include <freebsd/stdlib.h>
74 #else
75 #ifndef __sun__
76 #include <linux/if.h>
77 #include <linux/if_tun.h>
78 #include <pty.h>
79 #include <malloc.h>
80 #include <linux/rtc.h>
82 /* For the benefit of older linux systems which don't supply it,
83 we use a local copy of hpet.h. */
84 /* #include <linux/hpet.h> */
85 #include "hpet.h"
87 #include <linux/ppdev.h>
88 #include <linux/parport.h>
89 #else
90 #include <sys/stat.h>
91 #include <sys/ethernet.h>
92 #include <sys/sockio.h>
93 #include <netinet/arp.h>
94 #include <netinet/in.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/ip_icmp.h> // must come after ip.h
98 #include <netinet/udp.h>
99 #include <netinet/tcp.h>
100 #include <net/if.h>
101 #include <syslog.h>
102 #include <stropts.h>
103 #endif
104 #endif
105 #else
106 #include <winsock2.h>
107 int inet_aton(const char *cp, struct in_addr *ia);
108 #endif
110 #if defined(CONFIG_SLIRP)
111 #include "libslirp.h"
112 #endif
114 #if defined(CONFIG_VDE)
115 #include <libvdeplug.h>
116 #endif
118 #ifdef _WIN32
119 #include <malloc.h>
120 #include <sys/timeb.h>
121 #include <mmsystem.h>
122 #define getopt_long_only getopt_long
123 #define memalign(align, size) malloc(size)
124 #endif
126 #include "qemu_socket.h"
128 #ifdef CONFIG_SDL
129 #ifdef __APPLE__
130 #include <SDL/SDL.h>
131 #endif
132 #endif /* CONFIG_SDL */
134 #ifdef CONFIG_COCOA
135 #undef main
136 #define main qemu_main
137 #endif /* CONFIG_COCOA */
139 #include "disas.h"
141 #include "exec-all.h"
143 #include "qemu-kvm.h"
145 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
146 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
147 #ifdef __sun__
148 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
149 #else
150 #define SMBD_COMMAND "/usr/sbin/smbd"
151 #endif
153 //#define DEBUG_UNUSED_IOPORT
154 //#define DEBUG_IOPORT
156 #ifdef TARGET_PPC
157 #define DEFAULT_RAM_SIZE 144
158 #else
159 #define DEFAULT_RAM_SIZE 128
160 #endif
162 /* Max number of USB devices that can be specified on the commandline. */
163 #define MAX_USB_CMDLINE 8
165 /* XXX: use a two level table to limit memory usage */
166 #define MAX_IOPORTS 65536
168 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
169 const char *bios_name = NULL;
170 void *ioport_opaque[MAX_IOPORTS];
171 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
172 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
173 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
174 to store the VM snapshots */
175 DriveInfo drives_table[MAX_DRIVES+1];
176 int nb_drives;
177 int extboot_drive = -1;
178 /* point to the block driver where the snapshots are managed */
179 BlockDriverState *bs_snapshots;
180 int vga_ram_size;
181 static DisplayState display_state;
182 int nographic;
183 int curses;
184 const char* keyboard_layout = NULL;
185 int64_t ticks_per_sec;
186 ram_addr_t ram_size;
187 int pit_min_timer_count = 0;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 static int rtc_utc = 1;
192 static int rtc_date_offset = -1; /* -1 means no change */
193 int cirrus_vga_enabled = 1;
194 int vmsvga_enabled = 0;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 int full_screen = 0;
205 int no_frame = 0;
206 int no_quit = 0;
207 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
208 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
209 #ifdef TARGET_I386
210 int win2k_install_hack = 0;
211 #endif
212 int usb_enabled = 0;
213 static VLANState *first_vlan;
214 int smp_cpus = 1;
215 const char *vnc_display;
216 #if defined(TARGET_SPARC)
217 #define MAX_CPUS 16
218 #elif defined(TARGET_I386)
219 #define MAX_CPUS 255
220 #elif defined(TARGET_IA64)
221 #define MAX_CPUS 4
222 #else
223 #define MAX_CPUS 1
224 #endif
225 int acpi_enabled = 1;
226 int fd_bootchk = 1;
227 int no_reboot = 0;
228 int no_shutdown = 0;
229 int cursor_hide = 1;
230 int graphic_rotate = 0;
231 int daemonize = 0;
232 const char *incoming;
233 const char *option_rom[MAX_OPTION_ROMS];
234 int nb_option_roms;
235 int semihosting_enabled = 0;
236 int autostart = 1;
237 int time_drift_fix = 0;
238 unsigned int kvm_shadow_memory = 0;
239 const char *mem_path = NULL;
240 int hpagesize = 0;
241 const char *cpu_vendor_string;
242 #ifdef TARGET_ARM
243 int old_param = 0;
244 #endif
245 const char *qemu_name;
246 int alt_grab = 0;
247 #ifdef TARGET_SPARC
248 unsigned int nb_prom_envs = 0;
249 const char *prom_envs[MAX_PROM_ENVS];
250 #endif
251 int nb_drives_opt;
252 struct drive_opt drives_opt[MAX_DRIVES];
254 static CPUState *cur_cpu;
255 static CPUState *next_cpu;
256 static int event_pending = 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias;
263 QEMUTimer *icount_rt_timer;
264 QEMUTimer *icount_vm_timer;
266 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
268 /* KVM runs the main loop in a separate thread. If we update one of the lists
269 * that are polled before or after select(), we need to make sure to break out
270 * of the select() to ensure the new item is serviced.
272 static void main_loop_break(void)
274 if (kvm_enabled())
275 qemu_kvm_notify_work();
278 /***********************************************************/
279 /* x86 ISA bus support */
281 target_phys_addr_t isa_mem_base = 0;
282 PicState2 *isa_pic;
284 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
285 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
287 static uint32_t ioport_read(int index, uint32_t address)
289 static IOPortReadFunc *default_func[3] = {
290 default_ioport_readb,
291 default_ioport_readw,
292 default_ioport_readl
294 IOPortReadFunc *func = ioport_read_table[index][address];
295 if (!func)
296 func = default_func[index];
297 return func(ioport_opaque[address], address);
300 static void ioport_write(int index, uint32_t address, uint32_t data)
302 static IOPortWriteFunc *default_func[3] = {
303 default_ioport_writeb,
304 default_ioport_writew,
305 default_ioport_writel
307 IOPortWriteFunc *func = ioport_write_table[index][address];
308 if (!func)
309 func = default_func[index];
310 func(ioport_opaque[address], address, data);
313 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
315 #ifdef DEBUG_UNUSED_IOPORT
316 fprintf(stderr, "unused inb: port=0x%04x\n", address);
317 #endif
318 return 0xff;
321 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
323 #ifdef DEBUG_UNUSED_IOPORT
324 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
325 #endif
328 /* default is to make two byte accesses */
329 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
331 uint32_t data;
332 data = ioport_read(0, address);
333 address = (address + 1) & (MAX_IOPORTS - 1);
334 data |= ioport_read(0, address) << 8;
335 return data;
338 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
340 ioport_write(0, address, data & 0xff);
341 address = (address + 1) & (MAX_IOPORTS - 1);
342 ioport_write(0, address, (data >> 8) & 0xff);
345 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
347 #ifdef DEBUG_UNUSED_IOPORT
348 fprintf(stderr, "unused inl: port=0x%04x\n", address);
349 #endif
350 return 0xffffffff;
353 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
355 #ifdef DEBUG_UNUSED_IOPORT
356 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
357 #endif
360 /* size is the word size in byte */
361 int register_ioport_read(int start, int length, int size,
362 IOPortReadFunc *func, void *opaque)
364 int i, bsize;
366 if (size == 1) {
367 bsize = 0;
368 } else if (size == 2) {
369 bsize = 1;
370 } else if (size == 4) {
371 bsize = 2;
372 } else {
373 hw_error("register_ioport_read: invalid size");
374 return -1;
376 for(i = start; i < start + length; i += size) {
377 ioport_read_table[bsize][i] = func;
378 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
379 hw_error("register_ioport_read: invalid opaque");
380 ioport_opaque[i] = opaque;
382 return 0;
385 /* size is the word size in byte */
386 int register_ioport_write(int start, int length, int size,
387 IOPortWriteFunc *func, void *opaque)
389 int i, bsize;
391 if (size == 1) {
392 bsize = 0;
393 } else if (size == 2) {
394 bsize = 1;
395 } else if (size == 4) {
396 bsize = 2;
397 } else {
398 hw_error("register_ioport_write: invalid size");
399 return -1;
401 for(i = start; i < start + length; i += size) {
402 ioport_write_table[bsize][i] = func;
403 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
404 hw_error("register_ioport_write: invalid opaque");
405 ioport_opaque[i] = opaque;
407 return 0;
410 void isa_unassign_ioport(int start, int length)
412 int i;
414 for(i = start; i < start + length; i++) {
415 ioport_read_table[0][i] = default_ioport_readb;
416 ioport_read_table[1][i] = default_ioport_readw;
417 ioport_read_table[2][i] = default_ioport_readl;
419 ioport_write_table[0][i] = default_ioport_writeb;
420 ioport_write_table[1][i] = default_ioport_writew;
421 ioport_write_table[2][i] = default_ioport_writel;
423 ioport_opaque[i] = NULL;
427 /***********************************************************/
429 void cpu_outb(CPUState *env, int addr, int val)
431 #ifdef DEBUG_IOPORT
432 if (loglevel & CPU_LOG_IOPORT)
433 fprintf(logfile, "outb: %04x %02x\n", addr, val);
434 #endif
435 ioport_write(0, addr, val);
436 #ifdef USE_KQEMU
437 if (env)
438 env->last_io_time = cpu_get_time_fast();
439 #endif
442 void cpu_outw(CPUState *env, int addr, int val)
444 #ifdef DEBUG_IOPORT
445 if (loglevel & CPU_LOG_IOPORT)
446 fprintf(logfile, "outw: %04x %04x\n", addr, val);
447 #endif
448 ioport_write(1, addr, val);
449 #ifdef USE_KQEMU
450 if (env)
451 env->last_io_time = cpu_get_time_fast();
452 #endif
455 void cpu_outl(CPUState *env, int addr, int val)
457 #ifdef DEBUG_IOPORT
458 if (loglevel & CPU_LOG_IOPORT)
459 fprintf(logfile, "outl: %04x %08x\n", addr, val);
460 #endif
461 ioport_write(2, addr, val);
462 #ifdef USE_KQEMU
463 if (env)
464 env->last_io_time = cpu_get_time_fast();
465 #endif
468 int cpu_inb(CPUState *env, int addr)
470 int val;
471 val = ioport_read(0, addr);
472 #ifdef DEBUG_IOPORT
473 if (loglevel & CPU_LOG_IOPORT)
474 fprintf(logfile, "inb : %04x %02x\n", addr, val);
475 #endif
476 #ifdef USE_KQEMU
477 if (env)
478 env->last_io_time = cpu_get_time_fast();
479 #endif
480 return val;
483 int cpu_inw(CPUState *env, int addr)
485 int val;
486 val = ioport_read(1, addr);
487 #ifdef DEBUG_IOPORT
488 if (loglevel & CPU_LOG_IOPORT)
489 fprintf(logfile, "inw : %04x %04x\n", addr, val);
490 #endif
491 #ifdef USE_KQEMU
492 if (env)
493 env->last_io_time = cpu_get_time_fast();
494 #endif
495 return val;
498 int cpu_inl(CPUState *env, int addr)
500 int val;
501 val = ioport_read(2, addr);
502 #ifdef DEBUG_IOPORT
503 if (loglevel & CPU_LOG_IOPORT)
504 fprintf(logfile, "inl : %04x %08x\n", addr, val);
505 #endif
506 #ifdef USE_KQEMU
507 if (env)
508 env->last_io_time = cpu_get_time_fast();
509 #endif
510 return val;
513 /***********************************************************/
514 void hw_error(const char *fmt, ...)
516 va_list ap;
517 CPUState *env;
519 va_start(ap, fmt);
520 fprintf(stderr, "qemu: hardware error: ");
521 vfprintf(stderr, fmt, ap);
522 fprintf(stderr, "\n");
523 for(env = first_cpu; env != NULL; env = env->next_cpu) {
524 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
525 #ifdef TARGET_I386
526 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
527 #else
528 cpu_dump_state(env, stderr, fprintf, 0);
529 #endif
531 va_end(ap);
532 abort();
535 /***********************************************************/
536 /* keyboard/mouse */
538 static QEMUPutKBDEvent *qemu_put_kbd_event;
539 static void *qemu_put_kbd_event_opaque;
540 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
541 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
543 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
545 qemu_put_kbd_event_opaque = opaque;
546 qemu_put_kbd_event = func;
549 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
550 void *opaque, int absolute,
551 const char *name)
553 QEMUPutMouseEntry *s, *cursor;
555 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
556 if (!s)
557 return NULL;
559 s->qemu_put_mouse_event = func;
560 s->qemu_put_mouse_event_opaque = opaque;
561 s->qemu_put_mouse_event_absolute = absolute;
562 s->qemu_put_mouse_event_name = qemu_strdup(name);
563 s->next = NULL;
565 if (!qemu_put_mouse_event_head) {
566 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
567 return s;
570 cursor = qemu_put_mouse_event_head;
571 while (cursor->next != NULL)
572 cursor = cursor->next;
574 cursor->next = s;
575 qemu_put_mouse_event_current = s;
577 return s;
580 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
582 QEMUPutMouseEntry *prev = NULL, *cursor;
584 if (!qemu_put_mouse_event_head || entry == NULL)
585 return;
587 cursor = qemu_put_mouse_event_head;
588 while (cursor != NULL && cursor != entry) {
589 prev = cursor;
590 cursor = cursor->next;
593 if (cursor == NULL) // does not exist or list empty
594 return;
595 else if (prev == NULL) { // entry is head
596 qemu_put_mouse_event_head = cursor->next;
597 if (qemu_put_mouse_event_current == entry)
598 qemu_put_mouse_event_current = cursor->next;
599 qemu_free(entry->qemu_put_mouse_event_name);
600 qemu_free(entry);
601 return;
604 prev->next = entry->next;
606 if (qemu_put_mouse_event_current == entry)
607 qemu_put_mouse_event_current = prev;
609 qemu_free(entry->qemu_put_mouse_event_name);
610 qemu_free(entry);
613 void kbd_put_keycode(int keycode)
615 if (qemu_put_kbd_event) {
616 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
620 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
622 QEMUPutMouseEvent *mouse_event;
623 void *mouse_event_opaque;
624 int width;
626 if (!qemu_put_mouse_event_current) {
627 return;
630 mouse_event =
631 qemu_put_mouse_event_current->qemu_put_mouse_event;
632 mouse_event_opaque =
633 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
635 if (mouse_event) {
636 if (graphic_rotate) {
637 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
638 width = 0x7fff;
639 else
640 width = graphic_width - 1;
641 mouse_event(mouse_event_opaque,
642 width - dy, dx, dz, buttons_state);
643 } else
644 mouse_event(mouse_event_opaque,
645 dx, dy, dz, buttons_state);
649 int kbd_mouse_is_absolute(void)
651 if (!qemu_put_mouse_event_current)
652 return 0;
654 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
657 void do_info_mice(void)
659 QEMUPutMouseEntry *cursor;
660 int index = 0;
662 if (!qemu_put_mouse_event_head) {
663 term_printf("No mouse devices connected\n");
664 return;
667 term_printf("Mouse devices available:\n");
668 cursor = qemu_put_mouse_event_head;
669 while (cursor != NULL) {
670 term_printf("%c Mouse #%d: %s\n",
671 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
672 index, cursor->qemu_put_mouse_event_name);
673 index++;
674 cursor = cursor->next;
678 void do_mouse_set(int index)
680 QEMUPutMouseEntry *cursor;
681 int i = 0;
683 if (!qemu_put_mouse_event_head) {
684 term_printf("No mouse devices connected\n");
685 return;
688 cursor = qemu_put_mouse_event_head;
689 while (cursor != NULL && index != i) {
690 i++;
691 cursor = cursor->next;
694 if (cursor != NULL)
695 qemu_put_mouse_event_current = cursor;
696 else
697 term_printf("Mouse at given index not found\n");
700 /* compute with 96 bit intermediate result: (a*b)/c */
701 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
703 union {
704 uint64_t ll;
705 struct {
706 #ifdef WORDS_BIGENDIAN
707 uint32_t high, low;
708 #else
709 uint32_t low, high;
710 #endif
711 } l;
712 } u, res;
713 uint64_t rl, rh;
715 u.ll = a;
716 rl = (uint64_t)u.l.low * (uint64_t)b;
717 rh = (uint64_t)u.l.high * (uint64_t)b;
718 rh += (rl >> 32);
719 res.l.high = rh / c;
720 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
721 return res.ll;
724 /***********************************************************/
725 /* real time host monotonic timer */
727 #define QEMU_TIMER_BASE 1000000000LL
729 #ifdef WIN32
731 static int64_t clock_freq;
733 static void init_get_clock(void)
735 LARGE_INTEGER freq;
736 int ret;
737 ret = QueryPerformanceFrequency(&freq);
738 if (ret == 0) {
739 fprintf(stderr, "Could not calibrate ticks\n");
740 exit(1);
742 clock_freq = freq.QuadPart;
745 static int64_t get_clock(void)
747 LARGE_INTEGER ti;
748 QueryPerformanceCounter(&ti);
749 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
752 #else
754 static int use_rt_clock;
756 static void init_get_clock(void)
758 use_rt_clock = 0;
759 #if defined(__linux__)
761 struct timespec ts;
762 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
763 use_rt_clock = 1;
766 #endif
769 static int64_t get_clock(void)
771 #if defined(__linux__)
772 if (use_rt_clock) {
773 struct timespec ts;
774 clock_gettime(CLOCK_MONOTONIC, &ts);
775 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
776 } else
777 #endif
779 /* XXX: using gettimeofday leads to problems if the date
780 changes, so it should be avoided. */
781 struct timeval tv;
782 gettimeofday(&tv, NULL);
783 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
786 #endif
788 /* Return the virtual CPU time, based on the instruction counter. */
789 static int64_t cpu_get_icount(void)
791 int64_t icount;
792 CPUState *env = cpu_single_env;;
793 icount = qemu_icount;
794 if (env) {
795 if (!can_do_io(env))
796 fprintf(stderr, "Bad clock read\n");
797 icount -= (env->icount_decr.u16.low + env->icount_extra);
799 return qemu_icount_bias + (icount << icount_time_shift);
802 /***********************************************************/
803 /* guest cycle counter */
805 static int64_t cpu_ticks_prev;
806 static int64_t cpu_ticks_offset;
807 static int64_t cpu_clock_offset;
808 static int cpu_ticks_enabled;
810 /* return the host CPU cycle counter and handle stop/restart */
811 int64_t cpu_get_ticks(void)
813 if (use_icount) {
814 return cpu_get_icount();
816 if (!cpu_ticks_enabled) {
817 return cpu_ticks_offset;
818 } else {
819 int64_t ticks;
820 ticks = cpu_get_real_ticks();
821 if (cpu_ticks_prev > ticks) {
822 /* Note: non increasing ticks may happen if the host uses
823 software suspend */
824 cpu_ticks_offset += cpu_ticks_prev - ticks;
826 cpu_ticks_prev = ticks;
827 return ticks + cpu_ticks_offset;
831 /* return the host CPU monotonic timer and handle stop/restart */
832 static int64_t cpu_get_clock(void)
834 int64_t ti;
835 if (!cpu_ticks_enabled) {
836 return cpu_clock_offset;
837 } else {
838 ti = get_clock();
839 return ti + cpu_clock_offset;
843 /* enable cpu_get_ticks() */
844 void cpu_enable_ticks(void)
846 if (!cpu_ticks_enabled) {
847 cpu_ticks_offset -= cpu_get_real_ticks();
848 cpu_clock_offset -= get_clock();
849 cpu_ticks_enabled = 1;
853 /* disable cpu_get_ticks() : the clock is stopped. You must not call
854 cpu_get_ticks() after that. */
855 void cpu_disable_ticks(void)
857 if (cpu_ticks_enabled) {
858 cpu_ticks_offset = cpu_get_ticks();
859 cpu_clock_offset = cpu_get_clock();
860 cpu_ticks_enabled = 0;
864 /***********************************************************/
865 /* timers */
867 #define QEMU_TIMER_REALTIME 0
868 #define QEMU_TIMER_VIRTUAL 1
870 struct QEMUClock {
871 int type;
872 /* XXX: add frequency */
875 struct QEMUTimer {
876 QEMUClock *clock;
877 int64_t expire_time;
878 QEMUTimerCB *cb;
879 void *opaque;
880 struct QEMUTimer *next;
883 struct qemu_alarm_timer {
884 char const *name;
885 unsigned int flags;
887 int (*start)(struct qemu_alarm_timer *t);
888 void (*stop)(struct qemu_alarm_timer *t);
889 void (*rearm)(struct qemu_alarm_timer *t);
890 void *priv;
893 #define ALARM_FLAG_DYNTICKS 0x1
894 #define ALARM_FLAG_EXPIRED 0x2
896 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
898 return t->flags & ALARM_FLAG_DYNTICKS;
901 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
903 if (!alarm_has_dynticks(t))
904 return;
906 t->rearm(t);
909 /* TODO: MIN_TIMER_REARM_US should be optimized */
910 #define MIN_TIMER_REARM_US 250
912 static struct qemu_alarm_timer *alarm_timer;
914 #ifdef _WIN32
916 struct qemu_alarm_win32 {
917 MMRESULT timerId;
918 HANDLE host_alarm;
919 unsigned int period;
920 } alarm_win32_data = {0, NULL, -1};
922 static int win32_start_timer(struct qemu_alarm_timer *t);
923 static void win32_stop_timer(struct qemu_alarm_timer *t);
924 static void win32_rearm_timer(struct qemu_alarm_timer *t);
926 #else
928 static int unix_start_timer(struct qemu_alarm_timer *t);
929 static void unix_stop_timer(struct qemu_alarm_timer *t);
931 #ifdef __linux__
933 static int dynticks_start_timer(struct qemu_alarm_timer *t);
934 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
935 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
937 static int hpet_start_timer(struct qemu_alarm_timer *t);
938 static void hpet_stop_timer(struct qemu_alarm_timer *t);
940 static int rtc_start_timer(struct qemu_alarm_timer *t);
941 static void rtc_stop_timer(struct qemu_alarm_timer *t);
943 #endif /* __linux__ */
945 #endif /* _WIN32 */
947 /* Correlation between real and virtual time is always going to be
948 fairly approximate, so ignore small variation.
949 When the guest is idle real and virtual time will be aligned in
950 the IO wait loop. */
951 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
953 static void icount_adjust(void)
955 int64_t cur_time;
956 int64_t cur_icount;
957 int64_t delta;
958 static int64_t last_delta;
959 /* If the VM is not running, then do nothing. */
960 if (!vm_running)
961 return;
963 cur_time = cpu_get_clock();
964 cur_icount = qemu_get_clock(vm_clock);
965 delta = cur_icount - cur_time;
966 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
967 if (delta > 0
968 && last_delta + ICOUNT_WOBBLE < delta * 2
969 && icount_time_shift > 0) {
970 /* The guest is getting too far ahead. Slow time down. */
971 icount_time_shift--;
973 if (delta < 0
974 && last_delta - ICOUNT_WOBBLE > delta * 2
975 && icount_time_shift < MAX_ICOUNT_SHIFT) {
976 /* The guest is getting too far behind. Speed time up. */
977 icount_time_shift++;
979 last_delta = delta;
980 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
983 static void icount_adjust_rt(void * opaque)
985 qemu_mod_timer(icount_rt_timer,
986 qemu_get_clock(rt_clock) + 1000);
987 icount_adjust();
990 static void icount_adjust_vm(void * opaque)
992 qemu_mod_timer(icount_vm_timer,
993 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
994 icount_adjust();
997 static void init_icount_adjust(void)
999 /* Have both realtime and virtual time triggers for speed adjustment.
1000 The realtime trigger catches emulated time passing too slowly,
1001 the virtual time trigger catches emulated time passing too fast.
1002 Realtime triggers occur even when idle, so use them less frequently
1003 than VM triggers. */
1004 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1005 qemu_mod_timer(icount_rt_timer,
1006 qemu_get_clock(rt_clock) + 1000);
1007 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1008 qemu_mod_timer(icount_vm_timer,
1009 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1012 static struct qemu_alarm_timer alarm_timers[] = {
1013 #ifndef _WIN32
1014 #ifdef __linux__
1015 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1016 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1017 /* HPET - if available - is preferred */
1018 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1019 /* ...otherwise try RTC */
1020 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1021 #endif
1022 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1023 #else
1024 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1025 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1026 {"win32", 0, win32_start_timer,
1027 win32_stop_timer, NULL, &alarm_win32_data},
1028 #endif
1029 {NULL, }
1032 static void show_available_alarms(void)
1034 int i;
1036 printf("Available alarm timers, in order of precedence:\n");
1037 for (i = 0; alarm_timers[i].name; i++)
1038 printf("%s\n", alarm_timers[i].name);
1041 static void configure_alarms(char const *opt)
1043 int i;
1044 int cur = 0;
1045 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1046 char *arg;
1047 char *name;
1048 struct qemu_alarm_timer tmp;
1050 if (!strcmp(opt, "?")) {
1051 show_available_alarms();
1052 exit(0);
1055 arg = strdup(opt);
1057 /* Reorder the array */
1058 name = strtok(arg, ",");
1059 while (name) {
1060 for (i = 0; i < count && alarm_timers[i].name; i++) {
1061 if (!strcmp(alarm_timers[i].name, name))
1062 break;
1065 if (i == count) {
1066 fprintf(stderr, "Unknown clock %s\n", name);
1067 goto next;
1070 if (i < cur)
1071 /* Ignore */
1072 goto next;
1074 /* Swap */
1075 tmp = alarm_timers[i];
1076 alarm_timers[i] = alarm_timers[cur];
1077 alarm_timers[cur] = tmp;
1079 cur++;
1080 next:
1081 name = strtok(NULL, ",");
1084 free(arg);
1086 if (cur) {
1087 /* Disable remaining timers */
1088 for (i = cur; i < count; i++)
1089 alarm_timers[i].name = NULL;
1090 } else {
1091 show_available_alarms();
1092 exit(1);
1096 QEMUClock *rt_clock;
1097 QEMUClock *vm_clock;
1099 static QEMUTimer *active_timers[2];
1101 static QEMUClock *qemu_new_clock(int type)
1103 QEMUClock *clock;
1104 clock = qemu_mallocz(sizeof(QEMUClock));
1105 if (!clock)
1106 return NULL;
1107 clock->type = type;
1108 return clock;
1111 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1113 QEMUTimer *ts;
1115 ts = qemu_mallocz(sizeof(QEMUTimer));
1116 ts->clock = clock;
1117 ts->cb = cb;
1118 ts->opaque = opaque;
1119 return ts;
1122 void qemu_free_timer(QEMUTimer *ts)
1124 qemu_free(ts);
1127 /* stop a timer, but do not dealloc it */
1128 void qemu_del_timer(QEMUTimer *ts)
1130 QEMUTimer **pt, *t;
1132 /* NOTE: this code must be signal safe because
1133 qemu_timer_expired() can be called from a signal. */
1134 pt = &active_timers[ts->clock->type];
1135 for(;;) {
1136 t = *pt;
1137 if (!t)
1138 break;
1139 if (t == ts) {
1140 *pt = t->next;
1141 break;
1143 pt = &t->next;
1147 /* modify the current timer so that it will be fired when current_time
1148 >= expire_time. The corresponding callback will be called. */
1149 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1151 QEMUTimer **pt, *t;
1153 qemu_del_timer(ts);
1155 /* add the timer in the sorted list */
1156 /* NOTE: this code must be signal safe because
1157 qemu_timer_expired() can be called from a signal. */
1158 pt = &active_timers[ts->clock->type];
1159 for(;;) {
1160 t = *pt;
1161 if (!t)
1162 break;
1163 if (t->expire_time > expire_time)
1164 break;
1165 pt = &t->next;
1167 ts->expire_time = expire_time;
1168 ts->next = *pt;
1169 *pt = ts;
1171 /* Rearm if necessary */
1172 if (pt == &active_timers[ts->clock->type]) {
1173 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1174 qemu_rearm_alarm_timer(alarm_timer);
1176 /* Interrupt execution to force deadline recalculation. */
1177 if (use_icount && cpu_single_env) {
1178 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1183 int qemu_timer_pending(QEMUTimer *ts)
1185 QEMUTimer *t;
1186 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1187 if (t == ts)
1188 return 1;
1190 return 0;
1193 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1195 if (!timer_head)
1196 return 0;
1197 return (timer_head->expire_time <= current_time);
1200 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1202 QEMUTimer *ts;
1204 for(;;) {
1205 ts = *ptimer_head;
1206 if (!ts || ts->expire_time > current_time)
1207 break;
1208 /* remove timer from the list before calling the callback */
1209 *ptimer_head = ts->next;
1210 ts->next = NULL;
1212 /* run the callback (the timer list can be modified) */
1213 ts->cb(ts->opaque);
1217 int64_t qemu_get_clock(QEMUClock *clock)
1219 switch(clock->type) {
1220 case QEMU_TIMER_REALTIME:
1221 return get_clock() / 1000000;
1222 default:
1223 case QEMU_TIMER_VIRTUAL:
1224 if (use_icount) {
1225 return cpu_get_icount();
1226 } else {
1227 return cpu_get_clock();
1232 static void init_timers(void)
1234 init_get_clock();
1235 ticks_per_sec = QEMU_TIMER_BASE;
1236 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1237 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1240 /* save a timer */
1241 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1243 uint64_t expire_time;
1245 if (qemu_timer_pending(ts)) {
1246 expire_time = ts->expire_time;
1247 } else {
1248 expire_time = -1;
1250 qemu_put_be64(f, expire_time);
1253 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1255 uint64_t expire_time;
1257 expire_time = qemu_get_be64(f);
1258 if (expire_time != -1) {
1259 qemu_mod_timer(ts, expire_time);
1260 } else {
1261 qemu_del_timer(ts);
1265 static void timer_save(QEMUFile *f, void *opaque)
1267 if (cpu_ticks_enabled) {
1268 hw_error("cannot save state if virtual timers are running");
1270 qemu_put_be64(f, cpu_ticks_offset);
1271 qemu_put_be64(f, ticks_per_sec);
1272 qemu_put_be64(f, cpu_clock_offset);
1275 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1277 if (version_id != 1 && version_id != 2)
1278 return -EINVAL;
1279 if (cpu_ticks_enabled) {
1280 return -EINVAL;
1282 cpu_ticks_offset=qemu_get_be64(f);
1283 ticks_per_sec=qemu_get_be64(f);
1284 if (version_id == 2) {
1285 cpu_clock_offset=qemu_get_be64(f);
1287 return 0;
1290 #ifdef _WIN32
1291 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1292 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1293 #else
1294 static void host_alarm_handler(int host_signum)
1295 #endif
1297 #if 0
1298 #define DISP_FREQ 1000
1300 static int64_t delta_min = INT64_MAX;
1301 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1302 static int count;
1303 ti = qemu_get_clock(vm_clock);
1304 if (last_clock != 0) {
1305 delta = ti - last_clock;
1306 if (delta < delta_min)
1307 delta_min = delta;
1308 if (delta > delta_max)
1309 delta_max = delta;
1310 delta_cum += delta;
1311 if (++count == DISP_FREQ) {
1312 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1313 muldiv64(delta_min, 1000000, ticks_per_sec),
1314 muldiv64(delta_max, 1000000, ticks_per_sec),
1315 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1316 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1317 count = 0;
1318 delta_min = INT64_MAX;
1319 delta_max = 0;
1320 delta_cum = 0;
1323 last_clock = ti;
1325 #endif
1326 if (1 ||
1327 alarm_has_dynticks(alarm_timer) ||
1328 (!use_icount &&
1329 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1330 qemu_get_clock(vm_clock))) ||
1331 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1332 qemu_get_clock(rt_clock))) {
1333 #ifdef _WIN32
1334 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1335 SetEvent(data->host_alarm);
1336 #endif
1337 CPUState *env = next_cpu;
1339 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1341 if (env) {
1342 /* stop the currently executing cpu because a timer occured */
1343 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1344 #ifdef USE_KQEMU
1345 if (env->kqemu_enabled) {
1346 kqemu_cpu_interrupt(env);
1348 #endif
1350 event_pending = 1;
1354 static int64_t qemu_next_deadline(void)
1356 int64_t delta;
1358 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1359 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1360 qemu_get_clock(vm_clock);
1361 } else {
1362 /* To avoid problems with overflow limit this to 2^32. */
1363 delta = INT32_MAX;
1366 if (delta < 0)
1367 delta = 0;
1369 return delta;
1372 static uint64_t qemu_next_deadline_dyntick(void)
1374 int64_t delta;
1375 int64_t rtdelta;
1377 if (use_icount)
1378 delta = INT32_MAX;
1379 else
1380 delta = (qemu_next_deadline() + 999) / 1000;
1382 if (active_timers[QEMU_TIMER_REALTIME]) {
1383 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1384 qemu_get_clock(rt_clock))*1000;
1385 if (rtdelta < delta)
1386 delta = rtdelta;
1389 if (delta < MIN_TIMER_REARM_US)
1390 delta = MIN_TIMER_REARM_US;
1392 return delta;
1395 #ifndef _WIN32
1397 #if defined(__linux__)
1399 #define RTC_FREQ 1024
1401 static void enable_sigio_timer(int fd)
1403 struct sigaction act;
1405 /* timer signal */
1406 sigfillset(&act.sa_mask);
1407 act.sa_flags = 0;
1408 act.sa_handler = host_alarm_handler;
1410 sigaction(SIGIO, &act, NULL);
1411 fcntl(fd, F_SETFL, O_ASYNC);
1412 fcntl(fd, F_SETOWN, getpid());
1415 static int hpet_start_timer(struct qemu_alarm_timer *t)
1417 struct hpet_info info;
1418 int r, fd;
1420 fd = open("/dev/hpet", O_RDONLY);
1421 if (fd < 0)
1422 return -1;
1424 /* Set frequency */
1425 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1426 if (r < 0) {
1427 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1428 "error, but for better emulation accuracy type:\n"
1429 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1430 goto fail;
1433 /* Check capabilities */
1434 r = ioctl(fd, HPET_INFO, &info);
1435 if (r < 0)
1436 goto fail;
1438 /* Enable periodic mode */
1439 r = ioctl(fd, HPET_EPI, 0);
1440 if (info.hi_flags && (r < 0))
1441 goto fail;
1443 /* Enable interrupt */
1444 r = ioctl(fd, HPET_IE_ON, 0);
1445 if (r < 0)
1446 goto fail;
1448 enable_sigio_timer(fd);
1449 t->priv = (void *)(long)fd;
1451 return 0;
1452 fail:
1453 close(fd);
1454 return -1;
1457 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1459 int fd = (long)t->priv;
1461 close(fd);
1464 static int rtc_start_timer(struct qemu_alarm_timer *t)
1466 int rtc_fd;
1467 unsigned long current_rtc_freq = 0;
1469 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1470 if (rtc_fd < 0)
1471 return -1;
1472 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1473 if (current_rtc_freq != RTC_FREQ &&
1474 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1475 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1476 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1477 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1478 goto fail;
1480 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1481 fail:
1482 close(rtc_fd);
1483 return -1;
1486 enable_sigio_timer(rtc_fd);
1488 t->priv = (void *)(long)rtc_fd;
1490 return 0;
1493 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1495 int rtc_fd = (long)t->priv;
1497 close(rtc_fd);
1500 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1502 struct sigevent ev;
1503 timer_t host_timer;
1504 struct sigaction act;
1506 sigfillset(&act.sa_mask);
1507 act.sa_flags = 0;
1508 act.sa_handler = host_alarm_handler;
1510 sigaction(SIGALRM, &act, NULL);
1512 ev.sigev_value.sival_int = 0;
1513 ev.sigev_notify = SIGEV_SIGNAL;
1514 ev.sigev_signo = SIGALRM;
1516 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1517 perror("timer_create");
1519 /* disable dynticks */
1520 fprintf(stderr, "Dynamic Ticks disabled\n");
1522 return -1;
1525 t->priv = (void *)host_timer;
1527 return 0;
1530 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1532 timer_t host_timer = (timer_t)t->priv;
1534 timer_delete(host_timer);
1537 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1539 timer_t host_timer = (timer_t)t->priv;
1540 struct itimerspec timeout;
1541 int64_t nearest_delta_us = INT64_MAX;
1542 int64_t current_us;
1544 if (!active_timers[QEMU_TIMER_REALTIME] &&
1545 !active_timers[QEMU_TIMER_VIRTUAL])
1546 return;
1548 nearest_delta_us = qemu_next_deadline_dyntick();
1550 /* check whether a timer is already running */
1551 if (timer_gettime(host_timer, &timeout)) {
1552 perror("gettime");
1553 fprintf(stderr, "Internal timer error: aborting\n");
1554 exit(1);
1556 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1557 if (current_us && current_us <= nearest_delta_us)
1558 return;
1560 timeout.it_interval.tv_sec = 0;
1561 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1562 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1563 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1564 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1565 perror("settime");
1566 fprintf(stderr, "Internal timer error: aborting\n");
1567 exit(1);
1571 #endif /* defined(__linux__) */
1573 static int unix_start_timer(struct qemu_alarm_timer *t)
1575 struct sigaction act;
1576 struct itimerval itv;
1577 int err;
1579 /* timer signal */
1580 sigfillset(&act.sa_mask);
1581 act.sa_flags = 0;
1582 act.sa_handler = host_alarm_handler;
1584 sigaction(SIGALRM, &act, NULL);
1586 itv.it_interval.tv_sec = 0;
1587 /* for i386 kernel 2.6 to get 1 ms */
1588 itv.it_interval.tv_usec = 999;
1589 itv.it_value.tv_sec = 0;
1590 itv.it_value.tv_usec = 10 * 1000;
1592 err = setitimer(ITIMER_REAL, &itv, NULL);
1593 if (err)
1594 return -1;
1596 return 0;
1599 static void unix_stop_timer(struct qemu_alarm_timer *t)
1601 struct itimerval itv;
1603 memset(&itv, 0, sizeof(itv));
1604 setitimer(ITIMER_REAL, &itv, NULL);
1607 #endif /* !defined(_WIN32) */
1609 #ifdef _WIN32
1611 static int win32_start_timer(struct qemu_alarm_timer *t)
1613 TIMECAPS tc;
1614 struct qemu_alarm_win32 *data = t->priv;
1615 UINT flags;
1617 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1618 if (!data->host_alarm) {
1619 perror("Failed CreateEvent");
1620 return -1;
1623 memset(&tc, 0, sizeof(tc));
1624 timeGetDevCaps(&tc, sizeof(tc));
1626 if (data->period < tc.wPeriodMin)
1627 data->period = tc.wPeriodMin;
1629 timeBeginPeriod(data->period);
1631 flags = TIME_CALLBACK_FUNCTION;
1632 if (alarm_has_dynticks(t))
1633 flags |= TIME_ONESHOT;
1634 else
1635 flags |= TIME_PERIODIC;
1637 data->timerId = timeSetEvent(1, // interval (ms)
1638 data->period, // resolution
1639 host_alarm_handler, // function
1640 (DWORD)t, // parameter
1641 flags);
1643 if (!data->timerId) {
1644 perror("Failed to initialize win32 alarm timer");
1646 timeEndPeriod(data->period);
1647 CloseHandle(data->host_alarm);
1648 return -1;
1651 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1653 return 0;
1656 static void win32_stop_timer(struct qemu_alarm_timer *t)
1658 struct qemu_alarm_win32 *data = t->priv;
1660 timeKillEvent(data->timerId);
1661 timeEndPeriod(data->period);
1663 CloseHandle(data->host_alarm);
1666 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1668 struct qemu_alarm_win32 *data = t->priv;
1669 uint64_t nearest_delta_us;
1671 if (!active_timers[QEMU_TIMER_REALTIME] &&
1672 !active_timers[QEMU_TIMER_VIRTUAL])
1673 return;
1675 nearest_delta_us = qemu_next_deadline_dyntick();
1676 nearest_delta_us /= 1000;
1678 timeKillEvent(data->timerId);
1680 data->timerId = timeSetEvent(1,
1681 data->period,
1682 host_alarm_handler,
1683 (DWORD)t,
1684 TIME_ONESHOT | TIME_PERIODIC);
1686 if (!data->timerId) {
1687 perror("Failed to re-arm win32 alarm timer");
1689 timeEndPeriod(data->period);
1690 CloseHandle(data->host_alarm);
1691 exit(1);
1695 #endif /* _WIN32 */
1697 static void init_timer_alarm(void)
1699 struct qemu_alarm_timer *t;
1700 int i, err = -1;
1702 for (i = 0; alarm_timers[i].name; i++) {
1703 t = &alarm_timers[i];
1705 err = t->start(t);
1706 if (!err)
1707 break;
1710 if (err) {
1711 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1712 fprintf(stderr, "Terminating\n");
1713 exit(1);
1716 alarm_timer = t;
1719 static void quit_timers(void)
1721 alarm_timer->stop(alarm_timer);
1722 alarm_timer = NULL;
1725 /***********************************************************/
1726 /* host time/date access */
1727 void qemu_get_timedate(struct tm *tm, int offset)
1729 time_t ti;
1730 struct tm *ret;
1732 time(&ti);
1733 ti += offset;
1734 if (rtc_date_offset == -1) {
1735 if (rtc_utc)
1736 ret = gmtime(&ti);
1737 else
1738 ret = localtime(&ti);
1739 } else {
1740 ti -= rtc_date_offset;
1741 ret = gmtime(&ti);
1744 memcpy(tm, ret, sizeof(struct tm));
1747 int qemu_timedate_diff(struct tm *tm)
1749 time_t seconds;
1751 if (rtc_date_offset == -1)
1752 if (rtc_utc)
1753 seconds = mktimegm(tm);
1754 else
1755 seconds = mktime(tm);
1756 else
1757 seconds = mktimegm(tm) + rtc_date_offset;
1759 return seconds - time(NULL);
1762 /***********************************************************/
1763 /* character device */
1765 static void qemu_chr_event(CharDriverState *s, int event)
1767 if (!s->chr_event)
1768 return;
1769 s->chr_event(s->handler_opaque, event);
1772 static void qemu_chr_reset_bh(void *opaque)
1774 CharDriverState *s = opaque;
1775 qemu_chr_event(s, CHR_EVENT_RESET);
1776 qemu_bh_delete(s->bh);
1777 s->bh = NULL;
1780 void qemu_chr_reset(CharDriverState *s)
1782 if (s->bh == NULL) {
1783 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1784 qemu_bh_schedule(s->bh);
1788 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1790 return s->chr_write(s, buf, len);
1793 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1795 if (!s->chr_ioctl)
1796 return -ENOTSUP;
1797 return s->chr_ioctl(s, cmd, arg);
1800 int qemu_chr_can_read(CharDriverState *s)
1802 if (!s->chr_can_read)
1803 return 0;
1804 return s->chr_can_read(s->handler_opaque);
1807 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1809 s->chr_read(s->handler_opaque, buf, len);
1812 void qemu_chr_accept_input(CharDriverState *s)
1814 if (s->chr_accept_input)
1815 s->chr_accept_input(s);
1818 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1820 char buf[4096];
1821 va_list ap;
1822 va_start(ap, fmt);
1823 vsnprintf(buf, sizeof(buf), fmt, ap);
1824 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1825 va_end(ap);
1828 void qemu_chr_send_event(CharDriverState *s, int event)
1830 if (s->chr_send_event)
1831 s->chr_send_event(s, event);
1834 void qemu_chr_add_handlers(CharDriverState *s,
1835 IOCanRWHandler *fd_can_read,
1836 IOReadHandler *fd_read,
1837 IOEventHandler *fd_event,
1838 void *opaque)
1840 s->chr_can_read = fd_can_read;
1841 s->chr_read = fd_read;
1842 s->chr_event = fd_event;
1843 s->handler_opaque = opaque;
1844 if (s->chr_update_read_handler)
1845 s->chr_update_read_handler(s);
1848 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1850 return len;
1853 static CharDriverState *qemu_chr_open_null(void)
1855 CharDriverState *chr;
1857 chr = qemu_mallocz(sizeof(CharDriverState));
1858 if (!chr)
1859 return NULL;
1860 chr->chr_write = null_chr_write;
1861 return chr;
1864 /* MUX driver for serial I/O splitting */
1865 static int term_timestamps;
1866 static int64_t term_timestamps_start;
1867 #define MAX_MUX 4
1868 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1869 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1870 typedef struct {
1871 IOCanRWHandler *chr_can_read[MAX_MUX];
1872 IOReadHandler *chr_read[MAX_MUX];
1873 IOEventHandler *chr_event[MAX_MUX];
1874 void *ext_opaque[MAX_MUX];
1875 CharDriverState *drv;
1876 unsigned char buffer[MUX_BUFFER_SIZE];
1877 int prod;
1878 int cons;
1879 int mux_cnt;
1880 int term_got_escape;
1881 int max_size;
1882 } MuxDriver;
1885 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1887 MuxDriver *d = chr->opaque;
1888 int ret;
1889 if (!term_timestamps) {
1890 ret = d->drv->chr_write(d->drv, buf, len);
1891 } else {
1892 int i;
1894 ret = 0;
1895 for(i = 0; i < len; i++) {
1896 ret += d->drv->chr_write(d->drv, buf+i, 1);
1897 if (buf[i] == '\n') {
1898 char buf1[64];
1899 int64_t ti;
1900 int secs;
1902 ti = get_clock();
1903 if (term_timestamps_start == -1)
1904 term_timestamps_start = ti;
1905 ti -= term_timestamps_start;
1906 secs = ti / 1000000000;
1907 snprintf(buf1, sizeof(buf1),
1908 "[%02d:%02d:%02d.%03d] ",
1909 secs / 3600,
1910 (secs / 60) % 60,
1911 secs % 60,
1912 (int)((ti / 1000000) % 1000));
1913 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1917 return ret;
1920 static char *mux_help[] = {
1921 "% h print this help\n\r",
1922 "% x exit emulator\n\r",
1923 "% s save disk data back to file (if -snapshot)\n\r",
1924 "% t toggle console timestamps\n\r"
1925 "% b send break (magic sysrq)\n\r",
1926 "% c switch between console and monitor\n\r",
1927 "% % sends %\n\r",
1928 NULL
1931 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1932 static void mux_print_help(CharDriverState *chr)
1934 int i, j;
1935 char ebuf[15] = "Escape-Char";
1936 char cbuf[50] = "\n\r";
1938 if (term_escape_char > 0 && term_escape_char < 26) {
1939 snprintf(cbuf, sizeof(cbuf), "\n\r");
1940 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1941 } else {
1942 snprintf(cbuf, sizeof(cbuf),
1943 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1944 term_escape_char);
1946 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1947 for (i = 0; mux_help[i] != NULL; i++) {
1948 for (j=0; mux_help[i][j] != '\0'; j++) {
1949 if (mux_help[i][j] == '%')
1950 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1951 else
1952 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1957 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1959 if (d->term_got_escape) {
1960 d->term_got_escape = 0;
1961 if (ch == term_escape_char)
1962 goto send_char;
1963 switch(ch) {
1964 case '?':
1965 case 'h':
1966 mux_print_help(chr);
1967 break;
1968 case 'x':
1970 char *term = "QEMU: Terminated\n\r";
1971 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1972 exit(0);
1973 break;
1975 case 's':
1977 int i;
1978 for (i = 0; i < nb_drives; i++) {
1979 bdrv_commit(drives_table[i].bdrv);
1982 break;
1983 case 'b':
1984 qemu_chr_event(chr, CHR_EVENT_BREAK);
1985 break;
1986 case 'c':
1987 /* Switch to the next registered device */
1988 chr->focus++;
1989 if (chr->focus >= d->mux_cnt)
1990 chr->focus = 0;
1991 break;
1992 case 't':
1993 term_timestamps = !term_timestamps;
1994 term_timestamps_start = -1;
1995 break;
1997 } else if (ch == term_escape_char) {
1998 d->term_got_escape = 1;
1999 } else {
2000 send_char:
2001 return 1;
2003 return 0;
2006 static void mux_chr_accept_input(CharDriverState *chr)
2008 int m = chr->focus;
2009 MuxDriver *d = chr->opaque;
2011 while (d->prod != d->cons &&
2012 d->chr_can_read[m] &&
2013 d->chr_can_read[m](d->ext_opaque[m])) {
2014 d->chr_read[m](d->ext_opaque[m],
2015 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
2019 static int mux_chr_can_read(void *opaque)
2021 CharDriverState *chr = opaque;
2022 MuxDriver *d = chr->opaque;
2024 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2025 return 1;
2026 if (d->chr_can_read[chr->focus])
2027 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2028 return 0;
2031 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2033 CharDriverState *chr = opaque;
2034 MuxDriver *d = chr->opaque;
2035 int m = chr->focus;
2036 int i;
2038 mux_chr_accept_input (opaque);
2040 for(i = 0; i < size; i++)
2041 if (mux_proc_byte(chr, d, buf[i])) {
2042 if (d->prod == d->cons &&
2043 d->chr_can_read[m] &&
2044 d->chr_can_read[m](d->ext_opaque[m]))
2045 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2046 else
2047 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2051 static void mux_chr_event(void *opaque, int event)
2053 CharDriverState *chr = opaque;
2054 MuxDriver *d = chr->opaque;
2055 int i;
2057 /* Send the event to all registered listeners */
2058 for (i = 0; i < d->mux_cnt; i++)
2059 if (d->chr_event[i])
2060 d->chr_event[i](d->ext_opaque[i], event);
2063 static void mux_chr_update_read_handler(CharDriverState *chr)
2065 MuxDriver *d = chr->opaque;
2067 if (d->mux_cnt >= MAX_MUX) {
2068 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2069 return;
2071 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2072 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2073 d->chr_read[d->mux_cnt] = chr->chr_read;
2074 d->chr_event[d->mux_cnt] = chr->chr_event;
2075 /* Fix up the real driver with mux routines */
2076 if (d->mux_cnt == 0) {
2077 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2078 mux_chr_event, chr);
2080 chr->focus = d->mux_cnt;
2081 d->mux_cnt++;
2084 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2086 CharDriverState *chr;
2087 MuxDriver *d;
2089 chr = qemu_mallocz(sizeof(CharDriverState));
2090 if (!chr)
2091 return NULL;
2092 d = qemu_mallocz(sizeof(MuxDriver));
2093 if (!d) {
2094 free(chr);
2095 return NULL;
2098 chr->opaque = d;
2099 d->drv = drv;
2100 chr->focus = -1;
2101 chr->chr_write = mux_chr_write;
2102 chr->chr_update_read_handler = mux_chr_update_read_handler;
2103 chr->chr_accept_input = mux_chr_accept_input;
2104 return chr;
2108 #ifdef _WIN32
2110 static void socket_cleanup(void)
2112 WSACleanup();
2115 static int socket_init(void)
2117 WSADATA Data;
2118 int ret, err;
2120 ret = WSAStartup(MAKEWORD(2,2), &Data);
2121 if (ret != 0) {
2122 err = WSAGetLastError();
2123 fprintf(stderr, "WSAStartup: %d\n", err);
2124 return -1;
2126 atexit(socket_cleanup);
2127 return 0;
2130 static int send_all(int fd, const uint8_t *buf, int len1)
2132 int ret, len;
2134 len = len1;
2135 while (len > 0) {
2136 ret = send(fd, buf, len, 0);
2137 if (ret < 0) {
2138 int errno;
2139 errno = WSAGetLastError();
2140 if (errno != WSAEWOULDBLOCK) {
2141 return -1;
2143 } else if (ret == 0) {
2144 break;
2145 } else {
2146 buf += ret;
2147 len -= ret;
2150 return len1 - len;
2153 void socket_set_nonblock(int fd)
2155 unsigned long opt = 1;
2156 ioctlsocket(fd, FIONBIO, &opt);
2159 #else
2161 static int unix_write(int fd, const uint8_t *buf, int len1)
2163 int ret, len;
2165 len = len1;
2166 while (len > 0) {
2167 ret = write(fd, buf, len);
2168 if (ret < 0) {
2169 if (errno != EINTR && errno != EAGAIN)
2170 return -1;
2171 } else if (ret == 0) {
2172 break;
2173 } else {
2174 buf += ret;
2175 len -= ret;
2178 return len1 - len;
2181 static inline int send_all(int fd, const uint8_t *buf, int len1)
2183 return unix_write(fd, buf, len1);
2186 void socket_set_nonblock(int fd)
2188 int f;
2189 f = fcntl(fd, F_GETFL);
2190 fcntl(fd, F_SETFL, f | O_NONBLOCK);
2192 #endif /* !_WIN32 */
2194 #ifndef _WIN32
2196 typedef struct {
2197 int fd_in, fd_out;
2198 int max_size;
2199 } FDCharDriver;
2201 #define STDIO_MAX_CLIENTS 1
2202 static int stdio_nb_clients = 0;
2204 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2206 FDCharDriver *s = chr->opaque;
2207 return unix_write(s->fd_out, buf, len);
2210 static int fd_chr_read_poll(void *opaque)
2212 CharDriverState *chr = opaque;
2213 FDCharDriver *s = chr->opaque;
2215 s->max_size = qemu_chr_can_read(chr);
2216 return s->max_size;
2219 static void fd_chr_read(void *opaque)
2221 CharDriverState *chr = opaque;
2222 FDCharDriver *s = chr->opaque;
2223 int size, len;
2224 uint8_t buf[1024];
2226 len = sizeof(buf);
2227 if (len > s->max_size)
2228 len = s->max_size;
2229 if (len == 0)
2230 return;
2231 size = read(s->fd_in, buf, len);
2232 if (size == 0) {
2233 /* FD has been closed. Remove it from the active list. */
2234 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2235 return;
2237 if (size > 0) {
2238 qemu_chr_read(chr, buf, size);
2242 static void fd_chr_update_read_handler(CharDriverState *chr)
2244 FDCharDriver *s = chr->opaque;
2246 if (s->fd_in >= 0) {
2247 if (nographic && s->fd_in == 0) {
2248 } else {
2249 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2250 fd_chr_read, NULL, chr);
2255 static void fd_chr_close(struct CharDriverState *chr)
2257 FDCharDriver *s = chr->opaque;
2259 if (s->fd_in >= 0) {
2260 if (nographic && s->fd_in == 0) {
2261 } else {
2262 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2266 qemu_free(s);
2269 /* open a character device to a unix fd */
2270 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2272 CharDriverState *chr;
2273 FDCharDriver *s;
2275 chr = qemu_mallocz(sizeof(CharDriverState));
2276 if (!chr)
2277 return NULL;
2278 s = qemu_mallocz(sizeof(FDCharDriver));
2279 if (!s) {
2280 free(chr);
2281 return NULL;
2283 s->fd_in = fd_in;
2284 s->fd_out = fd_out;
2285 chr->opaque = s;
2286 chr->chr_write = fd_chr_write;
2287 chr->chr_update_read_handler = fd_chr_update_read_handler;
2288 chr->chr_close = fd_chr_close;
2290 qemu_chr_reset(chr);
2292 return chr;
2295 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2297 int fd_out;
2299 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2300 if (fd_out < 0)
2301 return NULL;
2302 return qemu_chr_open_fd(-1, fd_out);
2305 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2307 int fd_in, fd_out;
2308 char filename_in[256], filename_out[256];
2310 snprintf(filename_in, 256, "%s.in", filename);
2311 snprintf(filename_out, 256, "%s.out", filename);
2312 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2313 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2314 if (fd_in < 0 || fd_out < 0) {
2315 if (fd_in >= 0)
2316 close(fd_in);
2317 if (fd_out >= 0)
2318 close(fd_out);
2319 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2320 if (fd_in < 0)
2321 return NULL;
2323 return qemu_chr_open_fd(fd_in, fd_out);
2327 /* for STDIO, we handle the case where several clients use it
2328 (nographic mode) */
2330 #define TERM_FIFO_MAX_SIZE 1
2332 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2333 static int term_fifo_size;
2335 static int stdio_read_poll(void *opaque)
2337 CharDriverState *chr = opaque;
2339 /* try to flush the queue if needed */
2340 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2341 qemu_chr_read(chr, term_fifo, 1);
2342 term_fifo_size = 0;
2344 /* see if we can absorb more chars */
2345 if (term_fifo_size == 0)
2346 return 1;
2347 else
2348 return 0;
2351 static void stdio_read(void *opaque)
2353 int size;
2354 uint8_t buf[1];
2355 CharDriverState *chr = opaque;
2357 size = read(0, buf, 1);
2358 if (size == 0) {
2359 /* stdin has been closed. Remove it from the active list. */
2360 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2361 return;
2363 if (size > 0) {
2364 if (qemu_chr_can_read(chr) > 0) {
2365 qemu_chr_read(chr, buf, 1);
2366 } else if (term_fifo_size == 0) {
2367 term_fifo[term_fifo_size++] = buf[0];
2372 /* init terminal so that we can grab keys */
2373 static struct termios oldtty;
2374 static int old_fd0_flags;
2375 static int term_atexit_done;
2377 static void term_exit(void)
2379 tcsetattr (0, TCSANOW, &oldtty);
2380 fcntl(0, F_SETFL, old_fd0_flags);
2383 static void term_init(void)
2385 struct termios tty;
2387 tcgetattr (0, &tty);
2388 oldtty = tty;
2389 old_fd0_flags = fcntl(0, F_GETFL);
2391 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2392 |INLCR|IGNCR|ICRNL|IXON);
2393 tty.c_oflag |= OPOST;
2394 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2395 /* if graphical mode, we allow Ctrl-C handling */
2396 if (nographic)
2397 tty.c_lflag &= ~ISIG;
2398 tty.c_cflag &= ~(CSIZE|PARENB);
2399 tty.c_cflag |= CS8;
2400 tty.c_cc[VMIN] = 1;
2401 tty.c_cc[VTIME] = 0;
2403 tcsetattr (0, TCSANOW, &tty);
2405 if (!term_atexit_done++)
2406 atexit(term_exit);
2408 fcntl(0, F_SETFL, O_NONBLOCK);
2411 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2413 term_exit();
2414 stdio_nb_clients--;
2415 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2416 fd_chr_close(chr);
2419 static CharDriverState *qemu_chr_open_stdio(void)
2421 CharDriverState *chr;
2423 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2424 return NULL;
2425 chr = qemu_chr_open_fd(0, 1);
2426 chr->chr_close = qemu_chr_close_stdio;
2427 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2428 stdio_nb_clients++;
2429 term_init();
2431 return chr;
2434 #ifdef __sun__
2435 /* Once Solaris has openpty(), this is going to be removed. */
2436 int openpty(int *amaster, int *aslave, char *name,
2437 struct termios *termp, struct winsize *winp)
2439 const char *slave;
2440 int mfd = -1, sfd = -1;
2442 *amaster = *aslave = -1;
2444 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2445 if (mfd < 0)
2446 goto err;
2448 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2449 goto err;
2451 if ((slave = ptsname(mfd)) == NULL)
2452 goto err;
2454 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2455 goto err;
2457 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2458 (termp != NULL && tcgetattr(sfd, termp) < 0))
2459 goto err;
2461 if (amaster)
2462 *amaster = mfd;
2463 if (aslave)
2464 *aslave = sfd;
2465 if (winp)
2466 ioctl(sfd, TIOCSWINSZ, winp);
2468 return 0;
2470 err:
2471 if (sfd != -1)
2472 close(sfd);
2473 close(mfd);
2474 return -1;
2477 void cfmakeraw (struct termios *termios_p)
2479 termios_p->c_iflag &=
2480 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2481 termios_p->c_oflag &= ~OPOST;
2482 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2483 termios_p->c_cflag &= ~(CSIZE|PARENB);
2484 termios_p->c_cflag |= CS8;
2486 termios_p->c_cc[VMIN] = 0;
2487 termios_p->c_cc[VTIME] = 0;
2489 #endif
2491 #if defined(__linux__) || defined(__sun__)
2493 typedef struct {
2494 int fd;
2495 int connected;
2496 int polling;
2497 int read_bytes;
2498 QEMUTimer *timer;
2499 } PtyCharDriver;
2501 static void pty_chr_update_read_handler(CharDriverState *chr);
2502 static void pty_chr_state(CharDriverState *chr, int connected);
2504 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2506 PtyCharDriver *s = chr->opaque;
2508 if (!s->connected) {
2509 /* guest sends data, check for (re-)connect */
2510 pty_chr_update_read_handler(chr);
2511 return 0;
2513 return unix_write(s->fd, buf, len);
2516 static int pty_chr_read_poll(void *opaque)
2518 CharDriverState *chr = opaque;
2519 PtyCharDriver *s = chr->opaque;
2521 s->read_bytes = qemu_chr_can_read(chr);
2522 return s->read_bytes;
2525 static void pty_chr_read(void *opaque)
2527 CharDriverState *chr = opaque;
2528 PtyCharDriver *s = chr->opaque;
2529 int size, len;
2530 uint8_t buf[1024];
2532 len = sizeof(buf);
2533 if (len > s->read_bytes)
2534 len = s->read_bytes;
2535 if (len == 0)
2536 return;
2537 size = read(s->fd, buf, len);
2538 if ((size == -1 && errno == EIO) ||
2539 (size == 0)) {
2540 pty_chr_state(chr, 0);
2541 return;
2543 if (size > 0) {
2544 pty_chr_state(chr, 1);
2545 qemu_chr_read(chr, buf, size);
2549 static void pty_chr_update_read_handler(CharDriverState *chr)
2551 PtyCharDriver *s = chr->opaque;
2553 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2554 pty_chr_read, NULL, chr);
2555 s->polling = 1;
2557 * Short timeout here: just need wait long enougth that qemu makes
2558 * it through the poll loop once. When reconnected we want a
2559 * short timeout so we notice it almost instantly. Otherwise
2560 * read() gives us -EIO instantly, making pty_chr_state() reset the
2561 * timeout to the normal (much longer) poll interval before the
2562 * timer triggers.
2564 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2567 static void pty_chr_state(CharDriverState *chr, int connected)
2569 PtyCharDriver *s = chr->opaque;
2571 if (!connected) {
2572 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2573 s->connected = 0;
2574 s->polling = 0;
2575 /* (re-)connect poll interval for idle guests: once per second.
2576 * We check more frequently in case the guests sends data to
2577 * the virtual device linked to our pty. */
2578 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2579 } else {
2580 if (!s->connected)
2581 qemu_chr_reset(chr);
2582 s->connected = 1;
2586 static void pty_chr_timer(void *opaque)
2588 struct CharDriverState *chr = opaque;
2589 PtyCharDriver *s = chr->opaque;
2591 if (s->connected)
2592 return;
2593 if (s->polling) {
2594 /* If we arrive here without polling being cleared due
2595 * read returning -EIO, then we are (re-)connected */
2596 pty_chr_state(chr, 1);
2597 return;
2600 /* Next poll ... */
2601 pty_chr_update_read_handler(chr);
2604 static void pty_chr_close(struct CharDriverState *chr)
2606 PtyCharDriver *s = chr->opaque;
2608 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2609 close(s->fd);
2610 qemu_free(s);
2613 static CharDriverState *qemu_chr_open_pty(void)
2615 CharDriverState *chr;
2616 PtyCharDriver *s;
2617 struct termios tty;
2618 int slave_fd;
2620 chr = qemu_mallocz(sizeof(CharDriverState));
2621 if (!chr)
2622 return NULL;
2623 s = qemu_mallocz(sizeof(PtyCharDriver));
2624 if (!s) {
2625 qemu_free(chr);
2626 return NULL;
2629 if (openpty(&s->fd, &slave_fd, NULL, NULL, NULL) < 0) {
2630 return NULL;
2633 /* Set raw attributes on the pty. */
2634 cfmakeraw(&tty);
2635 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2636 close(slave_fd);
2638 fprintf(stderr, "char device redirected to %s\n", ptsname(s->fd));
2640 chr->opaque = s;
2641 chr->chr_write = pty_chr_write;
2642 chr->chr_update_read_handler = pty_chr_update_read_handler;
2643 chr->chr_close = pty_chr_close;
2645 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2647 return chr;
2650 static void tty_serial_init(int fd, int speed,
2651 int parity, int data_bits, int stop_bits)
2653 struct termios tty;
2654 speed_t spd;
2656 #if 0
2657 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2658 speed, parity, data_bits, stop_bits);
2659 #endif
2660 tcgetattr (fd, &tty);
2662 #define MARGIN 1.1
2663 if (speed <= 50 * MARGIN)
2664 spd = B50;
2665 else if (speed <= 75 * MARGIN)
2666 spd = B75;
2667 else if (speed <= 300 * MARGIN)
2668 spd = B300;
2669 else if (speed <= 600 * MARGIN)
2670 spd = B600;
2671 else if (speed <= 1200 * MARGIN)
2672 spd = B1200;
2673 else if (speed <= 2400 * MARGIN)
2674 spd = B2400;
2675 else if (speed <= 4800 * MARGIN)
2676 spd = B4800;
2677 else if (speed <= 9600 * MARGIN)
2678 spd = B9600;
2679 else if (speed <= 19200 * MARGIN)
2680 spd = B19200;
2681 else if (speed <= 38400 * MARGIN)
2682 spd = B38400;
2683 else if (speed <= 57600 * MARGIN)
2684 spd = B57600;
2685 else if (speed <= 115200 * MARGIN)
2686 spd = B115200;
2687 else
2688 spd = B115200;
2690 cfsetispeed(&tty, spd);
2691 cfsetospeed(&tty, spd);
2693 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2694 |INLCR|IGNCR|ICRNL|IXON);
2695 tty.c_oflag |= OPOST;
2696 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2697 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2698 switch(data_bits) {
2699 default:
2700 case 8:
2701 tty.c_cflag |= CS8;
2702 break;
2703 case 7:
2704 tty.c_cflag |= CS7;
2705 break;
2706 case 6:
2707 tty.c_cflag |= CS6;
2708 break;
2709 case 5:
2710 tty.c_cflag |= CS5;
2711 break;
2713 switch(parity) {
2714 default:
2715 case 'N':
2716 break;
2717 case 'E':
2718 tty.c_cflag |= PARENB;
2719 break;
2720 case 'O':
2721 tty.c_cflag |= PARENB | PARODD;
2722 break;
2724 if (stop_bits == 2)
2725 tty.c_cflag |= CSTOPB;
2727 tcsetattr (fd, TCSANOW, &tty);
2730 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2732 FDCharDriver *s = chr->opaque;
2734 switch(cmd) {
2735 case CHR_IOCTL_SERIAL_SET_PARAMS:
2737 QEMUSerialSetParams *ssp = arg;
2738 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2739 ssp->data_bits, ssp->stop_bits);
2741 break;
2742 case CHR_IOCTL_SERIAL_SET_BREAK:
2744 int enable = *(int *)arg;
2745 if (enable)
2746 tcsendbreak(s->fd_in, 1);
2748 break;
2749 case CHR_IOCTL_SERIAL_GET_TIOCM:
2751 int sarg = 0;
2752 int *targ = (int *)arg;
2753 ioctl(s->fd_in, TIOCMGET, &sarg);
2754 *targ = 0;
2755 if (sarg | TIOCM_CTS)
2756 *targ |= CHR_TIOCM_CTS;
2757 if (sarg | TIOCM_CAR)
2758 *targ |= CHR_TIOCM_CAR;
2759 if (sarg | TIOCM_DSR)
2760 *targ |= CHR_TIOCM_DSR;
2761 if (sarg | TIOCM_RI)
2762 *targ |= CHR_TIOCM_RI;
2763 if (sarg | TIOCM_DTR)
2764 *targ |= CHR_TIOCM_DTR;
2765 if (sarg | TIOCM_RTS)
2766 *targ |= CHR_TIOCM_RTS;
2768 break;
2769 case CHR_IOCTL_SERIAL_SET_TIOCM:
2771 int sarg = *(int *)arg;
2772 int targ = 0;
2773 if (sarg | CHR_TIOCM_DTR)
2774 targ |= TIOCM_DTR;
2775 if (sarg | CHR_TIOCM_RTS)
2776 targ |= TIOCM_RTS;
2777 ioctl(s->fd_in, TIOCMSET, &targ);
2779 break;
2780 default:
2781 return -ENOTSUP;
2783 return 0;
2786 static CharDriverState *qemu_chr_open_tty(const char *filename)
2788 CharDriverState *chr;
2789 int fd;
2791 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2792 tty_serial_init(fd, 115200, 'N', 8, 1);
2793 chr = qemu_chr_open_fd(fd, fd);
2794 if (!chr) {
2795 close(fd);
2796 return NULL;
2798 chr->chr_ioctl = tty_serial_ioctl;
2799 qemu_chr_reset(chr);
2800 return chr;
2802 #else /* ! __linux__ && ! __sun__ */
2803 static CharDriverState *qemu_chr_open_pty(void)
2805 return NULL;
2807 #endif /* __linux__ || __sun__ */
2809 #if defined(__linux__)
2810 typedef struct {
2811 int fd;
2812 int mode;
2813 } ParallelCharDriver;
2815 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2817 if (s->mode != mode) {
2818 int m = mode;
2819 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2820 return 0;
2821 s->mode = mode;
2823 return 1;
2826 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2828 ParallelCharDriver *drv = chr->opaque;
2829 int fd = drv->fd;
2830 uint8_t b;
2832 switch(cmd) {
2833 case CHR_IOCTL_PP_READ_DATA:
2834 if (ioctl(fd, PPRDATA, &b) < 0)
2835 return -ENOTSUP;
2836 *(uint8_t *)arg = b;
2837 break;
2838 case CHR_IOCTL_PP_WRITE_DATA:
2839 b = *(uint8_t *)arg;
2840 if (ioctl(fd, PPWDATA, &b) < 0)
2841 return -ENOTSUP;
2842 break;
2843 case CHR_IOCTL_PP_READ_CONTROL:
2844 if (ioctl(fd, PPRCONTROL, &b) < 0)
2845 return -ENOTSUP;
2846 /* Linux gives only the lowest bits, and no way to know data
2847 direction! For better compatibility set the fixed upper
2848 bits. */
2849 *(uint8_t *)arg = b | 0xc0;
2850 break;
2851 case CHR_IOCTL_PP_WRITE_CONTROL:
2852 b = *(uint8_t *)arg;
2853 if (ioctl(fd, PPWCONTROL, &b) < 0)
2854 return -ENOTSUP;
2855 break;
2856 case CHR_IOCTL_PP_READ_STATUS:
2857 if (ioctl(fd, PPRSTATUS, &b) < 0)
2858 return -ENOTSUP;
2859 *(uint8_t *)arg = b;
2860 break;
2861 case CHR_IOCTL_PP_DATA_DIR:
2862 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2863 return -ENOTSUP;
2864 break;
2865 case CHR_IOCTL_PP_EPP_READ_ADDR:
2866 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2867 struct ParallelIOArg *parg = arg;
2868 int n = read(fd, parg->buffer, parg->count);
2869 if (n != parg->count) {
2870 return -EIO;
2873 break;
2874 case CHR_IOCTL_PP_EPP_READ:
2875 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2876 struct ParallelIOArg *parg = arg;
2877 int n = read(fd, parg->buffer, parg->count);
2878 if (n != parg->count) {
2879 return -EIO;
2882 break;
2883 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2884 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2885 struct ParallelIOArg *parg = arg;
2886 int n = write(fd, parg->buffer, parg->count);
2887 if (n != parg->count) {
2888 return -EIO;
2891 break;
2892 case CHR_IOCTL_PP_EPP_WRITE:
2893 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2894 struct ParallelIOArg *parg = arg;
2895 int n = write(fd, parg->buffer, parg->count);
2896 if (n != parg->count) {
2897 return -EIO;
2900 break;
2901 default:
2902 return -ENOTSUP;
2904 return 0;
2907 static void pp_close(CharDriverState *chr)
2909 ParallelCharDriver *drv = chr->opaque;
2910 int fd = drv->fd;
2912 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2913 ioctl(fd, PPRELEASE);
2914 close(fd);
2915 qemu_free(drv);
2918 static CharDriverState *qemu_chr_open_pp(const char *filename)
2920 CharDriverState *chr;
2921 ParallelCharDriver *drv;
2922 int fd;
2924 TFR(fd = open(filename, O_RDWR));
2925 if (fd < 0)
2926 return NULL;
2928 if (ioctl(fd, PPCLAIM) < 0) {
2929 close(fd);
2930 return NULL;
2933 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2934 if (!drv) {
2935 close(fd);
2936 return NULL;
2938 drv->fd = fd;
2939 drv->mode = IEEE1284_MODE_COMPAT;
2941 chr = qemu_mallocz(sizeof(CharDriverState));
2942 if (!chr) {
2943 qemu_free(drv);
2944 close(fd);
2945 return NULL;
2947 chr->chr_write = null_chr_write;
2948 chr->chr_ioctl = pp_ioctl;
2949 chr->chr_close = pp_close;
2950 chr->opaque = drv;
2952 qemu_chr_reset(chr);
2954 return chr;
2956 #endif /* __linux__ */
2958 #else /* _WIN32 */
2960 typedef struct {
2961 int max_size;
2962 HANDLE hcom, hrecv, hsend;
2963 OVERLAPPED orecv, osend;
2964 BOOL fpipe;
2965 DWORD len;
2966 } WinCharState;
2968 #define NSENDBUF 2048
2969 #define NRECVBUF 2048
2970 #define MAXCONNECT 1
2971 #define NTIMEOUT 5000
2973 static int win_chr_poll(void *opaque);
2974 static int win_chr_pipe_poll(void *opaque);
2976 static void win_chr_close(CharDriverState *chr)
2978 WinCharState *s = chr->opaque;
2980 if (s->hsend) {
2981 CloseHandle(s->hsend);
2982 s->hsend = NULL;
2984 if (s->hrecv) {
2985 CloseHandle(s->hrecv);
2986 s->hrecv = NULL;
2988 if (s->hcom) {
2989 CloseHandle(s->hcom);
2990 s->hcom = NULL;
2992 if (s->fpipe)
2993 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2994 else
2995 qemu_del_polling_cb(win_chr_poll, chr);
2998 static int win_chr_init(CharDriverState *chr, const char *filename)
3000 WinCharState *s = chr->opaque;
3001 COMMCONFIG comcfg;
3002 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
3003 COMSTAT comstat;
3004 DWORD size;
3005 DWORD err;
3007 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3008 if (!s->hsend) {
3009 fprintf(stderr, "Failed CreateEvent\n");
3010 goto fail;
3012 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3013 if (!s->hrecv) {
3014 fprintf(stderr, "Failed CreateEvent\n");
3015 goto fail;
3018 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
3019 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
3020 if (s->hcom == INVALID_HANDLE_VALUE) {
3021 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
3022 s->hcom = NULL;
3023 goto fail;
3026 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3027 fprintf(stderr, "Failed SetupComm\n");
3028 goto fail;
3031 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3032 size = sizeof(COMMCONFIG);
3033 GetDefaultCommConfig(filename, &comcfg, &size);
3034 comcfg.dcb.DCBlength = sizeof(DCB);
3035 CommConfigDialog(filename, NULL, &comcfg);
3037 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3038 fprintf(stderr, "Failed SetCommState\n");
3039 goto fail;
3042 if (!SetCommMask(s->hcom, EV_ERR)) {
3043 fprintf(stderr, "Failed SetCommMask\n");
3044 goto fail;
3047 cto.ReadIntervalTimeout = MAXDWORD;
3048 if (!SetCommTimeouts(s->hcom, &cto)) {
3049 fprintf(stderr, "Failed SetCommTimeouts\n");
3050 goto fail;
3053 if (!ClearCommError(s->hcom, &err, &comstat)) {
3054 fprintf(stderr, "Failed ClearCommError\n");
3055 goto fail;
3057 qemu_add_polling_cb(win_chr_poll, chr);
3058 return 0;
3060 fail:
3061 win_chr_close(chr);
3062 return -1;
3065 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3067 WinCharState *s = chr->opaque;
3068 DWORD len, ret, size, err;
3070 len = len1;
3071 ZeroMemory(&s->osend, sizeof(s->osend));
3072 s->osend.hEvent = s->hsend;
3073 while (len > 0) {
3074 if (s->hsend)
3075 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3076 else
3077 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3078 if (!ret) {
3079 err = GetLastError();
3080 if (err == ERROR_IO_PENDING) {
3081 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3082 if (ret) {
3083 buf += size;
3084 len -= size;
3085 } else {
3086 break;
3088 } else {
3089 break;
3091 } else {
3092 buf += size;
3093 len -= size;
3096 return len1 - len;
3099 static int win_chr_read_poll(CharDriverState *chr)
3101 WinCharState *s = chr->opaque;
3103 s->max_size = qemu_chr_can_read(chr);
3104 return s->max_size;
3107 static void win_chr_readfile(CharDriverState *chr)
3109 WinCharState *s = chr->opaque;
3110 int ret, err;
3111 uint8_t buf[1024];
3112 DWORD size;
3114 ZeroMemory(&s->orecv, sizeof(s->orecv));
3115 s->orecv.hEvent = s->hrecv;
3116 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3117 if (!ret) {
3118 err = GetLastError();
3119 if (err == ERROR_IO_PENDING) {
3120 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3124 if (size > 0) {
3125 qemu_chr_read(chr, buf, size);
3129 static void win_chr_read(CharDriverState *chr)
3131 WinCharState *s = chr->opaque;
3133 if (s->len > s->max_size)
3134 s->len = s->max_size;
3135 if (s->len == 0)
3136 return;
3138 win_chr_readfile(chr);
3141 static int win_chr_poll(void *opaque)
3143 CharDriverState *chr = opaque;
3144 WinCharState *s = chr->opaque;
3145 COMSTAT status;
3146 DWORD comerr;
3148 ClearCommError(s->hcom, &comerr, &status);
3149 if (status.cbInQue > 0) {
3150 s->len = status.cbInQue;
3151 win_chr_read_poll(chr);
3152 win_chr_read(chr);
3153 return 1;
3155 return 0;
3158 static CharDriverState *qemu_chr_open_win(const char *filename)
3160 CharDriverState *chr;
3161 WinCharState *s;
3163 chr = qemu_mallocz(sizeof(CharDriverState));
3164 if (!chr)
3165 return NULL;
3166 s = qemu_mallocz(sizeof(WinCharState));
3167 if (!s) {
3168 free(chr);
3169 return NULL;
3171 chr->opaque = s;
3172 chr->chr_write = win_chr_write;
3173 chr->chr_close = win_chr_close;
3175 if (win_chr_init(chr, filename) < 0) {
3176 free(s);
3177 free(chr);
3178 return NULL;
3180 qemu_chr_reset(chr);
3181 return chr;
3184 static int win_chr_pipe_poll(void *opaque)
3186 CharDriverState *chr = opaque;
3187 WinCharState *s = chr->opaque;
3188 DWORD size;
3190 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3191 if (size > 0) {
3192 s->len = size;
3193 win_chr_read_poll(chr);
3194 win_chr_read(chr);
3195 return 1;
3197 return 0;
3200 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3202 WinCharState *s = chr->opaque;
3203 OVERLAPPED ov;
3204 int ret;
3205 DWORD size;
3206 char openname[256];
3208 s->fpipe = TRUE;
3210 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3211 if (!s->hsend) {
3212 fprintf(stderr, "Failed CreateEvent\n");
3213 goto fail;
3215 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3216 if (!s->hrecv) {
3217 fprintf(stderr, "Failed CreateEvent\n");
3218 goto fail;
3221 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3222 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3223 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3224 PIPE_WAIT,
3225 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3226 if (s->hcom == INVALID_HANDLE_VALUE) {
3227 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3228 s->hcom = NULL;
3229 goto fail;
3232 ZeroMemory(&ov, sizeof(ov));
3233 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3234 ret = ConnectNamedPipe(s->hcom, &ov);
3235 if (ret) {
3236 fprintf(stderr, "Failed ConnectNamedPipe\n");
3237 goto fail;
3240 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3241 if (!ret) {
3242 fprintf(stderr, "Failed GetOverlappedResult\n");
3243 if (ov.hEvent) {
3244 CloseHandle(ov.hEvent);
3245 ov.hEvent = NULL;
3247 goto fail;
3250 if (ov.hEvent) {
3251 CloseHandle(ov.hEvent);
3252 ov.hEvent = NULL;
3254 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3255 return 0;
3257 fail:
3258 win_chr_close(chr);
3259 return -1;
3263 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3265 CharDriverState *chr;
3266 WinCharState *s;
3268 chr = qemu_mallocz(sizeof(CharDriverState));
3269 if (!chr)
3270 return NULL;
3271 s = qemu_mallocz(sizeof(WinCharState));
3272 if (!s) {
3273 free(chr);
3274 return NULL;
3276 chr->opaque = s;
3277 chr->chr_write = win_chr_write;
3278 chr->chr_close = win_chr_close;
3280 if (win_chr_pipe_init(chr, filename) < 0) {
3281 free(s);
3282 free(chr);
3283 return NULL;
3285 qemu_chr_reset(chr);
3286 return chr;
3289 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3291 CharDriverState *chr;
3292 WinCharState *s;
3294 chr = qemu_mallocz(sizeof(CharDriverState));
3295 if (!chr)
3296 return NULL;
3297 s = qemu_mallocz(sizeof(WinCharState));
3298 if (!s) {
3299 free(chr);
3300 return NULL;
3302 s->hcom = fd_out;
3303 chr->opaque = s;
3304 chr->chr_write = win_chr_write;
3305 qemu_chr_reset(chr);
3306 return chr;
3309 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3311 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3314 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3316 HANDLE fd_out;
3318 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3319 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3320 if (fd_out == INVALID_HANDLE_VALUE)
3321 return NULL;
3323 return qemu_chr_open_win_file(fd_out);
3325 #endif /* !_WIN32 */
3327 /***********************************************************/
3328 /* UDP Net console */
3330 typedef struct {
3331 int fd;
3332 struct sockaddr_in daddr;
3333 uint8_t buf[1024];
3334 int bufcnt;
3335 int bufptr;
3336 int max_size;
3337 } NetCharDriver;
3339 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3341 NetCharDriver *s = chr->opaque;
3343 return sendto(s->fd, buf, len, 0,
3344 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3347 static int udp_chr_read_poll(void *opaque)
3349 CharDriverState *chr = opaque;
3350 NetCharDriver *s = chr->opaque;
3352 s->max_size = qemu_chr_can_read(chr);
3354 /* If there were any stray characters in the queue process them
3355 * first
3357 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3358 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3359 s->bufptr++;
3360 s->max_size = qemu_chr_can_read(chr);
3362 return s->max_size;
3365 static void udp_chr_read(void *opaque)
3367 CharDriverState *chr = opaque;
3368 NetCharDriver *s = chr->opaque;
3370 if (s->max_size == 0)
3371 return;
3372 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3373 s->bufptr = s->bufcnt;
3374 if (s->bufcnt <= 0)
3375 return;
3377 s->bufptr = 0;
3378 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3379 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3380 s->bufptr++;
3381 s->max_size = qemu_chr_can_read(chr);
3385 static void udp_chr_update_read_handler(CharDriverState *chr)
3387 NetCharDriver *s = chr->opaque;
3389 if (s->fd >= 0) {
3390 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3391 udp_chr_read, NULL, chr);
3395 #ifndef _WIN32
3396 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3397 #endif
3398 int parse_host_src_port(struct sockaddr_in *haddr,
3399 struct sockaddr_in *saddr,
3400 const char *str);
3402 static CharDriverState *qemu_chr_open_udp(const char *def)
3404 CharDriverState *chr = NULL;
3405 NetCharDriver *s = NULL;
3406 int fd = -1;
3407 struct sockaddr_in saddr;
3409 chr = qemu_mallocz(sizeof(CharDriverState));
3410 if (!chr)
3411 goto return_err;
3412 s = qemu_mallocz(sizeof(NetCharDriver));
3413 if (!s)
3414 goto return_err;
3416 fd = socket(PF_INET, SOCK_DGRAM, 0);
3417 if (fd < 0) {
3418 perror("socket(PF_INET, SOCK_DGRAM)");
3419 goto return_err;
3422 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3423 printf("Could not parse: %s\n", def);
3424 goto return_err;
3427 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3429 perror("bind");
3430 goto return_err;
3433 s->fd = fd;
3434 s->bufcnt = 0;
3435 s->bufptr = 0;
3436 chr->opaque = s;
3437 chr->chr_write = udp_chr_write;
3438 chr->chr_update_read_handler = udp_chr_update_read_handler;
3439 return chr;
3441 return_err:
3442 if (chr)
3443 free(chr);
3444 if (s)
3445 free(s);
3446 if (fd >= 0)
3447 closesocket(fd);
3448 return NULL;
3451 /***********************************************************/
3452 /* TCP Net console */
3454 typedef struct {
3455 int fd, listen_fd;
3456 int connected;
3457 int max_size;
3458 int do_telnetopt;
3459 int do_nodelay;
3460 int is_unix;
3461 } TCPCharDriver;
3463 static void tcp_chr_accept(void *opaque);
3465 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3467 TCPCharDriver *s = chr->opaque;
3468 if (s->connected) {
3469 return send_all(s->fd, buf, len);
3470 } else {
3471 /* XXX: indicate an error ? */
3472 return len;
3476 static int tcp_chr_read_poll(void *opaque)
3478 CharDriverState *chr = opaque;
3479 TCPCharDriver *s = chr->opaque;
3480 if (!s->connected)
3481 return 0;
3482 s->max_size = qemu_chr_can_read(chr);
3483 return s->max_size;
3486 #define IAC 255
3487 #define IAC_BREAK 243
3488 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3489 TCPCharDriver *s,
3490 uint8_t *buf, int *size)
3492 /* Handle any telnet client's basic IAC options to satisfy char by
3493 * char mode with no echo. All IAC options will be removed from
3494 * the buf and the do_telnetopt variable will be used to track the
3495 * state of the width of the IAC information.
3497 * IAC commands come in sets of 3 bytes with the exception of the
3498 * "IAC BREAK" command and the double IAC.
3501 int i;
3502 int j = 0;
3504 for (i = 0; i < *size; i++) {
3505 if (s->do_telnetopt > 1) {
3506 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3507 /* Double IAC means send an IAC */
3508 if (j != i)
3509 buf[j] = buf[i];
3510 j++;
3511 s->do_telnetopt = 1;
3512 } else {
3513 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3514 /* Handle IAC break commands by sending a serial break */
3515 qemu_chr_event(chr, CHR_EVENT_BREAK);
3516 s->do_telnetopt++;
3518 s->do_telnetopt++;
3520 if (s->do_telnetopt >= 4) {
3521 s->do_telnetopt = 1;
3523 } else {
3524 if ((unsigned char)buf[i] == IAC) {
3525 s->do_telnetopt = 2;
3526 } else {
3527 if (j != i)
3528 buf[j] = buf[i];
3529 j++;
3533 *size = j;
3536 static void tcp_chr_read(void *opaque)
3538 CharDriverState *chr = opaque;
3539 TCPCharDriver *s = chr->opaque;
3540 uint8_t buf[1024];
3541 int len, size;
3543 if (!s->connected || s->max_size <= 0)
3544 return;
3545 len = sizeof(buf);
3546 if (len > s->max_size)
3547 len = s->max_size;
3548 size = recv(s->fd, buf, len, 0);
3549 if (size == 0) {
3550 /* connection closed */
3551 s->connected = 0;
3552 if (s->listen_fd >= 0) {
3553 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3555 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3556 closesocket(s->fd);
3557 s->fd = -1;
3558 } else if (size > 0) {
3559 if (s->do_telnetopt)
3560 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3561 if (size > 0)
3562 qemu_chr_read(chr, buf, size);
3566 static void tcp_chr_connect(void *opaque)
3568 CharDriverState *chr = opaque;
3569 TCPCharDriver *s = chr->opaque;
3571 s->connected = 1;
3572 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3573 tcp_chr_read, NULL, chr);
3574 qemu_chr_reset(chr);
3577 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3578 static void tcp_chr_telnet_init(int fd)
3580 char buf[3];
3581 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3582 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3583 send(fd, (char *)buf, 3, 0);
3584 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3585 send(fd, (char *)buf, 3, 0);
3586 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3587 send(fd, (char *)buf, 3, 0);
3588 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3589 send(fd, (char *)buf, 3, 0);
3592 static void socket_set_nodelay(int fd)
3594 int val = 1;
3595 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3598 static void tcp_chr_accept(void *opaque)
3600 CharDriverState *chr = opaque;
3601 TCPCharDriver *s = chr->opaque;
3602 struct sockaddr_in saddr;
3603 #ifndef _WIN32
3604 struct sockaddr_un uaddr;
3605 #endif
3606 struct sockaddr *addr;
3607 socklen_t len;
3608 int fd;
3610 for(;;) {
3611 #ifndef _WIN32
3612 if (s->is_unix) {
3613 len = sizeof(uaddr);
3614 addr = (struct sockaddr *)&uaddr;
3615 } else
3616 #endif
3618 len = sizeof(saddr);
3619 addr = (struct sockaddr *)&saddr;
3621 fd = accept(s->listen_fd, addr, &len);
3622 if (fd < 0 && errno != EINTR) {
3623 return;
3624 } else if (fd >= 0) {
3625 if (s->do_telnetopt)
3626 tcp_chr_telnet_init(fd);
3627 break;
3630 socket_set_nonblock(fd);
3631 if (s->do_nodelay)
3632 socket_set_nodelay(fd);
3633 s->fd = fd;
3634 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3635 tcp_chr_connect(chr);
3638 static void tcp_chr_close(CharDriverState *chr)
3640 TCPCharDriver *s = chr->opaque;
3641 if (s->fd >= 0)
3642 closesocket(s->fd);
3643 if (s->listen_fd >= 0)
3644 closesocket(s->listen_fd);
3645 qemu_free(s);
3648 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3649 int is_telnet,
3650 int is_unix)
3652 CharDriverState *chr = NULL;
3653 TCPCharDriver *s = NULL;
3654 int fd = -1, ret, err, val;
3655 int is_listen = 0;
3656 int is_waitconnect = 1;
3657 int do_nodelay = 0;
3658 const char *ptr;
3659 struct sockaddr_in saddr;
3660 #ifndef _WIN32
3661 struct sockaddr_un uaddr;
3662 #endif
3663 struct sockaddr *addr;
3664 socklen_t addrlen;
3666 #ifndef _WIN32
3667 if (is_unix) {
3668 addr = (struct sockaddr *)&uaddr;
3669 addrlen = sizeof(uaddr);
3670 if (parse_unix_path(&uaddr, host_str) < 0)
3671 goto fail;
3672 } else
3673 #endif
3675 addr = (struct sockaddr *)&saddr;
3676 addrlen = sizeof(saddr);
3677 if (parse_host_port(&saddr, host_str) < 0)
3678 goto fail;
3681 ptr = host_str;
3682 while((ptr = strchr(ptr,','))) {
3683 ptr++;
3684 if (!strncmp(ptr,"server",6)) {
3685 is_listen = 1;
3686 } else if (!strncmp(ptr,"nowait",6)) {
3687 is_waitconnect = 0;
3688 } else if (!strncmp(ptr,"nodelay",6)) {
3689 do_nodelay = 1;
3690 } else {
3691 printf("Unknown option: %s\n", ptr);
3692 goto fail;
3695 if (!is_listen)
3696 is_waitconnect = 0;
3698 chr = qemu_mallocz(sizeof(CharDriverState));
3699 if (!chr)
3700 goto fail;
3701 s = qemu_mallocz(sizeof(TCPCharDriver));
3702 if (!s)
3703 goto fail;
3705 #ifndef _WIN32
3706 if (is_unix)
3707 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3708 else
3709 #endif
3710 fd = socket(PF_INET, SOCK_STREAM, 0);
3712 if (fd < 0)
3713 goto fail;
3715 if (!is_waitconnect)
3716 socket_set_nonblock(fd);
3718 s->connected = 0;
3719 s->fd = -1;
3720 s->listen_fd = -1;
3721 s->is_unix = is_unix;
3722 s->do_nodelay = do_nodelay && !is_unix;
3724 chr->opaque = s;
3725 chr->chr_write = tcp_chr_write;
3726 chr->chr_close = tcp_chr_close;
3728 if (is_listen) {
3729 /* allow fast reuse */
3730 #ifndef _WIN32
3731 if (is_unix) {
3732 char path[109];
3733 pstrcpy(path, sizeof(path), uaddr.sun_path);
3734 unlink(path);
3735 } else
3736 #endif
3738 val = 1;
3739 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3742 ret = bind(fd, addr, addrlen);
3743 if (ret < 0)
3744 goto fail;
3746 ret = listen(fd, 0);
3747 if (ret < 0)
3748 goto fail;
3750 s->listen_fd = fd;
3751 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3752 if (is_telnet)
3753 s->do_telnetopt = 1;
3754 } else {
3755 for(;;) {
3756 ret = connect(fd, addr, addrlen);
3757 if (ret < 0) {
3758 err = socket_error();
3759 if (err == EINTR || err == EWOULDBLOCK) {
3760 } else if (err == EINPROGRESS) {
3761 break;
3762 #ifdef _WIN32
3763 } else if (err == WSAEALREADY) {
3764 break;
3765 #endif
3766 } else {
3767 goto fail;
3769 } else {
3770 s->connected = 1;
3771 break;
3774 s->fd = fd;
3775 socket_set_nodelay(fd);
3776 if (s->connected)
3777 tcp_chr_connect(chr);
3778 else
3779 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3782 if (is_listen && is_waitconnect) {
3783 printf("QEMU waiting for connection on: %s\n", host_str);
3784 tcp_chr_accept(chr);
3785 socket_set_nonblock(s->listen_fd);
3788 return chr;
3789 fail:
3790 if (fd >= 0)
3791 closesocket(fd);
3792 qemu_free(s);
3793 qemu_free(chr);
3794 return NULL;
3797 CharDriverState *qemu_chr_open(const char *filename)
3799 const char *p;
3801 if (!strcmp(filename, "vc")) {
3802 return text_console_init(&display_state, 0);
3803 } else if (strstart(filename, "vc:", &p)) {
3804 return text_console_init(&display_state, p);
3805 } else if (!strcmp(filename, "null")) {
3806 return qemu_chr_open_null();
3807 } else
3808 if (strstart(filename, "tcp:", &p)) {
3809 return qemu_chr_open_tcp(p, 0, 0);
3810 } else
3811 if (strstart(filename, "telnet:", &p)) {
3812 return qemu_chr_open_tcp(p, 1, 0);
3813 } else
3814 if (strstart(filename, "udp:", &p)) {
3815 return qemu_chr_open_udp(p);
3816 } else
3817 if (strstart(filename, "mon:", &p)) {
3818 CharDriverState *drv = qemu_chr_open(p);
3819 if (drv) {
3820 drv = qemu_chr_open_mux(drv);
3821 monitor_init(drv, !nographic);
3822 return drv;
3824 printf("Unable to open driver: %s\n", p);
3825 return 0;
3826 } else
3827 #ifndef _WIN32
3828 if (strstart(filename, "unix:", &p)) {
3829 return qemu_chr_open_tcp(p, 0, 1);
3830 } else if (strstart(filename, "file:", &p)) {
3831 return qemu_chr_open_file_out(p);
3832 } else if (strstart(filename, "pipe:", &p)) {
3833 return qemu_chr_open_pipe(p);
3834 } else if (!strcmp(filename, "pty")) {
3835 return qemu_chr_open_pty();
3836 } else if (!strcmp(filename, "stdio")) {
3837 return qemu_chr_open_stdio();
3838 } else
3839 #if defined(__linux__)
3840 if (strstart(filename, "/dev/parport", NULL)) {
3841 return qemu_chr_open_pp(filename);
3842 } else
3843 #endif
3844 #if defined(__linux__) || defined(__sun__)
3845 if (strstart(filename, "/dev/", NULL)) {
3846 return qemu_chr_open_tty(filename);
3847 } else
3848 #endif
3849 #else /* !_WIN32 */
3850 if (strstart(filename, "COM", NULL)) {
3851 return qemu_chr_open_win(filename);
3852 } else
3853 if (strstart(filename, "pipe:", &p)) {
3854 return qemu_chr_open_win_pipe(p);
3855 } else
3856 if (strstart(filename, "con:", NULL)) {
3857 return qemu_chr_open_win_con(filename);
3858 } else
3859 if (strstart(filename, "file:", &p)) {
3860 return qemu_chr_open_win_file_out(p);
3861 } else
3862 #endif
3863 #ifdef CONFIG_BRLAPI
3864 if (!strcmp(filename, "braille")) {
3865 return chr_baum_init();
3866 } else
3867 #endif
3869 return NULL;
3873 void qemu_chr_close(CharDriverState *chr)
3875 if (chr->chr_close)
3876 chr->chr_close(chr);
3877 qemu_free(chr);
3880 /***********************************************************/
3881 /* network device redirectors */
3883 __attribute__ (( unused ))
3884 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3886 int len, i, j, c;
3888 for(i=0;i<size;i+=16) {
3889 len = size - i;
3890 if (len > 16)
3891 len = 16;
3892 fprintf(f, "%08x ", i);
3893 for(j=0;j<16;j++) {
3894 if (j < len)
3895 fprintf(f, " %02x", buf[i+j]);
3896 else
3897 fprintf(f, " ");
3899 fprintf(f, " ");
3900 for(j=0;j<len;j++) {
3901 c = buf[i+j];
3902 if (c < ' ' || c > '~')
3903 c = '.';
3904 fprintf(f, "%c", c);
3906 fprintf(f, "\n");
3910 static int parse_macaddr(uint8_t *macaddr, const char *p)
3912 int i;
3913 char *last_char;
3914 long int offset;
3916 errno = 0;
3917 offset = strtol(p, &last_char, 0);
3918 if (0 == errno && '\0' == *last_char &&
3919 offset >= 0 && offset <= 0xFFFFFF) {
3920 macaddr[3] = (offset & 0xFF0000) >> 16;
3921 macaddr[4] = (offset & 0xFF00) >> 8;
3922 macaddr[5] = offset & 0xFF;
3923 return 0;
3924 } else {
3925 for(i = 0; i < 6; i++) {
3926 macaddr[i] = strtol(p, (char **)&p, 16);
3927 if (i == 5) {
3928 if (*p != '\0')
3929 return -1;
3930 } else {
3931 if (*p != ':' && *p != '-')
3932 return -1;
3933 p++;
3936 return 0;
3939 return -1;
3942 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3944 const char *p, *p1;
3945 int len;
3946 p = *pp;
3947 p1 = strchr(p, sep);
3948 if (!p1)
3949 return -1;
3950 len = p1 - p;
3951 p1++;
3952 if (buf_size > 0) {
3953 if (len > buf_size - 1)
3954 len = buf_size - 1;
3955 memcpy(buf, p, len);
3956 buf[len] = '\0';
3958 *pp = p1;
3959 return 0;
3962 int parse_host_src_port(struct sockaddr_in *haddr,
3963 struct sockaddr_in *saddr,
3964 const char *input_str)
3966 char *str = strdup(input_str);
3967 char *host_str = str;
3968 char *src_str;
3969 char *ptr;
3972 * Chop off any extra arguments at the end of the string which
3973 * would start with a comma, then fill in the src port information
3974 * if it was provided else use the "any address" and "any port".
3976 if ((ptr = strchr(str,',')))
3977 *ptr = '\0';
3979 if ((src_str = strchr(input_str,'@'))) {
3980 *src_str = '\0';
3981 src_str++;
3984 if (parse_host_port(haddr, host_str) < 0)
3985 goto fail;
3987 if (!src_str || *src_str == '\0')
3988 src_str = ":0";
3990 if (parse_host_port(saddr, src_str) < 0)
3991 goto fail;
3993 free(str);
3994 return(0);
3996 fail:
3997 free(str);
3998 return -1;
4001 int parse_host_port(struct sockaddr_in *saddr, const char *str)
4003 char buf[512];
4004 struct hostent *he;
4005 const char *p, *r;
4006 int port;
4008 p = str;
4009 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4010 return -1;
4011 saddr->sin_family = AF_INET;
4012 if (buf[0] == '\0') {
4013 saddr->sin_addr.s_addr = 0;
4014 } else {
4015 if (isdigit(buf[0])) {
4016 if (!inet_aton(buf, &saddr->sin_addr))
4017 return -1;
4018 } else {
4019 if ((he = gethostbyname(buf)) == NULL)
4020 return - 1;
4021 saddr->sin_addr = *(struct in_addr *)he->h_addr;
4024 port = strtol(p, (char **)&r, 0);
4025 if (r == p)
4026 return -1;
4027 saddr->sin_port = htons(port);
4028 return 0;
4031 #ifndef _WIN32
4032 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4034 const char *p;
4035 int len;
4037 len = MIN(108, strlen(str));
4038 p = strchr(str, ',');
4039 if (p)
4040 len = MIN(len, p - str);
4042 memset(uaddr, 0, sizeof(*uaddr));
4044 uaddr->sun_family = AF_UNIX;
4045 memcpy(uaddr->sun_path, str, len);
4047 return 0;
4049 #endif
4051 /* find or alloc a new VLAN */
4052 VLANState *qemu_find_vlan(int id)
4054 VLANState **pvlan, *vlan;
4055 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4056 if (vlan->id == id)
4057 return vlan;
4059 vlan = qemu_mallocz(sizeof(VLANState));
4060 if (!vlan)
4061 return NULL;
4062 vlan->id = id;
4063 vlan->next = NULL;
4064 pvlan = &first_vlan;
4065 while (*pvlan != NULL)
4066 pvlan = &(*pvlan)->next;
4067 *pvlan = vlan;
4068 return vlan;
4071 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4072 IOReadHandler *fd_read,
4073 IOCanRWHandler *fd_can_read,
4074 void *opaque)
4076 VLANClientState *vc, **pvc;
4077 vc = qemu_mallocz(sizeof(VLANClientState));
4078 if (!vc)
4079 return NULL;
4080 vc->fd_read = fd_read;
4081 vc->fd_can_read = fd_can_read;
4082 vc->opaque = opaque;
4083 vc->vlan = vlan;
4085 vc->next = NULL;
4086 pvc = &vlan->first_client;
4087 while (*pvc != NULL)
4088 pvc = &(*pvc)->next;
4089 *pvc = vc;
4090 return vc;
4093 void qemu_del_vlan_client(VLANClientState *vc)
4095 VLANClientState **pvc = &vc->vlan->first_client;
4097 while (*pvc != NULL)
4098 if (*pvc == vc) {
4099 *pvc = vc->next;
4100 free(vc);
4101 break;
4102 } else
4103 pvc = &(*pvc)->next;
4106 int qemu_can_send_packet(VLANClientState *vc1)
4108 VLANState *vlan = vc1->vlan;
4109 VLANClientState *vc;
4111 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4112 if (vc != vc1) {
4113 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4114 return 1;
4117 return 0;
4120 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4122 VLANState *vlan = vc1->vlan;
4123 VLANClientState *vc;
4124 int ret = -EAGAIN;
4126 #if 0
4127 printf("vlan %d send:\n", vlan->id);
4128 hex_dump(stdout, buf, size);
4129 #endif
4130 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4131 if (vc != vc1) {
4132 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
4133 vc->fd_read(vc->opaque, buf, size);
4134 ret = 0;
4139 return ret;
4142 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
4143 int iovcnt)
4145 char buffer[4096];
4146 size_t offset = 0;
4147 int i;
4149 for (i = 0; i < iovcnt; i++) {
4150 size_t len;
4152 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
4153 memcpy(buffer + offset, iov[i].iov_base, len);
4154 offset += len;
4157 vc->fd_read(vc->opaque, buffer, offset);
4159 return offset;
4162 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
4163 int iovcnt)
4165 VLANState *vlan = vc1->vlan;
4166 VLANClientState *vc;
4167 ssize_t max_len = 0;
4169 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
4170 ssize_t len = 0;
4172 if (vc == vc1)
4173 continue;
4175 if (vc->fd_readv)
4176 len = vc->fd_readv(vc->opaque, iov, iovcnt);
4177 else if (vc->fd_read)
4178 len = vc_sendv_compat(vc, iov, iovcnt);
4180 max_len = MAX(max_len, len);
4183 return max_len;
4186 #if defined(CONFIG_SLIRP)
4188 /* slirp network adapter */
4190 static int slirp_inited;
4191 static VLANClientState *slirp_vc;
4193 int slirp_can_output(void)
4195 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4198 void slirp_output(const uint8_t *pkt, int pkt_len)
4200 #if 0
4201 printf("slirp output:\n");
4202 hex_dump(stdout, pkt, pkt_len);
4203 #endif
4204 if (!slirp_vc)
4205 return;
4206 qemu_send_packet(slirp_vc, pkt, pkt_len);
4209 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4211 #if 0
4212 printf("slirp input:\n");
4213 hex_dump(stdout, buf, size);
4214 #endif
4215 slirp_input(buf, size);
4218 static int net_slirp_init(VLANState *vlan)
4220 if (!slirp_inited) {
4221 slirp_inited = 1;
4222 slirp_init();
4224 slirp_vc = qemu_new_vlan_client(vlan,
4225 slirp_receive, NULL, NULL);
4226 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4227 return 0;
4230 static void net_slirp_redir(const char *redir_str)
4232 int is_udp;
4233 char buf[256], *r;
4234 const char *p;
4235 struct in_addr guest_addr;
4236 int host_port, guest_port;
4238 if (!slirp_inited) {
4239 slirp_inited = 1;
4240 slirp_init();
4243 p = redir_str;
4244 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4245 goto fail;
4246 if (!strcmp(buf, "tcp")) {
4247 is_udp = 0;
4248 } else if (!strcmp(buf, "udp")) {
4249 is_udp = 1;
4250 } else {
4251 goto fail;
4254 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4255 goto fail;
4256 host_port = strtol(buf, &r, 0);
4257 if (r == buf)
4258 goto fail;
4260 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4261 goto fail;
4262 if (buf[0] == '\0') {
4263 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4265 if (!inet_aton(buf, &guest_addr))
4266 goto fail;
4268 guest_port = strtol(p, &r, 0);
4269 if (r == p)
4270 goto fail;
4272 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4273 fprintf(stderr, "qemu: could not set up redirection\n");
4274 exit(1);
4276 return;
4277 fail:
4278 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4279 exit(1);
4282 #ifndef _WIN32
4284 char smb_dir[1024];
4286 static void erase_dir(char *dir_name)
4288 DIR *d;
4289 struct dirent *de;
4290 char filename[1024];
4292 /* erase all the files in the directory */
4293 if ((d = opendir(dir_name)) != 0) {
4294 for(;;) {
4295 de = readdir(d);
4296 if (!de)
4297 break;
4298 if (strcmp(de->d_name, ".") != 0 &&
4299 strcmp(de->d_name, "..") != 0) {
4300 snprintf(filename, sizeof(filename), "%s/%s",
4301 smb_dir, de->d_name);
4302 if (unlink(filename) != 0) /* is it a directory? */
4303 erase_dir(filename);
4306 closedir(d);
4307 rmdir(dir_name);
4311 /* automatic user mode samba server configuration */
4312 static void smb_exit(void)
4314 erase_dir(smb_dir);
4317 /* automatic user mode samba server configuration */
4318 static void net_slirp_smb(const char *exported_dir)
4320 char smb_conf[1024];
4321 char smb_cmdline[1024];
4322 FILE *f;
4324 if (!slirp_inited) {
4325 slirp_inited = 1;
4326 slirp_init();
4329 /* XXX: better tmp dir construction */
4330 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4331 if (mkdir(smb_dir, 0700) < 0) {
4332 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4333 exit(1);
4335 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4337 f = fopen(smb_conf, "w");
4338 if (!f) {
4339 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4340 exit(1);
4342 fprintf(f,
4343 "[global]\n"
4344 "private dir=%s\n"
4345 "smb ports=0\n"
4346 "socket address=127.0.0.1\n"
4347 "pid directory=%s\n"
4348 "lock directory=%s\n"
4349 "log file=%s/log.smbd\n"
4350 "smb passwd file=%s/smbpasswd\n"
4351 "security = share\n"
4352 "[qemu]\n"
4353 "path=%s\n"
4354 "read only=no\n"
4355 "guest ok=yes\n",
4356 smb_dir,
4357 smb_dir,
4358 smb_dir,
4359 smb_dir,
4360 smb_dir,
4361 exported_dir
4363 fclose(f);
4364 atexit(smb_exit);
4366 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4367 SMBD_COMMAND, smb_conf);
4369 slirp_add_exec(0, smb_cmdline, 4, 139);
4372 #endif /* !defined(_WIN32) */
4373 void do_info_slirp(void)
4375 slirp_stats();
4378 #endif /* CONFIG_SLIRP */
4380 #ifdef _WIN32
4382 int tap_has_vnet_hdr(void *opaque)
4384 return 0;
4387 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
4391 #else /* !defined(_WIN32) */
4393 #ifndef IFF_VNET_HDR
4394 #define TAP_BUFSIZE 4096
4395 #else
4396 #include <linux/virtio_net.h>
4397 #define ETH_HLEN 14
4398 #define ETH_DATA_LEN 1500
4399 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4400 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4401 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4402 #endif
4404 typedef struct TAPState {
4405 VLANClientState *vc;
4406 int fd;
4407 char down_script[1024];
4408 char buf[TAP_BUFSIZE];
4409 int size;
4410 unsigned int has_vnet_hdr : 1;
4411 unsigned int using_vnet_hdr : 1;
4412 } TAPState;
4414 static ssize_t tap_writev(void *opaque, const struct iovec *iov,
4415 int iovcnt)
4417 TAPState *s = opaque;
4418 ssize_t len;
4420 do {
4421 len = writev(s->fd, iov, iovcnt);
4422 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
4424 return len;
4427 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
4428 int iovcnt)
4430 #ifdef IFF_VNET_HDR
4431 TAPState *s = opaque;
4433 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4434 struct iovec *iov_copy;
4435 struct virtio_net_hdr hdr = { 0, };
4437 iov_copy = alloca(sizeof(struct iovec) * (iovcnt + 1));
4439 iov_copy[0].iov_base = &hdr;
4440 iov_copy[0].iov_len = sizeof(hdr);
4442 memcpy(&iov_copy[1], iov, sizeof(struct iovec) * iovcnt);
4444 return tap_writev(opaque, iov_copy, iovcnt + 1);
4446 #endif
4448 return tap_writev(opaque, iov, iovcnt);
4451 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4453 struct iovec iov[2];
4454 int i = 0;
4456 #ifdef IFF_VNET_HDR
4457 TAPState *s = opaque;
4458 struct virtio_net_hdr hdr = { 0, };
4460 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4461 iov[i].iov_base = &hdr;
4462 iov[i].iov_len = sizeof(hdr);
4463 i++;
4465 #endif
4467 iov[i].iov_base = (char *) buf;
4468 iov[i].iov_len = size;
4469 i++;
4471 tap_writev(opaque, iov, i);
4474 static int tap_can_send(void *opaque)
4476 TAPState *s = opaque;
4477 VLANClientState *vc;
4478 int can_receive = 0;
4480 /* Check to see if any of our clients can receive a packet */
4481 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
4482 /* Skip ourselves */
4483 if (vc == s->vc)
4484 continue;
4486 if (!vc->fd_can_read) {
4487 /* no fd_can_read handler, they always can receive */
4488 can_receive = 1;
4489 } else
4490 can_receive = vc->fd_can_read(vc->opaque);
4492 /* Once someone can receive, we try to send a packet */
4493 if (can_receive)
4494 break;
4497 return can_receive;
4500 static int tap_send_packet(TAPState *s)
4502 uint8_t *buf = s->buf;
4503 int size = s->size;
4505 #ifdef IFF_VNET_HDR
4506 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4507 buf += sizeof(struct virtio_net_hdr);
4508 size -= sizeof(struct virtio_net_hdr);
4510 #endif
4512 return qemu_send_packet(s->vc, buf, size);
4515 static void tap_send(void *opaque)
4517 TAPState *s = opaque;
4519 /* First try to send any buffered packet */
4520 if (s->size > 0) {
4521 int err;
4523 /* If noone can receive the packet, buffer it */
4524 err = tap_send_packet(s);
4525 if (err == -EAGAIN)
4526 return;
4529 /* Read packets until we hit EAGAIN */
4530 do {
4531 #ifdef __sun__
4532 struct strbuf sbuf;
4533 int f = 0;
4534 sbuf.maxlen = sizeof(s->buf);
4535 sbuf.buf = s->buf;
4536 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4537 #else
4538 kvm_sleep_begin();
4539 s->size = read(s->fd, s->buf, sizeof(s->buf));
4540 kvm_sleep_end();
4541 #endif
4543 if (s->size == -1 && errno == EINTR)
4544 continue;
4546 if (s->size > 0) {
4547 int err;
4549 /* If noone can receive the packet, buffer it */
4550 err = tap_send_packet(s);
4551 if (err == -EAGAIN)
4552 break;
4554 } while (s->size > 0);
4557 int tap_has_vnet_hdr(void *opaque)
4559 VLANClientState *vc = opaque;
4560 TAPState *s = vc->opaque;
4562 return s ? s->has_vnet_hdr : 0;
4565 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
4567 VLANClientState *vc = opaque;
4568 TAPState *s = vc->opaque;
4570 if (!s || !s->has_vnet_hdr)
4571 return;
4573 s->using_vnet_hdr = using_vnet_hdr != 0;
4576 static int tap_probe_vnet_hdr(int fd)
4578 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
4579 struct ifreq ifr;
4581 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
4582 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
4583 return 0;
4586 return ifr.ifr_flags & IFF_VNET_HDR;
4587 #else
4588 return 0;
4589 #endif
4592 #ifdef TUNSETOFFLOAD
4593 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
4594 int ecn)
4596 TAPState *s = vc->opaque;
4597 unsigned int offload = 0;
4599 if (csum) {
4600 offload |= TUN_F_CSUM;
4601 if (tso4)
4602 offload |= TUN_F_TSO4;
4603 if (tso6)
4604 offload |= TUN_F_TSO6;
4605 if ((tso4 || tso6) && ecn)
4606 offload |= TUN_F_TSO_ECN;
4609 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
4610 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
4611 strerror(errno));
4613 #endif /* TUNSETOFFLOAD */
4615 /* fd support */
4617 static TAPState *net_tap_fd_init(VLANState *vlan, int fd, int vnet_hdr)
4619 TAPState *s;
4621 s = qemu_mallocz(sizeof(TAPState));
4622 if (!s)
4623 return NULL;
4624 s->fd = fd;
4625 s->has_vnet_hdr = vnet_hdr != 0;
4626 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4627 s->vc->fd_readv = tap_receive_iov;
4628 #ifdef TUNSETOFFLOAD
4629 s->vc->set_offload = tap_set_offload;
4630 #endif
4631 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
4632 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4633 return s;
4636 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4637 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4639 int fd;
4640 char *dev;
4641 struct stat s;
4643 TFR(fd = open("/dev/tap", O_RDWR));
4644 if (fd < 0) {
4645 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4646 return -1;
4649 fstat(fd, &s);
4650 dev = devname(s.st_rdev, S_IFCHR);
4651 pstrcpy(ifname, ifname_size, dev);
4653 fcntl(fd, F_SETFL, O_NONBLOCK);
4654 return fd;
4656 #elif defined(__sun__)
4657 #define TUNNEWPPA (('T'<<16) | 0x0001)
4659 * Allocate TAP device, returns opened fd.
4660 * Stores dev name in the first arg(must be large enough).
4662 int tap_alloc(char *dev, size_t dev_size)
4664 int tap_fd, if_fd, ppa = -1;
4665 static int ip_fd = 0;
4666 char *ptr;
4668 static int arp_fd = 0;
4669 int ip_muxid, arp_muxid;
4670 struct strioctl strioc_if, strioc_ppa;
4671 int link_type = I_PLINK;;
4672 struct lifreq ifr;
4673 char actual_name[32] = "";
4675 memset(&ifr, 0x0, sizeof(ifr));
4677 if( *dev ){
4678 ptr = dev;
4679 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4680 ppa = atoi(ptr);
4683 /* Check if IP device was opened */
4684 if( ip_fd )
4685 close(ip_fd);
4687 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4688 if (ip_fd < 0) {
4689 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4690 return -1;
4693 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4694 if (tap_fd < 0) {
4695 syslog(LOG_ERR, "Can't open /dev/tap");
4696 return -1;
4699 /* Assign a new PPA and get its unit number. */
4700 strioc_ppa.ic_cmd = TUNNEWPPA;
4701 strioc_ppa.ic_timout = 0;
4702 strioc_ppa.ic_len = sizeof(ppa);
4703 strioc_ppa.ic_dp = (char *)&ppa;
4704 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4705 syslog (LOG_ERR, "Can't assign new interface");
4707 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4708 if (if_fd < 0) {
4709 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4710 return -1;
4712 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4713 syslog(LOG_ERR, "Can't push IP module");
4714 return -1;
4717 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4718 syslog(LOG_ERR, "Can't get flags\n");
4720 snprintf (actual_name, 32, "tap%d", ppa);
4721 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4723 ifr.lifr_ppa = ppa;
4724 /* Assign ppa according to the unit number returned by tun device */
4726 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4727 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4728 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4729 syslog (LOG_ERR, "Can't get flags\n");
4730 /* Push arp module to if_fd */
4731 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4732 syslog (LOG_ERR, "Can't push ARP module (2)");
4734 /* Push arp module to ip_fd */
4735 if (ioctl (ip_fd, I_POP, NULL) < 0)
4736 syslog (LOG_ERR, "I_POP failed\n");
4737 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4738 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4739 /* Open arp_fd */
4740 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4741 if (arp_fd < 0)
4742 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4744 /* Set ifname to arp */
4745 strioc_if.ic_cmd = SIOCSLIFNAME;
4746 strioc_if.ic_timout = 0;
4747 strioc_if.ic_len = sizeof(ifr);
4748 strioc_if.ic_dp = (char *)&ifr;
4749 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4750 syslog (LOG_ERR, "Can't set ifname to arp\n");
4753 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4754 syslog(LOG_ERR, "Can't link TAP device to IP");
4755 return -1;
4758 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4759 syslog (LOG_ERR, "Can't link TAP device to ARP");
4761 close (if_fd);
4763 memset(&ifr, 0x0, sizeof(ifr));
4764 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4765 ifr.lifr_ip_muxid = ip_muxid;
4766 ifr.lifr_arp_muxid = arp_muxid;
4768 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4770 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4771 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4772 syslog (LOG_ERR, "Can't set multiplexor id");
4775 snprintf(dev, dev_size, "tap%d", ppa);
4776 return tap_fd;
4779 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4781 char dev[10]="";
4782 int fd;
4783 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4784 fprintf(stderr, "Cannot allocate TAP device\n");
4785 return -1;
4787 pstrcpy(ifname, ifname_size, dev);
4788 fcntl(fd, F_SETFL, O_NONBLOCK);
4789 return fd;
4791 #else
4792 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4794 struct ifreq ifr;
4795 int fd, ret;
4797 TFR(fd = open("/dev/net/tun", O_RDWR));
4798 if (fd < 0) {
4799 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4800 return -1;
4802 memset(&ifr, 0, sizeof(ifr));
4803 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4805 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4807 unsigned int features;
4809 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
4810 features & IFF_VNET_HDR) {
4811 *vnet_hdr = 1;
4812 ifr.ifr_flags |= IFF_VNET_HDR;
4815 #endif
4817 if (ifname[0] != '\0')
4818 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4819 else
4820 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4821 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4822 if (ret != 0) {
4823 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4824 close(fd);
4825 return -1;
4827 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4828 fcntl(fd, F_SETFL, O_NONBLOCK);
4829 return fd;
4831 #endif
4833 static int launch_script(const char *setup_script, const char *ifname, int fd)
4835 int pid, status;
4836 char *args[3];
4837 char **parg;
4839 /* try to launch network script */
4840 pid = fork();
4841 if (pid >= 0) {
4842 if (pid == 0) {
4843 int open_max = sysconf (_SC_OPEN_MAX), i;
4844 for (i = 0; i < open_max; i++)
4845 if (i != STDIN_FILENO &&
4846 i != STDOUT_FILENO &&
4847 i != STDERR_FILENO &&
4848 i != fd)
4849 close(i);
4851 parg = args;
4852 *parg++ = (char *)setup_script;
4853 *parg++ = (char *)ifname;
4854 *parg++ = NULL;
4855 execv(setup_script, args);
4856 _exit(1);
4858 while (waitpid(pid, &status, 0) != pid);
4859 if (!WIFEXITED(status) ||
4860 WEXITSTATUS(status) != 0) {
4861 fprintf(stderr, "%s: could not launch network script\n",
4862 setup_script);
4863 return -1;
4866 return 0;
4869 static int net_tap_init(VLANState *vlan, const char *ifname1,
4870 const char *setup_script, const char *down_script)
4872 TAPState *s;
4873 int fd;
4874 int vnet_hdr;
4875 char ifname[128];
4877 if (ifname1 != NULL)
4878 pstrcpy(ifname, sizeof(ifname), ifname1);
4879 else
4880 ifname[0] = '\0';
4881 vnet_hdr = 0;
4882 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
4883 if (fd < 0)
4884 return -1;
4886 if (!setup_script || !strcmp(setup_script, "no"))
4887 setup_script = "";
4888 if (setup_script[0] != '\0') {
4889 if (launch_script(setup_script, ifname, fd))
4890 return -1;
4892 s = net_tap_fd_init(vlan, fd, vnet_hdr);
4893 if (!s)
4894 return -1;
4896 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4897 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4898 if (down_script && strcmp(down_script, "no"))
4899 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4900 return 0;
4903 #endif /* !_WIN32 */
4905 #if defined(CONFIG_VDE)
4906 typedef struct VDEState {
4907 VLANClientState *vc;
4908 VDECONN *vde;
4909 } VDEState;
4911 static void vde_to_qemu(void *opaque)
4913 VDEState *s = opaque;
4914 uint8_t buf[4096];
4915 int size;
4917 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4918 if (size > 0) {
4919 qemu_send_packet(s->vc, buf, size);
4923 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4925 VDEState *s = opaque;
4926 int ret;
4927 for(;;) {
4928 ret = vde_send(s->vde, buf, size, 0);
4929 if (ret < 0 && errno == EINTR) {
4930 } else {
4931 break;
4936 static int net_vde_init(VLANState *vlan, const char *sock, int port,
4937 const char *group, int mode)
4939 VDEState *s;
4940 char *init_group = strlen(group) ? (char *)group : NULL;
4941 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4943 struct vde_open_args args = {
4944 .port = port,
4945 .group = init_group,
4946 .mode = mode,
4949 s = qemu_mallocz(sizeof(VDEState));
4950 if (!s)
4951 return -1;
4952 s->vde = vde_open(init_sock, "QEMU", &args);
4953 if (!s->vde){
4954 free(s);
4955 return -1;
4957 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4958 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4959 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4960 sock, vde_datafd(s->vde));
4961 return 0;
4963 #endif
4965 /* network connection */
4966 typedef struct NetSocketState {
4967 VLANClientState *vc;
4968 int fd;
4969 int state; /* 0 = getting length, 1 = getting data */
4970 int index;
4971 int packet_len;
4972 uint8_t buf[4096];
4973 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4974 } NetSocketState;
4976 typedef struct NetSocketListenState {
4977 VLANState *vlan;
4978 int fd;
4979 } NetSocketListenState;
4981 /* XXX: we consider we can send the whole packet without blocking */
4982 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4984 NetSocketState *s = opaque;
4985 uint32_t len;
4986 len = htonl(size);
4988 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4989 send_all(s->fd, buf, size);
4992 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4994 NetSocketState *s = opaque;
4995 sendto(s->fd, buf, size, 0,
4996 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4999 static void net_socket_send(void *opaque)
5001 NetSocketState *s = opaque;
5002 int l, size, err;
5003 uint8_t buf1[4096];
5004 const uint8_t *buf;
5006 size = recv(s->fd, buf1, sizeof(buf1), 0);
5007 if (size < 0) {
5008 err = socket_error();
5009 if (err != EWOULDBLOCK)
5010 goto eoc;
5011 } else if (size == 0) {
5012 /* end of connection */
5013 eoc:
5014 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
5015 closesocket(s->fd);
5016 return;
5018 buf = buf1;
5019 while (size > 0) {
5020 /* reassemble a packet from the network */
5021 switch(s->state) {
5022 case 0:
5023 l = 4 - s->index;
5024 if (l > size)
5025 l = size;
5026 memcpy(s->buf + s->index, buf, l);
5027 buf += l;
5028 size -= l;
5029 s->index += l;
5030 if (s->index == 4) {
5031 /* got length */
5032 s->packet_len = ntohl(*(uint32_t *)s->buf);
5033 s->index = 0;
5034 s->state = 1;
5036 break;
5037 case 1:
5038 l = s->packet_len - s->index;
5039 if (l > size)
5040 l = size;
5041 memcpy(s->buf + s->index, buf, l);
5042 s->index += l;
5043 buf += l;
5044 size -= l;
5045 if (s->index >= s->packet_len) {
5046 qemu_send_packet(s->vc, s->buf, s->packet_len);
5047 s->index = 0;
5048 s->state = 0;
5050 break;
5055 static void net_socket_send_dgram(void *opaque)
5057 NetSocketState *s = opaque;
5058 int size;
5060 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
5061 if (size < 0)
5062 return;
5063 if (size == 0) {
5064 /* end of connection */
5065 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
5066 return;
5068 qemu_send_packet(s->vc, s->buf, size);
5071 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
5073 struct ip_mreq imr;
5074 int fd;
5075 int val, ret;
5076 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
5077 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5078 inet_ntoa(mcastaddr->sin_addr),
5079 (int)ntohl(mcastaddr->sin_addr.s_addr));
5080 return -1;
5083 fd = socket(PF_INET, SOCK_DGRAM, 0);
5084 if (fd < 0) {
5085 perror("socket(PF_INET, SOCK_DGRAM)");
5086 return -1;
5089 val = 1;
5090 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
5091 (const char *)&val, sizeof(val));
5092 if (ret < 0) {
5093 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5094 goto fail;
5097 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
5098 if (ret < 0) {
5099 perror("bind");
5100 goto fail;
5103 /* Add host to multicast group */
5104 imr.imr_multiaddr = mcastaddr->sin_addr;
5105 imr.imr_interface.s_addr = htonl(INADDR_ANY);
5107 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5108 (const char *)&imr, sizeof(struct ip_mreq));
5109 if (ret < 0) {
5110 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5111 goto fail;
5114 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5115 val = 1;
5116 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
5117 (const char *)&val, sizeof(val));
5118 if (ret < 0) {
5119 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5120 goto fail;
5123 socket_set_nonblock(fd);
5124 return fd;
5125 fail:
5126 if (fd >= 0)
5127 closesocket(fd);
5128 return -1;
5131 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
5132 int is_connected)
5134 struct sockaddr_in saddr;
5135 int newfd;
5136 socklen_t saddr_len;
5137 NetSocketState *s;
5139 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5140 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5141 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5144 if (is_connected) {
5145 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
5146 /* must be bound */
5147 if (saddr.sin_addr.s_addr==0) {
5148 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5149 fd);
5150 return NULL;
5152 /* clone dgram socket */
5153 newfd = net_socket_mcast_create(&saddr);
5154 if (newfd < 0) {
5155 /* error already reported by net_socket_mcast_create() */
5156 close(fd);
5157 return NULL;
5159 /* clone newfd to fd, close newfd */
5160 dup2(newfd, fd);
5161 close(newfd);
5163 } else {
5164 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5165 fd, strerror(errno));
5166 return NULL;
5170 s = qemu_mallocz(sizeof(NetSocketState));
5171 if (!s)
5172 return NULL;
5173 s->fd = fd;
5175 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
5176 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
5178 /* mcast: save bound address as dst */
5179 if (is_connected) s->dgram_dst=saddr;
5181 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5182 "socket: fd=%d (%s mcast=%s:%d)",
5183 fd, is_connected? "cloned" : "",
5184 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5185 return s;
5188 static void net_socket_connect(void *opaque)
5190 NetSocketState *s = opaque;
5191 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
5194 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
5195 int is_connected)
5197 NetSocketState *s;
5198 s = qemu_mallocz(sizeof(NetSocketState));
5199 if (!s)
5200 return NULL;
5201 s->fd = fd;
5202 s->vc = qemu_new_vlan_client(vlan,
5203 net_socket_receive, NULL, s);
5204 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5205 "socket: fd=%d", fd);
5206 if (is_connected) {
5207 net_socket_connect(s);
5208 } else {
5209 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
5211 return s;
5214 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
5215 int is_connected)
5217 int so_type=-1, optlen=sizeof(so_type);
5219 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
5220 (socklen_t *)&optlen)< 0) {
5221 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
5222 return NULL;
5224 switch(so_type) {
5225 case SOCK_DGRAM:
5226 return net_socket_fd_init_dgram(vlan, fd, is_connected);
5227 case SOCK_STREAM:
5228 return net_socket_fd_init_stream(vlan, fd, is_connected);
5229 default:
5230 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5231 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
5232 return net_socket_fd_init_stream(vlan, fd, is_connected);
5234 return NULL;
5237 static void net_socket_accept(void *opaque)
5239 NetSocketListenState *s = opaque;
5240 NetSocketState *s1;
5241 struct sockaddr_in saddr;
5242 socklen_t len;
5243 int fd;
5245 for(;;) {
5246 len = sizeof(saddr);
5247 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
5248 if (fd < 0 && errno != EINTR) {
5249 return;
5250 } else if (fd >= 0) {
5251 break;
5254 s1 = net_socket_fd_init(s->vlan, fd, 1);
5255 if (!s1) {
5256 closesocket(fd);
5257 } else {
5258 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
5259 "socket: connection from %s:%d",
5260 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5264 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
5266 NetSocketListenState *s;
5267 int fd, val, ret;
5268 struct sockaddr_in saddr;
5270 if (parse_host_port(&saddr, host_str) < 0)
5271 return -1;
5273 s = qemu_mallocz(sizeof(NetSocketListenState));
5274 if (!s)
5275 return -1;
5277 fd = socket(PF_INET, SOCK_STREAM, 0);
5278 if (fd < 0) {
5279 perror("socket");
5280 return -1;
5282 socket_set_nonblock(fd);
5284 /* allow fast reuse */
5285 val = 1;
5286 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5288 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5289 if (ret < 0) {
5290 perror("bind");
5291 return -1;
5293 ret = listen(fd, 0);
5294 if (ret < 0) {
5295 perror("listen");
5296 return -1;
5298 s->vlan = vlan;
5299 s->fd = fd;
5300 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5301 return 0;
5304 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5306 NetSocketState *s;
5307 int fd, connected, ret, err;
5308 struct sockaddr_in saddr;
5310 if (parse_host_port(&saddr, host_str) < 0)
5311 return -1;
5313 fd = socket(PF_INET, SOCK_STREAM, 0);
5314 if (fd < 0) {
5315 perror("socket");
5316 return -1;
5318 socket_set_nonblock(fd);
5320 connected = 0;
5321 for(;;) {
5322 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5323 if (ret < 0) {
5324 err = socket_error();
5325 if (err == EINTR || err == EWOULDBLOCK) {
5326 } else if (err == EINPROGRESS) {
5327 break;
5328 #ifdef _WIN32
5329 } else if (err == WSAEALREADY) {
5330 break;
5331 #endif
5332 } else {
5333 perror("connect");
5334 closesocket(fd);
5335 return -1;
5337 } else {
5338 connected = 1;
5339 break;
5342 s = net_socket_fd_init(vlan, fd, connected);
5343 if (!s)
5344 return -1;
5345 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5346 "socket: connect to %s:%d",
5347 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5348 return 0;
5351 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5353 NetSocketState *s;
5354 int fd;
5355 struct sockaddr_in saddr;
5357 if (parse_host_port(&saddr, host_str) < 0)
5358 return -1;
5361 fd = net_socket_mcast_create(&saddr);
5362 if (fd < 0)
5363 return -1;
5365 s = net_socket_fd_init(vlan, fd, 0);
5366 if (!s)
5367 return -1;
5369 s->dgram_dst = saddr;
5371 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5372 "socket: mcast=%s:%d",
5373 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5374 return 0;
5378 static const char *get_opt_name(char *buf, int buf_size, const char *p)
5380 char *q;
5382 q = buf;
5383 while (*p != '\0' && *p != '=') {
5384 if (q && (q - buf) < buf_size - 1)
5385 *q++ = *p;
5386 p++;
5388 if (q)
5389 *q = '\0';
5391 return p;
5394 static const char *get_opt_value(char *buf, int buf_size, const char *p)
5396 char *q;
5398 q = buf;
5399 while (*p != '\0') {
5400 if (*p == ',') {
5401 if (*(p + 1) != ',')
5402 break;
5403 p++;
5405 if (q && (q - buf) < buf_size - 1)
5406 *q++ = *p;
5407 p++;
5409 if (q)
5410 *q = '\0';
5412 return p;
5415 int get_param_value(char *buf, int buf_size,
5416 const char *tag, const char *str)
5418 const char *p;
5419 char option[128];
5421 p = str;
5422 for(;;) {
5423 p = get_opt_name(option, sizeof(option), p);
5424 if (*p != '=')
5425 break;
5426 p++;
5427 if (!strcmp(tag, option)) {
5428 (void)get_opt_value(buf, buf_size, p);
5429 return strlen(buf);
5430 } else {
5431 p = get_opt_value(NULL, 0, p);
5433 if (*p != ',')
5434 break;
5435 p++;
5437 return 0;
5440 int check_params(char *buf, int buf_size,
5441 char **params, const char *str)
5443 const char *p;
5444 int i;
5446 p = str;
5447 for(;;) {
5448 p = get_opt_name(buf, buf_size, p);
5449 if (*p != '=')
5450 return -1;
5451 p++;
5452 for(i = 0; params[i] != NULL; i++)
5453 if (!strcmp(params[i], buf))
5454 break;
5455 if (params[i] == NULL)
5456 return -1;
5457 p = get_opt_value(NULL, 0, p);
5458 if (*p != ',')
5459 break;
5460 p++;
5462 return 0;
5465 static int nic_get_free_idx(void)
5467 int index;
5469 for (index = 0; index < MAX_NICS; index++)
5470 if (!nd_table[index].used)
5471 return index;
5472 return -1;
5475 int net_client_init(const char *device, const char *p)
5477 char buf[1024];
5478 int vlan_id, ret;
5479 VLANState *vlan;
5481 vlan_id = 0;
5482 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5483 vlan_id = strtol(buf, NULL, 0);
5485 vlan = qemu_find_vlan(vlan_id);
5486 if (!vlan) {
5487 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5488 return -1;
5490 if (!strcmp(device, "nic")) {
5491 NICInfo *nd;
5492 uint8_t *macaddr;
5493 int idx = nic_get_free_idx();
5495 if (idx == -1 || nb_nics >= MAX_NICS) {
5496 fprintf(stderr, "Too Many NICs\n");
5497 return -1;
5499 nd = &nd_table[idx];
5500 macaddr = nd->macaddr;
5501 macaddr[0] = 0x52;
5502 macaddr[1] = 0x54;
5503 macaddr[2] = 0x00;
5504 macaddr[3] = 0x12;
5505 macaddr[4] = 0x34;
5506 macaddr[5] = 0x56 + idx;
5508 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5509 if (parse_macaddr(macaddr, buf) < 0) {
5510 fprintf(stderr, "invalid syntax for ethernet address\n");
5511 return -1;
5514 if (get_param_value(buf, sizeof(buf), "model", p)) {
5515 nd->model = strdup(buf);
5517 nd->vlan = vlan;
5518 nd->used = 1;
5519 nb_nics++;
5520 vlan->nb_guest_devs++;
5521 ret = idx;
5522 } else
5523 if (!strcmp(device, "none")) {
5524 /* does nothing. It is needed to signal that no network cards
5525 are wanted */
5526 ret = 0;
5527 } else
5528 #ifdef CONFIG_SLIRP
5529 if (!strcmp(device, "user")) {
5530 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5531 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5533 vlan->nb_host_devs++;
5534 ret = net_slirp_init(vlan);
5535 } else
5536 #endif
5537 #ifdef _WIN32
5538 if (!strcmp(device, "tap")) {
5539 char ifname[64];
5540 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5541 fprintf(stderr, "tap: no interface name\n");
5542 return -1;
5544 vlan->nb_host_devs++;
5545 ret = tap_win32_init(vlan, ifname);
5546 } else
5547 #else
5548 if (!strcmp(device, "tap")) {
5549 char ifname[64];
5550 char setup_script[1024], down_script[1024];
5551 int fd;
5552 vlan->nb_host_devs++;
5553 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5554 fd = strtol(buf, NULL, 0);
5555 fcntl(fd, F_SETFL, O_NONBLOCK);
5556 ret = -1;
5557 if (net_tap_fd_init(vlan, fd, tap_probe_vnet_hdr(fd)))
5558 ret = 0;
5559 } else {
5560 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5561 ifname[0] = '\0';
5563 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5564 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5566 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5567 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5569 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5571 } else
5572 #endif
5573 if (!strcmp(device, "socket")) {
5574 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5575 int fd;
5576 fd = strtol(buf, NULL, 0);
5577 ret = -1;
5578 if (net_socket_fd_init(vlan, fd, 1))
5579 ret = 0;
5580 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5581 ret = net_socket_listen_init(vlan, buf);
5582 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5583 ret = net_socket_connect_init(vlan, buf);
5584 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5585 ret = net_socket_mcast_init(vlan, buf);
5586 } else {
5587 fprintf(stderr, "Unknown socket options: %s\n", p);
5588 return -1;
5590 vlan->nb_host_devs++;
5591 } else
5592 #ifdef CONFIG_VDE
5593 if (!strcmp(device, "vde")) {
5594 char vde_sock[1024], vde_group[512];
5595 int vde_port, vde_mode;
5596 vlan->nb_host_devs++;
5597 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5598 vde_sock[0] = '\0';
5600 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5601 vde_port = strtol(buf, NULL, 10);
5602 } else {
5603 vde_port = 0;
5605 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5606 vde_group[0] = '\0';
5608 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5609 vde_mode = strtol(buf, NULL, 8);
5610 } else {
5611 vde_mode = 0700;
5613 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5614 } else
5615 #endif
5617 fprintf(stderr, "Unknown network device: %s\n", device);
5618 return -1;
5620 if (ret < 0) {
5621 fprintf(stderr, "Could not initialize device '%s'\n", device);
5624 return ret;
5627 void net_client_uninit(NICInfo *nd)
5629 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
5630 nb_nics--;
5631 nd->used = 0;
5632 free((void *)nd->model);
5635 static int net_client_parse(const char *str)
5637 const char *p;
5638 char *q;
5639 char device[64];
5641 p = str;
5642 q = device;
5643 while (*p != '\0' && *p != ',') {
5644 if ((q - device) < sizeof(device) - 1)
5645 *q++ = *p;
5646 p++;
5648 *q = '\0';
5649 if (*p == ',')
5650 p++;
5652 return net_client_init(device, p);
5655 void do_info_network(void)
5657 VLANState *vlan;
5658 VLANClientState *vc;
5660 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5661 term_printf("VLAN %d devices:\n", vlan->id);
5662 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5663 term_printf(" %s\n", vc->info_str);
5667 #define HD_ALIAS "index=%d,media=disk"
5668 #ifdef TARGET_PPC
5669 #define CDROM_ALIAS "index=1,media=cdrom"
5670 #else
5671 #define CDROM_ALIAS "index=2,media=cdrom"
5672 #endif
5673 #define FD_ALIAS "index=%d,if=floppy"
5674 #define PFLASH_ALIAS "if=pflash"
5675 #define MTD_ALIAS "if=mtd"
5676 #define SD_ALIAS "index=0,if=sd"
5678 static int drive_opt_get_free_idx(void)
5680 int index;
5682 for (index = 0; index < MAX_DRIVES; index++)
5683 if (!drives_opt[index].used) {
5684 drives_opt[index].used = 1;
5685 return index;
5688 return -1;
5691 static int drive_get_free_idx(void)
5693 int index;
5695 for (index = 0; index < MAX_DRIVES; index++)
5696 if (!drives_table[index].used) {
5697 drives_table[index].used = 1;
5698 return index;
5701 return -1;
5704 int drive_add(const char *file, const char *fmt, ...)
5706 va_list ap;
5707 int index = drive_opt_get_free_idx();
5709 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5710 fprintf(stderr, "qemu: too many drives\n");
5711 return -1;
5714 drives_opt[index].file = file;
5715 va_start(ap, fmt);
5716 vsnprintf(drives_opt[index].opt,
5717 sizeof(drives_opt[0].opt), fmt, ap);
5718 va_end(ap);
5720 nb_drives_opt++;
5721 return index;
5724 void drive_remove(int index)
5726 drives_opt[index].used = 0;
5727 nb_drives_opt--;
5730 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5732 int index;
5734 /* seek interface, bus and unit */
5736 for (index = 0; index < MAX_DRIVES; index++)
5737 if (drives_table[index].type == type &&
5738 drives_table[index].bus == bus &&
5739 drives_table[index].unit == unit &&
5740 drives_table[index].used)
5741 return index;
5743 return -1;
5746 int drive_get_max_bus(BlockInterfaceType type)
5748 int max_bus;
5749 int index;
5751 max_bus = -1;
5752 for (index = 0; index < nb_drives; index++) {
5753 if(drives_table[index].type == type &&
5754 drives_table[index].bus > max_bus)
5755 max_bus = drives_table[index].bus;
5757 return max_bus;
5760 static void bdrv_format_print(void *opaque, const char *name)
5762 fprintf(stderr, " %s", name);
5765 void drive_uninit(BlockDriverState *bdrv)
5767 int i;
5769 for (i = 0; i < MAX_DRIVES; i++)
5770 if (drives_table[i].bdrv == bdrv) {
5771 drives_table[i].bdrv = NULL;
5772 drives_table[i].used = 0;
5773 drive_remove(drives_table[i].drive_opt_idx);
5774 nb_drives--;
5775 break;
5779 int drive_init(struct drive_opt *arg, int snapshot,
5780 QEMUMachine *machine)
5782 char buf[128];
5783 char file[1024];
5784 char devname[128];
5785 const char *mediastr = "";
5786 BlockInterfaceType type;
5787 enum { MEDIA_DISK, MEDIA_CDROM } media;
5788 int bus_id, unit_id;
5789 int cyls, heads, secs, translation;
5790 BlockDriverState *bdrv;
5791 BlockDriver *drv = NULL;
5792 int max_devs;
5793 int index;
5794 int cache;
5795 int bdrv_flags;
5796 int drives_table_idx;
5797 char *str = arg->opt;
5798 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5799 "secs", "trans", "media", "snapshot", "file",
5800 "cache", "format", "boot", NULL };
5802 if (check_params(buf, sizeof(buf), params, str) < 0) {
5803 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5804 buf, str);
5805 return -1;
5808 file[0] = 0;
5809 cyls = heads = secs = 0;
5810 bus_id = 0;
5811 unit_id = -1;
5812 translation = BIOS_ATA_TRANSLATION_AUTO;
5813 index = -1;
5814 cache = 1;
5816 if (!strcmp(machine->name, "realview") ||
5817 !strcmp(machine->name, "SS-5") ||
5818 !strcmp(machine->name, "SS-10") ||
5819 !strcmp(machine->name, "SS-600MP") ||
5820 !strcmp(machine->name, "versatilepb") ||
5821 !strcmp(machine->name, "versatileab")) {
5822 type = IF_SCSI;
5823 max_devs = MAX_SCSI_DEVS;
5824 pstrcpy(devname, sizeof(devname), "scsi");
5825 } else {
5826 type = IF_IDE;
5827 max_devs = MAX_IDE_DEVS;
5828 pstrcpy(devname, sizeof(devname), "ide");
5830 media = MEDIA_DISK;
5832 /* extract parameters */
5834 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5835 bus_id = strtol(buf, NULL, 0);
5836 if (bus_id < 0) {
5837 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5838 return -1;
5842 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5843 unit_id = strtol(buf, NULL, 0);
5844 if (unit_id < 0) {
5845 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5846 return -1;
5850 if (get_param_value(buf, sizeof(buf), "if", str)) {
5851 pstrcpy(devname, sizeof(devname), buf);
5852 if (!strcmp(buf, "ide")) {
5853 type = IF_IDE;
5854 max_devs = MAX_IDE_DEVS;
5855 } else if (!strcmp(buf, "scsi")) {
5856 type = IF_SCSI;
5857 max_devs = MAX_SCSI_DEVS;
5858 } else if (!strcmp(buf, "floppy")) {
5859 type = IF_FLOPPY;
5860 max_devs = 0;
5861 } else if (!strcmp(buf, "pflash")) {
5862 type = IF_PFLASH;
5863 max_devs = 0;
5864 } else if (!strcmp(buf, "mtd")) {
5865 type = IF_MTD;
5866 max_devs = 0;
5867 } else if (!strcmp(buf, "sd")) {
5868 type = IF_SD;
5869 max_devs = 0;
5870 } else if (!strcmp(buf, "virtio")) {
5871 type = IF_VIRTIO;
5872 max_devs = 0;
5873 } else {
5874 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5875 return -1;
5879 if (get_param_value(buf, sizeof(buf), "index", str)) {
5880 index = strtol(buf, NULL, 0);
5881 if (index < 0) {
5882 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5883 return -1;
5887 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5888 cyls = strtol(buf, NULL, 0);
5891 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5892 heads = strtol(buf, NULL, 0);
5895 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5896 secs = strtol(buf, NULL, 0);
5899 if (cyls || heads || secs) {
5900 if (cyls < 1 || cyls > 16383) {
5901 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5902 return -1;
5904 if (heads < 1 || heads > 16) {
5905 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5906 return -1;
5908 if (secs < 1 || secs > 63) {
5909 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5910 return -1;
5914 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5915 if (!cyls) {
5916 fprintf(stderr,
5917 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5918 str);
5919 return -1;
5921 if (!strcmp(buf, "none"))
5922 translation = BIOS_ATA_TRANSLATION_NONE;
5923 else if (!strcmp(buf, "lba"))
5924 translation = BIOS_ATA_TRANSLATION_LBA;
5925 else if (!strcmp(buf, "auto"))
5926 translation = BIOS_ATA_TRANSLATION_AUTO;
5927 else {
5928 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5929 return -1;
5933 if (get_param_value(buf, sizeof(buf), "media", str)) {
5934 if (!strcmp(buf, "disk")) {
5935 media = MEDIA_DISK;
5936 } else if (!strcmp(buf, "cdrom")) {
5937 if (cyls || secs || heads) {
5938 fprintf(stderr,
5939 "qemu: '%s' invalid physical CHS format\n", str);
5940 return -1;
5942 media = MEDIA_CDROM;
5943 } else {
5944 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5945 return -1;
5949 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5950 if (!strcmp(buf, "on"))
5951 snapshot = 1;
5952 else if (!strcmp(buf, "off"))
5953 snapshot = 0;
5954 else {
5955 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5956 return -1;
5960 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5961 if (!strcmp(buf, "off"))
5962 cache = 0;
5963 else if (!strcmp(buf, "on"))
5964 cache = 1;
5965 else {
5966 fprintf(stderr, "qemu: invalid cache option\n");
5967 return -1;
5971 if (get_param_value(buf, sizeof(buf), "format", str)) {
5972 if (strcmp(buf, "?") == 0) {
5973 fprintf(stderr, "qemu: Supported formats:");
5974 bdrv_iterate_format(bdrv_format_print, NULL);
5975 fprintf(stderr, "\n");
5976 return -1;
5978 drv = bdrv_find_format(buf);
5979 if (!drv) {
5980 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5981 return -1;
5985 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5986 if (!strcmp(buf, "on")) {
5987 if (extboot_drive != -1) {
5988 fprintf(stderr, "qemu: two bootable drives specified\n");
5989 return -1;
5991 extboot_drive = nb_drives;
5992 } else if (strcmp(buf, "off")) {
5993 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5994 return -1;
5998 if (arg->file == NULL)
5999 get_param_value(file, sizeof(file), "file", str);
6000 else
6001 pstrcpy(file, sizeof(file), arg->file);
6003 /* compute bus and unit according index */
6005 if (index != -1) {
6006 if (bus_id != 0 || unit_id != -1) {
6007 fprintf(stderr,
6008 "qemu: '%s' index cannot be used with bus and unit\n", str);
6009 return -1;
6011 if (max_devs == 0)
6013 unit_id = index;
6014 bus_id = 0;
6015 } else {
6016 unit_id = index % max_devs;
6017 bus_id = index / max_devs;
6021 /* if user doesn't specify a unit_id,
6022 * try to find the first free
6025 if (unit_id == -1) {
6026 unit_id = 0;
6027 while (drive_get_index(type, bus_id, unit_id) != -1) {
6028 unit_id++;
6029 if (max_devs && unit_id >= max_devs) {
6030 unit_id -= max_devs;
6031 bus_id++;
6036 /* check unit id */
6038 if (max_devs && unit_id >= max_devs) {
6039 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
6040 str, unit_id, max_devs - 1);
6041 return -1;
6045 * ignore multiple definitions
6048 if (drive_get_index(type, bus_id, unit_id) != -1)
6049 return -2;
6051 /* init */
6053 if (type == IF_IDE || type == IF_SCSI)
6054 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
6055 if (max_devs)
6056 snprintf(buf, sizeof(buf), "%s%i%s%i",
6057 devname, bus_id, mediastr, unit_id);
6058 else
6059 snprintf(buf, sizeof(buf), "%s%s%i",
6060 devname, mediastr, unit_id);
6061 bdrv = bdrv_new(buf);
6062 drives_table_idx = drive_get_free_idx();
6063 drives_table[drives_table_idx].bdrv = bdrv;
6064 drives_table[drives_table_idx].type = type;
6065 drives_table[drives_table_idx].bus = bus_id;
6066 drives_table[drives_table_idx].unit = unit_id;
6067 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
6068 nb_drives++;
6070 switch(type) {
6071 case IF_IDE:
6072 case IF_SCSI:
6073 switch(media) {
6074 case MEDIA_DISK:
6075 if (cyls != 0) {
6076 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
6077 bdrv_set_translation_hint(bdrv, translation);
6079 break;
6080 case MEDIA_CDROM:
6081 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
6082 break;
6084 break;
6085 case IF_SD:
6086 /* FIXME: This isn't really a floppy, but it's a reasonable
6087 approximation. */
6088 case IF_FLOPPY:
6089 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
6090 break;
6091 case IF_PFLASH:
6092 case IF_MTD:
6093 case IF_VIRTIO:
6094 break;
6096 if (!file[0])
6097 return -2;
6098 bdrv_flags = 0;
6099 if (snapshot)
6100 bdrv_flags |= BDRV_O_SNAPSHOT;
6101 if (!cache)
6102 bdrv_flags |= BDRV_O_DIRECT;
6103 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
6104 fprintf(stderr, "qemu: could not open disk image %s\n",
6105 file);
6106 return -1;
6108 return drives_table_idx;
6111 /***********************************************************/
6112 /* USB devices */
6114 static USBPort *used_usb_ports;
6115 static USBPort *free_usb_ports;
6117 /* ??? Maybe change this to register a hub to keep track of the topology. */
6118 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
6119 usb_attachfn attach)
6121 port->opaque = opaque;
6122 port->index = index;
6123 port->attach = attach;
6124 port->next = free_usb_ports;
6125 free_usb_ports = port;
6128 int usb_device_add_dev(USBDevice *dev)
6130 USBPort *port;
6132 /* Find a USB port to add the device to. */
6133 port = free_usb_ports;
6134 if (!port->next) {
6135 USBDevice *hub;
6137 /* Create a new hub and chain it on. */
6138 free_usb_ports = NULL;
6139 port->next = used_usb_ports;
6140 used_usb_ports = port;
6142 hub = usb_hub_init(VM_USB_HUB_SIZE);
6143 usb_attach(port, hub);
6144 port = free_usb_ports;
6147 free_usb_ports = port->next;
6148 port->next = used_usb_ports;
6149 used_usb_ports = port;
6150 usb_attach(port, dev);
6151 return 0;
6154 static int usb_device_add(const char *devname)
6156 const char *p;
6157 USBDevice *dev;
6158 USBPort *port;
6160 if (!free_usb_ports)
6161 return -1;
6163 if (strstart(devname, "host:", &p)) {
6164 dev = usb_host_device_open(p);
6165 } else if (!strcmp(devname, "mouse")) {
6166 dev = usb_mouse_init();
6167 } else if (!strcmp(devname, "tablet")) {
6168 dev = usb_tablet_init();
6169 } else if (!strcmp(devname, "keyboard")) {
6170 dev = usb_keyboard_init();
6171 } else if (strstart(devname, "disk:", &p)) {
6172 dev = usb_msd_init(p);
6173 } else if (!strcmp(devname, "wacom-tablet")) {
6174 dev = usb_wacom_init();
6175 } else if (strstart(devname, "serial:", &p)) {
6176 dev = usb_serial_init(p);
6177 #ifdef CONFIG_BRLAPI
6178 } else if (!strcmp(devname, "braille")) {
6179 dev = usb_baum_init();
6180 #endif
6181 } else if (strstart(devname, "net:", &p)) {
6182 int nic = nb_nics;
6184 if (net_client_init("nic", p) < 0)
6185 return -1;
6186 nd_table[nic].model = "usb";
6187 dev = usb_net_init(&nd_table[nic]);
6188 } else {
6189 return -1;
6191 if (!dev)
6192 return -1;
6194 return usb_device_add_dev(dev);
6197 int usb_device_del_addr(int bus_num, int addr)
6199 USBPort *port;
6200 USBPort **lastp;
6201 USBDevice *dev;
6203 if (!used_usb_ports)
6204 return -1;
6206 if (bus_num != 0)
6207 return -1;
6209 lastp = &used_usb_ports;
6210 port = used_usb_ports;
6211 while (port && port->dev->addr != addr) {
6212 lastp = &port->next;
6213 port = port->next;
6216 if (!port)
6217 return -1;
6219 dev = port->dev;
6220 *lastp = port->next;
6221 usb_attach(port, NULL);
6222 dev->handle_destroy(dev);
6223 port->next = free_usb_ports;
6224 free_usb_ports = port;
6225 return 0;
6228 static int usb_device_del(const char *devname)
6230 int bus_num, addr;
6231 const char *p;
6233 if (!used_usb_ports)
6234 return -1;
6236 p = strchr(devname, '.');
6237 if (!p)
6238 return -1;
6239 bus_num = strtoul(devname, NULL, 0);
6240 addr = strtoul(p + 1, NULL, 0);
6242 return usb_device_del_addr(bus_num, addr);
6245 void do_usb_add(const char *devname)
6247 usb_device_add(devname);
6250 void do_usb_del(const char *devname)
6252 usb_device_del(devname);
6255 void usb_info(void)
6257 USBDevice *dev;
6258 USBPort *port;
6259 const char *speed_str;
6261 if (!usb_enabled) {
6262 term_printf("USB support not enabled\n");
6263 return;
6266 for (port = used_usb_ports; port; port = port->next) {
6267 dev = port->dev;
6268 if (!dev)
6269 continue;
6270 switch(dev->speed) {
6271 case USB_SPEED_LOW:
6272 speed_str = "1.5";
6273 break;
6274 case USB_SPEED_FULL:
6275 speed_str = "12";
6276 break;
6277 case USB_SPEED_HIGH:
6278 speed_str = "480";
6279 break;
6280 default:
6281 speed_str = "?";
6282 break;
6284 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6285 0, dev->addr, speed_str, dev->devname);
6289 /***********************************************************/
6290 /* PCMCIA/Cardbus */
6292 static struct pcmcia_socket_entry_s {
6293 struct pcmcia_socket_s *socket;
6294 struct pcmcia_socket_entry_s *next;
6295 } *pcmcia_sockets = 0;
6297 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
6299 struct pcmcia_socket_entry_s *entry;
6301 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
6302 entry->socket = socket;
6303 entry->next = pcmcia_sockets;
6304 pcmcia_sockets = entry;
6307 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
6309 struct pcmcia_socket_entry_s *entry, **ptr;
6311 ptr = &pcmcia_sockets;
6312 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
6313 if (entry->socket == socket) {
6314 *ptr = entry->next;
6315 qemu_free(entry);
6319 void pcmcia_info(void)
6321 struct pcmcia_socket_entry_s *iter;
6322 if (!pcmcia_sockets)
6323 term_printf("No PCMCIA sockets\n");
6325 for (iter = pcmcia_sockets; iter; iter = iter->next)
6326 term_printf("%s: %s\n", iter->socket->slot_string,
6327 iter->socket->attached ? iter->socket->card_string :
6328 "Empty");
6331 /***********************************************************/
6332 /* dumb display */
6334 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
6338 static void dumb_resize(DisplayState *ds, int w, int h)
6342 static void dumb_refresh(DisplayState *ds)
6344 #if defined(CONFIG_SDL)
6345 vga_hw_update();
6346 #endif
6349 static void dumb_display_init(DisplayState *ds)
6351 ds->data = NULL;
6352 ds->linesize = 0;
6353 ds->depth = 0;
6354 ds->dpy_update = dumb_update;
6355 ds->dpy_resize = dumb_resize;
6356 ds->dpy_refresh = dumb_refresh;
6357 ds->gui_timer_interval = 500;
6358 ds->idle = 1;
6361 /***********************************************************/
6362 /* I/O handling */
6364 #define MAX_IO_HANDLERS 64
6366 typedef struct IOHandlerRecord {
6367 int fd;
6368 IOCanRWHandler *fd_read_poll;
6369 IOHandler *fd_read;
6370 IOHandler *fd_write;
6371 int deleted;
6372 void *opaque;
6373 /* temporary data */
6374 struct pollfd *ufd;
6375 struct IOHandlerRecord *next;
6376 } IOHandlerRecord;
6378 static IOHandlerRecord *first_io_handler;
6380 /* XXX: fd_read_poll should be suppressed, but an API change is
6381 necessary in the character devices to suppress fd_can_read(). */
6382 int qemu_set_fd_handler2(int fd,
6383 IOCanRWHandler *fd_read_poll,
6384 IOHandler *fd_read,
6385 IOHandler *fd_write,
6386 void *opaque)
6388 IOHandlerRecord **pioh, *ioh;
6390 if (!fd_read && !fd_write) {
6391 pioh = &first_io_handler;
6392 for(;;) {
6393 ioh = *pioh;
6394 if (ioh == NULL)
6395 break;
6396 if (ioh->fd == fd) {
6397 ioh->deleted = 1;
6398 break;
6400 pioh = &ioh->next;
6402 } else {
6403 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6404 if (ioh->fd == fd)
6405 goto found;
6407 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6408 if (!ioh)
6409 return -1;
6410 ioh->next = first_io_handler;
6411 first_io_handler = ioh;
6412 found:
6413 ioh->fd = fd;
6414 ioh->fd_read_poll = fd_read_poll;
6415 ioh->fd_read = fd_read;
6416 ioh->fd_write = fd_write;
6417 ioh->opaque = opaque;
6418 ioh->deleted = 0;
6420 main_loop_break();
6421 return 0;
6424 int qemu_set_fd_handler(int fd,
6425 IOHandler *fd_read,
6426 IOHandler *fd_write,
6427 void *opaque)
6429 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6432 /***********************************************************/
6433 /* Polling handling */
6435 typedef struct PollingEntry {
6436 PollingFunc *func;
6437 void *opaque;
6438 struct PollingEntry *next;
6439 } PollingEntry;
6441 static PollingEntry *first_polling_entry;
6443 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6445 PollingEntry **ppe, *pe;
6446 pe = qemu_mallocz(sizeof(PollingEntry));
6447 if (!pe)
6448 return -1;
6449 pe->func = func;
6450 pe->opaque = opaque;
6451 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6452 *ppe = pe;
6453 return 0;
6456 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6458 PollingEntry **ppe, *pe;
6459 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6460 pe = *ppe;
6461 if (pe->func == func && pe->opaque == opaque) {
6462 *ppe = pe->next;
6463 qemu_free(pe);
6464 break;
6469 #ifdef _WIN32
6470 /***********************************************************/
6471 /* Wait objects support */
6472 typedef struct WaitObjects {
6473 int num;
6474 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6475 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6476 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6477 } WaitObjects;
6479 static WaitObjects wait_objects = {0};
6481 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6483 WaitObjects *w = &wait_objects;
6485 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6486 return -1;
6487 w->events[w->num] = handle;
6488 w->func[w->num] = func;
6489 w->opaque[w->num] = opaque;
6490 w->num++;
6491 return 0;
6494 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6496 int i, found;
6497 WaitObjects *w = &wait_objects;
6499 found = 0;
6500 for (i = 0; i < w->num; i++) {
6501 if (w->events[i] == handle)
6502 found = 1;
6503 if (found) {
6504 w->events[i] = w->events[i + 1];
6505 w->func[i] = w->func[i + 1];
6506 w->opaque[i] = w->opaque[i + 1];
6509 if (found)
6510 w->num--;
6512 #endif
6514 #define SELF_ANNOUNCE_ROUNDS 5
6515 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6516 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6517 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6519 static int announce_self_create(uint8_t *buf,
6520 uint8_t *mac_addr)
6522 uint32_t magic = EXPERIMENTAL_MAGIC;
6523 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
6525 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6527 memset(buf, 0xff, 6); /* h_dst */
6528 memcpy(buf + 6, mac_addr, 6); /* h_src */
6529 memcpy(buf + 12, &proto, 2); /* h_proto */
6530 memcpy(buf + 14, &magic, 4); /* magic */
6532 return 18; /* len */
6535 static void qemu_announce_self(void)
6537 int i, j, len;
6538 VLANState *vlan;
6539 VLANClientState *vc;
6540 uint8_t buf[256];
6542 for (i = 0; i < nb_nics; i++) {
6543 len = announce_self_create(buf, nd_table[i].macaddr);
6544 vlan = nd_table[i].vlan;
6545 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
6546 if (vc->fd_read == tap_receive) /* send only if tap */
6547 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
6548 vc->fd_read(vc->opaque, buf, len);
6553 /***********************************************************/
6554 /* savevm/loadvm support */
6556 #define IO_BUF_SIZE 32768
6558 struct QEMUFile {
6559 QEMUFilePutBufferFunc *put_buffer;
6560 QEMUFileGetBufferFunc *get_buffer;
6561 QEMUFileCloseFunc *close;
6562 void *opaque;
6564 int64_t buf_offset; /* start of buffer when writing, end of buffer
6565 when reading */
6566 int buf_index;
6567 int buf_size; /* 0 when writing */
6568 uint8_t buf[IO_BUF_SIZE];
6571 typedef struct QEMUFileFD
6573 int fd;
6574 } QEMUFileFD;
6576 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6578 QEMUFileFD *s = opaque;
6579 int offset = 0;
6580 ssize_t len;
6582 again:
6583 len = read(s->fd, buf + offset, size - offset);
6584 if (len == -1) {
6585 if (errno == EINTR || errno == EAGAIN)
6586 goto again;
6589 return len;
6592 QEMUFile *qemu_fopen_fd(int fd)
6594 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
6595 s->fd = fd;
6596 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
6599 typedef struct QEMUFileUnix
6601 FILE *outfile;
6602 } QEMUFileUnix;
6604 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6606 QEMUFileUnix *s = opaque;
6607 fseek(s->outfile, pos, SEEK_SET);
6608 fwrite(buf, 1, size, s->outfile);
6611 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6613 QEMUFileUnix *s = opaque;
6614 fseek(s->outfile, pos, SEEK_SET);
6615 return fread(buf, 1, size, s->outfile);
6618 static void file_close(void *opaque)
6620 QEMUFileUnix *s = opaque;
6621 fclose(s->outfile);
6622 qemu_free(s);
6625 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
6627 QEMUFileUnix *s;
6629 s = qemu_mallocz(sizeof(QEMUFileUnix));
6630 if (!s)
6631 return NULL;
6633 s->outfile = fopen(filename, mode);
6634 if (!s->outfile)
6635 goto fail;
6637 if (!strcmp(mode, "wb"))
6638 return qemu_fopen(s, file_put_buffer, NULL, file_close);
6639 else if (!strcmp(mode, "rb"))
6640 return qemu_fopen(s, NULL, file_get_buffer, file_close);
6642 fail:
6643 if (s->outfile)
6644 fclose(s->outfile);
6645 qemu_free(s);
6646 return NULL;
6649 typedef struct QEMUFileBdrv
6651 BlockDriverState *bs;
6652 int64_t base_offset;
6653 } QEMUFileBdrv;
6655 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6657 QEMUFileBdrv *s = opaque;
6658 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
6661 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6663 QEMUFileBdrv *s = opaque;
6664 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6667 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6669 QEMUFileBdrv *s;
6671 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6672 if (!s)
6673 return NULL;
6675 s->bs = bs;
6676 s->base_offset = offset;
6678 if (is_writable)
6679 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
6681 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
6684 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6685 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
6687 QEMUFile *f;
6689 f = qemu_mallocz(sizeof(QEMUFile));
6690 if (!f)
6691 return NULL;
6693 f->opaque = opaque;
6694 f->put_buffer = put_buffer;
6695 f->get_buffer = get_buffer;
6696 f->close = close;
6698 return f;
6701 void qemu_fflush(QEMUFile *f)
6703 if (!f->put_buffer)
6704 return;
6706 if (f->buf_index > 0) {
6707 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
6708 f->buf_offset += f->buf_index;
6709 f->buf_index = 0;
6713 static void qemu_fill_buffer(QEMUFile *f)
6715 int len;
6717 if (!f->get_buffer)
6718 return;
6720 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6721 if (len < 0)
6722 len = 0;
6724 f->buf_index = 0;
6725 f->buf_size = len;
6726 f->buf_offset += len;
6729 void qemu_fclose(QEMUFile *f)
6731 qemu_fflush(f);
6732 if (f->close)
6733 f->close(f->opaque);
6734 qemu_free(f);
6737 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6739 int l;
6740 while (size > 0) {
6741 l = IO_BUF_SIZE - f->buf_index;
6742 if (l > size)
6743 l = size;
6744 memcpy(f->buf + f->buf_index, buf, l);
6745 f->buf_index += l;
6746 buf += l;
6747 size -= l;
6748 if (f->buf_index >= IO_BUF_SIZE)
6749 qemu_fflush(f);
6753 void qemu_put_byte(QEMUFile *f, int v)
6755 f->buf[f->buf_index++] = v;
6756 if (f->buf_index >= IO_BUF_SIZE)
6757 qemu_fflush(f);
6760 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6762 int size, l;
6764 size = size1;
6765 while (size > 0) {
6766 l = f->buf_size - f->buf_index;
6767 if (l == 0) {
6768 qemu_fill_buffer(f);
6769 l = f->buf_size - f->buf_index;
6770 if (l == 0)
6771 break;
6773 if (l > size)
6774 l = size;
6775 memcpy(buf, f->buf + f->buf_index, l);
6776 f->buf_index += l;
6777 buf += l;
6778 size -= l;
6780 return size1 - size;
6783 int qemu_get_byte(QEMUFile *f)
6785 if (f->buf_index >= f->buf_size) {
6786 qemu_fill_buffer(f);
6787 if (f->buf_index >= f->buf_size)
6788 return 0;
6790 return f->buf[f->buf_index++];
6793 int64_t qemu_ftell(QEMUFile *f)
6795 return f->buf_offset - f->buf_size + f->buf_index;
6798 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6800 if (whence == SEEK_SET) {
6801 /* nothing to do */
6802 } else if (whence == SEEK_CUR) {
6803 pos += qemu_ftell(f);
6804 } else {
6805 /* SEEK_END not supported */
6806 return -1;
6808 if (f->put_buffer) {
6809 qemu_fflush(f);
6810 f->buf_offset = pos;
6811 } else {
6812 f->buf_offset = pos;
6813 f->buf_index = 0;
6814 f->buf_size = 0;
6816 return pos;
6819 void qemu_put_be16(QEMUFile *f, unsigned int v)
6821 qemu_put_byte(f, v >> 8);
6822 qemu_put_byte(f, v);
6825 void qemu_put_be32(QEMUFile *f, unsigned int v)
6827 qemu_put_byte(f, v >> 24);
6828 qemu_put_byte(f, v >> 16);
6829 qemu_put_byte(f, v >> 8);
6830 qemu_put_byte(f, v);
6833 void qemu_put_be64(QEMUFile *f, uint64_t v)
6835 qemu_put_be32(f, v >> 32);
6836 qemu_put_be32(f, v);
6839 unsigned int qemu_get_be16(QEMUFile *f)
6841 unsigned int v;
6842 v = qemu_get_byte(f) << 8;
6843 v |= qemu_get_byte(f);
6844 return v;
6847 unsigned int qemu_get_be32(QEMUFile *f)
6849 unsigned int v;
6850 v = qemu_get_byte(f) << 24;
6851 v |= qemu_get_byte(f) << 16;
6852 v |= qemu_get_byte(f) << 8;
6853 v |= qemu_get_byte(f);
6854 return v;
6857 uint64_t qemu_get_be64(QEMUFile *f)
6859 uint64_t v;
6860 v = (uint64_t)qemu_get_be32(f) << 32;
6861 v |= qemu_get_be32(f);
6862 return v;
6865 typedef struct SaveStateEntry {
6866 char idstr[256];
6867 int instance_id;
6868 int version_id;
6869 SaveStateHandler *save_state;
6870 LoadStateHandler *load_state;
6871 void *opaque;
6872 struct SaveStateEntry *next;
6873 } SaveStateEntry;
6875 static SaveStateEntry *first_se;
6877 /* TODO: Individual devices generally have very little idea about the rest
6878 of the system, so instance_id should be removed/replaced.
6879 Meanwhile pass -1 as instance_id if you do not already have a clearly
6880 distinguishing id for all instances of your device class. */
6881 int register_savevm(const char *idstr,
6882 int instance_id,
6883 int version_id,
6884 SaveStateHandler *save_state,
6885 LoadStateHandler *load_state,
6886 void *opaque)
6888 SaveStateEntry *se, **pse;
6890 se = qemu_malloc(sizeof(SaveStateEntry));
6891 if (!se)
6892 return -1;
6893 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6894 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6895 se->version_id = version_id;
6896 se->save_state = save_state;
6897 se->load_state = load_state;
6898 se->opaque = opaque;
6899 se->next = NULL;
6901 /* add at the end of list */
6902 pse = &first_se;
6903 while (*pse != NULL) {
6904 if (instance_id == -1
6905 && strcmp(se->idstr, (*pse)->idstr) == 0
6906 && se->instance_id <= (*pse)->instance_id)
6907 se->instance_id = (*pse)->instance_id + 1;
6908 pse = &(*pse)->next;
6910 *pse = se;
6911 return 0;
6914 #define QEMU_VM_FILE_MAGIC 0x5145564d
6915 #define QEMU_VM_FILE_VERSION 0x00000002
6917 static int qemu_savevm_state(QEMUFile *f)
6919 SaveStateEntry *se;
6920 int len, ret;
6921 int64_t cur_pos, len_pos, total_len_pos;
6923 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6924 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6925 total_len_pos = qemu_ftell(f);
6926 qemu_put_be64(f, 0); /* total size */
6928 for(se = first_se; se != NULL; se = se->next) {
6929 if (se->save_state == NULL)
6930 /* this one has a loader only, for backwards compatibility */
6931 continue;
6933 /* ID string */
6934 len = strlen(se->idstr);
6935 qemu_put_byte(f, len);
6936 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6938 qemu_put_be32(f, se->instance_id);
6939 qemu_put_be32(f, se->version_id);
6941 /* record size: filled later */
6942 len_pos = qemu_ftell(f);
6943 qemu_put_be32(f, 0);
6944 se->save_state(f, se->opaque);
6946 /* fill record size */
6947 cur_pos = qemu_ftell(f);
6948 len = cur_pos - len_pos - 4;
6949 qemu_fseek(f, len_pos, SEEK_SET);
6950 qemu_put_be32(f, len);
6951 qemu_fseek(f, cur_pos, SEEK_SET);
6953 cur_pos = qemu_ftell(f);
6954 qemu_fseek(f, total_len_pos, SEEK_SET);
6955 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6956 qemu_fseek(f, cur_pos, SEEK_SET);
6958 ret = 0;
6959 return ret;
6962 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6964 SaveStateEntry *se;
6966 for(se = first_se; se != NULL; se = se->next) {
6967 if (!strcmp(se->idstr, idstr) &&
6968 instance_id == se->instance_id)
6969 return se;
6971 return NULL;
6974 static int qemu_loadvm_state(QEMUFile *f)
6976 SaveStateEntry *se;
6977 int len, ret, instance_id, record_len, version_id;
6978 int64_t total_len, end_pos, cur_pos;
6979 unsigned int v;
6980 char idstr[256];
6982 v = qemu_get_be32(f);
6983 if (v != QEMU_VM_FILE_MAGIC)
6984 goto fail;
6985 v = qemu_get_be32(f);
6986 if (v != QEMU_VM_FILE_VERSION) {
6987 fail:
6988 ret = -1;
6989 goto the_end;
6991 total_len = qemu_get_be64(f);
6992 end_pos = total_len + qemu_ftell(f);
6993 for(;;) {
6994 if (qemu_ftell(f) >= end_pos)
6995 break;
6996 len = qemu_get_byte(f);
6997 qemu_get_buffer(f, (uint8_t *)idstr, len);
6998 idstr[len] = '\0';
6999 instance_id = qemu_get_be32(f);
7000 version_id = qemu_get_be32(f);
7001 record_len = qemu_get_be32(f);
7002 #if 0
7003 printf("idstr=%s instance=0x%x version=%d len=%d\n",
7004 idstr, instance_id, version_id, record_len);
7005 #endif
7006 cur_pos = qemu_ftell(f);
7007 se = find_se(idstr, instance_id);
7008 if (!se) {
7009 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7010 instance_id, idstr);
7011 } else {
7012 ret = se->load_state(f, se->opaque, version_id);
7013 if (ret < 0) {
7014 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7015 instance_id, idstr);
7016 goto the_end;
7019 /* always seek to exact end of record */
7020 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
7022 ret = 0;
7023 the_end:
7024 return ret;
7027 int qemu_live_savevm_state(QEMUFile *f)
7029 SaveStateEntry *se;
7030 int len, ret;
7032 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
7033 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
7035 for(se = first_se; se != NULL; se = se->next) {
7036 len = strlen(se->idstr);
7038 qemu_put_byte(f, len);
7039 qemu_put_buffer(f, se->idstr, len);
7040 qemu_put_be32(f, se->instance_id);
7041 qemu_put_be32(f, se->version_id);
7043 se->save_state(f, se->opaque);
7046 qemu_put_byte(f, 0);
7048 ret = 0;
7049 return ret;
7052 int qemu_live_loadvm_state(QEMUFile *f)
7054 SaveStateEntry *se;
7055 int len, ret, instance_id, version_id;
7056 unsigned int v;
7057 char idstr[256];
7059 v = qemu_get_be32(f);
7060 if (v != QEMU_VM_FILE_MAGIC)
7061 goto fail;
7062 v = qemu_get_be32(f);
7063 if (v != QEMU_VM_FILE_VERSION) {
7064 fail:
7065 ret = -1;
7066 goto the_end;
7069 for(;;) {
7070 len = qemu_get_byte(f);
7071 if (len == 0)
7072 break;
7073 qemu_get_buffer(f, idstr, len);
7074 idstr[len] = '\0';
7075 instance_id = qemu_get_be32(f);
7076 version_id = qemu_get_be32(f);
7077 se = find_se(idstr, instance_id);
7078 if (!se) {
7079 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7080 instance_id, idstr);
7081 } else {
7082 if (version_id > se->version_id) { /* src version > dst version */
7083 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7084 idstr, version_id, se->version_id);
7085 ret = -1;
7086 goto the_end;
7088 ret = se->load_state(f, se->opaque, version_id);
7089 if (ret < 0) {
7090 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7091 instance_id, idstr);
7092 goto the_end;
7096 ret = 0;
7098 qemu_announce_self();
7100 the_end:
7101 return ret;
7104 /* device can contain snapshots */
7105 static int bdrv_can_snapshot(BlockDriverState *bs)
7107 return (bs &&
7108 !bdrv_is_removable(bs) &&
7109 !bdrv_is_read_only(bs));
7112 /* device must be snapshots in order to have a reliable snapshot */
7113 static int bdrv_has_snapshot(BlockDriverState *bs)
7115 return (bs &&
7116 !bdrv_is_removable(bs) &&
7117 !bdrv_is_read_only(bs));
7120 static BlockDriverState *get_bs_snapshots(void)
7122 BlockDriverState *bs;
7123 int i;
7125 if (bs_snapshots)
7126 return bs_snapshots;
7127 for(i = 0; i <= nb_drives; i++) {
7128 bs = drives_table[i].bdrv;
7129 if (bdrv_can_snapshot(bs))
7130 goto ok;
7132 return NULL;
7134 bs_snapshots = bs;
7135 return bs;
7138 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
7139 const char *name)
7141 QEMUSnapshotInfo *sn_tab, *sn;
7142 int nb_sns, i, ret;
7144 ret = -ENOENT;
7145 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7146 if (nb_sns < 0)
7147 return ret;
7148 for(i = 0; i < nb_sns; i++) {
7149 sn = &sn_tab[i];
7150 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
7151 *sn_info = *sn;
7152 ret = 0;
7153 break;
7156 qemu_free(sn_tab);
7157 return ret;
7160 void do_savevm(const char *name)
7162 BlockDriverState *bs, *bs1;
7163 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
7164 int must_delete, ret, i;
7165 BlockDriverInfo bdi1, *bdi = &bdi1;
7166 QEMUFile *f;
7167 int saved_vm_running;
7168 #ifdef _WIN32
7169 struct _timeb tb;
7170 #else
7171 struct timeval tv;
7172 #endif
7174 bs = get_bs_snapshots();
7175 if (!bs) {
7176 term_printf("No block device can accept snapshots\n");
7177 return;
7180 /* ??? Should this occur after vm_stop? */
7181 qemu_aio_flush();
7183 saved_vm_running = vm_running;
7184 vm_stop(0);
7186 must_delete = 0;
7187 if (name) {
7188 ret = bdrv_snapshot_find(bs, old_sn, name);
7189 if (ret >= 0) {
7190 must_delete = 1;
7193 memset(sn, 0, sizeof(*sn));
7194 if (must_delete) {
7195 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
7196 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
7197 } else {
7198 if (name)
7199 pstrcpy(sn->name, sizeof(sn->name), name);
7202 /* fill auxiliary fields */
7203 #ifdef _WIN32
7204 _ftime(&tb);
7205 sn->date_sec = tb.time;
7206 sn->date_nsec = tb.millitm * 1000000;
7207 #else
7208 gettimeofday(&tv, NULL);
7209 sn->date_sec = tv.tv_sec;
7210 sn->date_nsec = tv.tv_usec * 1000;
7211 #endif
7212 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
7214 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7215 term_printf("Device %s does not support VM state snapshots\n",
7216 bdrv_get_device_name(bs));
7217 goto the_end;
7220 /* save the VM state */
7221 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
7222 if (!f) {
7223 term_printf("Could not open VM state file\n");
7224 goto the_end;
7226 ret = qemu_savevm_state(f);
7227 sn->vm_state_size = qemu_ftell(f);
7228 qemu_fclose(f);
7229 if (ret < 0) {
7230 term_printf("Error %d while writing VM\n", ret);
7231 goto the_end;
7234 /* create the snapshots */
7236 for(i = 0; i < nb_drives; i++) {
7237 bs1 = drives_table[i].bdrv;
7238 if (bdrv_has_snapshot(bs1)) {
7239 if (must_delete) {
7240 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
7241 if (ret < 0) {
7242 term_printf("Error while deleting snapshot on '%s'\n",
7243 bdrv_get_device_name(bs1));
7246 ret = bdrv_snapshot_create(bs1, sn);
7247 if (ret < 0) {
7248 term_printf("Error while creating snapshot on '%s'\n",
7249 bdrv_get_device_name(bs1));
7254 the_end:
7255 if (saved_vm_running)
7256 vm_start();
7259 void do_loadvm(const char *name)
7261 BlockDriverState *bs, *bs1;
7262 BlockDriverInfo bdi1, *bdi = &bdi1;
7263 QEMUFile *f;
7264 int i, ret;
7265 int saved_vm_running;
7267 bs = get_bs_snapshots();
7268 if (!bs) {
7269 term_printf("No block device supports snapshots\n");
7270 return;
7273 /* Flush all IO requests so they don't interfere with the new state. */
7274 qemu_aio_flush();
7276 saved_vm_running = vm_running;
7277 vm_stop(0);
7279 for(i = 0; i <= nb_drives; i++) {
7280 bs1 = drives_table[i].bdrv;
7281 if (bdrv_has_snapshot(bs1)) {
7282 ret = bdrv_snapshot_goto(bs1, name);
7283 if (ret < 0) {
7284 if (bs != bs1)
7285 term_printf("Warning: ");
7286 switch(ret) {
7287 case -ENOTSUP:
7288 term_printf("Snapshots not supported on device '%s'\n",
7289 bdrv_get_device_name(bs1));
7290 break;
7291 case -ENOENT:
7292 term_printf("Could not find snapshot '%s' on device '%s'\n",
7293 name, bdrv_get_device_name(bs1));
7294 break;
7295 default:
7296 term_printf("Error %d while activating snapshot on '%s'\n",
7297 ret, bdrv_get_device_name(bs1));
7298 break;
7300 /* fatal on snapshot block device */
7301 if (bs == bs1)
7302 goto the_end;
7307 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7308 term_printf("Device %s does not support VM state snapshots\n",
7309 bdrv_get_device_name(bs));
7310 return;
7313 /* restore the VM state */
7314 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
7315 if (!f) {
7316 term_printf("Could not open VM state file\n");
7317 goto the_end;
7319 ret = qemu_loadvm_state(f);
7320 qemu_fclose(f);
7321 if (ret < 0) {
7322 term_printf("Error %d while loading VM state\n", ret);
7324 the_end:
7325 if (saved_vm_running)
7326 vm_start();
7329 void do_delvm(const char *name)
7331 BlockDriverState *bs, *bs1;
7332 int i, ret;
7334 bs = get_bs_snapshots();
7335 if (!bs) {
7336 term_printf("No block device supports snapshots\n");
7337 return;
7340 for(i = 0; i <= nb_drives; i++) {
7341 bs1 = drives_table[i].bdrv;
7342 if (bdrv_has_snapshot(bs1)) {
7343 ret = bdrv_snapshot_delete(bs1, name);
7344 if (ret < 0) {
7345 if (ret == -ENOTSUP)
7346 term_printf("Snapshots not supported on device '%s'\n",
7347 bdrv_get_device_name(bs1));
7348 else
7349 term_printf("Error %d while deleting snapshot on '%s'\n",
7350 ret, bdrv_get_device_name(bs1));
7356 void do_info_snapshots(void)
7358 BlockDriverState *bs, *bs1;
7359 QEMUSnapshotInfo *sn_tab, *sn;
7360 int nb_sns, i;
7361 char buf[256];
7363 bs = get_bs_snapshots();
7364 if (!bs) {
7365 term_printf("No available block device supports snapshots\n");
7366 return;
7368 term_printf("Snapshot devices:");
7369 for(i = 0; i <= nb_drives; i++) {
7370 bs1 = drives_table[i].bdrv;
7371 if (bdrv_has_snapshot(bs1)) {
7372 if (bs == bs1)
7373 term_printf(" %s", bdrv_get_device_name(bs1));
7376 term_printf("\n");
7378 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7379 if (nb_sns < 0) {
7380 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
7381 return;
7383 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
7384 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
7385 for(i = 0; i < nb_sns; i++) {
7386 sn = &sn_tab[i];
7387 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
7389 qemu_free(sn_tab);
7392 /***********************************************************/
7393 /* ram save/restore */
7395 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7397 int v;
7399 v = qemu_get_byte(f);
7400 switch(v) {
7401 case 0:
7402 if (qemu_get_buffer(f, buf, len) != len)
7403 return -EIO;
7404 break;
7405 case 1:
7406 v = qemu_get_byte(f);
7407 memset(buf, v, len);
7408 break;
7409 default:
7410 return -EINVAL;
7412 return 0;
7415 static int ram_load_v1(QEMUFile *f, void *opaque)
7417 int ret;
7418 ram_addr_t i;
7420 if (qemu_get_be32(f) != phys_ram_size)
7421 return -EINVAL;
7422 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7423 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7424 continue;
7425 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7426 if (ret)
7427 return ret;
7429 return 0;
7432 #define BDRV_HASH_BLOCK_SIZE 1024
7433 #define IOBUF_SIZE 4096
7434 #define RAM_CBLOCK_MAGIC 0xfabe
7436 typedef struct RamCompressState {
7437 z_stream zstream;
7438 QEMUFile *f;
7439 uint8_t buf[IOBUF_SIZE];
7440 } RamCompressState;
7442 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7444 int ret;
7445 memset(s, 0, sizeof(*s));
7446 s->f = f;
7447 ret = deflateInit2(&s->zstream, 1,
7448 Z_DEFLATED, 15,
7449 9, Z_DEFAULT_STRATEGY);
7450 if (ret != Z_OK)
7451 return -1;
7452 s->zstream.avail_out = IOBUF_SIZE;
7453 s->zstream.next_out = s->buf;
7454 return 0;
7457 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7459 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7460 qemu_put_be16(s->f, len);
7461 qemu_put_buffer(s->f, buf, len);
7464 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7466 int ret;
7468 s->zstream.avail_in = len;
7469 s->zstream.next_in = (uint8_t *)buf;
7470 while (s->zstream.avail_in > 0) {
7471 ret = deflate(&s->zstream, Z_NO_FLUSH);
7472 if (ret != Z_OK)
7473 return -1;
7474 if (s->zstream.avail_out == 0) {
7475 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7476 s->zstream.avail_out = IOBUF_SIZE;
7477 s->zstream.next_out = s->buf;
7480 return 0;
7483 static void ram_compress_close(RamCompressState *s)
7485 int len, ret;
7487 /* compress last bytes */
7488 for(;;) {
7489 ret = deflate(&s->zstream, Z_FINISH);
7490 if (ret == Z_OK || ret == Z_STREAM_END) {
7491 len = IOBUF_SIZE - s->zstream.avail_out;
7492 if (len > 0) {
7493 ram_put_cblock(s, s->buf, len);
7495 s->zstream.avail_out = IOBUF_SIZE;
7496 s->zstream.next_out = s->buf;
7497 if (ret == Z_STREAM_END)
7498 break;
7499 } else {
7500 goto fail;
7503 fail:
7504 deflateEnd(&s->zstream);
7507 typedef struct RamDecompressState {
7508 z_stream zstream;
7509 QEMUFile *f;
7510 uint8_t buf[IOBUF_SIZE];
7511 } RamDecompressState;
7513 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7515 int ret;
7516 memset(s, 0, sizeof(*s));
7517 s->f = f;
7518 ret = inflateInit(&s->zstream);
7519 if (ret != Z_OK)
7520 return -1;
7521 return 0;
7524 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7526 int ret, clen;
7528 s->zstream.avail_out = len;
7529 s->zstream.next_out = buf;
7530 while (s->zstream.avail_out > 0) {
7531 if (s->zstream.avail_in == 0) {
7532 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7533 return -1;
7534 clen = qemu_get_be16(s->f);
7535 if (clen > IOBUF_SIZE)
7536 return -1;
7537 qemu_get_buffer(s->f, s->buf, clen);
7538 s->zstream.avail_in = clen;
7539 s->zstream.next_in = s->buf;
7541 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7542 if (ret != Z_OK && ret != Z_STREAM_END) {
7543 return -1;
7546 return 0;
7549 static void ram_decompress_close(RamDecompressState *s)
7551 inflateEnd(&s->zstream);
7554 static void ram_save_live(QEMUFile *f, void *opaque)
7556 target_ulong addr;
7558 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7559 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7560 continue;
7561 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7562 qemu_put_be32(f, addr);
7563 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7566 qemu_put_be32(f, 1);
7569 static void ram_save_static(QEMUFile *f, void *opaque)
7571 ram_addr_t i;
7572 RamCompressState s1, *s = &s1;
7573 uint8_t buf[10];
7575 qemu_put_be32(f, phys_ram_size);
7576 if (ram_compress_open(s, f) < 0)
7577 return;
7578 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7579 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7580 continue;
7581 #if 0
7582 if (tight_savevm_enabled) {
7583 int64_t sector_num;
7584 int j;
7586 /* find if the memory block is available on a virtual
7587 block device */
7588 sector_num = -1;
7589 for(j = 0; j < nb_drives; j++) {
7590 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7591 phys_ram_base + i,
7592 BDRV_HASH_BLOCK_SIZE);
7593 if (sector_num >= 0)
7594 break;
7596 if (j == nb_drives)
7597 goto normal_compress;
7598 buf[0] = 1;
7599 buf[1] = j;
7600 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7601 ram_compress_buf(s, buf, 10);
7602 } else
7603 #endif
7605 // normal_compress:
7606 buf[0] = 0;
7607 ram_compress_buf(s, buf, 1);
7608 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7611 ram_compress_close(s);
7614 static void ram_save(QEMUFile *f, void *opaque)
7616 int in_migration = cpu_physical_memory_get_dirty_tracking();
7618 qemu_put_byte(f, in_migration);
7620 if (in_migration)
7621 ram_save_live(f, opaque);
7622 else
7623 ram_save_static(f, opaque);
7626 static int ram_load_live(QEMUFile *f, void *opaque)
7628 target_ulong addr;
7630 do {
7631 addr = qemu_get_be32(f);
7632 if (addr == 1)
7633 break;
7635 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7636 } while (1);
7638 return 0;
7641 static int ram_load_static(QEMUFile *f, void *opaque)
7643 RamDecompressState s1, *s = &s1;
7644 uint8_t buf[10];
7645 ram_addr_t i;
7647 if (qemu_get_be32(f) != phys_ram_size)
7648 return -EINVAL;
7649 if (ram_decompress_open(s, f) < 0)
7650 return -EINVAL;
7651 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7652 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7653 continue;
7654 if (ram_decompress_buf(s, buf, 1) < 0) {
7655 fprintf(stderr, "Error while reading ram block header\n");
7656 goto error;
7658 if (buf[0] == 0) {
7659 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7660 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7661 goto error;
7663 } else
7664 #if 0
7665 if (buf[0] == 1) {
7666 int bs_index;
7667 int64_t sector_num;
7669 ram_decompress_buf(s, buf + 1, 9);
7670 bs_index = buf[1];
7671 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7672 if (bs_index >= nb_drives) {
7673 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7674 goto error;
7676 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7677 phys_ram_base + i,
7678 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7679 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7680 bs_index, sector_num);
7681 goto error;
7683 } else
7684 #endif
7686 error:
7687 printf("Error block header\n");
7688 return -EINVAL;
7691 ram_decompress_close(s);
7692 return 0;
7695 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7697 int ret;
7699 switch (version_id) {
7700 case 1:
7701 ret = ram_load_v1(f, opaque);
7702 break;
7703 case 3:
7704 if (qemu_get_byte(f)) {
7705 ret = ram_load_live(f, opaque);
7706 break;
7708 case 2:
7709 ret = ram_load_static(f, opaque);
7710 break;
7711 default:
7712 ret = -EINVAL;
7713 break;
7716 return ret;
7719 /***********************************************************/
7720 /* bottom halves (can be seen as timers which expire ASAP) */
7722 struct QEMUBH {
7723 QEMUBHFunc *cb;
7724 void *opaque;
7725 int scheduled;
7726 QEMUBH *next;
7729 static QEMUBH *first_bh = NULL;
7731 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7733 QEMUBH *bh;
7734 bh = qemu_mallocz(sizeof(QEMUBH));
7735 if (!bh)
7736 return NULL;
7737 bh->cb = cb;
7738 bh->opaque = opaque;
7739 return bh;
7742 int qemu_bh_poll(void)
7744 QEMUBH *bh, **pbh;
7745 int ret;
7747 ret = 0;
7748 for(;;) {
7749 pbh = &first_bh;
7750 bh = *pbh;
7751 if (!bh)
7752 break;
7753 ret = 1;
7754 *pbh = bh->next;
7755 bh->scheduled = 0;
7756 bh->cb(bh->opaque);
7758 return ret;
7761 void qemu_bh_schedule(QEMUBH *bh)
7763 CPUState *env = cpu_single_env;
7764 if (bh->scheduled)
7765 return;
7766 bh->scheduled = 1;
7767 bh->next = first_bh;
7768 first_bh = bh;
7770 /* stop the currently executing CPU to execute the BH ASAP */
7771 if (env) {
7772 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7774 main_loop_break();
7777 void qemu_bh_cancel(QEMUBH *bh)
7779 QEMUBH **pbh;
7780 if (bh->scheduled) {
7781 pbh = &first_bh;
7782 while (*pbh != bh)
7783 pbh = &(*pbh)->next;
7784 *pbh = bh->next;
7785 bh->scheduled = 0;
7789 void qemu_bh_delete(QEMUBH *bh)
7791 qemu_bh_cancel(bh);
7792 qemu_free(bh);
7795 /***********************************************************/
7796 /* machine registration */
7798 QEMUMachine *first_machine = NULL;
7799 QEMUMachine *current_machine = NULL;
7801 int qemu_register_machine(QEMUMachine *m)
7803 QEMUMachine **pm;
7804 pm = &first_machine;
7805 while (*pm != NULL)
7806 pm = &(*pm)->next;
7807 m->next = NULL;
7808 *pm = m;
7809 return 0;
7812 static QEMUMachine *find_machine(const char *name)
7814 QEMUMachine *m;
7816 for(m = first_machine; m != NULL; m = m->next) {
7817 if (!strcmp(m->name, name))
7818 return m;
7820 return NULL;
7823 /***********************************************************/
7824 /* main execution loop */
7826 static void gui_update(void *opaque)
7828 DisplayState *ds = opaque;
7829 ds->dpy_refresh(ds);
7830 qemu_mod_timer(ds->gui_timer,
7831 (ds->gui_timer_interval ?
7832 ds->gui_timer_interval :
7833 GUI_REFRESH_INTERVAL)
7834 + qemu_get_clock(rt_clock));
7837 struct vm_change_state_entry {
7838 VMChangeStateHandler *cb;
7839 void *opaque;
7840 LIST_ENTRY (vm_change_state_entry) entries;
7843 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7845 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7846 void *opaque)
7848 VMChangeStateEntry *e;
7850 e = qemu_mallocz(sizeof (*e));
7851 if (!e)
7852 return NULL;
7854 e->cb = cb;
7855 e->opaque = opaque;
7856 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7857 return e;
7860 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7862 LIST_REMOVE (e, entries);
7863 qemu_free (e);
7866 static void vm_state_notify(int running)
7868 VMChangeStateEntry *e;
7870 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7871 e->cb(e->opaque, running);
7875 /* XXX: support several handlers */
7876 static VMStopHandler *vm_stop_cb;
7877 static void *vm_stop_opaque;
7879 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7881 vm_stop_cb = cb;
7882 vm_stop_opaque = opaque;
7883 return 0;
7886 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7888 vm_stop_cb = NULL;
7891 void vm_start(void)
7893 if (!vm_running) {
7894 cpu_enable_ticks();
7895 vm_running = 1;
7896 vm_state_notify(1);
7897 qemu_rearm_alarm_timer(alarm_timer);
7901 void vm_stop(int reason)
7903 if (vm_running) {
7904 cpu_disable_ticks();
7905 vm_running = 0;
7906 if (reason != 0) {
7907 if (vm_stop_cb) {
7908 vm_stop_cb(vm_stop_opaque, reason);
7911 vm_state_notify(0);
7915 /* reset/shutdown handler */
7917 typedef struct QEMUResetEntry {
7918 QEMUResetHandler *func;
7919 void *opaque;
7920 struct QEMUResetEntry *next;
7921 } QEMUResetEntry;
7923 static QEMUResetEntry *first_reset_entry;
7924 static int reset_requested;
7925 static int shutdown_requested;
7926 static int powerdown_requested;
7928 int qemu_shutdown_requested(void)
7930 int r = shutdown_requested;
7931 shutdown_requested = 0;
7932 return r;
7935 int qemu_reset_requested(void)
7937 int r = reset_requested;
7938 reset_requested = 0;
7939 return r;
7942 int qemu_powerdown_requested(void)
7944 int r = powerdown_requested;
7945 powerdown_requested = 0;
7946 return r;
7949 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7951 QEMUResetEntry **pre, *re;
7953 pre = &first_reset_entry;
7954 while (*pre != NULL)
7955 pre = &(*pre)->next;
7956 re = qemu_mallocz(sizeof(QEMUResetEntry));
7957 re->func = func;
7958 re->opaque = opaque;
7959 re->next = NULL;
7960 *pre = re;
7963 void qemu_system_reset(void)
7965 QEMUResetEntry *re;
7967 /* reset all devices */
7968 for(re = first_reset_entry; re != NULL; re = re->next) {
7969 re->func(re->opaque);
7973 void qemu_system_reset_request(void)
7975 if (no_reboot) {
7976 shutdown_requested = 1;
7977 } else {
7978 reset_requested = 1;
7980 if (cpu_single_env)
7981 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7982 main_loop_break();
7985 void qemu_system_shutdown_request(void)
7987 shutdown_requested = 1;
7988 if (cpu_single_env)
7989 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7992 void qemu_system_powerdown_request(void)
7994 powerdown_requested = 1;
7995 if (cpu_single_env)
7996 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7999 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
8000 struct timeval *tv)
8002 int ret;
8004 /* KVM holds a mutex while QEMU code is running, we need hooks to
8005 release the mutex whenever QEMU code sleeps. */
8007 kvm_sleep_begin();
8009 ret = select(max_fd, rfds, wfds, xfds, tv);
8011 kvm_sleep_end();
8013 return ret;
8016 void main_loop_wait(int timeout)
8018 IOHandlerRecord *ioh;
8019 fd_set rfds, wfds, xfds;
8020 int ret, nfds;
8021 #ifdef _WIN32
8022 int ret2, i;
8023 #endif
8024 struct timeval tv;
8025 PollingEntry *pe;
8028 /* XXX: need to suppress polling by better using win32 events */
8029 ret = 0;
8030 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
8031 ret |= pe->func(pe->opaque);
8033 #ifdef _WIN32
8034 if (ret == 0) {
8035 int err;
8036 WaitObjects *w = &wait_objects;
8038 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
8039 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
8040 if (w->func[ret - WAIT_OBJECT_0])
8041 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
8043 /* Check for additional signaled events */
8044 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
8046 /* Check if event is signaled */
8047 ret2 = WaitForSingleObject(w->events[i], 0);
8048 if(ret2 == WAIT_OBJECT_0) {
8049 if (w->func[i])
8050 w->func[i](w->opaque[i]);
8051 } else if (ret2 == WAIT_TIMEOUT) {
8052 } else {
8053 err = GetLastError();
8054 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
8057 } else if (ret == WAIT_TIMEOUT) {
8058 } else {
8059 err = GetLastError();
8060 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
8063 #endif
8064 /* poll any events */
8065 /* XXX: separate device handlers from system ones */
8066 nfds = -1;
8067 FD_ZERO(&rfds);
8068 FD_ZERO(&wfds);
8069 FD_ZERO(&xfds);
8070 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
8071 if (ioh->deleted)
8072 continue;
8073 if (ioh->fd_read &&
8074 (!ioh->fd_read_poll ||
8075 ioh->fd_read_poll(ioh->opaque) != 0)) {
8076 FD_SET(ioh->fd, &rfds);
8077 if (ioh->fd > nfds)
8078 nfds = ioh->fd;
8080 if (ioh->fd_write) {
8081 FD_SET(ioh->fd, &wfds);
8082 if (ioh->fd > nfds)
8083 nfds = ioh->fd;
8087 #ifdef _WIN32
8088 tv.tv_sec = 0;
8089 tv.tv_usec = 0;
8090 #else
8091 tv.tv_sec = timeout / 1000;
8092 tv.tv_usec = (timeout % 1000) * 1000;
8093 #endif
8094 #if defined(CONFIG_SLIRP)
8095 if (slirp_inited) {
8096 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
8098 #endif
8099 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
8100 if (ret > 0) {
8101 IOHandlerRecord **pioh;
8103 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
8104 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
8105 ioh->fd_read(ioh->opaque);
8106 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
8107 FD_CLR(ioh->fd, &rfds);
8109 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
8110 ioh->fd_write(ioh->opaque);
8114 /* remove deleted IO handlers */
8115 pioh = &first_io_handler;
8116 while (*pioh) {
8117 ioh = *pioh;
8118 if (ioh->deleted) {
8119 *pioh = ioh->next;
8120 qemu_free(ioh);
8121 } else
8122 pioh = &ioh->next;
8125 #if defined(CONFIG_SLIRP)
8126 if (slirp_inited) {
8127 if (ret < 0) {
8128 FD_ZERO(&rfds);
8129 FD_ZERO(&wfds);
8130 FD_ZERO(&xfds);
8132 slirp_select_poll(&rfds, &wfds, &xfds);
8134 #endif
8135 qemu_aio_poll();
8136 if (vm_running) {
8137 if (likely(!cur_cpu || !(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
8138 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
8139 qemu_get_clock(vm_clock));
8140 /* run dma transfers, if any */
8141 DMA_run();
8144 /* real time timers */
8145 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
8146 qemu_get_clock(rt_clock));
8148 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
8149 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
8150 qemu_rearm_alarm_timer(alarm_timer);
8153 /* Check bottom-halves last in case any of the earlier events triggered
8154 them. */
8155 qemu_bh_poll();
8159 static int main_loop(void)
8161 int ret, timeout;
8162 #ifdef CONFIG_PROFILER
8163 int64_t ti;
8164 #endif
8165 CPUState *env;
8168 if (kvm_enabled()) {
8169 kvm_main_loop();
8170 cpu_disable_ticks();
8171 return 0;
8174 cur_cpu = first_cpu;
8175 next_cpu = cur_cpu->next_cpu ?: first_cpu;
8176 for(;;) {
8177 if (vm_running) {
8179 for(;;) {
8180 /* get next cpu */
8181 env = next_cpu;
8182 #ifdef CONFIG_PROFILER
8183 ti = profile_getclock();
8184 #endif
8185 if (use_icount) {
8186 int64_t count;
8187 int decr;
8188 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
8189 env->icount_decr.u16.low = 0;
8190 env->icount_extra = 0;
8191 count = qemu_next_deadline();
8192 count = (count + (1 << icount_time_shift) - 1)
8193 >> icount_time_shift;
8194 qemu_icount += count;
8195 decr = (count > 0xffff) ? 0xffff : count;
8196 count -= decr;
8197 env->icount_decr.u16.low = decr;
8198 env->icount_extra = count;
8200 ret = cpu_exec(env);
8201 #ifdef CONFIG_PROFILER
8202 qemu_time += profile_getclock() - ti;
8203 #endif
8204 if (use_icount) {
8205 /* Fold pending instructions back into the
8206 instruction counter, and clear the interrupt flag. */
8207 qemu_icount -= (env->icount_decr.u16.low
8208 + env->icount_extra);
8209 env->icount_decr.u32 = 0;
8210 env->icount_extra = 0;
8212 next_cpu = env->next_cpu ?: first_cpu;
8213 if (event_pending && likely(ret != EXCP_DEBUG)) {
8214 ret = EXCP_INTERRUPT;
8215 event_pending = 0;
8216 break;
8218 if (ret == EXCP_HLT) {
8219 /* Give the next CPU a chance to run. */
8220 cur_cpu = env;
8221 continue;
8223 if (ret != EXCP_HALTED)
8224 break;
8225 /* all CPUs are halted ? */
8226 if (env == cur_cpu)
8227 break;
8229 cur_cpu = env;
8231 if (shutdown_requested) {
8232 ret = EXCP_INTERRUPT;
8233 if (no_shutdown) {
8234 vm_stop(0);
8235 no_shutdown = 0;
8237 else
8238 break;
8240 if (reset_requested) {
8241 reset_requested = 0;
8242 qemu_system_reset();
8243 if (kvm_enabled())
8244 kvm_load_registers(env);
8245 ret = EXCP_INTERRUPT;
8247 if (powerdown_requested) {
8248 powerdown_requested = 0;
8249 qemu_system_powerdown();
8250 ret = EXCP_INTERRUPT;
8252 if (unlikely(ret == EXCP_DEBUG)) {
8253 vm_stop(EXCP_DEBUG);
8255 /* If all cpus are halted then wait until the next IRQ */
8256 /* XXX: use timeout computed from timers */
8257 if (ret == EXCP_HALTED) {
8258 if (use_icount) {
8259 int64_t add;
8260 int64_t delta;
8261 /* Advance virtual time to the next event. */
8262 if (use_icount == 1) {
8263 /* When not using an adaptive execution frequency
8264 we tend to get badly out of sync with real time,
8265 so just delay for a reasonable amount of time. */
8266 delta = 0;
8267 } else {
8268 delta = cpu_get_icount() - cpu_get_clock();
8270 if (delta > 0) {
8271 /* If virtual time is ahead of real time then just
8272 wait for IO. */
8273 timeout = (delta / 1000000) + 1;
8274 } else {
8275 /* Wait for either IO to occur or the next
8276 timer event. */
8277 add = qemu_next_deadline();
8278 /* We advance the timer before checking for IO.
8279 Limit the amount we advance so that early IO
8280 activity won't get the guest too far ahead. */
8281 if (add > 10000000)
8282 add = 10000000;
8283 delta += add;
8284 add = (add + (1 << icount_time_shift) - 1)
8285 >> icount_time_shift;
8286 qemu_icount += add;
8287 timeout = delta / 1000000;
8288 if (timeout < 0)
8289 timeout = 0;
8291 } else {
8292 timeout = 10;
8294 } else {
8295 timeout = 0;
8297 } else {
8298 if (shutdown_requested)
8299 break;
8300 timeout = 10;
8302 #ifdef CONFIG_PROFILER
8303 ti = profile_getclock();
8304 #endif
8305 main_loop_wait(timeout);
8306 #ifdef CONFIG_PROFILER
8307 dev_time += profile_getclock() - ti;
8308 #endif
8310 cpu_disable_ticks();
8311 return ret;
8314 static void help(int exitcode)
8316 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
8317 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8318 "usage: %s [options] [disk_image]\n"
8319 "\n"
8320 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8321 "\n"
8322 "Standard options:\n"
8323 "-M machine select emulated machine (-M ? for list)\n"
8324 "-cpu cpu select CPU (-cpu ? for list)\n"
8325 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8326 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8327 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8328 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8329 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8330 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8331 " [,cache=on|off][,format=f][,boot=on|off]\n"
8332 " use 'file' as a drive image\n"
8333 "-mtdblock file use 'file' as on-board Flash memory image\n"
8334 "-sd file use 'file' as SecureDigital card image\n"
8335 "-pflash file use 'file' as a parallel flash image\n"
8336 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8337 "-snapshot write to temporary files instead of disk image files\n"
8338 #ifdef CONFIG_SDL
8339 "-no-frame open SDL window without a frame and window decorations\n"
8340 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8341 "-no-quit disable SDL window close capability\n"
8342 #endif
8343 #ifdef TARGET_I386
8344 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8345 #endif
8346 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8347 "-smp n set the number of CPUs to 'n' [default=1]\n"
8348 "-nographic disable graphical output and redirect serial I/Os to console\n"
8349 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8350 #ifndef _WIN32
8351 "-k language use keyboard layout (for example \"fr\" for French)\n"
8352 #endif
8353 #ifdef HAS_AUDIO
8354 "-audio-help print list of audio drivers and their options\n"
8355 "-soundhw c1,... enable audio support\n"
8356 " and only specified sound cards (comma separated list)\n"
8357 " use -soundhw ? to get the list of supported cards\n"
8358 " use -soundhw all to enable all of them\n"
8359 #endif
8360 "-localtime set the real time clock to local time [default=utc]\n"
8361 "-full-screen start in full screen\n"
8362 #ifdef TARGET_I386
8363 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8364 #endif
8365 "-usb enable the USB driver (will be the default soon)\n"
8366 "-usbdevice name add the host or guest USB device 'name'\n"
8367 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8368 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8369 #endif
8370 "-name string set the name of the guest\n"
8371 "\n"
8372 "Network options:\n"
8373 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8374 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8375 #ifdef CONFIG_SLIRP
8376 "-net user[,vlan=n][,hostname=host]\n"
8377 " connect the user mode network stack to VLAN 'n' and send\n"
8378 " hostname 'host' to DHCP clients\n"
8379 #endif
8380 #ifdef _WIN32
8381 "-net tap[,vlan=n],ifname=name\n"
8382 " connect the host TAP network interface to VLAN 'n'\n"
8383 #else
8384 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8385 " connect the host TAP network interface to VLAN 'n' and use the\n"
8386 " network scripts 'file' (default=%s)\n"
8387 " and 'dfile' (default=%s);\n"
8388 " use '[down]script=no' to disable script execution;\n"
8389 " use 'fd=h' to connect to an already opened TAP interface\n"
8390 #endif
8391 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8392 " connect the vlan 'n' to another VLAN using a socket connection\n"
8393 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8394 " connect the vlan 'n' to multicast maddr and port\n"
8395 #ifdef CONFIG_VDE
8396 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8397 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8398 " on host and listening for incoming connections on 'socketpath'.\n"
8399 " Use group 'groupname' and mode 'octalmode' to change default\n"
8400 " ownership and permissions for communication port.\n"
8401 #endif
8402 "-net none use it alone to have zero network devices; if no -net option\n"
8403 " is provided, the default is '-net nic -net user'\n"
8404 "\n"
8405 #ifdef CONFIG_SLIRP
8406 "-tftp dir allow tftp access to files in dir [-net user]\n"
8407 "-bootp file advertise file in BOOTP replies\n"
8408 #ifndef _WIN32
8409 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8410 #endif
8411 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8412 " redirect TCP or UDP connections from host to guest [-net user]\n"
8413 #endif
8414 "\n"
8415 "Linux boot specific:\n"
8416 "-kernel bzImage use 'bzImage' as kernel image\n"
8417 "-append cmdline use 'cmdline' as kernel command line\n"
8418 "-initrd file use 'file' as initial ram disk\n"
8419 "\n"
8420 "Debug/Expert options:\n"
8421 "-monitor dev redirect the monitor to char device 'dev'\n"
8422 "-serial dev redirect the serial port to char device 'dev'\n"
8423 "-parallel dev redirect the parallel port to char device 'dev'\n"
8424 "-pidfile file Write PID to 'file'\n"
8425 "-S freeze CPU at startup (use 'c' to start execution)\n"
8426 "-s wait gdb connection to port\n"
8427 "-p port set gdb connection port [default=%s]\n"
8428 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8429 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8430 " translation (t=none or lba) (usually qemu can guess them)\n"
8431 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8432 #ifdef USE_KQEMU
8433 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8434 "-no-kqemu disable KQEMU kernel module usage\n"
8435 #endif
8436 #ifdef USE_KVM
8437 #ifndef NO_CPU_EMULATION
8438 "-no-kvm disable KVM hardware virtualization\n"
8439 #endif
8440 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8441 "-no-kvm-pit disable KVM kernel mode PIT\n"
8442 #endif
8443 #ifdef TARGET_I386
8444 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8445 " (default is CL-GD5446 PCI VGA)\n"
8446 "-no-acpi disable ACPI\n"
8447 #endif
8448 #ifdef CONFIG_CURSES
8449 "-curses use a curses/ncurses interface instead of SDL\n"
8450 #endif
8451 "-no-reboot exit instead of rebooting\n"
8452 "-no-shutdown stop before shutdown\n"
8453 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8454 "-vnc display start a VNC server on display\n"
8455 #ifndef _WIN32
8456 "-daemonize daemonize QEMU after initializing\n"
8457 #endif
8458 "-tdf inject timer interrupts that got lost\n"
8459 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8460 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8461 "-option-rom rom load a file, rom, into the option ROM space\n"
8462 #ifdef TARGET_SPARC
8463 "-prom-env variable=value set OpenBIOS nvram variables\n"
8464 #endif
8465 "-clock force the use of the given methods for timer alarm.\n"
8466 " To see what timers are available use -clock ?\n"
8467 "-startdate select initial date of the clock\n"
8468 "-icount [N|auto]\n"
8469 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8470 "\n"
8471 "During emulation, the following keys are useful:\n"
8472 "ctrl-alt-f toggle full screen\n"
8473 "ctrl-alt-n switch to virtual console 'n'\n"
8474 "ctrl-alt toggle mouse and keyboard grab\n"
8475 "\n"
8476 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8478 "qemu",
8479 DEFAULT_RAM_SIZE,
8480 #ifndef _WIN32
8481 DEFAULT_NETWORK_SCRIPT,
8482 DEFAULT_NETWORK_DOWN_SCRIPT,
8483 #endif
8484 DEFAULT_GDBSTUB_PORT,
8485 "/tmp/qemu.log");
8486 exit(exitcode);
8489 #define HAS_ARG 0x0001
8491 enum {
8492 QEMU_OPTION_h,
8494 QEMU_OPTION_M,
8495 QEMU_OPTION_cpu,
8496 QEMU_OPTION_fda,
8497 QEMU_OPTION_fdb,
8498 QEMU_OPTION_hda,
8499 QEMU_OPTION_hdb,
8500 QEMU_OPTION_hdc,
8501 QEMU_OPTION_hdd,
8502 QEMU_OPTION_drive,
8503 QEMU_OPTION_cdrom,
8504 QEMU_OPTION_mtdblock,
8505 QEMU_OPTION_sd,
8506 QEMU_OPTION_pflash,
8507 QEMU_OPTION_boot,
8508 QEMU_OPTION_snapshot,
8509 #ifdef TARGET_I386
8510 QEMU_OPTION_no_fd_bootchk,
8511 #endif
8512 QEMU_OPTION_m,
8513 QEMU_OPTION_nographic,
8514 QEMU_OPTION_portrait,
8515 #ifdef HAS_AUDIO
8516 QEMU_OPTION_audio_help,
8517 QEMU_OPTION_soundhw,
8518 #endif
8520 QEMU_OPTION_net,
8521 QEMU_OPTION_tftp,
8522 QEMU_OPTION_bootp,
8523 QEMU_OPTION_smb,
8524 QEMU_OPTION_redir,
8526 QEMU_OPTION_kernel,
8527 QEMU_OPTION_append,
8528 QEMU_OPTION_initrd,
8530 QEMU_OPTION_S,
8531 QEMU_OPTION_s,
8532 QEMU_OPTION_p,
8533 QEMU_OPTION_d,
8534 QEMU_OPTION_hdachs,
8535 QEMU_OPTION_L,
8536 QEMU_OPTION_bios,
8537 QEMU_OPTION_k,
8538 QEMU_OPTION_localtime,
8539 QEMU_OPTION_cirrusvga,
8540 QEMU_OPTION_vmsvga,
8541 QEMU_OPTION_g,
8542 QEMU_OPTION_std_vga,
8543 QEMU_OPTION_echr,
8544 QEMU_OPTION_monitor,
8545 QEMU_OPTION_serial,
8546 QEMU_OPTION_parallel,
8547 QEMU_OPTION_loadvm,
8548 QEMU_OPTION_full_screen,
8549 QEMU_OPTION_no_frame,
8550 QEMU_OPTION_alt_grab,
8551 QEMU_OPTION_no_quit,
8552 QEMU_OPTION_pidfile,
8553 QEMU_OPTION_no_kqemu,
8554 QEMU_OPTION_kernel_kqemu,
8555 QEMU_OPTION_win2k_hack,
8556 QEMU_OPTION_usb,
8557 QEMU_OPTION_usbdevice,
8558 QEMU_OPTION_smp,
8559 QEMU_OPTION_vnc,
8560 QEMU_OPTION_no_acpi,
8561 QEMU_OPTION_curses,
8562 QEMU_OPTION_no_kvm,
8563 QEMU_OPTION_no_kvm_irqchip,
8564 QEMU_OPTION_no_kvm_pit,
8565 QEMU_OPTION_no_reboot,
8566 QEMU_OPTION_no_shutdown,
8567 QEMU_OPTION_show_cursor,
8568 QEMU_OPTION_daemonize,
8569 QEMU_OPTION_option_rom,
8570 QEMU_OPTION_semihosting,
8571 QEMU_OPTION_cpu_vendor,
8572 QEMU_OPTION_name,
8573 QEMU_OPTION_prom_env,
8574 QEMU_OPTION_old_param,
8575 QEMU_OPTION_clock,
8576 QEMU_OPTION_startdate,
8577 QEMU_OPTION_tb_size,
8578 QEMU_OPTION_icount,
8579 QEMU_OPTION_incoming,
8580 QEMU_OPTION_tdf,
8581 QEMU_OPTION_kvm_shadow_memory,
8582 QEMU_OPTION_mempath,
8585 typedef struct QEMUOption {
8586 const char *name;
8587 int flags;
8588 int index;
8589 } QEMUOption;
8591 const QEMUOption qemu_options[] = {
8592 { "h", 0, QEMU_OPTION_h },
8593 { "help", 0, QEMU_OPTION_h },
8595 { "M", HAS_ARG, QEMU_OPTION_M },
8596 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8597 { "fda", HAS_ARG, QEMU_OPTION_fda },
8598 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8599 { "hda", HAS_ARG, QEMU_OPTION_hda },
8600 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8601 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8602 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8603 { "drive", HAS_ARG, QEMU_OPTION_drive },
8604 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8605 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8606 { "sd", HAS_ARG, QEMU_OPTION_sd },
8607 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8608 { "boot", HAS_ARG, QEMU_OPTION_boot },
8609 { "snapshot", 0, QEMU_OPTION_snapshot },
8610 #ifdef TARGET_I386
8611 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8612 #endif
8613 { "m", HAS_ARG, QEMU_OPTION_m },
8614 { "nographic", 0, QEMU_OPTION_nographic },
8615 { "portrait", 0, QEMU_OPTION_portrait },
8616 { "k", HAS_ARG, QEMU_OPTION_k },
8617 #ifdef HAS_AUDIO
8618 { "audio-help", 0, QEMU_OPTION_audio_help },
8619 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8620 #endif
8622 { "net", HAS_ARG, QEMU_OPTION_net},
8623 #ifdef CONFIG_SLIRP
8624 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8625 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8626 #ifndef _WIN32
8627 { "smb", HAS_ARG, QEMU_OPTION_smb },
8628 #endif
8629 { "redir", HAS_ARG, QEMU_OPTION_redir },
8630 #endif
8632 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8633 { "append", HAS_ARG, QEMU_OPTION_append },
8634 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8636 { "S", 0, QEMU_OPTION_S },
8637 { "s", 0, QEMU_OPTION_s },
8638 { "p", HAS_ARG, QEMU_OPTION_p },
8639 { "d", HAS_ARG, QEMU_OPTION_d },
8640 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8641 { "L", HAS_ARG, QEMU_OPTION_L },
8642 { "bios", HAS_ARG, QEMU_OPTION_bios },
8643 #ifdef USE_KQEMU
8644 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8645 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8646 #endif
8647 #ifdef USE_KVM
8648 #ifndef NO_CPU_EMULATION
8649 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8650 #endif
8651 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8652 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8653 #endif
8654 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8655 { "g", 1, QEMU_OPTION_g },
8656 #endif
8657 { "localtime", 0, QEMU_OPTION_localtime },
8658 { "std-vga", 0, QEMU_OPTION_std_vga },
8659 { "echr", HAS_ARG, QEMU_OPTION_echr },
8660 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8661 { "serial", HAS_ARG, QEMU_OPTION_serial },
8662 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8663 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8664 { "incoming", 1, QEMU_OPTION_incoming },
8665 { "full-screen", 0, QEMU_OPTION_full_screen },
8666 #ifdef CONFIG_SDL
8667 { "no-frame", 0, QEMU_OPTION_no_frame },
8668 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8669 { "no-quit", 0, QEMU_OPTION_no_quit },
8670 #endif
8671 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8672 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8673 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8674 { "smp", HAS_ARG, QEMU_OPTION_smp },
8675 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8676 #ifdef CONFIG_CURSES
8677 { "curses", 0, QEMU_OPTION_curses },
8678 #endif
8680 /* temporary options */
8681 { "usb", 0, QEMU_OPTION_usb },
8682 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8683 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8684 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8685 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8686 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8687 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8688 { "daemonize", 0, QEMU_OPTION_daemonize },
8689 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8690 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8691 { "semihosting", 0, QEMU_OPTION_semihosting },
8692 #endif
8693 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8694 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8695 { "name", HAS_ARG, QEMU_OPTION_name },
8696 #if defined(TARGET_SPARC)
8697 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8698 #endif
8699 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8700 #if defined(TARGET_ARM)
8701 { "old-param", 0, QEMU_OPTION_old_param },
8702 #endif
8703 { "clock", HAS_ARG, QEMU_OPTION_clock },
8704 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8705 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8706 { "icount", HAS_ARG, QEMU_OPTION_icount },
8707 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8708 { NULL },
8711 /* password input */
8713 int qemu_key_check(BlockDriverState *bs, const char *name)
8715 char password[256];
8716 int i;
8718 if (!bdrv_is_encrypted(bs))
8719 return 0;
8721 term_printf("%s is encrypted.\n", name);
8722 for(i = 0; i < 3; i++) {
8723 monitor_readline("Password: ", 1, password, sizeof(password));
8724 if (bdrv_set_key(bs, password) == 0)
8725 return 0;
8726 term_printf("invalid password\n");
8728 return -EPERM;
8731 static BlockDriverState *get_bdrv(int index)
8733 if (index > nb_drives)
8734 return NULL;
8735 return drives_table[index].bdrv;
8738 static void read_passwords(void)
8740 BlockDriverState *bs;
8741 int i;
8743 for(i = 0; i < 6; i++) {
8744 bs = get_bdrv(i);
8745 if (bs)
8746 qemu_key_check(bs, bdrv_get_device_name(bs));
8750 #ifdef HAS_AUDIO
8751 struct soundhw soundhw[] = {
8752 #ifdef HAS_AUDIO_CHOICE
8753 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8755 "pcspk",
8756 "PC speaker",
8759 { .init_isa = pcspk_audio_init }
8761 #endif
8763 "sb16",
8764 "Creative Sound Blaster 16",
8767 { .init_isa = SB16_init }
8770 #ifdef CONFIG_CS4231A
8772 "cs4231a",
8773 "CS4231A",
8776 { .init_isa = cs4231a_init }
8778 #endif
8780 #ifdef CONFIG_ADLIB
8782 "adlib",
8783 #ifdef HAS_YMF262
8784 "Yamaha YMF262 (OPL3)",
8785 #else
8786 "Yamaha YM3812 (OPL2)",
8787 #endif
8790 { .init_isa = Adlib_init }
8792 #endif
8794 #ifdef CONFIG_GUS
8796 "gus",
8797 "Gravis Ultrasound GF1",
8800 { .init_isa = GUS_init }
8802 #endif
8804 #ifdef CONFIG_AC97
8806 "ac97",
8807 "Intel 82801AA AC97 Audio",
8810 { .init_pci = ac97_init }
8812 #endif
8815 "es1370",
8816 "ENSONIQ AudioPCI ES1370",
8819 { .init_pci = es1370_init }
8821 #endif
8823 { NULL, NULL, 0, 0, { NULL } }
8826 static void select_soundhw (const char *optarg)
8828 struct soundhw *c;
8830 if (*optarg == '?') {
8831 show_valid_cards:
8833 printf ("Valid sound card names (comma separated):\n");
8834 for (c = soundhw; c->name; ++c) {
8835 printf ("%-11s %s\n", c->name, c->descr);
8837 printf ("\n-soundhw all will enable all of the above\n");
8838 exit (*optarg != '?');
8840 else {
8841 size_t l;
8842 const char *p;
8843 char *e;
8844 int bad_card = 0;
8846 if (!strcmp (optarg, "all")) {
8847 for (c = soundhw; c->name; ++c) {
8848 c->enabled = 1;
8850 return;
8853 p = optarg;
8854 while (*p) {
8855 e = strchr (p, ',');
8856 l = !e ? strlen (p) : (size_t) (e - p);
8858 for (c = soundhw; c->name; ++c) {
8859 if (!strncmp (c->name, p, l)) {
8860 c->enabled = 1;
8861 break;
8865 if (!c->name) {
8866 if (l > 80) {
8867 fprintf (stderr,
8868 "Unknown sound card name (too big to show)\n");
8870 else {
8871 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8872 (int) l, p);
8874 bad_card = 1;
8876 p += l + (e != NULL);
8879 if (bad_card)
8880 goto show_valid_cards;
8883 #endif
8885 #ifdef _WIN32
8886 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8888 exit(STATUS_CONTROL_C_EXIT);
8889 return TRUE;
8891 #endif
8893 #define MAX_NET_CLIENTS 32
8895 static int saved_argc;
8896 static char **saved_argv;
8898 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8900 *argc = saved_argc;
8901 *argv = saved_argv;
8902 *opt_daemonize = daemonize;
8903 *opt_incoming = incoming;
8907 static int gethugepagesize(void)
8909 int ret, fd;
8910 char buf[4096];
8911 char *needle = "Hugepagesize:";
8912 char *size;
8913 unsigned long hugepagesize;
8915 fd = open("/proc/meminfo", O_RDONLY);
8916 if (fd < 0) {
8917 perror("open");
8918 exit(0);
8921 ret = read(fd, buf, sizeof(buf));
8922 if (ret < 0) {
8923 perror("read");
8924 exit(0);
8927 size = strstr(buf, needle);
8928 if (!size)
8929 return 0;
8930 size += strlen(needle);
8931 hugepagesize = strtol(size, NULL, 0);
8932 return hugepagesize;
8935 void *alloc_mem_area(unsigned long memory, const char *path)
8937 char *filename;
8938 void *area;
8939 int fd;
8941 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8942 return NULL;
8944 hpagesize = gethugepagesize() * 1024;
8945 if (!hpagesize)
8946 return NULL;
8948 fd = mkstemp(filename);
8949 if (fd < 0) {
8950 perror("mkstemp");
8951 free(filename);
8952 return NULL;
8954 unlink(filename);
8955 free(filename);
8957 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8960 * ftruncate is not supported by hugetlbfs in older
8961 * hosts, so don't bother checking for errors.
8962 * If anything goes wrong with it under other filesystems,
8963 * mmap will fail.
8965 ftruncate(fd, memory);
8967 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8968 if (area == MAP_FAILED) {
8969 perror("mmap");
8970 close(fd);
8971 return NULL;
8974 return area;
8977 void *qemu_alloc_physram(unsigned long memory)
8979 void *area = NULL;
8981 if (mem_path)
8982 area = alloc_mem_area(memory, mem_path);
8983 if (!area)
8984 area = qemu_vmalloc(memory);
8986 return area;
8989 #ifndef _WIN32
8991 static void termsig_handler(int signal)
8993 qemu_system_shutdown_request();
8996 void termsig_setup(void)
8998 struct sigaction act;
9000 memset(&act, 0, sizeof(act));
9001 act.sa_handler = termsig_handler;
9002 sigaction(SIGINT, &act, NULL);
9003 sigaction(SIGHUP, &act, NULL);
9004 sigaction(SIGTERM, &act, NULL);
9007 #endif
9009 int main(int argc, char **argv)
9011 #ifdef CONFIG_GDBSTUB
9012 int use_gdbstub;
9013 const char *gdbstub_port;
9014 #endif
9015 uint32_t boot_devices_bitmap = 0;
9016 int i;
9017 int snapshot, linux_boot, net_boot;
9018 const char *initrd_filename;
9019 const char *kernel_filename, *kernel_cmdline;
9020 const char *boot_devices = "";
9021 DisplayState *ds = &display_state;
9022 int cyls, heads, secs, translation;
9023 const char *net_clients[MAX_NET_CLIENTS];
9024 int nb_net_clients;
9025 int hda_index;
9026 int optind;
9027 const char *r, *optarg;
9028 CharDriverState *monitor_hd;
9029 const char *monitor_device;
9030 const char *serial_devices[MAX_SERIAL_PORTS];
9031 int serial_device_index;
9032 const char *parallel_devices[MAX_PARALLEL_PORTS];
9033 int parallel_device_index;
9034 const char *loadvm = NULL;
9035 QEMUMachine *machine;
9036 const char *cpu_model;
9037 const char *usb_devices[MAX_USB_CMDLINE];
9038 int usb_devices_index;
9039 int fds[2];
9040 int tb_size;
9041 const char *pid_file = NULL;
9042 VLANState *vlan;
9044 saved_argc = argc;
9045 saved_argv = argv;
9047 LIST_INIT (&vm_change_state_head);
9048 #ifndef _WIN32
9050 struct sigaction act;
9051 sigfillset(&act.sa_mask);
9052 act.sa_flags = 0;
9053 act.sa_handler = SIG_IGN;
9054 sigaction(SIGPIPE, &act, NULL);
9056 #else
9057 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
9058 /* Note: cpu_interrupt() is currently not SMP safe, so we force
9059 QEMU to run on a single CPU */
9061 HANDLE h;
9062 DWORD mask, smask;
9063 int i;
9064 h = GetCurrentProcess();
9065 if (GetProcessAffinityMask(h, &mask, &smask)) {
9066 for(i = 0; i < 32; i++) {
9067 if (mask & (1 << i))
9068 break;
9070 if (i != 32) {
9071 mask = 1 << i;
9072 SetProcessAffinityMask(h, mask);
9076 #endif
9078 register_machines();
9079 machine = first_machine;
9080 cpu_model = NULL;
9081 initrd_filename = NULL;
9082 ram_size = 0;
9083 vga_ram_size = VGA_RAM_SIZE;
9084 #ifdef CONFIG_GDBSTUB
9085 use_gdbstub = 0;
9086 gdbstub_port = DEFAULT_GDBSTUB_PORT;
9087 #endif
9088 snapshot = 0;
9089 nographic = 0;
9090 curses = 0;
9091 kernel_filename = NULL;
9092 kernel_cmdline = "";
9093 cyls = heads = secs = 0;
9094 translation = BIOS_ATA_TRANSLATION_AUTO;
9095 monitor_device = "vc";
9097 serial_devices[0] = "vc:80Cx24C";
9098 for(i = 1; i < MAX_SERIAL_PORTS; i++)
9099 serial_devices[i] = NULL;
9100 serial_device_index = 0;
9102 parallel_devices[0] = "vc:640x480";
9103 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
9104 parallel_devices[i] = NULL;
9105 parallel_device_index = 0;
9107 usb_devices_index = 0;
9109 nb_net_clients = 0;
9110 nb_drives = 0;
9111 nb_drives_opt = 0;
9112 hda_index = -1;
9114 nb_nics = 0;
9116 tb_size = 0;
9118 optind = 1;
9119 for(;;) {
9120 if (optind >= argc)
9121 break;
9122 r = argv[optind];
9123 if (r[0] != '-') {
9124 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
9125 } else {
9126 const QEMUOption *popt;
9128 optind++;
9129 /* Treat --foo the same as -foo. */
9130 if (r[1] == '-')
9131 r++;
9132 popt = qemu_options;
9133 for(;;) {
9134 if (!popt->name) {
9135 fprintf(stderr, "%s: invalid option -- '%s'\n",
9136 argv[0], r);
9137 exit(1);
9139 if (!strcmp(popt->name, r + 1))
9140 break;
9141 popt++;
9143 if (popt->flags & HAS_ARG) {
9144 if (optind >= argc) {
9145 fprintf(stderr, "%s: option '%s' requires an argument\n",
9146 argv[0], r);
9147 exit(1);
9149 optarg = argv[optind++];
9150 } else {
9151 optarg = NULL;
9154 switch(popt->index) {
9155 case QEMU_OPTION_M:
9156 machine = find_machine(optarg);
9157 if (!machine) {
9158 QEMUMachine *m;
9159 printf("Supported machines are:\n");
9160 for(m = first_machine; m != NULL; m = m->next) {
9161 printf("%-10s %s%s\n",
9162 m->name, m->desc,
9163 m == first_machine ? " (default)" : "");
9165 exit(*optarg != '?');
9167 break;
9168 case QEMU_OPTION_cpu:
9169 /* hw initialization will check this */
9170 if (*optarg == '?') {
9171 /* XXX: implement xxx_cpu_list for targets that still miss it */
9172 #if defined(cpu_list)
9173 cpu_list(stdout, &fprintf);
9174 #endif
9175 exit(0);
9176 } else {
9177 cpu_model = optarg;
9179 break;
9180 case QEMU_OPTION_initrd:
9181 initrd_filename = optarg;
9182 break;
9183 case QEMU_OPTION_hda:
9184 if (cyls == 0)
9185 hda_index = drive_add(optarg, HD_ALIAS, 0);
9186 else
9187 hda_index = drive_add(optarg, HD_ALIAS
9188 ",cyls=%d,heads=%d,secs=%d%s",
9189 0, cyls, heads, secs,
9190 translation == BIOS_ATA_TRANSLATION_LBA ?
9191 ",trans=lba" :
9192 translation == BIOS_ATA_TRANSLATION_NONE ?
9193 ",trans=none" : "");
9194 break;
9195 case QEMU_OPTION_hdb:
9196 case QEMU_OPTION_hdc:
9197 case QEMU_OPTION_hdd:
9198 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
9199 break;
9200 case QEMU_OPTION_drive:
9201 drive_add(NULL, "%s", optarg);
9202 break;
9203 case QEMU_OPTION_mtdblock:
9204 drive_add(optarg, MTD_ALIAS);
9205 break;
9206 case QEMU_OPTION_sd:
9207 drive_add(optarg, SD_ALIAS);
9208 break;
9209 case QEMU_OPTION_pflash:
9210 drive_add(optarg, PFLASH_ALIAS);
9211 break;
9212 case QEMU_OPTION_snapshot:
9213 snapshot = 1;
9214 break;
9215 case QEMU_OPTION_hdachs:
9217 const char *p;
9218 p = optarg;
9219 cyls = strtol(p, (char **)&p, 0);
9220 if (cyls < 1 || cyls > 16383)
9221 goto chs_fail;
9222 if (*p != ',')
9223 goto chs_fail;
9224 p++;
9225 heads = strtol(p, (char **)&p, 0);
9226 if (heads < 1 || heads > 16)
9227 goto chs_fail;
9228 if (*p != ',')
9229 goto chs_fail;
9230 p++;
9231 secs = strtol(p, (char **)&p, 0);
9232 if (secs < 1 || secs > 63)
9233 goto chs_fail;
9234 if (*p == ',') {
9235 p++;
9236 if (!strcmp(p, "none"))
9237 translation = BIOS_ATA_TRANSLATION_NONE;
9238 else if (!strcmp(p, "lba"))
9239 translation = BIOS_ATA_TRANSLATION_LBA;
9240 else if (!strcmp(p, "auto"))
9241 translation = BIOS_ATA_TRANSLATION_AUTO;
9242 else
9243 goto chs_fail;
9244 } else if (*p != '\0') {
9245 chs_fail:
9246 fprintf(stderr, "qemu: invalid physical CHS format\n");
9247 exit(1);
9249 if (hda_index != -1)
9250 snprintf(drives_opt[hda_index].opt,
9251 sizeof(drives_opt[hda_index].opt),
9252 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
9253 0, cyls, heads, secs,
9254 translation == BIOS_ATA_TRANSLATION_LBA ?
9255 ",trans=lba" :
9256 translation == BIOS_ATA_TRANSLATION_NONE ?
9257 ",trans=none" : "");
9259 break;
9260 case QEMU_OPTION_nographic:
9261 nographic = 1;
9262 break;
9263 #ifdef CONFIG_CURSES
9264 case QEMU_OPTION_curses:
9265 curses = 1;
9266 break;
9267 #endif
9268 case QEMU_OPTION_portrait:
9269 graphic_rotate = 1;
9270 break;
9271 case QEMU_OPTION_kernel:
9272 kernel_filename = optarg;
9273 break;
9274 case QEMU_OPTION_append:
9275 kernel_cmdline = optarg;
9276 break;
9277 case QEMU_OPTION_cdrom:
9278 drive_add(optarg, CDROM_ALIAS);
9279 break;
9280 case QEMU_OPTION_boot:
9281 boot_devices = optarg;
9282 /* We just do some generic consistency checks */
9284 /* Could easily be extended to 64 devices if needed */
9285 const char *p;
9287 boot_devices_bitmap = 0;
9288 for (p = boot_devices; *p != '\0'; p++) {
9289 /* Allowed boot devices are:
9290 * a b : floppy disk drives
9291 * c ... f : IDE disk drives
9292 * g ... m : machine implementation dependant drives
9293 * n ... p : network devices
9294 * It's up to each machine implementation to check
9295 * if the given boot devices match the actual hardware
9296 * implementation and firmware features.
9298 if (*p < 'a' || *p > 'q') {
9299 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9300 exit(1);
9302 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9303 fprintf(stderr,
9304 "Boot device '%c' was given twice\n",*p);
9305 exit(1);
9307 boot_devices_bitmap |= 1 << (*p - 'a');
9310 break;
9311 case QEMU_OPTION_fda:
9312 case QEMU_OPTION_fdb:
9313 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9314 break;
9315 #ifdef TARGET_I386
9316 case QEMU_OPTION_no_fd_bootchk:
9317 fd_bootchk = 0;
9318 break;
9319 #endif
9320 case QEMU_OPTION_net:
9321 if (nb_net_clients >= MAX_NET_CLIENTS) {
9322 fprintf(stderr, "qemu: too many network clients\n");
9323 exit(1);
9325 net_clients[nb_net_clients] = optarg;
9326 nb_net_clients++;
9327 break;
9328 #ifdef CONFIG_SLIRP
9329 case QEMU_OPTION_tftp:
9330 tftp_prefix = optarg;
9331 break;
9332 case QEMU_OPTION_bootp:
9333 bootp_filename = optarg;
9334 break;
9335 #ifndef _WIN32
9336 case QEMU_OPTION_smb:
9337 net_slirp_smb(optarg);
9338 break;
9339 #endif
9340 case QEMU_OPTION_redir:
9341 net_slirp_redir(optarg);
9342 break;
9343 #endif
9344 #ifdef HAS_AUDIO
9345 case QEMU_OPTION_audio_help:
9346 AUD_help ();
9347 exit (0);
9348 break;
9349 case QEMU_OPTION_soundhw:
9350 select_soundhw (optarg);
9351 break;
9352 #endif
9353 case QEMU_OPTION_h:
9354 help(0);
9355 break;
9356 case QEMU_OPTION_m: {
9357 uint64_t value;
9358 char *ptr;
9360 value = strtoul(optarg, &ptr, 10);
9361 switch (*ptr) {
9362 case 0: case 'M': case 'm':
9363 value <<= 20;
9364 break;
9365 case 'G': case 'g':
9366 value <<= 30;
9367 break;
9368 default:
9369 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
9370 exit(1);
9373 /* On 32-bit hosts, QEMU is limited by virtual address space */
9374 if (value > (2047 << 20)
9375 #ifndef USE_KQEMU
9376 && HOST_LONG_BITS == 32
9377 #endif
9379 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
9380 exit(1);
9382 if (value != (uint64_t)(ram_addr_t)value) {
9383 fprintf(stderr, "qemu: ram size too large\n");
9384 exit(1);
9386 ram_size = value;
9387 break;
9389 case QEMU_OPTION_d:
9391 int mask;
9392 CPULogItem *item;
9394 mask = cpu_str_to_log_mask(optarg);
9395 if (!mask) {
9396 printf("Log items (comma separated):\n");
9397 for(item = cpu_log_items; item->mask != 0; item++) {
9398 printf("%-10s %s\n", item->name, item->help);
9400 exit(1);
9402 cpu_set_log(mask);
9404 break;
9405 #ifdef CONFIG_GDBSTUB
9406 case QEMU_OPTION_s:
9407 use_gdbstub = 1;
9408 break;
9409 case QEMU_OPTION_p:
9410 gdbstub_port = optarg;
9411 break;
9412 #endif
9413 case QEMU_OPTION_L:
9414 bios_dir = optarg;
9415 break;
9416 case QEMU_OPTION_bios:
9417 bios_name = optarg;
9418 break;
9419 case QEMU_OPTION_S:
9420 autostart = 0;
9421 break;
9422 case QEMU_OPTION_k:
9423 keyboard_layout = optarg;
9424 break;
9425 case QEMU_OPTION_localtime:
9426 rtc_utc = 0;
9427 break;
9428 case QEMU_OPTION_cirrusvga:
9429 cirrus_vga_enabled = 1;
9430 vmsvga_enabled = 0;
9431 break;
9432 case QEMU_OPTION_vmsvga:
9433 cirrus_vga_enabled = 0;
9434 vmsvga_enabled = 1;
9435 break;
9436 case QEMU_OPTION_std_vga:
9437 cirrus_vga_enabled = 0;
9438 vmsvga_enabled = 0;
9439 break;
9440 case QEMU_OPTION_g:
9442 const char *p;
9443 int w, h, depth;
9444 p = optarg;
9445 w = strtol(p, (char **)&p, 10);
9446 if (w <= 0) {
9447 graphic_error:
9448 fprintf(stderr, "qemu: invalid resolution or depth\n");
9449 exit(1);
9451 if (*p != 'x')
9452 goto graphic_error;
9453 p++;
9454 h = strtol(p, (char **)&p, 10);
9455 if (h <= 0)
9456 goto graphic_error;
9457 if (*p == 'x') {
9458 p++;
9459 depth = strtol(p, (char **)&p, 10);
9460 if (depth != 8 && depth != 15 && depth != 16 &&
9461 depth != 24 && depth != 32)
9462 goto graphic_error;
9463 } else if (*p == '\0') {
9464 depth = graphic_depth;
9465 } else {
9466 goto graphic_error;
9469 graphic_width = w;
9470 graphic_height = h;
9471 graphic_depth = depth;
9473 break;
9474 case QEMU_OPTION_echr:
9476 char *r;
9477 term_escape_char = strtol(optarg, &r, 0);
9478 if (r == optarg)
9479 printf("Bad argument to echr\n");
9480 break;
9482 case QEMU_OPTION_monitor:
9483 monitor_device = optarg;
9484 break;
9485 case QEMU_OPTION_serial:
9486 if (serial_device_index >= MAX_SERIAL_PORTS) {
9487 fprintf(stderr, "qemu: too many serial ports\n");
9488 exit(1);
9490 serial_devices[serial_device_index] = optarg;
9491 serial_device_index++;
9492 break;
9493 case QEMU_OPTION_parallel:
9494 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9495 fprintf(stderr, "qemu: too many parallel ports\n");
9496 exit(1);
9498 parallel_devices[parallel_device_index] = optarg;
9499 parallel_device_index++;
9500 break;
9501 case QEMU_OPTION_loadvm:
9502 loadvm = optarg;
9503 break;
9504 case QEMU_OPTION_incoming:
9505 incoming = optarg;
9506 break;
9507 case QEMU_OPTION_full_screen:
9508 full_screen = 1;
9509 break;
9510 #ifdef CONFIG_SDL
9511 case QEMU_OPTION_no_frame:
9512 no_frame = 1;
9513 break;
9514 case QEMU_OPTION_alt_grab:
9515 alt_grab = 1;
9516 break;
9517 case QEMU_OPTION_no_quit:
9518 no_quit = 1;
9519 break;
9520 #endif
9521 case QEMU_OPTION_pidfile:
9522 pid_file = optarg;
9523 break;
9524 #ifdef TARGET_I386
9525 case QEMU_OPTION_win2k_hack:
9526 win2k_install_hack = 1;
9527 break;
9528 #endif
9529 #ifdef USE_KQEMU
9530 case QEMU_OPTION_no_kqemu:
9531 kqemu_allowed = 0;
9532 break;
9533 case QEMU_OPTION_kernel_kqemu:
9534 kqemu_allowed = 2;
9535 break;
9536 #endif
9537 #ifdef USE_KVM
9538 case QEMU_OPTION_no_kvm:
9539 kvm_allowed = 0;
9540 break;
9541 case QEMU_OPTION_no_kvm_irqchip: {
9542 extern int kvm_irqchip, kvm_pit;
9543 kvm_irqchip = 0;
9544 kvm_pit = 0;
9545 break;
9547 case QEMU_OPTION_no_kvm_pit: {
9548 extern int kvm_pit;
9549 kvm_pit = 0;
9550 break;
9552 #endif
9553 case QEMU_OPTION_usb:
9554 usb_enabled = 1;
9555 break;
9556 case QEMU_OPTION_usbdevice:
9557 usb_enabled = 1;
9558 if (usb_devices_index >= MAX_USB_CMDLINE) {
9559 fprintf(stderr, "Too many USB devices\n");
9560 exit(1);
9562 usb_devices[usb_devices_index] = optarg;
9563 usb_devices_index++;
9564 break;
9565 case QEMU_OPTION_smp:
9566 smp_cpus = atoi(optarg);
9567 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9568 fprintf(stderr, "Invalid number of CPUs\n");
9569 exit(1);
9571 break;
9572 case QEMU_OPTION_vnc:
9573 vnc_display = optarg;
9574 break;
9575 case QEMU_OPTION_no_acpi:
9576 acpi_enabled = 0;
9577 break;
9578 case QEMU_OPTION_no_reboot:
9579 no_reboot = 1;
9580 break;
9581 case QEMU_OPTION_no_shutdown:
9582 no_shutdown = 1;
9583 break;
9584 case QEMU_OPTION_show_cursor:
9585 cursor_hide = 0;
9586 break;
9587 case QEMU_OPTION_daemonize:
9588 daemonize = 1;
9589 break;
9590 case QEMU_OPTION_option_rom:
9591 if (nb_option_roms >= MAX_OPTION_ROMS) {
9592 fprintf(stderr, "Too many option ROMs\n");
9593 exit(1);
9595 option_rom[nb_option_roms] = optarg;
9596 nb_option_roms++;
9597 break;
9598 case QEMU_OPTION_semihosting:
9599 semihosting_enabled = 1;
9600 break;
9601 case QEMU_OPTION_tdf:
9602 time_drift_fix = 1;
9603 break;
9604 case QEMU_OPTION_kvm_shadow_memory:
9605 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9606 break;
9607 case QEMU_OPTION_mempath:
9608 mem_path = optarg;
9609 break;
9610 case QEMU_OPTION_name:
9611 qemu_name = optarg;
9612 break;
9613 #ifdef TARGET_SPARC
9614 case QEMU_OPTION_prom_env:
9615 if (nb_prom_envs >= MAX_PROM_ENVS) {
9616 fprintf(stderr, "Too many prom variables\n");
9617 exit(1);
9619 prom_envs[nb_prom_envs] = optarg;
9620 nb_prom_envs++;
9621 break;
9622 #endif
9623 case QEMU_OPTION_cpu_vendor:
9624 cpu_vendor_string = optarg;
9625 break;
9626 #ifdef TARGET_ARM
9627 case QEMU_OPTION_old_param:
9628 old_param = 1;
9629 break;
9630 #endif
9631 case QEMU_OPTION_clock:
9632 configure_alarms(optarg);
9633 break;
9634 case QEMU_OPTION_startdate:
9636 struct tm tm;
9637 time_t rtc_start_date;
9638 if (!strcmp(optarg, "now")) {
9639 rtc_date_offset = -1;
9640 } else {
9641 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9642 &tm.tm_year,
9643 &tm.tm_mon,
9644 &tm.tm_mday,
9645 &tm.tm_hour,
9646 &tm.tm_min,
9647 &tm.tm_sec) == 6) {
9648 /* OK */
9649 } else if (sscanf(optarg, "%d-%d-%d",
9650 &tm.tm_year,
9651 &tm.tm_mon,
9652 &tm.tm_mday) == 3) {
9653 tm.tm_hour = 0;
9654 tm.tm_min = 0;
9655 tm.tm_sec = 0;
9656 } else {
9657 goto date_fail;
9659 tm.tm_year -= 1900;
9660 tm.tm_mon--;
9661 rtc_start_date = mktimegm(&tm);
9662 if (rtc_start_date == -1) {
9663 date_fail:
9664 fprintf(stderr, "Invalid date format. Valid format are:\n"
9665 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9666 exit(1);
9668 rtc_date_offset = time(NULL) - rtc_start_date;
9671 break;
9672 case QEMU_OPTION_tb_size:
9673 tb_size = strtol(optarg, NULL, 0);
9674 if (tb_size < 0)
9675 tb_size = 0;
9676 break;
9677 case QEMU_OPTION_icount:
9678 use_icount = 1;
9679 if (strcmp(optarg, "auto") == 0) {
9680 icount_time_shift = -1;
9681 } else {
9682 icount_time_shift = strtol(optarg, NULL, 0);
9684 break;
9689 if (nographic) {
9690 if (serial_device_index == 0)
9691 serial_devices[0] = "stdio";
9692 if (parallel_device_index == 0)
9693 parallel_devices[0] = "null";
9694 if (strncmp(monitor_device, "vc", 2) == 0)
9695 monitor_device = "stdio";
9698 #ifndef _WIN32
9699 if (daemonize) {
9700 pid_t pid;
9702 if (pipe(fds) == -1)
9703 exit(1);
9705 pid = fork();
9706 if (pid > 0) {
9707 uint8_t status;
9708 ssize_t len;
9710 close(fds[1]);
9712 again:
9713 len = read(fds[0], &status, 1);
9714 if (len == -1 && (errno == EINTR))
9715 goto again;
9717 if (len != 1)
9718 exit(1);
9719 else if (status == 1) {
9720 fprintf(stderr, "Could not acquire pidfile\n");
9721 exit(1);
9722 } else
9723 exit(0);
9724 } else if (pid < 0)
9725 exit(1);
9727 setsid();
9729 pid = fork();
9730 if (pid > 0)
9731 exit(0);
9732 else if (pid < 0)
9733 exit(1);
9735 umask(027);
9737 signal(SIGTSTP, SIG_IGN);
9738 signal(SIGTTOU, SIG_IGN);
9739 signal(SIGTTIN, SIG_IGN);
9741 #endif
9743 #if USE_KVM
9744 if (kvm_enabled()) {
9745 if (kvm_qemu_init() < 0) {
9746 extern int kvm_allowed;
9747 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9748 #ifdef NO_CPU_EMULATION
9749 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9750 exit(1);
9751 #endif
9752 kvm_allowed = 0;
9755 #endif
9757 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9758 if (daemonize) {
9759 uint8_t status = 1;
9760 write(fds[1], &status, 1);
9761 } else
9762 fprintf(stderr, "Could not acquire pid file\n");
9763 exit(1);
9766 #ifdef USE_KQEMU
9767 if (smp_cpus > 1)
9768 kqemu_allowed = 0;
9769 #endif
9770 linux_boot = (kernel_filename != NULL);
9771 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9773 if (!linux_boot && net_boot == 0 &&
9774 !machine->nodisk_ok && nb_drives_opt == 0)
9775 help(1);
9777 if (!linux_boot && *kernel_cmdline != '\0') {
9778 fprintf(stderr, "-append only allowed with -kernel option\n");
9779 exit(1);
9782 if (!linux_boot && initrd_filename != NULL) {
9783 fprintf(stderr, "-initrd only allowed with -kernel option\n");
9784 exit(1);
9787 /* boot to floppy or the default cd if no hard disk defined yet */
9788 if (!boot_devices[0]) {
9789 boot_devices = "cad";
9791 setvbuf(stdout, NULL, _IOLBF, 0);
9793 init_timers();
9794 init_timer_alarm();
9795 qemu_aio_init();
9796 if (use_icount && icount_time_shift < 0) {
9797 use_icount = 2;
9798 /* 125MIPS seems a reasonable initial guess at the guest speed.
9799 It will be corrected fairly quickly anyway. */
9800 icount_time_shift = 3;
9801 init_icount_adjust();
9804 #ifdef _WIN32
9805 socket_init();
9806 #endif
9808 /* init network clients */
9809 if (nb_net_clients == 0) {
9810 /* if no clients, we use a default config */
9811 net_clients[0] = "nic";
9812 net_clients[1] = "user";
9813 nb_net_clients = 2;
9816 for(i = 0;i < nb_net_clients; i++) {
9817 if (net_client_parse(net_clients[i]) < 0)
9818 exit(1);
9820 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9821 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9822 continue;
9823 if (vlan->nb_guest_devs == 0)
9824 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9825 if (vlan->nb_host_devs == 0)
9826 fprintf(stderr,
9827 "Warning: vlan %d is not connected to host network\n",
9828 vlan->id);
9831 #ifdef TARGET_I386
9832 /* XXX: this should be moved in the PC machine instantiation code */
9833 if (net_boot != 0) {
9834 int netroms = 0;
9835 for (i = 0; i < nb_nics && i < 4; i++) {
9836 const char *model = nd_table[i].model;
9837 char buf[1024];
9838 if (net_boot & (1 << i)) {
9839 if (model == NULL)
9840 model = "rtl8139";
9841 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9842 if (get_image_size(buf) > 0) {
9843 if (nb_option_roms >= MAX_OPTION_ROMS) {
9844 fprintf(stderr, "Too many option ROMs\n");
9845 exit(1);
9847 option_rom[nb_option_roms] = strdup(buf);
9848 nb_option_roms++;
9849 netroms++;
9853 if (netroms == 0) {
9854 fprintf(stderr, "No valid PXE rom found for network device\n");
9855 exit(1);
9858 #endif
9860 /* init the memory */
9861 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9863 if (machine->ram_require & RAMSIZE_FIXED) {
9864 if (ram_size > 0) {
9865 if (ram_size < phys_ram_size) {
9866 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9867 machine->name, (unsigned long long) phys_ram_size);
9868 exit(-1);
9871 phys_ram_size = ram_size;
9872 } else
9873 ram_size = phys_ram_size;
9874 } else {
9875 if (ram_size == 0)
9876 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9878 phys_ram_size += ram_size;
9881 /* Initialize kvm */
9882 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9883 #define KVM_EXTRA_PAGES 3
9884 #else
9885 #define KVM_EXTRA_PAGES 0
9886 #endif
9887 if (kvm_enabled()) {
9888 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9889 if (kvm_qemu_create_context() < 0) {
9890 fprintf(stderr, "Could not create KVM context\n");
9891 exit(1);
9893 #ifdef KVM_CAP_USER_MEMORY
9895 int ret;
9897 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9898 if (ret) {
9899 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9900 if (!phys_ram_base) {
9901 fprintf(stderr, "Could not allocate physical memory\n");
9902 exit(1);
9906 #endif
9907 } else {
9908 phys_ram_base = qemu_vmalloc(phys_ram_size);
9909 if (!phys_ram_base) {
9910 fprintf(stderr, "Could not allocate physical memory\n");
9911 exit(1);
9915 /* init the dynamic translator */
9916 cpu_exec_init_all(tb_size * 1024 * 1024);
9918 bdrv_init();
9920 /* we always create the cdrom drive, even if no disk is there */
9922 if (nb_drives_opt < MAX_DRIVES)
9923 drive_add(NULL, CDROM_ALIAS);
9925 /* we always create at least one floppy */
9927 if (nb_drives_opt < MAX_DRIVES)
9928 drive_add(NULL, FD_ALIAS, 0);
9930 /* we always create one sd slot, even if no card is in it */
9932 if (nb_drives_opt < MAX_DRIVES)
9933 drive_add(NULL, SD_ALIAS);
9935 /* open the virtual block devices
9936 * note that migration with device
9937 * hot add/remove is broken.
9939 for(i = 0; i < nb_drives_opt; i++)
9940 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9941 exit(1);
9943 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9944 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9946 /* terminal init */
9947 memset(&display_state, 0, sizeof(display_state));
9948 if (nographic) {
9949 if (curses) {
9950 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9951 exit(1);
9953 /* nearly nothing to do */
9954 dumb_display_init(ds);
9955 } else if (vnc_display != NULL) {
9956 vnc_display_init(ds);
9957 if (vnc_display_open(ds, vnc_display) < 0)
9958 exit(1);
9959 } else
9960 #if defined(CONFIG_CURSES)
9961 if (curses) {
9962 curses_display_init(ds, full_screen);
9963 } else
9964 #endif
9966 #if defined(CONFIG_SDL)
9967 sdl_display_init(ds, full_screen, no_frame);
9968 #elif defined(CONFIG_COCOA)
9969 cocoa_display_init(ds, full_screen);
9970 #else
9971 dumb_display_init(ds);
9972 #endif
9975 #ifndef _WIN32
9976 /* must be after terminal init, SDL library changes signal handlers */
9977 termsig_setup();
9978 #endif
9980 /* Maintain compatibility with multiple stdio monitors */
9981 if (!strcmp(monitor_device,"stdio")) {
9982 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9983 const char *devname = serial_devices[i];
9984 if (devname && !strcmp(devname,"mon:stdio")) {
9985 monitor_device = NULL;
9986 break;
9987 } else if (devname && !strcmp(devname,"stdio")) {
9988 monitor_device = NULL;
9989 serial_devices[i] = "mon:stdio";
9990 break;
9994 if (monitor_device) {
9995 monitor_hd = qemu_chr_open(monitor_device);
9996 if (!monitor_hd) {
9997 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9998 exit(1);
10000 monitor_init(monitor_hd, !nographic);
10003 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
10004 const char *devname = serial_devices[i];
10005 if (devname && strcmp(devname, "none")) {
10006 serial_hds[i] = qemu_chr_open(devname);
10007 if (!serial_hds[i]) {
10008 fprintf(stderr, "qemu: could not open serial device '%s'\n",
10009 devname);
10010 exit(1);
10012 if (strstart(devname, "vc", 0))
10013 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
10017 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
10018 const char *devname = parallel_devices[i];
10019 if (devname && strcmp(devname, "none")) {
10020 parallel_hds[i] = qemu_chr_open(devname);
10021 if (!parallel_hds[i]) {
10022 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
10023 devname);
10024 exit(1);
10026 if (strstart(devname, "vc", 0))
10027 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
10031 if (kvm_enabled())
10032 kvm_init_ap();
10034 machine->init(ram_size, vga_ram_size, boot_devices, ds,
10035 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
10037 current_machine = machine;
10039 /* init USB devices */
10040 if (usb_enabled) {
10041 for(i = 0; i < usb_devices_index; i++) {
10042 if (usb_device_add(usb_devices[i]) < 0) {
10043 fprintf(stderr, "Warning: could not add USB device %s\n",
10044 usb_devices[i]);
10049 if (display_state.dpy_refresh) {
10050 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
10051 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
10054 #ifdef CONFIG_GDBSTUB
10055 if (use_gdbstub) {
10056 /* XXX: use standard host:port notation and modify options
10057 accordingly. */
10058 if (gdbserver_start(gdbstub_port) < 0) {
10059 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
10060 gdbstub_port);
10061 exit(1);
10064 #endif
10066 if (loadvm)
10067 do_loadvm(loadvm);
10069 if (incoming) {
10070 int rc;
10072 rc = migrate_incoming(incoming);
10073 if (rc != 0) {
10074 fprintf(stderr, "Migration failed rc=%d\n", rc);
10075 exit(rc);
10080 /* XXX: simplify init */
10081 read_passwords();
10082 if (autostart) {
10083 vm_start();
10087 if (daemonize) {
10088 uint8_t status = 0;
10089 ssize_t len;
10090 int fd;
10092 again1:
10093 len = write(fds[1], &status, 1);
10094 if (len == -1 && (errno == EINTR))
10095 goto again1;
10097 if (len != 1)
10098 exit(1);
10100 chdir("/");
10101 TFR(fd = open("/dev/null", O_RDWR));
10102 if (fd == -1)
10103 exit(1);
10105 dup2(fd, 0);
10106 dup2(fd, 1);
10107 dup2(fd, 2);
10109 close(fd);
10112 main_loop();
10113 quit_timers();
10115 #if !defined(_WIN32)
10116 /* close network clients */
10117 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
10118 VLANClientState *vc;
10120 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
10121 if (vc->fd_read == tap_receive) {
10122 char ifname[64];
10123 TAPState *s = vc->opaque;
10125 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
10126 s->down_script[0])
10127 launch_script(s->down_script, ifname, s->fd);
10129 #if defined(CONFIG_VDE)
10130 if (vc->fd_read == vde_from_qemu) {
10131 VDEState *s = vc->opaque;
10132 vde_close(s->vde);
10134 #endif
10137 #endif
10138 return 0;