Merge branch 'qemu-cvs'
[kvm-userspace.git] / qemu / vl.c
blob2fb85526314c38d75691597209af8207a5226e80
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 "balloon.h"
42 #include "qemu-kvm.h"
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <time.h>
48 #include <errno.h>
49 #include <sys/time.h>
50 #include <zlib.h>
52 #ifndef _WIN32
53 #include <sys/times.h>
54 #include <sys/wait.h>
55 #include <termios.h>
56 #include <sys/poll.h>
57 #include <sys/mman.h>
58 #include <sys/ioctl.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <dirent.h>
62 #include <netdb.h>
63 #include <sys/select.h>
64 #include <arpa/inet.h>
65 #ifdef _BSD
66 #include <sys/stat.h>
67 #if !defined(__APPLE__) && !defined(__OpenBSD__)
68 #include <libutil.h>
69 #endif
70 #ifdef __OpenBSD__
71 #include <net/if.h>
72 #endif
73 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
74 #include <freebsd/stdlib.h>
75 #else
76 #ifndef __sun__
77 #include <linux/if.h>
78 #include <linux/if_tun.h>
79 #include <pty.h>
80 #include <malloc.h>
81 #include <linux/rtc.h>
83 /* For the benefit of older linux systems which don't supply it,
84 we use a local copy of hpet.h. */
85 /* #include <linux/hpet.h> */
86 #include "hpet.h"
88 #include <linux/ppdev.h>
89 #include <linux/parport.h>
90 #else
91 #include <sys/stat.h>
92 #include <sys/ethernet.h>
93 #include <sys/sockio.h>
94 #include <netinet/arp.h>
95 #include <netinet/in.h>
96 #include <netinet/in_systm.h>
97 #include <netinet/ip.h>
98 #include <netinet/ip_icmp.h> // must come after ip.h
99 #include <netinet/udp.h>
100 #include <netinet/tcp.h>
101 #include <net/if.h>
102 #include <syslog.h>
103 #include <stropts.h>
104 #endif
105 #endif
106 #endif
108 #include "qemu_socket.h"
110 #if defined(CONFIG_SLIRP)
111 #include "libslirp.h"
112 #endif
114 #if defined(__OpenBSD__)
115 #include <util.h>
116 #endif
118 #if defined(CONFIG_VDE)
119 #include <libvdeplug.h>
120 #endif
122 #ifdef _WIN32
123 #include <malloc.h>
124 #include <sys/timeb.h>
125 #include <mmsystem.h>
126 #define getopt_long_only getopt_long
127 #define memalign(align, size) malloc(size)
128 #endif
130 #ifdef CONFIG_SDL
131 #ifdef __APPLE__
132 #include <SDL/SDL.h>
133 #endif
134 #endif /* CONFIG_SDL */
136 #ifdef CONFIG_COCOA
137 #undef main
138 #define main qemu_main
139 #endif /* CONFIG_COCOA */
141 #include "disas.h"
143 #include "exec-all.h"
145 #include "qemu-kvm.h"
147 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
148 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
149 #ifdef __sun__
150 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
151 #else
152 #define SMBD_COMMAND "/usr/sbin/smbd"
153 #endif
155 //#define DEBUG_UNUSED_IOPORT
156 //#define DEBUG_IOPORT
158 #ifdef TARGET_PPC
159 #define DEFAULT_RAM_SIZE 144
160 #else
161 #define DEFAULT_RAM_SIZE 128
162 #endif
164 /* Max number of USB devices that can be specified on the commandline. */
165 #define MAX_USB_CMDLINE 8
167 /* XXX: use a two level table to limit memory usage */
168 #define MAX_IOPORTS 65536
170 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
171 const char *bios_name = NULL;
172 void *ioport_opaque[MAX_IOPORTS];
173 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
174 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
175 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
176 to store the VM snapshots */
177 DriveInfo drives_table[MAX_DRIVES+1];
178 int nb_drives;
179 int extboot_drive = -1;
180 /* point to the block driver where the snapshots are managed */
181 BlockDriverState *bs_snapshots;
182 int vga_ram_size;
183 static DisplayState display_state;
184 int nographic;
185 int curses;
186 const char* keyboard_layout = NULL;
187 int64_t ticks_per_sec;
188 ram_addr_t ram_size;
189 int pit_min_timer_count = 0;
190 int nb_nics;
191 NICInfo nd_table[MAX_NICS];
192 int vm_running;
193 static int rtc_utc = 1;
194 static int rtc_date_offset = -1; /* -1 means no change */
195 int cirrus_vga_enabled = 1;
196 int vmsvga_enabled = 0;
197 #ifdef TARGET_SPARC
198 int graphic_width = 1024;
199 int graphic_height = 768;
200 int graphic_depth = 8;
201 #else
202 int graphic_width = 800;
203 int graphic_height = 600;
204 int graphic_depth = 15;
205 #endif
206 int full_screen = 0;
207 int no_frame = 0;
208 int no_quit = 0;
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 #ifdef TARGET_I386
212 int win2k_install_hack = 0;
213 #endif
214 int usb_enabled = 0;
215 static VLANState *first_vlan;
216 int smp_cpus = 1;
217 const char *vnc_display;
218 #if defined(TARGET_SPARC)
219 #define MAX_CPUS 16
220 #elif defined(TARGET_I386)
221 #define MAX_CPUS 255
222 #elif defined(TARGET_IA64)
223 #define MAX_CPUS 4
224 #else
225 #define MAX_CPUS 1
226 #endif
227 int acpi_enabled = 1;
228 int fd_bootchk = 1;
229 int no_reboot = 0;
230 int no_shutdown = 0;
231 int cursor_hide = 1;
232 int graphic_rotate = 0;
233 int daemonize = 0;
234 const char *incoming;
235 const char *option_rom[MAX_OPTION_ROMS];
236 int nb_option_roms;
237 int semihosting_enabled = 0;
238 int autostart = 1;
239 int time_drift_fix = 0;
240 unsigned int kvm_shadow_memory = 0;
241 const char *mem_path = NULL;
242 int hpagesize = 0;
243 const char *cpu_vendor_string;
244 #ifdef TARGET_ARM
245 int old_param = 0;
246 #endif
247 const char *qemu_name;
248 int alt_grab = 0;
249 #ifdef TARGET_SPARC
250 unsigned int nb_prom_envs = 0;
251 const char *prom_envs[MAX_PROM_ENVS];
252 #endif
253 int nb_drives_opt;
254 struct drive_opt drives_opt[MAX_DRIVES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int event_pending = 1;
259 /* Conversion factor from emulated instructions to virtual clock ticks. */
260 static int icount_time_shift;
261 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
262 #define MAX_ICOUNT_SHIFT 10
263 /* Compensate for varying guest execution speed. */
264 static int64_t qemu_icount_bias;
265 QEMUTimer *icount_rt_timer;
266 QEMUTimer *icount_vm_timer;
268 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
270 /* KVM runs the main loop in a separate thread. If we update one of the lists
271 * that are polled before or after select(), we need to make sure to break out
272 * of the select() to ensure the new item is serviced.
274 static void main_loop_break(void)
276 if (kvm_enabled())
277 qemu_kvm_notify_work();
280 /***********************************************************/
281 /* x86 ISA bus support */
283 target_phys_addr_t isa_mem_base = 0;
284 PicState2 *isa_pic;
286 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
287 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
289 static uint32_t ioport_read(int index, uint32_t address)
291 static IOPortReadFunc *default_func[3] = {
292 default_ioport_readb,
293 default_ioport_readw,
294 default_ioport_readl
296 IOPortReadFunc *func = ioport_read_table[index][address];
297 if (!func)
298 func = default_func[index];
299 return func(ioport_opaque[address], address);
302 static void ioport_write(int index, uint32_t address, uint32_t data)
304 static IOPortWriteFunc *default_func[3] = {
305 default_ioport_writeb,
306 default_ioport_writew,
307 default_ioport_writel
309 IOPortWriteFunc *func = ioport_write_table[index][address];
310 if (!func)
311 func = default_func[index];
312 func(ioport_opaque[address], address, data);
315 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
317 #ifdef DEBUG_UNUSED_IOPORT
318 fprintf(stderr, "unused inb: port=0x%04x\n", address);
319 #endif
320 return 0xff;
323 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
325 #ifdef DEBUG_UNUSED_IOPORT
326 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
327 #endif
330 /* default is to make two byte accesses */
331 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
333 uint32_t data;
334 data = ioport_read(0, address);
335 address = (address + 1) & (MAX_IOPORTS - 1);
336 data |= ioport_read(0, address) << 8;
337 return data;
340 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
342 ioport_write(0, address, data & 0xff);
343 address = (address + 1) & (MAX_IOPORTS - 1);
344 ioport_write(0, address, (data >> 8) & 0xff);
347 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
349 #ifdef DEBUG_UNUSED_IOPORT
350 fprintf(stderr, "unused inl: port=0x%04x\n", address);
351 #endif
352 return 0xffffffff;
355 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
357 #ifdef DEBUG_UNUSED_IOPORT
358 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
359 #endif
362 /* size is the word size in byte */
363 int register_ioport_read(int start, int length, int size,
364 IOPortReadFunc *func, void *opaque)
366 int i, bsize;
368 if (size == 1) {
369 bsize = 0;
370 } else if (size == 2) {
371 bsize = 1;
372 } else if (size == 4) {
373 bsize = 2;
374 } else {
375 hw_error("register_ioport_read: invalid size");
376 return -1;
378 for(i = start; i < start + length; i += size) {
379 ioport_read_table[bsize][i] = func;
380 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
381 hw_error("register_ioport_read: invalid opaque");
382 ioport_opaque[i] = opaque;
384 return 0;
387 /* size is the word size in byte */
388 int register_ioport_write(int start, int length, int size,
389 IOPortWriteFunc *func, void *opaque)
391 int i, bsize;
393 if (size == 1) {
394 bsize = 0;
395 } else if (size == 2) {
396 bsize = 1;
397 } else if (size == 4) {
398 bsize = 2;
399 } else {
400 hw_error("register_ioport_write: invalid size");
401 return -1;
403 for(i = start; i < start + length; i += size) {
404 ioport_write_table[bsize][i] = func;
405 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
406 hw_error("register_ioport_write: invalid opaque");
407 ioport_opaque[i] = opaque;
409 return 0;
412 void isa_unassign_ioport(int start, int length)
414 int i;
416 for(i = start; i < start + length; i++) {
417 ioport_read_table[0][i] = default_ioport_readb;
418 ioport_read_table[1][i] = default_ioport_readw;
419 ioport_read_table[2][i] = default_ioport_readl;
421 ioport_write_table[0][i] = default_ioport_writeb;
422 ioport_write_table[1][i] = default_ioport_writew;
423 ioport_write_table[2][i] = default_ioport_writel;
425 ioport_opaque[i] = NULL;
429 /***********************************************************/
431 void cpu_outb(CPUState *env, int addr, int val)
433 #ifdef DEBUG_IOPORT
434 if (loglevel & CPU_LOG_IOPORT)
435 fprintf(logfile, "outb: %04x %02x\n", addr, val);
436 #endif
437 ioport_write(0, addr, val);
438 #ifdef USE_KQEMU
439 if (env)
440 env->last_io_time = cpu_get_time_fast();
441 #endif
444 void cpu_outw(CPUState *env, int addr, int val)
446 #ifdef DEBUG_IOPORT
447 if (loglevel & CPU_LOG_IOPORT)
448 fprintf(logfile, "outw: %04x %04x\n", addr, val);
449 #endif
450 ioport_write(1, addr, val);
451 #ifdef USE_KQEMU
452 if (env)
453 env->last_io_time = cpu_get_time_fast();
454 #endif
457 void cpu_outl(CPUState *env, int addr, int val)
459 #ifdef DEBUG_IOPORT
460 if (loglevel & CPU_LOG_IOPORT)
461 fprintf(logfile, "outl: %04x %08x\n", addr, val);
462 #endif
463 ioport_write(2, addr, val);
464 #ifdef USE_KQEMU
465 if (env)
466 env->last_io_time = cpu_get_time_fast();
467 #endif
470 int cpu_inb(CPUState *env, int addr)
472 int val;
473 val = ioport_read(0, addr);
474 #ifdef DEBUG_IOPORT
475 if (loglevel & CPU_LOG_IOPORT)
476 fprintf(logfile, "inb : %04x %02x\n", addr, val);
477 #endif
478 #ifdef USE_KQEMU
479 if (env)
480 env->last_io_time = cpu_get_time_fast();
481 #endif
482 return val;
485 int cpu_inw(CPUState *env, int addr)
487 int val;
488 val = ioport_read(1, addr);
489 #ifdef DEBUG_IOPORT
490 if (loglevel & CPU_LOG_IOPORT)
491 fprintf(logfile, "inw : %04x %04x\n", addr, val);
492 #endif
493 #ifdef USE_KQEMU
494 if (env)
495 env->last_io_time = cpu_get_time_fast();
496 #endif
497 return val;
500 int cpu_inl(CPUState *env, int addr)
502 int val;
503 val = ioport_read(2, addr);
504 #ifdef DEBUG_IOPORT
505 if (loglevel & CPU_LOG_IOPORT)
506 fprintf(logfile, "inl : %04x %08x\n", addr, val);
507 #endif
508 #ifdef USE_KQEMU
509 if (env)
510 env->last_io_time = cpu_get_time_fast();
511 #endif
512 return val;
515 /***********************************************************/
516 void hw_error(const char *fmt, ...)
518 va_list ap;
519 CPUState *env;
521 va_start(ap, fmt);
522 fprintf(stderr, "qemu: hardware error: ");
523 vfprintf(stderr, fmt, ap);
524 fprintf(stderr, "\n");
525 for(env = first_cpu; env != NULL; env = env->next_cpu) {
526 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
527 #ifdef TARGET_I386
528 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
529 #else
530 cpu_dump_state(env, stderr, fprintf, 0);
531 #endif
533 va_end(ap);
534 abort();
537 /***************/
538 /* ballooning */
540 static QEMUBalloonEvent *qemu_balloon_event;
541 void *qemu_balloon_event_opaque;
543 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
545 qemu_balloon_event = func;
546 qemu_balloon_event_opaque = opaque;
549 void qemu_balloon(ram_addr_t target)
551 if (qemu_balloon_event)
552 qemu_balloon_event(qemu_balloon_event_opaque, target);
555 ram_addr_t qemu_balloon_status(void)
557 if (qemu_balloon_event)
558 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
559 return 0;
562 /***********************************************************/
563 /* keyboard/mouse */
565 static QEMUPutKBDEvent *qemu_put_kbd_event;
566 static void *qemu_put_kbd_event_opaque;
567 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
568 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
570 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
572 qemu_put_kbd_event_opaque = opaque;
573 qemu_put_kbd_event = func;
576 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
577 void *opaque, int absolute,
578 const char *name)
580 QEMUPutMouseEntry *s, *cursor;
582 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
583 if (!s)
584 return NULL;
586 s->qemu_put_mouse_event = func;
587 s->qemu_put_mouse_event_opaque = opaque;
588 s->qemu_put_mouse_event_absolute = absolute;
589 s->qemu_put_mouse_event_name = qemu_strdup(name);
590 s->next = NULL;
592 if (!qemu_put_mouse_event_head) {
593 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
594 return s;
597 cursor = qemu_put_mouse_event_head;
598 while (cursor->next != NULL)
599 cursor = cursor->next;
601 cursor->next = s;
602 qemu_put_mouse_event_current = s;
604 return s;
607 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
609 QEMUPutMouseEntry *prev = NULL, *cursor;
611 if (!qemu_put_mouse_event_head || entry == NULL)
612 return;
614 cursor = qemu_put_mouse_event_head;
615 while (cursor != NULL && cursor != entry) {
616 prev = cursor;
617 cursor = cursor->next;
620 if (cursor == NULL) // does not exist or list empty
621 return;
622 else if (prev == NULL) { // entry is head
623 qemu_put_mouse_event_head = cursor->next;
624 if (qemu_put_mouse_event_current == entry)
625 qemu_put_mouse_event_current = cursor->next;
626 qemu_free(entry->qemu_put_mouse_event_name);
627 qemu_free(entry);
628 return;
631 prev->next = entry->next;
633 if (qemu_put_mouse_event_current == entry)
634 qemu_put_mouse_event_current = prev;
636 qemu_free(entry->qemu_put_mouse_event_name);
637 qemu_free(entry);
640 void kbd_put_keycode(int keycode)
642 if (qemu_put_kbd_event) {
643 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
647 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
649 QEMUPutMouseEvent *mouse_event;
650 void *mouse_event_opaque;
651 int width;
653 if (!qemu_put_mouse_event_current) {
654 return;
657 mouse_event =
658 qemu_put_mouse_event_current->qemu_put_mouse_event;
659 mouse_event_opaque =
660 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
662 if (mouse_event) {
663 if (graphic_rotate) {
664 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
665 width = 0x7fff;
666 else
667 width = graphic_width - 1;
668 mouse_event(mouse_event_opaque,
669 width - dy, dx, dz, buttons_state);
670 } else
671 mouse_event(mouse_event_opaque,
672 dx, dy, dz, buttons_state);
676 int kbd_mouse_is_absolute(void)
678 if (!qemu_put_mouse_event_current)
679 return 0;
681 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
684 void do_info_mice(void)
686 QEMUPutMouseEntry *cursor;
687 int index = 0;
689 if (!qemu_put_mouse_event_head) {
690 term_printf("No mouse devices connected\n");
691 return;
694 term_printf("Mouse devices available:\n");
695 cursor = qemu_put_mouse_event_head;
696 while (cursor != NULL) {
697 term_printf("%c Mouse #%d: %s\n",
698 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
699 index, cursor->qemu_put_mouse_event_name);
700 index++;
701 cursor = cursor->next;
705 void do_mouse_set(int index)
707 QEMUPutMouseEntry *cursor;
708 int i = 0;
710 if (!qemu_put_mouse_event_head) {
711 term_printf("No mouse devices connected\n");
712 return;
715 cursor = qemu_put_mouse_event_head;
716 while (cursor != NULL && index != i) {
717 i++;
718 cursor = cursor->next;
721 if (cursor != NULL)
722 qemu_put_mouse_event_current = cursor;
723 else
724 term_printf("Mouse at given index not found\n");
727 /* compute with 96 bit intermediate result: (a*b)/c */
728 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
730 union {
731 uint64_t ll;
732 struct {
733 #ifdef WORDS_BIGENDIAN
734 uint32_t high, low;
735 #else
736 uint32_t low, high;
737 #endif
738 } l;
739 } u, res;
740 uint64_t rl, rh;
742 u.ll = a;
743 rl = (uint64_t)u.l.low * (uint64_t)b;
744 rh = (uint64_t)u.l.high * (uint64_t)b;
745 rh += (rl >> 32);
746 res.l.high = rh / c;
747 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
748 return res.ll;
751 /***********************************************************/
752 /* real time host monotonic timer */
754 #define QEMU_TIMER_BASE 1000000000LL
756 #ifdef WIN32
758 static int64_t clock_freq;
760 static void init_get_clock(void)
762 LARGE_INTEGER freq;
763 int ret;
764 ret = QueryPerformanceFrequency(&freq);
765 if (ret == 0) {
766 fprintf(stderr, "Could not calibrate ticks\n");
767 exit(1);
769 clock_freq = freq.QuadPart;
772 static int64_t get_clock(void)
774 LARGE_INTEGER ti;
775 QueryPerformanceCounter(&ti);
776 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
779 #else
781 static int use_rt_clock;
783 static void init_get_clock(void)
785 use_rt_clock = 0;
786 #if defined(__linux__)
788 struct timespec ts;
789 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
790 use_rt_clock = 1;
793 #endif
796 static int64_t get_clock(void)
798 #if defined(__linux__)
799 if (use_rt_clock) {
800 struct timespec ts;
801 clock_gettime(CLOCK_MONOTONIC, &ts);
802 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
803 } else
804 #endif
806 /* XXX: using gettimeofday leads to problems if the date
807 changes, so it should be avoided. */
808 struct timeval tv;
809 gettimeofday(&tv, NULL);
810 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
813 #endif
815 /* Return the virtual CPU time, based on the instruction counter. */
816 static int64_t cpu_get_icount(void)
818 int64_t icount;
819 CPUState *env = cpu_single_env;;
820 icount = qemu_icount;
821 if (env) {
822 if (!can_do_io(env))
823 fprintf(stderr, "Bad clock read\n");
824 icount -= (env->icount_decr.u16.low + env->icount_extra);
826 return qemu_icount_bias + (icount << icount_time_shift);
829 /***********************************************************/
830 /* guest cycle counter */
832 static int64_t cpu_ticks_prev;
833 static int64_t cpu_ticks_offset;
834 static int64_t cpu_clock_offset;
835 static int cpu_ticks_enabled;
837 /* return the host CPU cycle counter and handle stop/restart */
838 int64_t cpu_get_ticks(void)
840 if (use_icount) {
841 return cpu_get_icount();
843 if (!cpu_ticks_enabled) {
844 return cpu_ticks_offset;
845 } else {
846 int64_t ticks;
847 ticks = cpu_get_real_ticks();
848 if (cpu_ticks_prev > ticks) {
849 /* Note: non increasing ticks may happen if the host uses
850 software suspend */
851 cpu_ticks_offset += cpu_ticks_prev - ticks;
853 cpu_ticks_prev = ticks;
854 return ticks + cpu_ticks_offset;
858 /* return the host CPU monotonic timer and handle stop/restart */
859 static int64_t cpu_get_clock(void)
861 int64_t ti;
862 if (!cpu_ticks_enabled) {
863 return cpu_clock_offset;
864 } else {
865 ti = get_clock();
866 return ti + cpu_clock_offset;
870 /* enable cpu_get_ticks() */
871 void cpu_enable_ticks(void)
873 if (!cpu_ticks_enabled) {
874 cpu_ticks_offset -= cpu_get_real_ticks();
875 cpu_clock_offset -= get_clock();
876 cpu_ticks_enabled = 1;
880 /* disable cpu_get_ticks() : the clock is stopped. You must not call
881 cpu_get_ticks() after that. */
882 void cpu_disable_ticks(void)
884 if (cpu_ticks_enabled) {
885 cpu_ticks_offset = cpu_get_ticks();
886 cpu_clock_offset = cpu_get_clock();
887 cpu_ticks_enabled = 0;
891 /***********************************************************/
892 /* timers */
894 #define QEMU_TIMER_REALTIME 0
895 #define QEMU_TIMER_VIRTUAL 1
897 struct QEMUClock {
898 int type;
899 /* XXX: add frequency */
902 struct QEMUTimer {
903 QEMUClock *clock;
904 int64_t expire_time;
905 QEMUTimerCB *cb;
906 void *opaque;
907 struct QEMUTimer *next;
910 struct qemu_alarm_timer {
911 char const *name;
912 unsigned int flags;
914 int (*start)(struct qemu_alarm_timer *t);
915 void (*stop)(struct qemu_alarm_timer *t);
916 void (*rearm)(struct qemu_alarm_timer *t);
917 void *priv;
920 #define ALARM_FLAG_DYNTICKS 0x1
921 #define ALARM_FLAG_EXPIRED 0x2
923 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
925 return t->flags & ALARM_FLAG_DYNTICKS;
928 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
930 if (!alarm_has_dynticks(t))
931 return;
933 t->rearm(t);
936 /* TODO: MIN_TIMER_REARM_US should be optimized */
937 #define MIN_TIMER_REARM_US 250
939 static struct qemu_alarm_timer *alarm_timer;
941 #ifdef _WIN32
943 struct qemu_alarm_win32 {
944 MMRESULT timerId;
945 HANDLE host_alarm;
946 unsigned int period;
947 } alarm_win32_data = {0, NULL, -1};
949 static int win32_start_timer(struct qemu_alarm_timer *t);
950 static void win32_stop_timer(struct qemu_alarm_timer *t);
951 static void win32_rearm_timer(struct qemu_alarm_timer *t);
953 #else
955 static int unix_start_timer(struct qemu_alarm_timer *t);
956 static void unix_stop_timer(struct qemu_alarm_timer *t);
958 #ifdef __linux__
960 static int dynticks_start_timer(struct qemu_alarm_timer *t);
961 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
962 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
964 static int hpet_start_timer(struct qemu_alarm_timer *t);
965 static void hpet_stop_timer(struct qemu_alarm_timer *t);
967 static int rtc_start_timer(struct qemu_alarm_timer *t);
968 static void rtc_stop_timer(struct qemu_alarm_timer *t);
970 #endif /* __linux__ */
972 #endif /* _WIN32 */
974 /* Correlation between real and virtual time is always going to be
975 fairly approximate, so ignore small variation.
976 When the guest is idle real and virtual time will be aligned in
977 the IO wait loop. */
978 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
980 static void icount_adjust(void)
982 int64_t cur_time;
983 int64_t cur_icount;
984 int64_t delta;
985 static int64_t last_delta;
986 /* If the VM is not running, then do nothing. */
987 if (!vm_running)
988 return;
990 cur_time = cpu_get_clock();
991 cur_icount = qemu_get_clock(vm_clock);
992 delta = cur_icount - cur_time;
993 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
994 if (delta > 0
995 && last_delta + ICOUNT_WOBBLE < delta * 2
996 && icount_time_shift > 0) {
997 /* The guest is getting too far ahead. Slow time down. */
998 icount_time_shift--;
1000 if (delta < 0
1001 && last_delta - ICOUNT_WOBBLE > delta * 2
1002 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1003 /* The guest is getting too far behind. Speed time up. */
1004 icount_time_shift++;
1006 last_delta = delta;
1007 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1010 static void icount_adjust_rt(void * opaque)
1012 qemu_mod_timer(icount_rt_timer,
1013 qemu_get_clock(rt_clock) + 1000);
1014 icount_adjust();
1017 static void icount_adjust_vm(void * opaque)
1019 qemu_mod_timer(icount_vm_timer,
1020 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1021 icount_adjust();
1024 static void init_icount_adjust(void)
1026 /* Have both realtime and virtual time triggers for speed adjustment.
1027 The realtime trigger catches emulated time passing too slowly,
1028 the virtual time trigger catches emulated time passing too fast.
1029 Realtime triggers occur even when idle, so use them less frequently
1030 than VM triggers. */
1031 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1032 qemu_mod_timer(icount_rt_timer,
1033 qemu_get_clock(rt_clock) + 1000);
1034 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1035 qemu_mod_timer(icount_vm_timer,
1036 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1039 static struct qemu_alarm_timer alarm_timers[] = {
1040 #ifndef _WIN32
1041 #ifdef __linux__
1042 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1043 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1044 /* HPET - if available - is preferred */
1045 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1046 /* ...otherwise try RTC */
1047 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1048 #endif
1049 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1050 #else
1051 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1052 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1053 {"win32", 0, win32_start_timer,
1054 win32_stop_timer, NULL, &alarm_win32_data},
1055 #endif
1056 {NULL, }
1059 static void show_available_alarms(void)
1061 int i;
1063 printf("Available alarm timers, in order of precedence:\n");
1064 for (i = 0; alarm_timers[i].name; i++)
1065 printf("%s\n", alarm_timers[i].name);
1068 static void configure_alarms(char const *opt)
1070 int i;
1071 int cur = 0;
1072 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1073 char *arg;
1074 char *name;
1075 struct qemu_alarm_timer tmp;
1077 if (!strcmp(opt, "?")) {
1078 show_available_alarms();
1079 exit(0);
1082 arg = strdup(opt);
1084 /* Reorder the array */
1085 name = strtok(arg, ",");
1086 while (name) {
1087 for (i = 0; i < count && alarm_timers[i].name; i++) {
1088 if (!strcmp(alarm_timers[i].name, name))
1089 break;
1092 if (i == count) {
1093 fprintf(stderr, "Unknown clock %s\n", name);
1094 goto next;
1097 if (i < cur)
1098 /* Ignore */
1099 goto next;
1101 /* Swap */
1102 tmp = alarm_timers[i];
1103 alarm_timers[i] = alarm_timers[cur];
1104 alarm_timers[cur] = tmp;
1106 cur++;
1107 next:
1108 name = strtok(NULL, ",");
1111 free(arg);
1113 if (cur) {
1114 /* Disable remaining timers */
1115 for (i = cur; i < count; i++)
1116 alarm_timers[i].name = NULL;
1117 } else {
1118 show_available_alarms();
1119 exit(1);
1123 QEMUClock *rt_clock;
1124 QEMUClock *vm_clock;
1126 static QEMUTimer *active_timers[2];
1128 static QEMUClock *qemu_new_clock(int type)
1130 QEMUClock *clock;
1131 clock = qemu_mallocz(sizeof(QEMUClock));
1132 if (!clock)
1133 return NULL;
1134 clock->type = type;
1135 return clock;
1138 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1140 QEMUTimer *ts;
1142 ts = qemu_mallocz(sizeof(QEMUTimer));
1143 ts->clock = clock;
1144 ts->cb = cb;
1145 ts->opaque = opaque;
1146 return ts;
1149 void qemu_free_timer(QEMUTimer *ts)
1151 qemu_free(ts);
1154 /* stop a timer, but do not dealloc it */
1155 void qemu_del_timer(QEMUTimer *ts)
1157 QEMUTimer **pt, *t;
1159 /* NOTE: this code must be signal safe because
1160 qemu_timer_expired() can be called from a signal. */
1161 pt = &active_timers[ts->clock->type];
1162 for(;;) {
1163 t = *pt;
1164 if (!t)
1165 break;
1166 if (t == ts) {
1167 *pt = t->next;
1168 break;
1170 pt = &t->next;
1174 /* modify the current timer so that it will be fired when current_time
1175 >= expire_time. The corresponding callback will be called. */
1176 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1178 QEMUTimer **pt, *t;
1180 qemu_del_timer(ts);
1182 /* add the timer in the sorted list */
1183 /* NOTE: this code must be signal safe because
1184 qemu_timer_expired() can be called from a signal. */
1185 pt = &active_timers[ts->clock->type];
1186 for(;;) {
1187 t = *pt;
1188 if (!t)
1189 break;
1190 if (t->expire_time > expire_time)
1191 break;
1192 pt = &t->next;
1194 ts->expire_time = expire_time;
1195 ts->next = *pt;
1196 *pt = ts;
1198 /* Rearm if necessary */
1199 if (pt == &active_timers[ts->clock->type]) {
1200 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1201 qemu_rearm_alarm_timer(alarm_timer);
1203 /* Interrupt execution to force deadline recalculation. */
1204 if (use_icount && cpu_single_env) {
1205 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1210 int qemu_timer_pending(QEMUTimer *ts)
1212 QEMUTimer *t;
1213 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1214 if (t == ts)
1215 return 1;
1217 return 0;
1220 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1222 if (!timer_head)
1223 return 0;
1224 return (timer_head->expire_time <= current_time);
1227 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1229 QEMUTimer *ts;
1231 for(;;) {
1232 ts = *ptimer_head;
1233 if (!ts || ts->expire_time > current_time)
1234 break;
1235 /* remove timer from the list before calling the callback */
1236 *ptimer_head = ts->next;
1237 ts->next = NULL;
1239 /* run the callback (the timer list can be modified) */
1240 ts->cb(ts->opaque);
1244 int64_t qemu_get_clock(QEMUClock *clock)
1246 switch(clock->type) {
1247 case QEMU_TIMER_REALTIME:
1248 return get_clock() / 1000000;
1249 default:
1250 case QEMU_TIMER_VIRTUAL:
1251 if (use_icount) {
1252 return cpu_get_icount();
1253 } else {
1254 return cpu_get_clock();
1259 static void init_timers(void)
1261 init_get_clock();
1262 ticks_per_sec = QEMU_TIMER_BASE;
1263 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1264 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1267 /* save a timer */
1268 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1270 uint64_t expire_time;
1272 if (qemu_timer_pending(ts)) {
1273 expire_time = ts->expire_time;
1274 } else {
1275 expire_time = -1;
1277 qemu_put_be64(f, expire_time);
1280 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1282 uint64_t expire_time;
1284 expire_time = qemu_get_be64(f);
1285 if (expire_time != -1) {
1286 qemu_mod_timer(ts, expire_time);
1287 } else {
1288 qemu_del_timer(ts);
1292 static void timer_save(QEMUFile *f, void *opaque)
1294 if (cpu_ticks_enabled) {
1295 hw_error("cannot save state if virtual timers are running");
1297 qemu_put_be64(f, cpu_ticks_offset);
1298 qemu_put_be64(f, ticks_per_sec);
1299 qemu_put_be64(f, cpu_clock_offset);
1302 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1304 if (version_id != 1 && version_id != 2)
1305 return -EINVAL;
1306 if (cpu_ticks_enabled) {
1307 return -EINVAL;
1309 cpu_ticks_offset=qemu_get_be64(f);
1310 ticks_per_sec=qemu_get_be64(f);
1311 if (version_id == 2) {
1312 cpu_clock_offset=qemu_get_be64(f);
1314 return 0;
1317 #ifdef _WIN32
1318 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1319 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1320 #else
1321 static void host_alarm_handler(int host_signum)
1322 #endif
1324 #if 0
1325 #define DISP_FREQ 1000
1327 static int64_t delta_min = INT64_MAX;
1328 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1329 static int count;
1330 ti = qemu_get_clock(vm_clock);
1331 if (last_clock != 0) {
1332 delta = ti - last_clock;
1333 if (delta < delta_min)
1334 delta_min = delta;
1335 if (delta > delta_max)
1336 delta_max = delta;
1337 delta_cum += delta;
1338 if (++count == DISP_FREQ) {
1339 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1340 muldiv64(delta_min, 1000000, ticks_per_sec),
1341 muldiv64(delta_max, 1000000, ticks_per_sec),
1342 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1343 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1344 count = 0;
1345 delta_min = INT64_MAX;
1346 delta_max = 0;
1347 delta_cum = 0;
1350 last_clock = ti;
1352 #endif
1353 if (1 ||
1354 alarm_has_dynticks(alarm_timer) ||
1355 (!use_icount &&
1356 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1357 qemu_get_clock(vm_clock))) ||
1358 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1359 qemu_get_clock(rt_clock))) {
1360 #ifdef _WIN32
1361 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1362 SetEvent(data->host_alarm);
1363 #endif
1364 CPUState *env = next_cpu;
1366 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1368 if (env) {
1369 /* stop the currently executing cpu because a timer occured */
1370 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1371 #ifdef USE_KQEMU
1372 if (env->kqemu_enabled) {
1373 kqemu_cpu_interrupt(env);
1375 #endif
1377 event_pending = 1;
1381 static int64_t qemu_next_deadline(void)
1383 int64_t delta;
1385 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1386 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1387 qemu_get_clock(vm_clock);
1388 } else {
1389 /* To avoid problems with overflow limit this to 2^32. */
1390 delta = INT32_MAX;
1393 if (delta < 0)
1394 delta = 0;
1396 return delta;
1399 #if defined(__linux__) || defined(_WIN32)
1400 static uint64_t qemu_next_deadline_dyntick(void)
1402 int64_t delta;
1403 int64_t rtdelta;
1405 if (use_icount)
1406 delta = INT32_MAX;
1407 else
1408 delta = (qemu_next_deadline() + 999) / 1000;
1410 if (active_timers[QEMU_TIMER_REALTIME]) {
1411 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1412 qemu_get_clock(rt_clock))*1000;
1413 if (rtdelta < delta)
1414 delta = rtdelta;
1417 if (delta < MIN_TIMER_REARM_US)
1418 delta = MIN_TIMER_REARM_US;
1420 return delta;
1422 #endif
1424 #ifndef _WIN32
1426 #if defined(__linux__)
1428 #define RTC_FREQ 1024
1430 static void enable_sigio_timer(int fd)
1432 struct sigaction act;
1434 /* timer signal */
1435 sigfillset(&act.sa_mask);
1436 act.sa_flags = 0;
1437 act.sa_handler = host_alarm_handler;
1439 sigaction(SIGIO, &act, NULL);
1440 fcntl(fd, F_SETFL, O_ASYNC);
1441 fcntl(fd, F_SETOWN, getpid());
1444 static int hpet_start_timer(struct qemu_alarm_timer *t)
1446 struct hpet_info info;
1447 int r, fd;
1449 fd = open("/dev/hpet", O_RDONLY);
1450 if (fd < 0)
1451 return -1;
1453 /* Set frequency */
1454 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1455 if (r < 0) {
1456 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1457 "error, but for better emulation accuracy type:\n"
1458 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1459 goto fail;
1462 /* Check capabilities */
1463 r = ioctl(fd, HPET_INFO, &info);
1464 if (r < 0)
1465 goto fail;
1467 /* Enable periodic mode */
1468 r = ioctl(fd, HPET_EPI, 0);
1469 if (info.hi_flags && (r < 0))
1470 goto fail;
1472 /* Enable interrupt */
1473 r = ioctl(fd, HPET_IE_ON, 0);
1474 if (r < 0)
1475 goto fail;
1477 enable_sigio_timer(fd);
1478 t->priv = (void *)(long)fd;
1480 return 0;
1481 fail:
1482 close(fd);
1483 return -1;
1486 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1488 int fd = (long)t->priv;
1490 close(fd);
1493 static int rtc_start_timer(struct qemu_alarm_timer *t)
1495 int rtc_fd;
1496 unsigned long current_rtc_freq = 0;
1498 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1499 if (rtc_fd < 0)
1500 return -1;
1501 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1502 if (current_rtc_freq != RTC_FREQ &&
1503 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1504 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1505 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1506 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1507 goto fail;
1509 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1510 fail:
1511 close(rtc_fd);
1512 return -1;
1515 enable_sigio_timer(rtc_fd);
1517 t->priv = (void *)(long)rtc_fd;
1519 return 0;
1522 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1524 int rtc_fd = (long)t->priv;
1526 close(rtc_fd);
1529 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1531 struct sigevent ev;
1532 timer_t host_timer;
1533 struct sigaction act;
1535 sigfillset(&act.sa_mask);
1536 act.sa_flags = 0;
1537 act.sa_handler = host_alarm_handler;
1539 sigaction(SIGALRM, &act, NULL);
1541 ev.sigev_value.sival_int = 0;
1542 ev.sigev_notify = SIGEV_SIGNAL;
1543 ev.sigev_signo = SIGALRM;
1545 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1546 perror("timer_create");
1548 /* disable dynticks */
1549 fprintf(stderr, "Dynamic Ticks disabled\n");
1551 return -1;
1554 t->priv = (void *)host_timer;
1556 return 0;
1559 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1561 timer_t host_timer = (timer_t)t->priv;
1563 timer_delete(host_timer);
1566 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1568 timer_t host_timer = (timer_t)t->priv;
1569 struct itimerspec timeout;
1570 int64_t nearest_delta_us = INT64_MAX;
1571 int64_t current_us;
1573 if (!active_timers[QEMU_TIMER_REALTIME] &&
1574 !active_timers[QEMU_TIMER_VIRTUAL])
1575 return;
1577 nearest_delta_us = qemu_next_deadline_dyntick();
1579 /* check whether a timer is already running */
1580 if (timer_gettime(host_timer, &timeout)) {
1581 perror("gettime");
1582 fprintf(stderr, "Internal timer error: aborting\n");
1583 exit(1);
1585 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1586 if (current_us && current_us <= nearest_delta_us)
1587 return;
1589 timeout.it_interval.tv_sec = 0;
1590 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1591 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1592 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1593 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1594 perror("settime");
1595 fprintf(stderr, "Internal timer error: aborting\n");
1596 exit(1);
1600 #endif /* defined(__linux__) */
1602 static int unix_start_timer(struct qemu_alarm_timer *t)
1604 struct sigaction act;
1605 struct itimerval itv;
1606 int err;
1608 /* timer signal */
1609 sigfillset(&act.sa_mask);
1610 act.sa_flags = 0;
1611 act.sa_handler = host_alarm_handler;
1613 sigaction(SIGALRM, &act, NULL);
1615 itv.it_interval.tv_sec = 0;
1616 /* for i386 kernel 2.6 to get 1 ms */
1617 itv.it_interval.tv_usec = 999;
1618 itv.it_value.tv_sec = 0;
1619 itv.it_value.tv_usec = 10 * 1000;
1621 err = setitimer(ITIMER_REAL, &itv, NULL);
1622 if (err)
1623 return -1;
1625 return 0;
1628 static void unix_stop_timer(struct qemu_alarm_timer *t)
1630 struct itimerval itv;
1632 memset(&itv, 0, sizeof(itv));
1633 setitimer(ITIMER_REAL, &itv, NULL);
1636 #endif /* !defined(_WIN32) */
1638 #ifdef _WIN32
1640 static int win32_start_timer(struct qemu_alarm_timer *t)
1642 TIMECAPS tc;
1643 struct qemu_alarm_win32 *data = t->priv;
1644 UINT flags;
1646 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1647 if (!data->host_alarm) {
1648 perror("Failed CreateEvent");
1649 return -1;
1652 memset(&tc, 0, sizeof(tc));
1653 timeGetDevCaps(&tc, sizeof(tc));
1655 if (data->period < tc.wPeriodMin)
1656 data->period = tc.wPeriodMin;
1658 timeBeginPeriod(data->period);
1660 flags = TIME_CALLBACK_FUNCTION;
1661 if (alarm_has_dynticks(t))
1662 flags |= TIME_ONESHOT;
1663 else
1664 flags |= TIME_PERIODIC;
1666 data->timerId = timeSetEvent(1, // interval (ms)
1667 data->period, // resolution
1668 host_alarm_handler, // function
1669 (DWORD)t, // parameter
1670 flags);
1672 if (!data->timerId) {
1673 perror("Failed to initialize win32 alarm timer");
1675 timeEndPeriod(data->period);
1676 CloseHandle(data->host_alarm);
1677 return -1;
1680 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1682 return 0;
1685 static void win32_stop_timer(struct qemu_alarm_timer *t)
1687 struct qemu_alarm_win32 *data = t->priv;
1689 timeKillEvent(data->timerId);
1690 timeEndPeriod(data->period);
1692 CloseHandle(data->host_alarm);
1695 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1697 struct qemu_alarm_win32 *data = t->priv;
1698 uint64_t nearest_delta_us;
1700 if (!active_timers[QEMU_TIMER_REALTIME] &&
1701 !active_timers[QEMU_TIMER_VIRTUAL])
1702 return;
1704 nearest_delta_us = qemu_next_deadline_dyntick();
1705 nearest_delta_us /= 1000;
1707 timeKillEvent(data->timerId);
1709 data->timerId = timeSetEvent(1,
1710 data->period,
1711 host_alarm_handler,
1712 (DWORD)t,
1713 TIME_ONESHOT | TIME_PERIODIC);
1715 if (!data->timerId) {
1716 perror("Failed to re-arm win32 alarm timer");
1718 timeEndPeriod(data->period);
1719 CloseHandle(data->host_alarm);
1720 exit(1);
1724 #endif /* _WIN32 */
1726 static void init_timer_alarm(void)
1728 struct qemu_alarm_timer *t;
1729 int i, err = -1;
1731 for (i = 0; alarm_timers[i].name; i++) {
1732 t = &alarm_timers[i];
1734 err = t->start(t);
1735 if (!err)
1736 break;
1739 if (err) {
1740 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1741 fprintf(stderr, "Terminating\n");
1742 exit(1);
1745 alarm_timer = t;
1748 static void quit_timers(void)
1750 alarm_timer->stop(alarm_timer);
1751 alarm_timer = NULL;
1754 /***********************************************************/
1755 /* host time/date access */
1756 void qemu_get_timedate(struct tm *tm, int offset)
1758 time_t ti;
1759 struct tm *ret;
1761 time(&ti);
1762 ti += offset;
1763 if (rtc_date_offset == -1) {
1764 if (rtc_utc)
1765 ret = gmtime(&ti);
1766 else
1767 ret = localtime(&ti);
1768 } else {
1769 ti -= rtc_date_offset;
1770 ret = gmtime(&ti);
1773 memcpy(tm, ret, sizeof(struct tm));
1776 int qemu_timedate_diff(struct tm *tm)
1778 time_t seconds;
1780 if (rtc_date_offset == -1)
1781 if (rtc_utc)
1782 seconds = mktimegm(tm);
1783 else
1784 seconds = mktime(tm);
1785 else
1786 seconds = mktimegm(tm) + rtc_date_offset;
1788 return seconds - time(NULL);
1791 /***********************************************************/
1792 /* character device */
1794 static void qemu_chr_event(CharDriverState *s, int event)
1796 if (!s->chr_event)
1797 return;
1798 s->chr_event(s->handler_opaque, event);
1801 static void qemu_chr_reset_bh(void *opaque)
1803 CharDriverState *s = opaque;
1804 qemu_chr_event(s, CHR_EVENT_RESET);
1805 qemu_bh_delete(s->bh);
1806 s->bh = NULL;
1809 void qemu_chr_reset(CharDriverState *s)
1811 if (s->bh == NULL) {
1812 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1813 qemu_bh_schedule(s->bh);
1817 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1819 return s->chr_write(s, buf, len);
1822 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1824 if (!s->chr_ioctl)
1825 return -ENOTSUP;
1826 return s->chr_ioctl(s, cmd, arg);
1829 int qemu_chr_can_read(CharDriverState *s)
1831 if (!s->chr_can_read)
1832 return 0;
1833 return s->chr_can_read(s->handler_opaque);
1836 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1838 s->chr_read(s->handler_opaque, buf, len);
1841 void qemu_chr_accept_input(CharDriverState *s)
1843 if (s->chr_accept_input)
1844 s->chr_accept_input(s);
1847 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1849 char buf[4096];
1850 va_list ap;
1851 va_start(ap, fmt);
1852 vsnprintf(buf, sizeof(buf), fmt, ap);
1853 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1854 va_end(ap);
1857 void qemu_chr_send_event(CharDriverState *s, int event)
1859 if (s->chr_send_event)
1860 s->chr_send_event(s, event);
1863 void qemu_chr_add_handlers(CharDriverState *s,
1864 IOCanRWHandler *fd_can_read,
1865 IOReadHandler *fd_read,
1866 IOEventHandler *fd_event,
1867 void *opaque)
1869 s->chr_can_read = fd_can_read;
1870 s->chr_read = fd_read;
1871 s->chr_event = fd_event;
1872 s->handler_opaque = opaque;
1873 if (s->chr_update_read_handler)
1874 s->chr_update_read_handler(s);
1877 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1879 return len;
1882 static CharDriverState *qemu_chr_open_null(void)
1884 CharDriverState *chr;
1886 chr = qemu_mallocz(sizeof(CharDriverState));
1887 if (!chr)
1888 return NULL;
1889 chr->chr_write = null_chr_write;
1890 return chr;
1893 /* MUX driver for serial I/O splitting */
1894 static int term_timestamps;
1895 static int64_t term_timestamps_start;
1896 #define MAX_MUX 4
1897 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1898 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1899 typedef struct {
1900 IOCanRWHandler *chr_can_read[MAX_MUX];
1901 IOReadHandler *chr_read[MAX_MUX];
1902 IOEventHandler *chr_event[MAX_MUX];
1903 void *ext_opaque[MAX_MUX];
1904 CharDriverState *drv;
1905 unsigned char buffer[MUX_BUFFER_SIZE];
1906 int prod;
1907 int cons;
1908 int mux_cnt;
1909 int term_got_escape;
1910 int max_size;
1911 } MuxDriver;
1914 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1916 MuxDriver *d = chr->opaque;
1917 int ret;
1918 if (!term_timestamps) {
1919 ret = d->drv->chr_write(d->drv, buf, len);
1920 } else {
1921 int i;
1923 ret = 0;
1924 for(i = 0; i < len; i++) {
1925 ret += d->drv->chr_write(d->drv, buf+i, 1);
1926 if (buf[i] == '\n') {
1927 char buf1[64];
1928 int64_t ti;
1929 int secs;
1931 ti = get_clock();
1932 if (term_timestamps_start == -1)
1933 term_timestamps_start = ti;
1934 ti -= term_timestamps_start;
1935 secs = ti / 1000000000;
1936 snprintf(buf1, sizeof(buf1),
1937 "[%02d:%02d:%02d.%03d] ",
1938 secs / 3600,
1939 (secs / 60) % 60,
1940 secs % 60,
1941 (int)((ti / 1000000) % 1000));
1942 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1946 return ret;
1949 static const char * const mux_help[] = {
1950 "% h print this help\n\r",
1951 "% x exit emulator\n\r",
1952 "% s save disk data back to file (if -snapshot)\n\r",
1953 "% t toggle console timestamps\n\r"
1954 "% b send break (magic sysrq)\n\r",
1955 "% c switch between console and monitor\n\r",
1956 "% % sends %\n\r",
1957 NULL
1960 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1961 static void mux_print_help(CharDriverState *chr)
1963 int i, j;
1964 char ebuf[15] = "Escape-Char";
1965 char cbuf[50] = "\n\r";
1967 if (term_escape_char > 0 && term_escape_char < 26) {
1968 snprintf(cbuf, sizeof(cbuf), "\n\r");
1969 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1970 } else {
1971 snprintf(cbuf, sizeof(cbuf),
1972 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1973 term_escape_char);
1975 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1976 for (i = 0; mux_help[i] != NULL; i++) {
1977 for (j=0; mux_help[i][j] != '\0'; j++) {
1978 if (mux_help[i][j] == '%')
1979 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1980 else
1981 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1986 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1988 if (d->term_got_escape) {
1989 d->term_got_escape = 0;
1990 if (ch == term_escape_char)
1991 goto send_char;
1992 switch(ch) {
1993 case '?':
1994 case 'h':
1995 mux_print_help(chr);
1996 break;
1997 case 'x':
1999 const char *term = "QEMU: Terminated\n\r";
2000 chr->chr_write(chr,(uint8_t *)term,strlen(term));
2001 exit(0);
2002 break;
2004 case 's':
2006 int i;
2007 for (i = 0; i < nb_drives; i++) {
2008 bdrv_commit(drives_table[i].bdrv);
2011 break;
2012 case 'b':
2013 qemu_chr_event(chr, CHR_EVENT_BREAK);
2014 break;
2015 case 'c':
2016 /* Switch to the next registered device */
2017 chr->focus++;
2018 if (chr->focus >= d->mux_cnt)
2019 chr->focus = 0;
2020 break;
2021 case 't':
2022 term_timestamps = !term_timestamps;
2023 term_timestamps_start = -1;
2024 break;
2026 } else if (ch == term_escape_char) {
2027 d->term_got_escape = 1;
2028 } else {
2029 send_char:
2030 return 1;
2032 return 0;
2035 static void mux_chr_accept_input(CharDriverState *chr)
2037 int m = chr->focus;
2038 MuxDriver *d = chr->opaque;
2040 while (d->prod != d->cons &&
2041 d->chr_can_read[m] &&
2042 d->chr_can_read[m](d->ext_opaque[m])) {
2043 d->chr_read[m](d->ext_opaque[m],
2044 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
2048 static int mux_chr_can_read(void *opaque)
2050 CharDriverState *chr = opaque;
2051 MuxDriver *d = chr->opaque;
2053 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2054 return 1;
2055 if (d->chr_can_read[chr->focus])
2056 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2057 return 0;
2060 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2062 CharDriverState *chr = opaque;
2063 MuxDriver *d = chr->opaque;
2064 int m = chr->focus;
2065 int i;
2067 mux_chr_accept_input (opaque);
2069 for(i = 0; i < size; i++)
2070 if (mux_proc_byte(chr, d, buf[i])) {
2071 if (d->prod == d->cons &&
2072 d->chr_can_read[m] &&
2073 d->chr_can_read[m](d->ext_opaque[m]))
2074 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2075 else
2076 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2080 static void mux_chr_event(void *opaque, int event)
2082 CharDriverState *chr = opaque;
2083 MuxDriver *d = chr->opaque;
2084 int i;
2086 /* Send the event to all registered listeners */
2087 for (i = 0; i < d->mux_cnt; i++)
2088 if (d->chr_event[i])
2089 d->chr_event[i](d->ext_opaque[i], event);
2092 static void mux_chr_update_read_handler(CharDriverState *chr)
2094 MuxDriver *d = chr->opaque;
2096 if (d->mux_cnt >= MAX_MUX) {
2097 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2098 return;
2100 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2101 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2102 d->chr_read[d->mux_cnt] = chr->chr_read;
2103 d->chr_event[d->mux_cnt] = chr->chr_event;
2104 /* Fix up the real driver with mux routines */
2105 if (d->mux_cnt == 0) {
2106 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2107 mux_chr_event, chr);
2109 chr->focus = d->mux_cnt;
2110 d->mux_cnt++;
2113 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2115 CharDriverState *chr;
2116 MuxDriver *d;
2118 chr = qemu_mallocz(sizeof(CharDriverState));
2119 if (!chr)
2120 return NULL;
2121 d = qemu_mallocz(sizeof(MuxDriver));
2122 if (!d) {
2123 free(chr);
2124 return NULL;
2127 chr->opaque = d;
2128 d->drv = drv;
2129 chr->focus = -1;
2130 chr->chr_write = mux_chr_write;
2131 chr->chr_update_read_handler = mux_chr_update_read_handler;
2132 chr->chr_accept_input = mux_chr_accept_input;
2133 return chr;
2137 #ifdef _WIN32
2139 static void socket_cleanup(void)
2141 WSACleanup();
2144 static int socket_init(void)
2146 WSADATA Data;
2147 int ret, err;
2149 ret = WSAStartup(MAKEWORD(2,2), &Data);
2150 if (ret != 0) {
2151 err = WSAGetLastError();
2152 fprintf(stderr, "WSAStartup: %d\n", err);
2153 return -1;
2155 atexit(socket_cleanup);
2156 return 0;
2159 static int send_all(int fd, const uint8_t *buf, int len1)
2161 int ret, len;
2163 len = len1;
2164 while (len > 0) {
2165 ret = send(fd, buf, len, 0);
2166 if (ret < 0) {
2167 int errno;
2168 errno = WSAGetLastError();
2169 if (errno != WSAEWOULDBLOCK) {
2170 return -1;
2172 } else if (ret == 0) {
2173 break;
2174 } else {
2175 buf += ret;
2176 len -= ret;
2179 return len1 - len;
2182 #else
2184 static int unix_write(int fd, const uint8_t *buf, int len1)
2186 int ret, len;
2188 len = len1;
2189 while (len > 0) {
2190 ret = write(fd, buf, len);
2191 if (ret < 0) {
2192 if (errno != EINTR && errno != EAGAIN)
2193 return -1;
2194 } else if (ret == 0) {
2195 break;
2196 } else {
2197 buf += ret;
2198 len -= ret;
2201 return len1 - len;
2204 static inline int send_all(int fd, const uint8_t *buf, int len1)
2206 return unix_write(fd, buf, len1);
2208 #endif /* !_WIN32 */
2210 #ifndef _WIN32
2212 typedef struct {
2213 int fd_in, fd_out;
2214 int max_size;
2215 } FDCharDriver;
2217 #define STDIO_MAX_CLIENTS 1
2218 static int stdio_nb_clients = 0;
2220 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2222 FDCharDriver *s = chr->opaque;
2223 return unix_write(s->fd_out, buf, len);
2226 static int fd_chr_read_poll(void *opaque)
2228 CharDriverState *chr = opaque;
2229 FDCharDriver *s = chr->opaque;
2231 s->max_size = qemu_chr_can_read(chr);
2232 return s->max_size;
2235 static void fd_chr_read(void *opaque)
2237 CharDriverState *chr = opaque;
2238 FDCharDriver *s = chr->opaque;
2239 int size, len;
2240 uint8_t buf[1024];
2242 len = sizeof(buf);
2243 if (len > s->max_size)
2244 len = s->max_size;
2245 if (len == 0)
2246 return;
2247 size = read(s->fd_in, buf, len);
2248 if (size == 0) {
2249 /* FD has been closed. Remove it from the active list. */
2250 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2251 return;
2253 if (size > 0) {
2254 qemu_chr_read(chr, buf, size);
2258 static void fd_chr_update_read_handler(CharDriverState *chr)
2260 FDCharDriver *s = chr->opaque;
2262 if (s->fd_in >= 0) {
2263 if (nographic && s->fd_in == 0) {
2264 } else {
2265 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2266 fd_chr_read, NULL, chr);
2271 static void fd_chr_close(struct CharDriverState *chr)
2273 FDCharDriver *s = chr->opaque;
2275 if (s->fd_in >= 0) {
2276 if (nographic && s->fd_in == 0) {
2277 } else {
2278 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2282 qemu_free(s);
2285 /* open a character device to a unix fd */
2286 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2288 CharDriverState *chr;
2289 FDCharDriver *s;
2291 chr = qemu_mallocz(sizeof(CharDriverState));
2292 if (!chr)
2293 return NULL;
2294 s = qemu_mallocz(sizeof(FDCharDriver));
2295 if (!s) {
2296 free(chr);
2297 return NULL;
2299 s->fd_in = fd_in;
2300 s->fd_out = fd_out;
2301 chr->opaque = s;
2302 chr->chr_write = fd_chr_write;
2303 chr->chr_update_read_handler = fd_chr_update_read_handler;
2304 chr->chr_close = fd_chr_close;
2306 qemu_chr_reset(chr);
2308 return chr;
2311 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2313 int fd_out;
2315 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2316 if (fd_out < 0)
2317 return NULL;
2318 return qemu_chr_open_fd(-1, fd_out);
2321 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2323 int fd_in, fd_out;
2324 char filename_in[256], filename_out[256];
2326 snprintf(filename_in, 256, "%s.in", filename);
2327 snprintf(filename_out, 256, "%s.out", filename);
2328 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2329 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2330 if (fd_in < 0 || fd_out < 0) {
2331 if (fd_in >= 0)
2332 close(fd_in);
2333 if (fd_out >= 0)
2334 close(fd_out);
2335 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2336 if (fd_in < 0)
2337 return NULL;
2339 return qemu_chr_open_fd(fd_in, fd_out);
2343 /* for STDIO, we handle the case where several clients use it
2344 (nographic mode) */
2346 #define TERM_FIFO_MAX_SIZE 1
2348 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2349 static int term_fifo_size;
2351 static int stdio_read_poll(void *opaque)
2353 CharDriverState *chr = opaque;
2355 /* try to flush the queue if needed */
2356 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2357 qemu_chr_read(chr, term_fifo, 1);
2358 term_fifo_size = 0;
2360 /* see if we can absorb more chars */
2361 if (term_fifo_size == 0)
2362 return 1;
2363 else
2364 return 0;
2367 static void stdio_read(void *opaque)
2369 int size;
2370 uint8_t buf[1];
2371 CharDriverState *chr = opaque;
2373 size = read(0, buf, 1);
2374 if (size == 0) {
2375 /* stdin has been closed. Remove it from the active list. */
2376 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2377 return;
2379 if (size > 0) {
2380 if (qemu_chr_can_read(chr) > 0) {
2381 qemu_chr_read(chr, buf, 1);
2382 } else if (term_fifo_size == 0) {
2383 term_fifo[term_fifo_size++] = buf[0];
2388 /* init terminal so that we can grab keys */
2389 static struct termios oldtty;
2390 static int old_fd0_flags;
2391 static int term_atexit_done;
2393 static void term_exit(void)
2395 tcsetattr (0, TCSANOW, &oldtty);
2396 fcntl(0, F_SETFL, old_fd0_flags);
2399 static void term_init(void)
2401 struct termios tty;
2403 tcgetattr (0, &tty);
2404 oldtty = tty;
2405 old_fd0_flags = fcntl(0, F_GETFL);
2407 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2408 |INLCR|IGNCR|ICRNL|IXON);
2409 tty.c_oflag |= OPOST;
2410 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2411 /* if graphical mode, we allow Ctrl-C handling */
2412 if (nographic)
2413 tty.c_lflag &= ~ISIG;
2414 tty.c_cflag &= ~(CSIZE|PARENB);
2415 tty.c_cflag |= CS8;
2416 tty.c_cc[VMIN] = 1;
2417 tty.c_cc[VTIME] = 0;
2419 tcsetattr (0, TCSANOW, &tty);
2421 if (!term_atexit_done++)
2422 atexit(term_exit);
2424 fcntl(0, F_SETFL, O_NONBLOCK);
2427 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2429 term_exit();
2430 stdio_nb_clients--;
2431 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2432 fd_chr_close(chr);
2435 static CharDriverState *qemu_chr_open_stdio(void)
2437 CharDriverState *chr;
2439 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2440 return NULL;
2441 chr = qemu_chr_open_fd(0, 1);
2442 chr->chr_close = qemu_chr_close_stdio;
2443 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2444 stdio_nb_clients++;
2445 term_init();
2447 return chr;
2450 #ifdef __sun__
2451 /* Once Solaris has openpty(), this is going to be removed. */
2452 int openpty(int *amaster, int *aslave, char *name,
2453 struct termios *termp, struct winsize *winp)
2455 const char *slave;
2456 int mfd = -1, sfd = -1;
2458 *amaster = *aslave = -1;
2460 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2461 if (mfd < 0)
2462 goto err;
2464 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2465 goto err;
2467 if ((slave = ptsname(mfd)) == NULL)
2468 goto err;
2470 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2471 goto err;
2473 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2474 (termp != NULL && tcgetattr(sfd, termp) < 0))
2475 goto err;
2477 if (amaster)
2478 *amaster = mfd;
2479 if (aslave)
2480 *aslave = sfd;
2481 if (winp)
2482 ioctl(sfd, TIOCSWINSZ, winp);
2484 return 0;
2486 err:
2487 if (sfd != -1)
2488 close(sfd);
2489 close(mfd);
2490 return -1;
2493 void cfmakeraw (struct termios *termios_p)
2495 termios_p->c_iflag &=
2496 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2497 termios_p->c_oflag &= ~OPOST;
2498 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2499 termios_p->c_cflag &= ~(CSIZE|PARENB);
2500 termios_p->c_cflag |= CS8;
2502 termios_p->c_cc[VMIN] = 0;
2503 termios_p->c_cc[VTIME] = 0;
2505 #endif
2507 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2508 || defined(__NetBSD__) || defined(__OpenBSD__)
2510 typedef struct {
2511 int fd;
2512 int connected;
2513 int polling;
2514 int read_bytes;
2515 QEMUTimer *timer;
2516 } PtyCharDriver;
2518 static void pty_chr_update_read_handler(CharDriverState *chr);
2519 static void pty_chr_state(CharDriverState *chr, int connected);
2521 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2523 PtyCharDriver *s = chr->opaque;
2525 if (!s->connected) {
2526 /* guest sends data, check for (re-)connect */
2527 pty_chr_update_read_handler(chr);
2528 return 0;
2530 return unix_write(s->fd, buf, len);
2533 static int pty_chr_read_poll(void *opaque)
2535 CharDriverState *chr = opaque;
2536 PtyCharDriver *s = chr->opaque;
2538 s->read_bytes = qemu_chr_can_read(chr);
2539 return s->read_bytes;
2542 static void pty_chr_read(void *opaque)
2544 CharDriverState *chr = opaque;
2545 PtyCharDriver *s = chr->opaque;
2546 int size, len;
2547 uint8_t buf[1024];
2549 len = sizeof(buf);
2550 if (len > s->read_bytes)
2551 len = s->read_bytes;
2552 if (len == 0)
2553 return;
2554 size = read(s->fd, buf, len);
2555 if ((size == -1 && errno == EIO) ||
2556 (size == 0)) {
2557 pty_chr_state(chr, 0);
2558 return;
2560 if (size > 0) {
2561 pty_chr_state(chr, 1);
2562 qemu_chr_read(chr, buf, size);
2566 static void pty_chr_update_read_handler(CharDriverState *chr)
2568 PtyCharDriver *s = chr->opaque;
2570 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2571 pty_chr_read, NULL, chr);
2572 s->polling = 1;
2574 * Short timeout here: just need wait long enougth that qemu makes
2575 * it through the poll loop once. When reconnected we want a
2576 * short timeout so we notice it almost instantly. Otherwise
2577 * read() gives us -EIO instantly, making pty_chr_state() reset the
2578 * timeout to the normal (much longer) poll interval before the
2579 * timer triggers.
2581 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2584 static void pty_chr_state(CharDriverState *chr, int connected)
2586 PtyCharDriver *s = chr->opaque;
2588 if (!connected) {
2589 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2590 s->connected = 0;
2591 s->polling = 0;
2592 /* (re-)connect poll interval for idle guests: once per second.
2593 * We check more frequently in case the guests sends data to
2594 * the virtual device linked to our pty. */
2595 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2596 } else {
2597 if (!s->connected)
2598 qemu_chr_reset(chr);
2599 s->connected = 1;
2603 static void pty_chr_timer(void *opaque)
2605 struct CharDriverState *chr = opaque;
2606 PtyCharDriver *s = chr->opaque;
2608 if (s->connected)
2609 return;
2610 if (s->polling) {
2611 /* If we arrive here without polling being cleared due
2612 * read returning -EIO, then we are (re-)connected */
2613 pty_chr_state(chr, 1);
2614 return;
2617 /* Next poll ... */
2618 pty_chr_update_read_handler(chr);
2621 static void pty_chr_close(struct CharDriverState *chr)
2623 PtyCharDriver *s = chr->opaque;
2625 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2626 close(s->fd);
2627 qemu_free(s);
2630 static CharDriverState *qemu_chr_open_pty(void)
2632 CharDriverState *chr;
2633 PtyCharDriver *s;
2634 struct termios tty;
2635 int slave_fd;
2636 #if defined(__OpenBSD__)
2637 char pty_name[PATH_MAX];
2638 #define q_ptsname(x) pty_name
2639 #else
2640 char *pty_name = NULL;
2641 #define q_ptsname(x) ptsname(x)
2642 #endif
2644 chr = qemu_mallocz(sizeof(CharDriverState));
2645 if (!chr)
2646 return NULL;
2647 s = qemu_mallocz(sizeof(PtyCharDriver));
2648 if (!s) {
2649 qemu_free(chr);
2650 return NULL;
2653 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2654 return NULL;
2657 /* Set raw attributes on the pty. */
2658 cfmakeraw(&tty);
2659 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2660 close(slave_fd);
2662 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2664 chr->opaque = s;
2665 chr->chr_write = pty_chr_write;
2666 chr->chr_update_read_handler = pty_chr_update_read_handler;
2667 chr->chr_close = pty_chr_close;
2669 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2671 return chr;
2674 static void tty_serial_init(int fd, int speed,
2675 int parity, int data_bits, int stop_bits)
2677 struct termios tty;
2678 speed_t spd;
2680 #if 0
2681 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2682 speed, parity, data_bits, stop_bits);
2683 #endif
2684 tcgetattr (fd, &tty);
2686 #define MARGIN 1.1
2687 if (speed <= 50 * MARGIN)
2688 spd = B50;
2689 else if (speed <= 75 * MARGIN)
2690 spd = B75;
2691 else if (speed <= 300 * MARGIN)
2692 spd = B300;
2693 else if (speed <= 600 * MARGIN)
2694 spd = B600;
2695 else if (speed <= 1200 * MARGIN)
2696 spd = B1200;
2697 else if (speed <= 2400 * MARGIN)
2698 spd = B2400;
2699 else if (speed <= 4800 * MARGIN)
2700 spd = B4800;
2701 else if (speed <= 9600 * MARGIN)
2702 spd = B9600;
2703 else if (speed <= 19200 * MARGIN)
2704 spd = B19200;
2705 else if (speed <= 38400 * MARGIN)
2706 spd = B38400;
2707 else if (speed <= 57600 * MARGIN)
2708 spd = B57600;
2709 else if (speed <= 115200 * MARGIN)
2710 spd = B115200;
2711 else
2712 spd = B115200;
2714 cfsetispeed(&tty, spd);
2715 cfsetospeed(&tty, spd);
2717 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2718 |INLCR|IGNCR|ICRNL|IXON);
2719 tty.c_oflag |= OPOST;
2720 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2721 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2722 switch(data_bits) {
2723 default:
2724 case 8:
2725 tty.c_cflag |= CS8;
2726 break;
2727 case 7:
2728 tty.c_cflag |= CS7;
2729 break;
2730 case 6:
2731 tty.c_cflag |= CS6;
2732 break;
2733 case 5:
2734 tty.c_cflag |= CS5;
2735 break;
2737 switch(parity) {
2738 default:
2739 case 'N':
2740 break;
2741 case 'E':
2742 tty.c_cflag |= PARENB;
2743 break;
2744 case 'O':
2745 tty.c_cflag |= PARENB | PARODD;
2746 break;
2748 if (stop_bits == 2)
2749 tty.c_cflag |= CSTOPB;
2751 tcsetattr (fd, TCSANOW, &tty);
2754 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2756 FDCharDriver *s = chr->opaque;
2758 switch(cmd) {
2759 case CHR_IOCTL_SERIAL_SET_PARAMS:
2761 QEMUSerialSetParams *ssp = arg;
2762 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2763 ssp->data_bits, ssp->stop_bits);
2765 break;
2766 case CHR_IOCTL_SERIAL_SET_BREAK:
2768 int enable = *(int *)arg;
2769 if (enable)
2770 tcsendbreak(s->fd_in, 1);
2772 break;
2773 case CHR_IOCTL_SERIAL_GET_TIOCM:
2775 int sarg = 0;
2776 int *targ = (int *)arg;
2777 ioctl(s->fd_in, TIOCMGET, &sarg);
2778 *targ = 0;
2779 if (sarg | TIOCM_CTS)
2780 *targ |= CHR_TIOCM_CTS;
2781 if (sarg | TIOCM_CAR)
2782 *targ |= CHR_TIOCM_CAR;
2783 if (sarg | TIOCM_DSR)
2784 *targ |= CHR_TIOCM_DSR;
2785 if (sarg | TIOCM_RI)
2786 *targ |= CHR_TIOCM_RI;
2787 if (sarg | TIOCM_DTR)
2788 *targ |= CHR_TIOCM_DTR;
2789 if (sarg | TIOCM_RTS)
2790 *targ |= CHR_TIOCM_RTS;
2792 break;
2793 case CHR_IOCTL_SERIAL_SET_TIOCM:
2795 int sarg = *(int *)arg;
2796 int targ = 0;
2797 if (sarg | CHR_TIOCM_DTR)
2798 targ |= TIOCM_DTR;
2799 if (sarg | CHR_TIOCM_RTS)
2800 targ |= TIOCM_RTS;
2801 ioctl(s->fd_in, TIOCMSET, &targ);
2803 break;
2804 default:
2805 return -ENOTSUP;
2807 return 0;
2810 static CharDriverState *qemu_chr_open_tty(const char *filename)
2812 CharDriverState *chr;
2813 int fd;
2815 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2816 tty_serial_init(fd, 115200, 'N', 8, 1);
2817 chr = qemu_chr_open_fd(fd, fd);
2818 if (!chr) {
2819 close(fd);
2820 return NULL;
2822 chr->chr_ioctl = tty_serial_ioctl;
2823 qemu_chr_reset(chr);
2824 return chr;
2826 #else /* ! __linux__ && ! __sun__ */
2827 static CharDriverState *qemu_chr_open_pty(void)
2829 return NULL;
2831 #endif /* __linux__ || __sun__ */
2833 #if defined(__linux__)
2834 typedef struct {
2835 int fd;
2836 int mode;
2837 } ParallelCharDriver;
2839 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2841 if (s->mode != mode) {
2842 int m = mode;
2843 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2844 return 0;
2845 s->mode = mode;
2847 return 1;
2850 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2852 ParallelCharDriver *drv = chr->opaque;
2853 int fd = drv->fd;
2854 uint8_t b;
2856 switch(cmd) {
2857 case CHR_IOCTL_PP_READ_DATA:
2858 if (ioctl(fd, PPRDATA, &b) < 0)
2859 return -ENOTSUP;
2860 *(uint8_t *)arg = b;
2861 break;
2862 case CHR_IOCTL_PP_WRITE_DATA:
2863 b = *(uint8_t *)arg;
2864 if (ioctl(fd, PPWDATA, &b) < 0)
2865 return -ENOTSUP;
2866 break;
2867 case CHR_IOCTL_PP_READ_CONTROL:
2868 if (ioctl(fd, PPRCONTROL, &b) < 0)
2869 return -ENOTSUP;
2870 /* Linux gives only the lowest bits, and no way to know data
2871 direction! For better compatibility set the fixed upper
2872 bits. */
2873 *(uint8_t *)arg = b | 0xc0;
2874 break;
2875 case CHR_IOCTL_PP_WRITE_CONTROL:
2876 b = *(uint8_t *)arg;
2877 if (ioctl(fd, PPWCONTROL, &b) < 0)
2878 return -ENOTSUP;
2879 break;
2880 case CHR_IOCTL_PP_READ_STATUS:
2881 if (ioctl(fd, PPRSTATUS, &b) < 0)
2882 return -ENOTSUP;
2883 *(uint8_t *)arg = b;
2884 break;
2885 case CHR_IOCTL_PP_DATA_DIR:
2886 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2887 return -ENOTSUP;
2888 break;
2889 case CHR_IOCTL_PP_EPP_READ_ADDR:
2890 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2891 struct ParallelIOArg *parg = arg;
2892 int n = read(fd, parg->buffer, parg->count);
2893 if (n != parg->count) {
2894 return -EIO;
2897 break;
2898 case CHR_IOCTL_PP_EPP_READ:
2899 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2900 struct ParallelIOArg *parg = arg;
2901 int n = read(fd, parg->buffer, parg->count);
2902 if (n != parg->count) {
2903 return -EIO;
2906 break;
2907 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2908 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2909 struct ParallelIOArg *parg = arg;
2910 int n = write(fd, parg->buffer, parg->count);
2911 if (n != parg->count) {
2912 return -EIO;
2915 break;
2916 case CHR_IOCTL_PP_EPP_WRITE:
2917 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2918 struct ParallelIOArg *parg = arg;
2919 int n = write(fd, parg->buffer, parg->count);
2920 if (n != parg->count) {
2921 return -EIO;
2924 break;
2925 default:
2926 return -ENOTSUP;
2928 return 0;
2931 static void pp_close(CharDriverState *chr)
2933 ParallelCharDriver *drv = chr->opaque;
2934 int fd = drv->fd;
2936 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2937 ioctl(fd, PPRELEASE);
2938 close(fd);
2939 qemu_free(drv);
2942 static CharDriverState *qemu_chr_open_pp(const char *filename)
2944 CharDriverState *chr;
2945 ParallelCharDriver *drv;
2946 int fd;
2948 TFR(fd = open(filename, O_RDWR));
2949 if (fd < 0)
2950 return NULL;
2952 if (ioctl(fd, PPCLAIM) < 0) {
2953 close(fd);
2954 return NULL;
2957 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2958 if (!drv) {
2959 close(fd);
2960 return NULL;
2962 drv->fd = fd;
2963 drv->mode = IEEE1284_MODE_COMPAT;
2965 chr = qemu_mallocz(sizeof(CharDriverState));
2966 if (!chr) {
2967 qemu_free(drv);
2968 close(fd);
2969 return NULL;
2971 chr->chr_write = null_chr_write;
2972 chr->chr_ioctl = pp_ioctl;
2973 chr->chr_close = pp_close;
2974 chr->opaque = drv;
2976 qemu_chr_reset(chr);
2978 return chr;
2980 #endif /* __linux__ */
2982 #else /* _WIN32 */
2984 typedef struct {
2985 int max_size;
2986 HANDLE hcom, hrecv, hsend;
2987 OVERLAPPED orecv, osend;
2988 BOOL fpipe;
2989 DWORD len;
2990 } WinCharState;
2992 #define NSENDBUF 2048
2993 #define NRECVBUF 2048
2994 #define MAXCONNECT 1
2995 #define NTIMEOUT 5000
2997 static int win_chr_poll(void *opaque);
2998 static int win_chr_pipe_poll(void *opaque);
3000 static void win_chr_close(CharDriverState *chr)
3002 WinCharState *s = chr->opaque;
3004 if (s->hsend) {
3005 CloseHandle(s->hsend);
3006 s->hsend = NULL;
3008 if (s->hrecv) {
3009 CloseHandle(s->hrecv);
3010 s->hrecv = NULL;
3012 if (s->hcom) {
3013 CloseHandle(s->hcom);
3014 s->hcom = NULL;
3016 if (s->fpipe)
3017 qemu_del_polling_cb(win_chr_pipe_poll, chr);
3018 else
3019 qemu_del_polling_cb(win_chr_poll, chr);
3022 static int win_chr_init(CharDriverState *chr, const char *filename)
3024 WinCharState *s = chr->opaque;
3025 COMMCONFIG comcfg;
3026 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
3027 COMSTAT comstat;
3028 DWORD size;
3029 DWORD err;
3031 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3032 if (!s->hsend) {
3033 fprintf(stderr, "Failed CreateEvent\n");
3034 goto fail;
3036 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3037 if (!s->hrecv) {
3038 fprintf(stderr, "Failed CreateEvent\n");
3039 goto fail;
3042 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
3043 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
3044 if (s->hcom == INVALID_HANDLE_VALUE) {
3045 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
3046 s->hcom = NULL;
3047 goto fail;
3050 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3051 fprintf(stderr, "Failed SetupComm\n");
3052 goto fail;
3055 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3056 size = sizeof(COMMCONFIG);
3057 GetDefaultCommConfig(filename, &comcfg, &size);
3058 comcfg.dcb.DCBlength = sizeof(DCB);
3059 CommConfigDialog(filename, NULL, &comcfg);
3061 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3062 fprintf(stderr, "Failed SetCommState\n");
3063 goto fail;
3066 if (!SetCommMask(s->hcom, EV_ERR)) {
3067 fprintf(stderr, "Failed SetCommMask\n");
3068 goto fail;
3071 cto.ReadIntervalTimeout = MAXDWORD;
3072 if (!SetCommTimeouts(s->hcom, &cto)) {
3073 fprintf(stderr, "Failed SetCommTimeouts\n");
3074 goto fail;
3077 if (!ClearCommError(s->hcom, &err, &comstat)) {
3078 fprintf(stderr, "Failed ClearCommError\n");
3079 goto fail;
3081 qemu_add_polling_cb(win_chr_poll, chr);
3082 return 0;
3084 fail:
3085 win_chr_close(chr);
3086 return -1;
3089 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3091 WinCharState *s = chr->opaque;
3092 DWORD len, ret, size, err;
3094 len = len1;
3095 ZeroMemory(&s->osend, sizeof(s->osend));
3096 s->osend.hEvent = s->hsend;
3097 while (len > 0) {
3098 if (s->hsend)
3099 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3100 else
3101 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3102 if (!ret) {
3103 err = GetLastError();
3104 if (err == ERROR_IO_PENDING) {
3105 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3106 if (ret) {
3107 buf += size;
3108 len -= size;
3109 } else {
3110 break;
3112 } else {
3113 break;
3115 } else {
3116 buf += size;
3117 len -= size;
3120 return len1 - len;
3123 static int win_chr_read_poll(CharDriverState *chr)
3125 WinCharState *s = chr->opaque;
3127 s->max_size = qemu_chr_can_read(chr);
3128 return s->max_size;
3131 static void win_chr_readfile(CharDriverState *chr)
3133 WinCharState *s = chr->opaque;
3134 int ret, err;
3135 uint8_t buf[1024];
3136 DWORD size;
3138 ZeroMemory(&s->orecv, sizeof(s->orecv));
3139 s->orecv.hEvent = s->hrecv;
3140 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3141 if (!ret) {
3142 err = GetLastError();
3143 if (err == ERROR_IO_PENDING) {
3144 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3148 if (size > 0) {
3149 qemu_chr_read(chr, buf, size);
3153 static void win_chr_read(CharDriverState *chr)
3155 WinCharState *s = chr->opaque;
3157 if (s->len > s->max_size)
3158 s->len = s->max_size;
3159 if (s->len == 0)
3160 return;
3162 win_chr_readfile(chr);
3165 static int win_chr_poll(void *opaque)
3167 CharDriverState *chr = opaque;
3168 WinCharState *s = chr->opaque;
3169 COMSTAT status;
3170 DWORD comerr;
3172 ClearCommError(s->hcom, &comerr, &status);
3173 if (status.cbInQue > 0) {
3174 s->len = status.cbInQue;
3175 win_chr_read_poll(chr);
3176 win_chr_read(chr);
3177 return 1;
3179 return 0;
3182 static CharDriverState *qemu_chr_open_win(const char *filename)
3184 CharDriverState *chr;
3185 WinCharState *s;
3187 chr = qemu_mallocz(sizeof(CharDriverState));
3188 if (!chr)
3189 return NULL;
3190 s = qemu_mallocz(sizeof(WinCharState));
3191 if (!s) {
3192 free(chr);
3193 return NULL;
3195 chr->opaque = s;
3196 chr->chr_write = win_chr_write;
3197 chr->chr_close = win_chr_close;
3199 if (win_chr_init(chr, filename) < 0) {
3200 free(s);
3201 free(chr);
3202 return NULL;
3204 qemu_chr_reset(chr);
3205 return chr;
3208 static int win_chr_pipe_poll(void *opaque)
3210 CharDriverState *chr = opaque;
3211 WinCharState *s = chr->opaque;
3212 DWORD size;
3214 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3215 if (size > 0) {
3216 s->len = size;
3217 win_chr_read_poll(chr);
3218 win_chr_read(chr);
3219 return 1;
3221 return 0;
3224 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3226 WinCharState *s = chr->opaque;
3227 OVERLAPPED ov;
3228 int ret;
3229 DWORD size;
3230 char openname[256];
3232 s->fpipe = TRUE;
3234 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3235 if (!s->hsend) {
3236 fprintf(stderr, "Failed CreateEvent\n");
3237 goto fail;
3239 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3240 if (!s->hrecv) {
3241 fprintf(stderr, "Failed CreateEvent\n");
3242 goto fail;
3245 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3246 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3247 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3248 PIPE_WAIT,
3249 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3250 if (s->hcom == INVALID_HANDLE_VALUE) {
3251 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3252 s->hcom = NULL;
3253 goto fail;
3256 ZeroMemory(&ov, sizeof(ov));
3257 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3258 ret = ConnectNamedPipe(s->hcom, &ov);
3259 if (ret) {
3260 fprintf(stderr, "Failed ConnectNamedPipe\n");
3261 goto fail;
3264 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3265 if (!ret) {
3266 fprintf(stderr, "Failed GetOverlappedResult\n");
3267 if (ov.hEvent) {
3268 CloseHandle(ov.hEvent);
3269 ov.hEvent = NULL;
3271 goto fail;
3274 if (ov.hEvent) {
3275 CloseHandle(ov.hEvent);
3276 ov.hEvent = NULL;
3278 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3279 return 0;
3281 fail:
3282 win_chr_close(chr);
3283 return -1;
3287 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3289 CharDriverState *chr;
3290 WinCharState *s;
3292 chr = qemu_mallocz(sizeof(CharDriverState));
3293 if (!chr)
3294 return NULL;
3295 s = qemu_mallocz(sizeof(WinCharState));
3296 if (!s) {
3297 free(chr);
3298 return NULL;
3300 chr->opaque = s;
3301 chr->chr_write = win_chr_write;
3302 chr->chr_close = win_chr_close;
3304 if (win_chr_pipe_init(chr, filename) < 0) {
3305 free(s);
3306 free(chr);
3307 return NULL;
3309 qemu_chr_reset(chr);
3310 return chr;
3313 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3315 CharDriverState *chr;
3316 WinCharState *s;
3318 chr = qemu_mallocz(sizeof(CharDriverState));
3319 if (!chr)
3320 return NULL;
3321 s = qemu_mallocz(sizeof(WinCharState));
3322 if (!s) {
3323 free(chr);
3324 return NULL;
3326 s->hcom = fd_out;
3327 chr->opaque = s;
3328 chr->chr_write = win_chr_write;
3329 qemu_chr_reset(chr);
3330 return chr;
3333 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3335 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3338 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3340 HANDLE fd_out;
3342 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3343 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3344 if (fd_out == INVALID_HANDLE_VALUE)
3345 return NULL;
3347 return qemu_chr_open_win_file(fd_out);
3349 #endif /* !_WIN32 */
3351 /***********************************************************/
3352 /* UDP Net console */
3354 typedef struct {
3355 int fd;
3356 struct sockaddr_in daddr;
3357 uint8_t buf[1024];
3358 int bufcnt;
3359 int bufptr;
3360 int max_size;
3361 } NetCharDriver;
3363 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3365 NetCharDriver *s = chr->opaque;
3367 return sendto(s->fd, buf, len, 0,
3368 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3371 static int udp_chr_read_poll(void *opaque)
3373 CharDriverState *chr = opaque;
3374 NetCharDriver *s = chr->opaque;
3376 s->max_size = qemu_chr_can_read(chr);
3378 /* If there were any stray characters in the queue process them
3379 * first
3381 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3382 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3383 s->bufptr++;
3384 s->max_size = qemu_chr_can_read(chr);
3386 return s->max_size;
3389 static void udp_chr_read(void *opaque)
3391 CharDriverState *chr = opaque;
3392 NetCharDriver *s = chr->opaque;
3394 if (s->max_size == 0)
3395 return;
3396 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3397 s->bufptr = s->bufcnt;
3398 if (s->bufcnt <= 0)
3399 return;
3401 s->bufptr = 0;
3402 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3403 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3404 s->bufptr++;
3405 s->max_size = qemu_chr_can_read(chr);
3409 static void udp_chr_update_read_handler(CharDriverState *chr)
3411 NetCharDriver *s = chr->opaque;
3413 if (s->fd >= 0) {
3414 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3415 udp_chr_read, NULL, chr);
3419 #ifndef _WIN32
3420 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3421 #endif
3422 int parse_host_src_port(struct sockaddr_in *haddr,
3423 struct sockaddr_in *saddr,
3424 const char *str);
3426 static CharDriverState *qemu_chr_open_udp(const char *def)
3428 CharDriverState *chr = NULL;
3429 NetCharDriver *s = NULL;
3430 int fd = -1;
3431 struct sockaddr_in saddr;
3433 chr = qemu_mallocz(sizeof(CharDriverState));
3434 if (!chr)
3435 goto return_err;
3436 s = qemu_mallocz(sizeof(NetCharDriver));
3437 if (!s)
3438 goto return_err;
3440 fd = socket(PF_INET, SOCK_DGRAM, 0);
3441 if (fd < 0) {
3442 perror("socket(PF_INET, SOCK_DGRAM)");
3443 goto return_err;
3446 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3447 printf("Could not parse: %s\n", def);
3448 goto return_err;
3451 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3453 perror("bind");
3454 goto return_err;
3457 s->fd = fd;
3458 s->bufcnt = 0;
3459 s->bufptr = 0;
3460 chr->opaque = s;
3461 chr->chr_write = udp_chr_write;
3462 chr->chr_update_read_handler = udp_chr_update_read_handler;
3463 return chr;
3465 return_err:
3466 if (chr)
3467 free(chr);
3468 if (s)
3469 free(s);
3470 if (fd >= 0)
3471 closesocket(fd);
3472 return NULL;
3475 /***********************************************************/
3476 /* TCP Net console */
3478 typedef struct {
3479 int fd, listen_fd;
3480 int connected;
3481 int max_size;
3482 int do_telnetopt;
3483 int do_nodelay;
3484 int is_unix;
3485 } TCPCharDriver;
3487 static void tcp_chr_accept(void *opaque);
3489 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3491 TCPCharDriver *s = chr->opaque;
3492 if (s->connected) {
3493 return send_all(s->fd, buf, len);
3494 } else {
3495 /* XXX: indicate an error ? */
3496 return len;
3500 static int tcp_chr_read_poll(void *opaque)
3502 CharDriverState *chr = opaque;
3503 TCPCharDriver *s = chr->opaque;
3504 if (!s->connected)
3505 return 0;
3506 s->max_size = qemu_chr_can_read(chr);
3507 return s->max_size;
3510 #define IAC 255
3511 #define IAC_BREAK 243
3512 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3513 TCPCharDriver *s,
3514 uint8_t *buf, int *size)
3516 /* Handle any telnet client's basic IAC options to satisfy char by
3517 * char mode with no echo. All IAC options will be removed from
3518 * the buf and the do_telnetopt variable will be used to track the
3519 * state of the width of the IAC information.
3521 * IAC commands come in sets of 3 bytes with the exception of the
3522 * "IAC BREAK" command and the double IAC.
3525 int i;
3526 int j = 0;
3528 for (i = 0; i < *size; i++) {
3529 if (s->do_telnetopt > 1) {
3530 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3531 /* Double IAC means send an IAC */
3532 if (j != i)
3533 buf[j] = buf[i];
3534 j++;
3535 s->do_telnetopt = 1;
3536 } else {
3537 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3538 /* Handle IAC break commands by sending a serial break */
3539 qemu_chr_event(chr, CHR_EVENT_BREAK);
3540 s->do_telnetopt++;
3542 s->do_telnetopt++;
3544 if (s->do_telnetopt >= 4) {
3545 s->do_telnetopt = 1;
3547 } else {
3548 if ((unsigned char)buf[i] == IAC) {
3549 s->do_telnetopt = 2;
3550 } else {
3551 if (j != i)
3552 buf[j] = buf[i];
3553 j++;
3557 *size = j;
3560 static void tcp_chr_read(void *opaque)
3562 CharDriverState *chr = opaque;
3563 TCPCharDriver *s = chr->opaque;
3564 uint8_t buf[1024];
3565 int len, size;
3567 if (!s->connected || s->max_size <= 0)
3568 return;
3569 len = sizeof(buf);
3570 if (len > s->max_size)
3571 len = s->max_size;
3572 size = recv(s->fd, buf, len, 0);
3573 if (size == 0) {
3574 /* connection closed */
3575 s->connected = 0;
3576 if (s->listen_fd >= 0) {
3577 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3579 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3580 closesocket(s->fd);
3581 s->fd = -1;
3582 } else if (size > 0) {
3583 if (s->do_telnetopt)
3584 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3585 if (size > 0)
3586 qemu_chr_read(chr, buf, size);
3590 static void tcp_chr_connect(void *opaque)
3592 CharDriverState *chr = opaque;
3593 TCPCharDriver *s = chr->opaque;
3595 s->connected = 1;
3596 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3597 tcp_chr_read, NULL, chr);
3598 qemu_chr_reset(chr);
3601 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3602 static void tcp_chr_telnet_init(int fd)
3604 char buf[3];
3605 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3606 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3607 send(fd, (char *)buf, 3, 0);
3608 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3609 send(fd, (char *)buf, 3, 0);
3610 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3611 send(fd, (char *)buf, 3, 0);
3612 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3613 send(fd, (char *)buf, 3, 0);
3616 static void socket_set_nodelay(int fd)
3618 int val = 1;
3619 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3622 static void tcp_chr_accept(void *opaque)
3624 CharDriverState *chr = opaque;
3625 TCPCharDriver *s = chr->opaque;
3626 struct sockaddr_in saddr;
3627 #ifndef _WIN32
3628 struct sockaddr_un uaddr;
3629 #endif
3630 struct sockaddr *addr;
3631 socklen_t len;
3632 int fd;
3634 for(;;) {
3635 #ifndef _WIN32
3636 if (s->is_unix) {
3637 len = sizeof(uaddr);
3638 addr = (struct sockaddr *)&uaddr;
3639 } else
3640 #endif
3642 len = sizeof(saddr);
3643 addr = (struct sockaddr *)&saddr;
3645 fd = accept(s->listen_fd, addr, &len);
3646 if (fd < 0 && errno != EINTR) {
3647 return;
3648 } else if (fd >= 0) {
3649 if (s->do_telnetopt)
3650 tcp_chr_telnet_init(fd);
3651 break;
3654 socket_set_nonblock(fd);
3655 if (s->do_nodelay)
3656 socket_set_nodelay(fd);
3657 s->fd = fd;
3658 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3659 tcp_chr_connect(chr);
3662 static void tcp_chr_close(CharDriverState *chr)
3664 TCPCharDriver *s = chr->opaque;
3665 if (s->fd >= 0)
3666 closesocket(s->fd);
3667 if (s->listen_fd >= 0)
3668 closesocket(s->listen_fd);
3669 qemu_free(s);
3672 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3673 int is_telnet,
3674 int is_unix)
3676 CharDriverState *chr = NULL;
3677 TCPCharDriver *s = NULL;
3678 int fd = -1, ret, err, val;
3679 int is_listen = 0;
3680 int is_waitconnect = 1;
3681 int do_nodelay = 0;
3682 const char *ptr;
3683 struct sockaddr_in saddr;
3684 #ifndef _WIN32
3685 struct sockaddr_un uaddr;
3686 #endif
3687 struct sockaddr *addr;
3688 socklen_t addrlen;
3690 #ifndef _WIN32
3691 if (is_unix) {
3692 addr = (struct sockaddr *)&uaddr;
3693 addrlen = sizeof(uaddr);
3694 if (parse_unix_path(&uaddr, host_str) < 0)
3695 goto fail;
3696 } else
3697 #endif
3699 addr = (struct sockaddr *)&saddr;
3700 addrlen = sizeof(saddr);
3701 if (parse_host_port(&saddr, host_str) < 0)
3702 goto fail;
3705 ptr = host_str;
3706 while((ptr = strchr(ptr,','))) {
3707 ptr++;
3708 if (!strncmp(ptr,"server",6)) {
3709 is_listen = 1;
3710 } else if (!strncmp(ptr,"nowait",6)) {
3711 is_waitconnect = 0;
3712 } else if (!strncmp(ptr,"nodelay",6)) {
3713 do_nodelay = 1;
3714 } else {
3715 printf("Unknown option: %s\n", ptr);
3716 goto fail;
3719 if (!is_listen)
3720 is_waitconnect = 0;
3722 chr = qemu_mallocz(sizeof(CharDriverState));
3723 if (!chr)
3724 goto fail;
3725 s = qemu_mallocz(sizeof(TCPCharDriver));
3726 if (!s)
3727 goto fail;
3729 #ifndef _WIN32
3730 if (is_unix)
3731 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3732 else
3733 #endif
3734 fd = socket(PF_INET, SOCK_STREAM, 0);
3736 if (fd < 0)
3737 goto fail;
3739 if (!is_waitconnect)
3740 socket_set_nonblock(fd);
3742 s->connected = 0;
3743 s->fd = -1;
3744 s->listen_fd = -1;
3745 s->is_unix = is_unix;
3746 s->do_nodelay = do_nodelay && !is_unix;
3748 chr->opaque = s;
3749 chr->chr_write = tcp_chr_write;
3750 chr->chr_close = tcp_chr_close;
3752 if (is_listen) {
3753 /* allow fast reuse */
3754 #ifndef _WIN32
3755 if (is_unix) {
3756 char path[109];
3757 pstrcpy(path, sizeof(path), uaddr.sun_path);
3758 unlink(path);
3759 } else
3760 #endif
3762 val = 1;
3763 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3766 ret = bind(fd, addr, addrlen);
3767 if (ret < 0)
3768 goto fail;
3770 ret = listen(fd, 0);
3771 if (ret < 0)
3772 goto fail;
3774 s->listen_fd = fd;
3775 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3776 if (is_telnet)
3777 s->do_telnetopt = 1;
3778 } else {
3779 for(;;) {
3780 ret = connect(fd, addr, addrlen);
3781 if (ret < 0) {
3782 err = socket_error();
3783 if (err == EINTR || err == EWOULDBLOCK) {
3784 } else if (err == EINPROGRESS) {
3785 break;
3786 #ifdef _WIN32
3787 } else if (err == WSAEALREADY) {
3788 break;
3789 #endif
3790 } else {
3791 goto fail;
3793 } else {
3794 s->connected = 1;
3795 break;
3798 s->fd = fd;
3799 socket_set_nodelay(fd);
3800 if (s->connected)
3801 tcp_chr_connect(chr);
3802 else
3803 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3806 if (is_listen && is_waitconnect) {
3807 printf("QEMU waiting for connection on: %s\n", host_str);
3808 tcp_chr_accept(chr);
3809 socket_set_nonblock(s->listen_fd);
3812 return chr;
3813 fail:
3814 if (fd >= 0)
3815 closesocket(fd);
3816 qemu_free(s);
3817 qemu_free(chr);
3818 return NULL;
3821 CharDriverState *qemu_chr_open(const char *filename)
3823 const char *p;
3825 if (!strcmp(filename, "vc")) {
3826 return text_console_init(&display_state, 0);
3827 } else if (strstart(filename, "vc:", &p)) {
3828 return text_console_init(&display_state, p);
3829 } else if (!strcmp(filename, "null")) {
3830 return qemu_chr_open_null();
3831 } else
3832 if (strstart(filename, "tcp:", &p)) {
3833 return qemu_chr_open_tcp(p, 0, 0);
3834 } else
3835 if (strstart(filename, "telnet:", &p)) {
3836 return qemu_chr_open_tcp(p, 1, 0);
3837 } else
3838 if (strstart(filename, "udp:", &p)) {
3839 return qemu_chr_open_udp(p);
3840 } else
3841 if (strstart(filename, "mon:", &p)) {
3842 CharDriverState *drv = qemu_chr_open(p);
3843 if (drv) {
3844 drv = qemu_chr_open_mux(drv);
3845 monitor_init(drv, !nographic);
3846 return drv;
3848 printf("Unable to open driver: %s\n", p);
3849 return 0;
3850 } else
3851 #ifndef _WIN32
3852 if (strstart(filename, "unix:", &p)) {
3853 return qemu_chr_open_tcp(p, 0, 1);
3854 } else if (strstart(filename, "file:", &p)) {
3855 return qemu_chr_open_file_out(p);
3856 } else if (strstart(filename, "pipe:", &p)) {
3857 return qemu_chr_open_pipe(p);
3858 } else if (!strcmp(filename, "pty")) {
3859 return qemu_chr_open_pty();
3860 } else if (!strcmp(filename, "stdio")) {
3861 return qemu_chr_open_stdio();
3862 } else
3863 #if defined(__linux__)
3864 if (strstart(filename, "/dev/parport", NULL)) {
3865 return qemu_chr_open_pp(filename);
3866 } else
3867 #endif
3868 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3869 || defined(__NetBSD__) || defined(__OpenBSD__)
3870 if (strstart(filename, "/dev/", NULL)) {
3871 return qemu_chr_open_tty(filename);
3872 } else
3873 #endif
3874 #else /* !_WIN32 */
3875 if (strstart(filename, "COM", NULL)) {
3876 return qemu_chr_open_win(filename);
3877 } else
3878 if (strstart(filename, "pipe:", &p)) {
3879 return qemu_chr_open_win_pipe(p);
3880 } else
3881 if (strstart(filename, "con:", NULL)) {
3882 return qemu_chr_open_win_con(filename);
3883 } else
3884 if (strstart(filename, "file:", &p)) {
3885 return qemu_chr_open_win_file_out(p);
3886 } else
3887 #endif
3888 #ifdef CONFIG_BRLAPI
3889 if (!strcmp(filename, "braille")) {
3890 return chr_baum_init();
3891 } else
3892 #endif
3894 return NULL;
3898 void qemu_chr_close(CharDriverState *chr)
3900 if (chr->chr_close)
3901 chr->chr_close(chr);
3902 qemu_free(chr);
3905 /***********************************************************/
3906 /* network device redirectors */
3908 __attribute__ (( unused ))
3909 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3911 int len, i, j, c;
3913 for(i=0;i<size;i+=16) {
3914 len = size - i;
3915 if (len > 16)
3916 len = 16;
3917 fprintf(f, "%08x ", i);
3918 for(j=0;j<16;j++) {
3919 if (j < len)
3920 fprintf(f, " %02x", buf[i+j]);
3921 else
3922 fprintf(f, " ");
3924 fprintf(f, " ");
3925 for(j=0;j<len;j++) {
3926 c = buf[i+j];
3927 if (c < ' ' || c > '~')
3928 c = '.';
3929 fprintf(f, "%c", c);
3931 fprintf(f, "\n");
3935 static int parse_macaddr(uint8_t *macaddr, const char *p)
3937 int i;
3938 char *last_char;
3939 long int offset;
3941 errno = 0;
3942 offset = strtol(p, &last_char, 0);
3943 if (0 == errno && '\0' == *last_char &&
3944 offset >= 0 && offset <= 0xFFFFFF) {
3945 macaddr[3] = (offset & 0xFF0000) >> 16;
3946 macaddr[4] = (offset & 0xFF00) >> 8;
3947 macaddr[5] = offset & 0xFF;
3948 return 0;
3949 } else {
3950 for(i = 0; i < 6; i++) {
3951 macaddr[i] = strtol(p, (char **)&p, 16);
3952 if (i == 5) {
3953 if (*p != '\0')
3954 return -1;
3955 } else {
3956 if (*p != ':' && *p != '-')
3957 return -1;
3958 p++;
3961 return 0;
3964 return -1;
3967 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3969 const char *p, *p1;
3970 int len;
3971 p = *pp;
3972 p1 = strchr(p, sep);
3973 if (!p1)
3974 return -1;
3975 len = p1 - p;
3976 p1++;
3977 if (buf_size > 0) {
3978 if (len > buf_size - 1)
3979 len = buf_size - 1;
3980 memcpy(buf, p, len);
3981 buf[len] = '\0';
3983 *pp = p1;
3984 return 0;
3987 int parse_host_src_port(struct sockaddr_in *haddr,
3988 struct sockaddr_in *saddr,
3989 const char *input_str)
3991 char *str = strdup(input_str);
3992 char *host_str = str;
3993 char *src_str;
3994 const char *src_str2;
3995 char *ptr;
3998 * Chop off any extra arguments at the end of the string which
3999 * would start with a comma, then fill in the src port information
4000 * if it was provided else use the "any address" and "any port".
4002 if ((ptr = strchr(str,',')))
4003 *ptr = '\0';
4005 if ((src_str = strchr(input_str,'@'))) {
4006 *src_str = '\0';
4007 src_str++;
4010 if (parse_host_port(haddr, host_str) < 0)
4011 goto fail;
4013 src_str2 = src_str;
4014 if (!src_str || *src_str == '\0')
4015 src_str2 = ":0";
4017 if (parse_host_port(saddr, src_str2) < 0)
4018 goto fail;
4020 free(str);
4021 return(0);
4023 fail:
4024 free(str);
4025 return -1;
4028 int parse_host_port(struct sockaddr_in *saddr, const char *str)
4030 char buf[512];
4031 struct hostent *he;
4032 const char *p, *r;
4033 int port;
4035 p = str;
4036 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4037 return -1;
4038 saddr->sin_family = AF_INET;
4039 if (buf[0] == '\0') {
4040 saddr->sin_addr.s_addr = 0;
4041 } else {
4042 if (isdigit(buf[0])) {
4043 if (!inet_aton(buf, &saddr->sin_addr))
4044 return -1;
4045 } else {
4046 if ((he = gethostbyname(buf)) == NULL)
4047 return - 1;
4048 saddr->sin_addr = *(struct in_addr *)he->h_addr;
4051 port = strtol(p, (char **)&r, 0);
4052 if (r == p)
4053 return -1;
4054 saddr->sin_port = htons(port);
4055 return 0;
4058 #ifndef _WIN32
4059 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4061 const char *p;
4062 int len;
4064 len = MIN(108, strlen(str));
4065 p = strchr(str, ',');
4066 if (p)
4067 len = MIN(len, p - str);
4069 memset(uaddr, 0, sizeof(*uaddr));
4071 uaddr->sun_family = AF_UNIX;
4072 memcpy(uaddr->sun_path, str, len);
4074 return 0;
4076 #endif
4078 /* find or alloc a new VLAN */
4079 VLANState *qemu_find_vlan(int id)
4081 VLANState **pvlan, *vlan;
4082 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4083 if (vlan->id == id)
4084 return vlan;
4086 vlan = qemu_mallocz(sizeof(VLANState));
4087 if (!vlan)
4088 return NULL;
4089 vlan->id = id;
4090 vlan->next = NULL;
4091 pvlan = &first_vlan;
4092 while (*pvlan != NULL)
4093 pvlan = &(*pvlan)->next;
4094 *pvlan = vlan;
4095 return vlan;
4098 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4099 IOReadHandler *fd_read,
4100 IOCanRWHandler *fd_can_read,
4101 void *opaque)
4103 VLANClientState *vc, **pvc;
4104 vc = qemu_mallocz(sizeof(VLANClientState));
4105 if (!vc)
4106 return NULL;
4107 vc->fd_read = fd_read;
4108 vc->fd_can_read = fd_can_read;
4109 vc->opaque = opaque;
4110 vc->vlan = vlan;
4112 vc->next = NULL;
4113 pvc = &vlan->first_client;
4114 while (*pvc != NULL)
4115 pvc = &(*pvc)->next;
4116 *pvc = vc;
4117 return vc;
4120 void qemu_del_vlan_client(VLANClientState *vc)
4122 VLANClientState **pvc = &vc->vlan->first_client;
4124 while (*pvc != NULL)
4125 if (*pvc == vc) {
4126 *pvc = vc->next;
4127 free(vc);
4128 break;
4129 } else
4130 pvc = &(*pvc)->next;
4133 int qemu_can_send_packet(VLANClientState *vc1)
4135 VLANState *vlan = vc1->vlan;
4136 VLANClientState *vc;
4138 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4139 if (vc != vc1) {
4140 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4141 return 1;
4144 return 0;
4147 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4149 VLANState *vlan = vc1->vlan;
4150 VLANClientState *vc;
4151 int ret = -EAGAIN;
4153 #if 0
4154 printf("vlan %d send:\n", vlan->id);
4155 hex_dump(stdout, buf, size);
4156 #endif
4157 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4158 if (vc != vc1) {
4159 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
4160 vc->fd_read(vc->opaque, buf, size);
4161 ret = 0;
4166 return ret;
4169 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
4170 int iovcnt)
4172 char buffer[4096];
4173 size_t offset = 0;
4174 int i;
4176 for (i = 0; i < iovcnt; i++) {
4177 size_t len;
4179 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
4180 memcpy(buffer + offset, iov[i].iov_base, len);
4181 offset += len;
4184 vc->fd_read(vc->opaque, buffer, offset);
4186 return offset;
4189 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
4190 int iovcnt)
4192 VLANState *vlan = vc1->vlan;
4193 VLANClientState *vc;
4194 ssize_t max_len = 0;
4196 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
4197 ssize_t len = 0;
4199 if (vc == vc1)
4200 continue;
4202 if (vc->fd_readv)
4203 len = vc->fd_readv(vc->opaque, iov, iovcnt);
4204 else if (vc->fd_read)
4205 len = vc_sendv_compat(vc, iov, iovcnt);
4207 max_len = MAX(max_len, len);
4210 return max_len;
4213 #if defined(CONFIG_SLIRP)
4215 /* slirp network adapter */
4217 static int slirp_inited;
4218 static VLANClientState *slirp_vc;
4220 int slirp_can_output(void)
4222 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4225 void slirp_output(const uint8_t *pkt, int pkt_len)
4227 #if 0
4228 printf("slirp output:\n");
4229 hex_dump(stdout, pkt, pkt_len);
4230 #endif
4231 if (!slirp_vc)
4232 return;
4233 qemu_send_packet(slirp_vc, pkt, pkt_len);
4236 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4238 #if 0
4239 printf("slirp input:\n");
4240 hex_dump(stdout, buf, size);
4241 #endif
4242 slirp_input(buf, size);
4245 static int net_slirp_init(VLANState *vlan)
4247 if (!slirp_inited) {
4248 slirp_inited = 1;
4249 slirp_init();
4251 slirp_vc = qemu_new_vlan_client(vlan,
4252 slirp_receive, NULL, NULL);
4253 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4254 return 0;
4257 static void net_slirp_redir(const char *redir_str)
4259 int is_udp;
4260 char buf[256], *r;
4261 const char *p;
4262 struct in_addr guest_addr;
4263 int host_port, guest_port;
4265 if (!slirp_inited) {
4266 slirp_inited = 1;
4267 slirp_init();
4270 p = redir_str;
4271 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4272 goto fail;
4273 if (!strcmp(buf, "tcp")) {
4274 is_udp = 0;
4275 } else if (!strcmp(buf, "udp")) {
4276 is_udp = 1;
4277 } else {
4278 goto fail;
4281 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4282 goto fail;
4283 host_port = strtol(buf, &r, 0);
4284 if (r == buf)
4285 goto fail;
4287 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4288 goto fail;
4289 if (buf[0] == '\0') {
4290 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4292 if (!inet_aton(buf, &guest_addr))
4293 goto fail;
4295 guest_port = strtol(p, &r, 0);
4296 if (r == p)
4297 goto fail;
4299 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4300 fprintf(stderr, "qemu: could not set up redirection\n");
4301 exit(1);
4303 return;
4304 fail:
4305 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4306 exit(1);
4309 #ifndef _WIN32
4311 char smb_dir[1024];
4313 static void erase_dir(char *dir_name)
4315 DIR *d;
4316 struct dirent *de;
4317 char filename[1024];
4319 /* erase all the files in the directory */
4320 if ((d = opendir(dir_name)) != 0) {
4321 for(;;) {
4322 de = readdir(d);
4323 if (!de)
4324 break;
4325 if (strcmp(de->d_name, ".") != 0 &&
4326 strcmp(de->d_name, "..") != 0) {
4327 snprintf(filename, sizeof(filename), "%s/%s",
4328 smb_dir, de->d_name);
4329 if (unlink(filename) != 0) /* is it a directory? */
4330 erase_dir(filename);
4333 closedir(d);
4334 rmdir(dir_name);
4338 /* automatic user mode samba server configuration */
4339 static void smb_exit(void)
4341 erase_dir(smb_dir);
4344 /* automatic user mode samba server configuration */
4345 static void net_slirp_smb(const char *exported_dir)
4347 char smb_conf[1024];
4348 char smb_cmdline[1024];
4349 FILE *f;
4351 if (!slirp_inited) {
4352 slirp_inited = 1;
4353 slirp_init();
4356 /* XXX: better tmp dir construction */
4357 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4358 if (mkdir(smb_dir, 0700) < 0) {
4359 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4360 exit(1);
4362 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4364 f = fopen(smb_conf, "w");
4365 if (!f) {
4366 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4367 exit(1);
4369 fprintf(f,
4370 "[global]\n"
4371 "private dir=%s\n"
4372 "smb ports=0\n"
4373 "socket address=127.0.0.1\n"
4374 "pid directory=%s\n"
4375 "lock directory=%s\n"
4376 "log file=%s/log.smbd\n"
4377 "smb passwd file=%s/smbpasswd\n"
4378 "security = share\n"
4379 "[qemu]\n"
4380 "path=%s\n"
4381 "read only=no\n"
4382 "guest ok=yes\n",
4383 smb_dir,
4384 smb_dir,
4385 smb_dir,
4386 smb_dir,
4387 smb_dir,
4388 exported_dir
4390 fclose(f);
4391 atexit(smb_exit);
4393 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4394 SMBD_COMMAND, smb_conf);
4396 slirp_add_exec(0, smb_cmdline, 4, 139);
4399 #endif /* !defined(_WIN32) */
4400 void do_info_slirp(void)
4402 slirp_stats();
4405 #endif /* CONFIG_SLIRP */
4407 #ifdef _WIN32
4409 int tap_has_vnet_hdr(void *opaque)
4411 return 0;
4414 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
4418 #else /* !defined(_WIN32) */
4420 #ifndef IFF_VNET_HDR
4421 #define TAP_BUFSIZE 4096
4422 #else
4423 #include <linux/virtio_net.h>
4424 #define ETH_HLEN 14
4425 #define ETH_DATA_LEN 1500
4426 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4427 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4428 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4429 #endif
4431 typedef struct TAPState {
4432 VLANClientState *vc;
4433 int fd;
4434 char down_script[1024];
4435 char buf[TAP_BUFSIZE];
4436 int size;
4437 unsigned int has_vnet_hdr : 1;
4438 unsigned int using_vnet_hdr : 1;
4439 } TAPState;
4441 static ssize_t tap_writev(void *opaque, const struct iovec *iov,
4442 int iovcnt)
4444 TAPState *s = opaque;
4445 ssize_t len;
4447 do {
4448 len = writev(s->fd, iov, iovcnt);
4449 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
4451 return len;
4454 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
4455 int iovcnt)
4457 #ifdef IFF_VNET_HDR
4458 TAPState *s = opaque;
4460 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4461 struct iovec *iov_copy;
4462 struct virtio_net_hdr hdr = { 0, };
4464 iov_copy = alloca(sizeof(struct iovec) * (iovcnt + 1));
4466 iov_copy[0].iov_base = &hdr;
4467 iov_copy[0].iov_len = sizeof(hdr);
4469 memcpy(&iov_copy[1], iov, sizeof(struct iovec) * iovcnt);
4471 return tap_writev(opaque, iov_copy, iovcnt + 1);
4473 #endif
4475 return tap_writev(opaque, iov, iovcnt);
4478 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4480 struct iovec iov[2];
4481 int i = 0;
4483 #ifdef IFF_VNET_HDR
4484 TAPState *s = opaque;
4485 struct virtio_net_hdr hdr = { 0, };
4487 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4488 iov[i].iov_base = &hdr;
4489 iov[i].iov_len = sizeof(hdr);
4490 i++;
4492 #endif
4494 iov[i].iov_base = (char *) buf;
4495 iov[i].iov_len = size;
4496 i++;
4498 tap_writev(opaque, iov, i);
4501 static int tap_can_send(void *opaque)
4503 TAPState *s = opaque;
4504 VLANClientState *vc;
4505 int can_receive = 0;
4507 /* Check to see if any of our clients can receive a packet */
4508 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
4509 /* Skip ourselves */
4510 if (vc == s->vc)
4511 continue;
4513 if (!vc->fd_can_read) {
4514 /* no fd_can_read handler, they always can receive */
4515 can_receive = 1;
4516 } else
4517 can_receive = vc->fd_can_read(vc->opaque);
4519 /* Once someone can receive, we try to send a packet */
4520 if (can_receive)
4521 break;
4524 return can_receive;
4527 static int tap_send_packet(TAPState *s)
4529 uint8_t *buf = s->buf;
4530 int size = s->size;
4532 #ifdef IFF_VNET_HDR
4533 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4534 buf += sizeof(struct virtio_net_hdr);
4535 size -= sizeof(struct virtio_net_hdr);
4537 #endif
4539 return qemu_send_packet(s->vc, buf, size);
4542 static void tap_send(void *opaque)
4544 TAPState *s = opaque;
4546 /* First try to send any buffered packet */
4547 if (s->size > 0) {
4548 int err;
4550 /* If noone can receive the packet, buffer it */
4551 err = tap_send_packet(s);
4552 if (err == -EAGAIN)
4553 return;
4556 /* Read packets until we hit EAGAIN */
4557 do {
4558 #ifdef __sun__
4559 struct strbuf sbuf;
4560 int f = 0;
4561 sbuf.maxlen = sizeof(s->buf);
4562 sbuf.buf = s->buf;
4563 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4564 #else
4565 kvm_sleep_begin();
4566 s->size = read(s->fd, s->buf, sizeof(s->buf));
4567 kvm_sleep_end();
4568 #endif
4570 if (s->size == -1 && errno == EINTR)
4571 continue;
4573 if (s->size > 0) {
4574 int err;
4576 /* If noone can receive the packet, buffer it */
4577 err = tap_send_packet(s);
4578 if (err == -EAGAIN)
4579 break;
4581 } while (s->size > 0);
4584 int tap_has_vnet_hdr(void *opaque)
4586 VLANClientState *vc = opaque;
4587 TAPState *s = vc->opaque;
4589 return s ? s->has_vnet_hdr : 0;
4592 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
4594 VLANClientState *vc = opaque;
4595 TAPState *s = vc->opaque;
4597 if (!s || !s->has_vnet_hdr)
4598 return;
4600 s->using_vnet_hdr = using_vnet_hdr != 0;
4603 static int tap_probe_vnet_hdr(int fd)
4605 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
4606 struct ifreq ifr;
4608 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
4609 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
4610 return 0;
4613 return ifr.ifr_flags & IFF_VNET_HDR;
4614 #else
4615 return 0;
4616 #endif
4619 #ifdef TUNSETOFFLOAD
4620 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
4621 int ecn)
4623 TAPState *s = vc->opaque;
4624 unsigned int offload = 0;
4626 if (csum) {
4627 offload |= TUN_F_CSUM;
4628 if (tso4)
4629 offload |= TUN_F_TSO4;
4630 if (tso6)
4631 offload |= TUN_F_TSO6;
4632 if ((tso4 || tso6) && ecn)
4633 offload |= TUN_F_TSO_ECN;
4636 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
4637 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
4638 strerror(errno));
4640 #endif /* TUNSETOFFLOAD */
4642 /* fd support */
4644 static TAPState *net_tap_fd_init(VLANState *vlan, int fd, int vnet_hdr)
4646 TAPState *s;
4648 s = qemu_mallocz(sizeof(TAPState));
4649 if (!s)
4650 return NULL;
4651 s->fd = fd;
4652 s->has_vnet_hdr = vnet_hdr != 0;
4653 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4654 s->vc->fd_readv = tap_receive_iov;
4655 #ifdef TUNSETOFFLOAD
4656 s->vc->set_offload = tap_set_offload;
4657 #endif
4658 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
4659 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4660 return s;
4663 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4664 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4666 int fd;
4667 char *dev;
4668 struct stat s;
4670 TFR(fd = open("/dev/tap", O_RDWR));
4671 if (fd < 0) {
4672 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4673 return -1;
4676 fstat(fd, &s);
4677 dev = devname(s.st_rdev, S_IFCHR);
4678 pstrcpy(ifname, ifname_size, dev);
4680 fcntl(fd, F_SETFL, O_NONBLOCK);
4681 return fd;
4683 #elif defined(__sun__)
4684 #define TUNNEWPPA (('T'<<16) | 0x0001)
4686 * Allocate TAP device, returns opened fd.
4687 * Stores dev name in the first arg(must be large enough).
4689 int tap_alloc(char *dev, size_t dev_size)
4691 int tap_fd, if_fd, ppa = -1;
4692 static int ip_fd = 0;
4693 char *ptr;
4695 static int arp_fd = 0;
4696 int ip_muxid, arp_muxid;
4697 struct strioctl strioc_if, strioc_ppa;
4698 int link_type = I_PLINK;;
4699 struct lifreq ifr;
4700 char actual_name[32] = "";
4702 memset(&ifr, 0x0, sizeof(ifr));
4704 if( *dev ){
4705 ptr = dev;
4706 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4707 ppa = atoi(ptr);
4710 /* Check if IP device was opened */
4711 if( ip_fd )
4712 close(ip_fd);
4714 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4715 if (ip_fd < 0) {
4716 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4717 return -1;
4720 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4721 if (tap_fd < 0) {
4722 syslog(LOG_ERR, "Can't open /dev/tap");
4723 return -1;
4726 /* Assign a new PPA and get its unit number. */
4727 strioc_ppa.ic_cmd = TUNNEWPPA;
4728 strioc_ppa.ic_timout = 0;
4729 strioc_ppa.ic_len = sizeof(ppa);
4730 strioc_ppa.ic_dp = (char *)&ppa;
4731 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4732 syslog (LOG_ERR, "Can't assign new interface");
4734 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4735 if (if_fd < 0) {
4736 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4737 return -1;
4739 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4740 syslog(LOG_ERR, "Can't push IP module");
4741 return -1;
4744 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4745 syslog(LOG_ERR, "Can't get flags\n");
4747 snprintf (actual_name, 32, "tap%d", ppa);
4748 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4750 ifr.lifr_ppa = ppa;
4751 /* Assign ppa according to the unit number returned by tun device */
4753 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4754 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4755 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4756 syslog (LOG_ERR, "Can't get flags\n");
4757 /* Push arp module to if_fd */
4758 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4759 syslog (LOG_ERR, "Can't push ARP module (2)");
4761 /* Push arp module to ip_fd */
4762 if (ioctl (ip_fd, I_POP, NULL) < 0)
4763 syslog (LOG_ERR, "I_POP failed\n");
4764 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4765 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4766 /* Open arp_fd */
4767 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4768 if (arp_fd < 0)
4769 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4771 /* Set ifname to arp */
4772 strioc_if.ic_cmd = SIOCSLIFNAME;
4773 strioc_if.ic_timout = 0;
4774 strioc_if.ic_len = sizeof(ifr);
4775 strioc_if.ic_dp = (char *)&ifr;
4776 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4777 syslog (LOG_ERR, "Can't set ifname to arp\n");
4780 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4781 syslog(LOG_ERR, "Can't link TAP device to IP");
4782 return -1;
4785 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4786 syslog (LOG_ERR, "Can't link TAP device to ARP");
4788 close (if_fd);
4790 memset(&ifr, 0x0, sizeof(ifr));
4791 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4792 ifr.lifr_ip_muxid = ip_muxid;
4793 ifr.lifr_arp_muxid = arp_muxid;
4795 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4797 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4798 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4799 syslog (LOG_ERR, "Can't set multiplexor id");
4802 snprintf(dev, dev_size, "tap%d", ppa);
4803 return tap_fd;
4806 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4808 char dev[10]="";
4809 int fd;
4810 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4811 fprintf(stderr, "Cannot allocate TAP device\n");
4812 return -1;
4814 pstrcpy(ifname, ifname_size, dev);
4815 fcntl(fd, F_SETFL, O_NONBLOCK);
4816 return fd;
4818 #else
4819 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4821 struct ifreq ifr;
4822 int fd, ret;
4824 TFR(fd = open("/dev/net/tun", O_RDWR));
4825 if (fd < 0) {
4826 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4827 return -1;
4829 memset(&ifr, 0, sizeof(ifr));
4830 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4832 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4834 unsigned int features;
4836 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
4837 features & IFF_VNET_HDR) {
4838 *vnet_hdr = 1;
4839 ifr.ifr_flags |= IFF_VNET_HDR;
4842 #endif
4844 if (ifname[0] != '\0')
4845 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4846 else
4847 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4848 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4849 if (ret != 0) {
4850 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4851 close(fd);
4852 return -1;
4854 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4855 fcntl(fd, F_SETFL, O_NONBLOCK);
4856 return fd;
4858 #endif
4860 static int launch_script(const char *setup_script, const char *ifname, int fd)
4862 int pid, status;
4863 char *args[3];
4864 char **parg;
4866 /* try to launch network script */
4867 pid = fork();
4868 if (pid >= 0) {
4869 if (pid == 0) {
4870 int open_max = sysconf (_SC_OPEN_MAX), i;
4871 for (i = 0; i < open_max; i++)
4872 if (i != STDIN_FILENO &&
4873 i != STDOUT_FILENO &&
4874 i != STDERR_FILENO &&
4875 i != fd)
4876 close(i);
4878 parg = args;
4879 *parg++ = (char *)setup_script;
4880 *parg++ = (char *)ifname;
4881 *parg++ = NULL;
4882 execv(setup_script, args);
4883 _exit(1);
4885 while (waitpid(pid, &status, 0) != pid);
4886 if (!WIFEXITED(status) ||
4887 WEXITSTATUS(status) != 0) {
4888 fprintf(stderr, "%s: could not launch network script\n",
4889 setup_script);
4890 return -1;
4893 return 0;
4896 static int net_tap_init(VLANState *vlan, const char *ifname1,
4897 const char *setup_script, const char *down_script)
4899 TAPState *s;
4900 int fd;
4901 int vnet_hdr;
4902 char ifname[128];
4904 if (ifname1 != NULL)
4905 pstrcpy(ifname, sizeof(ifname), ifname1);
4906 else
4907 ifname[0] = '\0';
4908 vnet_hdr = 0;
4909 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
4910 if (fd < 0)
4911 return -1;
4913 if (!setup_script || !strcmp(setup_script, "no"))
4914 setup_script = "";
4915 if (setup_script[0] != '\0') {
4916 if (launch_script(setup_script, ifname, fd))
4917 return -1;
4919 s = net_tap_fd_init(vlan, fd, vnet_hdr);
4920 if (!s)
4921 return -1;
4923 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4924 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4925 if (down_script && strcmp(down_script, "no"))
4926 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4927 return 0;
4930 #endif /* !_WIN32 */
4932 #if defined(CONFIG_VDE)
4933 typedef struct VDEState {
4934 VLANClientState *vc;
4935 VDECONN *vde;
4936 } VDEState;
4938 static void vde_to_qemu(void *opaque)
4940 VDEState *s = opaque;
4941 uint8_t buf[4096];
4942 int size;
4944 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4945 if (size > 0) {
4946 qemu_send_packet(s->vc, buf, size);
4950 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4952 VDEState *s = opaque;
4953 int ret;
4954 for(;;) {
4955 ret = vde_send(s->vde, buf, size, 0);
4956 if (ret < 0 && errno == EINTR) {
4957 } else {
4958 break;
4963 static int net_vde_init(VLANState *vlan, const char *sock, int port,
4964 const char *group, int mode)
4966 VDEState *s;
4967 char *init_group = strlen(group) ? (char *)group : NULL;
4968 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4970 struct vde_open_args args = {
4971 .port = port,
4972 .group = init_group,
4973 .mode = mode,
4976 s = qemu_mallocz(sizeof(VDEState));
4977 if (!s)
4978 return -1;
4979 s->vde = vde_open(init_sock, "QEMU", &args);
4980 if (!s->vde){
4981 free(s);
4982 return -1;
4984 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4985 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4986 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4987 sock, vde_datafd(s->vde));
4988 return 0;
4990 #endif
4992 /* network connection */
4993 typedef struct NetSocketState {
4994 VLANClientState *vc;
4995 int fd;
4996 int state; /* 0 = getting length, 1 = getting data */
4997 int index;
4998 int packet_len;
4999 uint8_t buf[4096];
5000 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
5001 } NetSocketState;
5003 typedef struct NetSocketListenState {
5004 VLANState *vlan;
5005 int fd;
5006 } NetSocketListenState;
5008 /* XXX: we consider we can send the whole packet without blocking */
5009 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
5011 NetSocketState *s = opaque;
5012 uint32_t len;
5013 len = htonl(size);
5015 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
5016 send_all(s->fd, buf, size);
5019 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
5021 NetSocketState *s = opaque;
5022 sendto(s->fd, buf, size, 0,
5023 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
5026 static void net_socket_send(void *opaque)
5028 NetSocketState *s = opaque;
5029 int l, size, err;
5030 uint8_t buf1[4096];
5031 const uint8_t *buf;
5033 size = recv(s->fd, buf1, sizeof(buf1), 0);
5034 if (size < 0) {
5035 err = socket_error();
5036 if (err != EWOULDBLOCK)
5037 goto eoc;
5038 } else if (size == 0) {
5039 /* end of connection */
5040 eoc:
5041 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
5042 closesocket(s->fd);
5043 return;
5045 buf = buf1;
5046 while (size > 0) {
5047 /* reassemble a packet from the network */
5048 switch(s->state) {
5049 case 0:
5050 l = 4 - s->index;
5051 if (l > size)
5052 l = size;
5053 memcpy(s->buf + s->index, buf, l);
5054 buf += l;
5055 size -= l;
5056 s->index += l;
5057 if (s->index == 4) {
5058 /* got length */
5059 s->packet_len = ntohl(*(uint32_t *)s->buf);
5060 s->index = 0;
5061 s->state = 1;
5063 break;
5064 case 1:
5065 l = s->packet_len - s->index;
5066 if (l > size)
5067 l = size;
5068 memcpy(s->buf + s->index, buf, l);
5069 s->index += l;
5070 buf += l;
5071 size -= l;
5072 if (s->index >= s->packet_len) {
5073 qemu_send_packet(s->vc, s->buf, s->packet_len);
5074 s->index = 0;
5075 s->state = 0;
5077 break;
5082 static void net_socket_send_dgram(void *opaque)
5084 NetSocketState *s = opaque;
5085 int size;
5087 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
5088 if (size < 0)
5089 return;
5090 if (size == 0) {
5091 /* end of connection */
5092 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
5093 return;
5095 qemu_send_packet(s->vc, s->buf, size);
5098 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
5100 struct ip_mreq imr;
5101 int fd;
5102 int val, ret;
5103 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
5104 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5105 inet_ntoa(mcastaddr->sin_addr),
5106 (int)ntohl(mcastaddr->sin_addr.s_addr));
5107 return -1;
5110 fd = socket(PF_INET, SOCK_DGRAM, 0);
5111 if (fd < 0) {
5112 perror("socket(PF_INET, SOCK_DGRAM)");
5113 return -1;
5116 val = 1;
5117 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
5118 (const char *)&val, sizeof(val));
5119 if (ret < 0) {
5120 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5121 goto fail;
5124 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
5125 if (ret < 0) {
5126 perror("bind");
5127 goto fail;
5130 /* Add host to multicast group */
5131 imr.imr_multiaddr = mcastaddr->sin_addr;
5132 imr.imr_interface.s_addr = htonl(INADDR_ANY);
5134 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5135 (const char *)&imr, sizeof(struct ip_mreq));
5136 if (ret < 0) {
5137 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5138 goto fail;
5141 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5142 val = 1;
5143 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
5144 (const char *)&val, sizeof(val));
5145 if (ret < 0) {
5146 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5147 goto fail;
5150 socket_set_nonblock(fd);
5151 return fd;
5152 fail:
5153 if (fd >= 0)
5154 closesocket(fd);
5155 return -1;
5158 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
5159 int is_connected)
5161 struct sockaddr_in saddr;
5162 int newfd;
5163 socklen_t saddr_len;
5164 NetSocketState *s;
5166 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5167 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5168 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5171 if (is_connected) {
5172 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
5173 /* must be bound */
5174 if (saddr.sin_addr.s_addr==0) {
5175 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5176 fd);
5177 return NULL;
5179 /* clone dgram socket */
5180 newfd = net_socket_mcast_create(&saddr);
5181 if (newfd < 0) {
5182 /* error already reported by net_socket_mcast_create() */
5183 close(fd);
5184 return NULL;
5186 /* clone newfd to fd, close newfd */
5187 dup2(newfd, fd);
5188 close(newfd);
5190 } else {
5191 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5192 fd, strerror(errno));
5193 return NULL;
5197 s = qemu_mallocz(sizeof(NetSocketState));
5198 if (!s)
5199 return NULL;
5200 s->fd = fd;
5202 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
5203 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
5205 /* mcast: save bound address as dst */
5206 if (is_connected) s->dgram_dst=saddr;
5208 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5209 "socket: fd=%d (%s mcast=%s:%d)",
5210 fd, is_connected? "cloned" : "",
5211 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5212 return s;
5215 static void net_socket_connect(void *opaque)
5217 NetSocketState *s = opaque;
5218 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
5221 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
5222 int is_connected)
5224 NetSocketState *s;
5225 s = qemu_mallocz(sizeof(NetSocketState));
5226 if (!s)
5227 return NULL;
5228 s->fd = fd;
5229 s->vc = qemu_new_vlan_client(vlan,
5230 net_socket_receive, NULL, s);
5231 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5232 "socket: fd=%d", fd);
5233 if (is_connected) {
5234 net_socket_connect(s);
5235 } else {
5236 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
5238 return s;
5241 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
5242 int is_connected)
5244 int so_type=-1, optlen=sizeof(so_type);
5246 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
5247 (socklen_t *)&optlen)< 0) {
5248 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
5249 return NULL;
5251 switch(so_type) {
5252 case SOCK_DGRAM:
5253 return net_socket_fd_init_dgram(vlan, fd, is_connected);
5254 case SOCK_STREAM:
5255 return net_socket_fd_init_stream(vlan, fd, is_connected);
5256 default:
5257 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5258 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
5259 return net_socket_fd_init_stream(vlan, fd, is_connected);
5261 return NULL;
5264 static void net_socket_accept(void *opaque)
5266 NetSocketListenState *s = opaque;
5267 NetSocketState *s1;
5268 struct sockaddr_in saddr;
5269 socklen_t len;
5270 int fd;
5272 for(;;) {
5273 len = sizeof(saddr);
5274 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
5275 if (fd < 0 && errno != EINTR) {
5276 return;
5277 } else if (fd >= 0) {
5278 break;
5281 s1 = net_socket_fd_init(s->vlan, fd, 1);
5282 if (!s1) {
5283 closesocket(fd);
5284 } else {
5285 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
5286 "socket: connection from %s:%d",
5287 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5291 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
5293 NetSocketListenState *s;
5294 int fd, val, ret;
5295 struct sockaddr_in saddr;
5297 if (parse_host_port(&saddr, host_str) < 0)
5298 return -1;
5300 s = qemu_mallocz(sizeof(NetSocketListenState));
5301 if (!s)
5302 return -1;
5304 fd = socket(PF_INET, SOCK_STREAM, 0);
5305 if (fd < 0) {
5306 perror("socket");
5307 return -1;
5309 socket_set_nonblock(fd);
5311 /* allow fast reuse */
5312 val = 1;
5313 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5315 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5316 if (ret < 0) {
5317 perror("bind");
5318 return -1;
5320 ret = listen(fd, 0);
5321 if (ret < 0) {
5322 perror("listen");
5323 return -1;
5325 s->vlan = vlan;
5326 s->fd = fd;
5327 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5328 return 0;
5331 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5333 NetSocketState *s;
5334 int fd, connected, ret, err;
5335 struct sockaddr_in saddr;
5337 if (parse_host_port(&saddr, host_str) < 0)
5338 return -1;
5340 fd = socket(PF_INET, SOCK_STREAM, 0);
5341 if (fd < 0) {
5342 perror("socket");
5343 return -1;
5345 socket_set_nonblock(fd);
5347 connected = 0;
5348 for(;;) {
5349 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5350 if (ret < 0) {
5351 err = socket_error();
5352 if (err == EINTR || err == EWOULDBLOCK) {
5353 } else if (err == EINPROGRESS) {
5354 break;
5355 #ifdef _WIN32
5356 } else if (err == WSAEALREADY) {
5357 break;
5358 #endif
5359 } else {
5360 perror("connect");
5361 closesocket(fd);
5362 return -1;
5364 } else {
5365 connected = 1;
5366 break;
5369 s = net_socket_fd_init(vlan, fd, connected);
5370 if (!s)
5371 return -1;
5372 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5373 "socket: connect to %s:%d",
5374 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5375 return 0;
5378 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5380 NetSocketState *s;
5381 int fd;
5382 struct sockaddr_in saddr;
5384 if (parse_host_port(&saddr, host_str) < 0)
5385 return -1;
5388 fd = net_socket_mcast_create(&saddr);
5389 if (fd < 0)
5390 return -1;
5392 s = net_socket_fd_init(vlan, fd, 0);
5393 if (!s)
5394 return -1;
5396 s->dgram_dst = saddr;
5398 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5399 "socket: mcast=%s:%d",
5400 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5401 return 0;
5405 static const char *get_opt_name(char *buf, int buf_size, const char *p)
5407 char *q;
5409 q = buf;
5410 while (*p != '\0' && *p != '=') {
5411 if (q && (q - buf) < buf_size - 1)
5412 *q++ = *p;
5413 p++;
5415 if (q)
5416 *q = '\0';
5418 return p;
5421 static const char *get_opt_value(char *buf, int buf_size, const char *p)
5423 char *q;
5425 q = buf;
5426 while (*p != '\0') {
5427 if (*p == ',') {
5428 if (*(p + 1) != ',')
5429 break;
5430 p++;
5432 if (q && (q - buf) < buf_size - 1)
5433 *q++ = *p;
5434 p++;
5436 if (q)
5437 *q = '\0';
5439 return p;
5442 int get_param_value(char *buf, int buf_size,
5443 const char *tag, const char *str)
5445 const char *p;
5446 char option[128];
5448 p = str;
5449 for(;;) {
5450 p = get_opt_name(option, sizeof(option), p);
5451 if (*p != '=')
5452 break;
5453 p++;
5454 if (!strcmp(tag, option)) {
5455 (void)get_opt_value(buf, buf_size, p);
5456 return strlen(buf);
5457 } else {
5458 p = get_opt_value(NULL, 0, p);
5460 if (*p != ',')
5461 break;
5462 p++;
5464 return 0;
5467 int check_params(char *buf, int buf_size,
5468 const char * const *params, const char *str)
5470 const char *p;
5471 int i;
5473 p = str;
5474 for(;;) {
5475 p = get_opt_name(buf, buf_size, p);
5476 if (*p != '=')
5477 return -1;
5478 p++;
5479 for(i = 0; params[i] != NULL; i++)
5480 if (!strcmp(params[i], buf))
5481 break;
5482 if (params[i] == NULL)
5483 return -1;
5484 p = get_opt_value(NULL, 0, p);
5485 if (*p != ',')
5486 break;
5487 p++;
5489 return 0;
5492 static int nic_get_free_idx(void)
5494 int index;
5496 for (index = 0; index < MAX_NICS; index++)
5497 if (!nd_table[index].used)
5498 return index;
5499 return -1;
5502 int net_client_init(const char *device, const char *p)
5504 char buf[1024];
5505 int vlan_id, ret;
5506 VLANState *vlan;
5508 vlan_id = 0;
5509 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5510 vlan_id = strtol(buf, NULL, 0);
5512 vlan = qemu_find_vlan(vlan_id);
5513 if (!vlan) {
5514 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5515 return -1;
5517 if (!strcmp(device, "nic")) {
5518 NICInfo *nd;
5519 uint8_t *macaddr;
5520 int idx = nic_get_free_idx();
5522 if (idx == -1 || nb_nics >= MAX_NICS) {
5523 fprintf(stderr, "Too Many NICs\n");
5524 return -1;
5526 nd = &nd_table[idx];
5527 macaddr = nd->macaddr;
5528 macaddr[0] = 0x52;
5529 macaddr[1] = 0x54;
5530 macaddr[2] = 0x00;
5531 macaddr[3] = 0x12;
5532 macaddr[4] = 0x34;
5533 macaddr[5] = 0x56 + idx;
5535 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5536 if (parse_macaddr(macaddr, buf) < 0) {
5537 fprintf(stderr, "invalid syntax for ethernet address\n");
5538 return -1;
5541 if (get_param_value(buf, sizeof(buf), "model", p)) {
5542 nd->model = strdup(buf);
5544 nd->vlan = vlan;
5545 nd->used = 1;
5546 nb_nics++;
5547 vlan->nb_guest_devs++;
5548 ret = idx;
5549 } else
5550 if (!strcmp(device, "none")) {
5551 /* does nothing. It is needed to signal that no network cards
5552 are wanted */
5553 ret = 0;
5554 } else
5555 #ifdef CONFIG_SLIRP
5556 if (!strcmp(device, "user")) {
5557 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5558 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5560 vlan->nb_host_devs++;
5561 ret = net_slirp_init(vlan);
5562 } else
5563 #endif
5564 #ifdef _WIN32
5565 if (!strcmp(device, "tap")) {
5566 char ifname[64];
5567 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5568 fprintf(stderr, "tap: no interface name\n");
5569 return -1;
5571 vlan->nb_host_devs++;
5572 ret = tap_win32_init(vlan, ifname);
5573 } else
5574 #else
5575 if (!strcmp(device, "tap")) {
5576 char ifname[64];
5577 char setup_script[1024], down_script[1024];
5578 int fd;
5579 vlan->nb_host_devs++;
5580 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5581 fd = strtol(buf, NULL, 0);
5582 fcntl(fd, F_SETFL, O_NONBLOCK);
5583 ret = -1;
5584 if (net_tap_fd_init(vlan, fd, tap_probe_vnet_hdr(fd)))
5585 ret = 0;
5586 } else {
5587 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5588 ifname[0] = '\0';
5590 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5591 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5593 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5594 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5596 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5598 } else
5599 #endif
5600 if (!strcmp(device, "socket")) {
5601 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5602 int fd;
5603 fd = strtol(buf, NULL, 0);
5604 ret = -1;
5605 if (net_socket_fd_init(vlan, fd, 1))
5606 ret = 0;
5607 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5608 ret = net_socket_listen_init(vlan, buf);
5609 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5610 ret = net_socket_connect_init(vlan, buf);
5611 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5612 ret = net_socket_mcast_init(vlan, buf);
5613 } else {
5614 fprintf(stderr, "Unknown socket options: %s\n", p);
5615 return -1;
5617 vlan->nb_host_devs++;
5618 } else
5619 #ifdef CONFIG_VDE
5620 if (!strcmp(device, "vde")) {
5621 char vde_sock[1024], vde_group[512];
5622 int vde_port, vde_mode;
5623 vlan->nb_host_devs++;
5624 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5625 vde_sock[0] = '\0';
5627 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5628 vde_port = strtol(buf, NULL, 10);
5629 } else {
5630 vde_port = 0;
5632 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5633 vde_group[0] = '\0';
5635 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5636 vde_mode = strtol(buf, NULL, 8);
5637 } else {
5638 vde_mode = 0700;
5640 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5641 } else
5642 #endif
5644 fprintf(stderr, "Unknown network device: %s\n", device);
5645 return -1;
5647 if (ret < 0) {
5648 fprintf(stderr, "Could not initialize device '%s'\n", device);
5651 return ret;
5654 void net_client_uninit(NICInfo *nd)
5656 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
5657 nb_nics--;
5658 nd->used = 0;
5659 free((void *)nd->model);
5662 static int net_client_parse(const char *str)
5664 const char *p;
5665 char *q;
5666 char device[64];
5668 p = str;
5669 q = device;
5670 while (*p != '\0' && *p != ',') {
5671 if ((q - device) < sizeof(device) - 1)
5672 *q++ = *p;
5673 p++;
5675 *q = '\0';
5676 if (*p == ',')
5677 p++;
5679 return net_client_init(device, p);
5682 void do_info_network(void)
5684 VLANState *vlan;
5685 VLANClientState *vc;
5687 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5688 term_printf("VLAN %d devices:\n", vlan->id);
5689 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5690 term_printf(" %s\n", vc->info_str);
5694 #define HD_ALIAS "index=%d,media=disk"
5695 #ifdef TARGET_PPC
5696 #define CDROM_ALIAS "index=1,media=cdrom"
5697 #else
5698 #define CDROM_ALIAS "index=2,media=cdrom"
5699 #endif
5700 #define FD_ALIAS "index=%d,if=floppy"
5701 #define PFLASH_ALIAS "if=pflash"
5702 #define MTD_ALIAS "if=mtd"
5703 #define SD_ALIAS "index=0,if=sd"
5705 static int drive_opt_get_free_idx(void)
5707 int index;
5709 for (index = 0; index < MAX_DRIVES; index++)
5710 if (!drives_opt[index].used) {
5711 drives_opt[index].used = 1;
5712 return index;
5715 return -1;
5718 static int drive_get_free_idx(void)
5720 int index;
5722 for (index = 0; index < MAX_DRIVES; index++)
5723 if (!drives_table[index].used) {
5724 drives_table[index].used = 1;
5725 return index;
5728 return -1;
5731 int drive_add(const char *file, const char *fmt, ...)
5733 va_list ap;
5734 int index = drive_opt_get_free_idx();
5736 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5737 fprintf(stderr, "qemu: too many drives\n");
5738 return -1;
5741 drives_opt[index].file = file;
5742 va_start(ap, fmt);
5743 vsnprintf(drives_opt[index].opt,
5744 sizeof(drives_opt[0].opt), fmt, ap);
5745 va_end(ap);
5747 nb_drives_opt++;
5748 return index;
5751 void drive_remove(int index)
5753 drives_opt[index].used = 0;
5754 nb_drives_opt--;
5757 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5759 int index;
5761 /* seek interface, bus and unit */
5763 for (index = 0; index < MAX_DRIVES; index++)
5764 if (drives_table[index].type == type &&
5765 drives_table[index].bus == bus &&
5766 drives_table[index].unit == unit &&
5767 drives_table[index].used)
5768 return index;
5770 return -1;
5773 int drive_get_max_bus(BlockInterfaceType type)
5775 int max_bus;
5776 int index;
5778 max_bus = -1;
5779 for (index = 0; index < nb_drives; index++) {
5780 if(drives_table[index].type == type &&
5781 drives_table[index].bus > max_bus)
5782 max_bus = drives_table[index].bus;
5784 return max_bus;
5787 static void bdrv_format_print(void *opaque, const char *name)
5789 fprintf(stderr, " %s", name);
5792 void drive_uninit(BlockDriverState *bdrv)
5794 int i;
5796 for (i = 0; i < MAX_DRIVES; i++)
5797 if (drives_table[i].bdrv == bdrv) {
5798 drives_table[i].bdrv = NULL;
5799 drives_table[i].used = 0;
5800 drive_remove(drives_table[i].drive_opt_idx);
5801 nb_drives--;
5802 break;
5806 int drive_init(struct drive_opt *arg, int snapshot,
5807 QEMUMachine *machine)
5809 char buf[128];
5810 char file[1024];
5811 char devname[128];
5812 const char *mediastr = "";
5813 BlockInterfaceType type;
5814 enum { MEDIA_DISK, MEDIA_CDROM } media;
5815 int bus_id, unit_id;
5816 int cyls, heads, secs, translation;
5817 BlockDriverState *bdrv;
5818 BlockDriver *drv = NULL;
5819 int max_devs;
5820 int index;
5821 int cache;
5822 int bdrv_flags;
5823 int drives_table_idx;
5824 char *str = arg->opt;
5825 static const char * const params[] = { "bus", "unit", "if", "index",
5826 "cyls", "heads", "secs", "trans",
5827 "media", "snapshot", "file",
5828 "cache", "format", "boot", NULL };
5830 if (check_params(buf, sizeof(buf), params, str) < 0) {
5831 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5832 buf, str);
5833 return -1;
5836 file[0] = 0;
5837 cyls = heads = secs = 0;
5838 bus_id = 0;
5839 unit_id = -1;
5840 translation = BIOS_ATA_TRANSLATION_AUTO;
5841 index = -1;
5842 cache = 1;
5844 if (!strcmp(machine->name, "realview") ||
5845 !strcmp(machine->name, "SS-5") ||
5846 !strcmp(machine->name, "SS-10") ||
5847 !strcmp(machine->name, "SS-600MP") ||
5848 !strcmp(machine->name, "versatilepb") ||
5849 !strcmp(machine->name, "versatileab")) {
5850 type = IF_SCSI;
5851 max_devs = MAX_SCSI_DEVS;
5852 pstrcpy(devname, sizeof(devname), "scsi");
5853 } else {
5854 type = IF_IDE;
5855 max_devs = MAX_IDE_DEVS;
5856 pstrcpy(devname, sizeof(devname), "ide");
5858 media = MEDIA_DISK;
5860 /* extract parameters */
5862 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5863 bus_id = strtol(buf, NULL, 0);
5864 if (bus_id < 0) {
5865 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5866 return -1;
5870 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5871 unit_id = strtol(buf, NULL, 0);
5872 if (unit_id < 0) {
5873 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5874 return -1;
5878 if (get_param_value(buf, sizeof(buf), "if", str)) {
5879 pstrcpy(devname, sizeof(devname), buf);
5880 if (!strcmp(buf, "ide")) {
5881 type = IF_IDE;
5882 max_devs = MAX_IDE_DEVS;
5883 } else if (!strcmp(buf, "scsi")) {
5884 type = IF_SCSI;
5885 max_devs = MAX_SCSI_DEVS;
5886 } else if (!strcmp(buf, "floppy")) {
5887 type = IF_FLOPPY;
5888 max_devs = 0;
5889 } else if (!strcmp(buf, "pflash")) {
5890 type = IF_PFLASH;
5891 max_devs = 0;
5892 } else if (!strcmp(buf, "mtd")) {
5893 type = IF_MTD;
5894 max_devs = 0;
5895 } else if (!strcmp(buf, "sd")) {
5896 type = IF_SD;
5897 max_devs = 0;
5898 } else if (!strcmp(buf, "virtio")) {
5899 type = IF_VIRTIO;
5900 max_devs = 0;
5901 } else {
5902 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5903 return -1;
5907 if (get_param_value(buf, sizeof(buf), "index", str)) {
5908 index = strtol(buf, NULL, 0);
5909 if (index < 0) {
5910 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5911 return -1;
5915 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5916 cyls = strtol(buf, NULL, 0);
5919 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5920 heads = strtol(buf, NULL, 0);
5923 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5924 secs = strtol(buf, NULL, 0);
5927 if (cyls || heads || secs) {
5928 if (cyls < 1 || cyls > 16383) {
5929 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5930 return -1;
5932 if (heads < 1 || heads > 16) {
5933 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5934 return -1;
5936 if (secs < 1 || secs > 63) {
5937 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5938 return -1;
5942 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5943 if (!cyls) {
5944 fprintf(stderr,
5945 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5946 str);
5947 return -1;
5949 if (!strcmp(buf, "none"))
5950 translation = BIOS_ATA_TRANSLATION_NONE;
5951 else if (!strcmp(buf, "lba"))
5952 translation = BIOS_ATA_TRANSLATION_LBA;
5953 else if (!strcmp(buf, "auto"))
5954 translation = BIOS_ATA_TRANSLATION_AUTO;
5955 else {
5956 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5957 return -1;
5961 if (get_param_value(buf, sizeof(buf), "media", str)) {
5962 if (!strcmp(buf, "disk")) {
5963 media = MEDIA_DISK;
5964 } else if (!strcmp(buf, "cdrom")) {
5965 if (cyls || secs || heads) {
5966 fprintf(stderr,
5967 "qemu: '%s' invalid physical CHS format\n", str);
5968 return -1;
5970 media = MEDIA_CDROM;
5971 } else {
5972 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5973 return -1;
5977 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5978 if (!strcmp(buf, "on"))
5979 snapshot = 1;
5980 else if (!strcmp(buf, "off"))
5981 snapshot = 0;
5982 else {
5983 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5984 return -1;
5988 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5989 if (!strcmp(buf, "off"))
5990 cache = 0;
5991 else if (!strcmp(buf, "on"))
5992 cache = 1;
5993 else {
5994 fprintf(stderr, "qemu: invalid cache option\n");
5995 return -1;
5999 if (get_param_value(buf, sizeof(buf), "format", str)) {
6000 if (strcmp(buf, "?") == 0) {
6001 fprintf(stderr, "qemu: Supported formats:");
6002 bdrv_iterate_format(bdrv_format_print, NULL);
6003 fprintf(stderr, "\n");
6004 return -1;
6006 drv = bdrv_find_format(buf);
6007 if (!drv) {
6008 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
6009 return -1;
6013 if (get_param_value(buf, sizeof(buf), "boot", str)) {
6014 if (!strcmp(buf, "on")) {
6015 if (extboot_drive != -1) {
6016 fprintf(stderr, "qemu: two bootable drives specified\n");
6017 return -1;
6019 extboot_drive = nb_drives;
6020 } else if (strcmp(buf, "off")) {
6021 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
6022 return -1;
6026 if (arg->file == NULL)
6027 get_param_value(file, sizeof(file), "file", str);
6028 else
6029 pstrcpy(file, sizeof(file), arg->file);
6031 /* compute bus and unit according index */
6033 if (index != -1) {
6034 if (bus_id != 0 || unit_id != -1) {
6035 fprintf(stderr,
6036 "qemu: '%s' index cannot be used with bus and unit\n", str);
6037 return -1;
6039 if (max_devs == 0)
6041 unit_id = index;
6042 bus_id = 0;
6043 } else {
6044 unit_id = index % max_devs;
6045 bus_id = index / max_devs;
6049 /* if user doesn't specify a unit_id,
6050 * try to find the first free
6053 if (unit_id == -1) {
6054 unit_id = 0;
6055 while (drive_get_index(type, bus_id, unit_id) != -1) {
6056 unit_id++;
6057 if (max_devs && unit_id >= max_devs) {
6058 unit_id -= max_devs;
6059 bus_id++;
6064 /* check unit id */
6066 if (max_devs && unit_id >= max_devs) {
6067 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
6068 str, unit_id, max_devs - 1);
6069 return -1;
6073 * ignore multiple definitions
6076 if (drive_get_index(type, bus_id, unit_id) != -1)
6077 return -2;
6079 /* init */
6081 if (type == IF_IDE || type == IF_SCSI)
6082 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
6083 if (max_devs)
6084 snprintf(buf, sizeof(buf), "%s%i%s%i",
6085 devname, bus_id, mediastr, unit_id);
6086 else
6087 snprintf(buf, sizeof(buf), "%s%s%i",
6088 devname, mediastr, unit_id);
6089 bdrv = bdrv_new(buf);
6090 drives_table_idx = drive_get_free_idx();
6091 drives_table[drives_table_idx].bdrv = bdrv;
6092 drives_table[drives_table_idx].type = type;
6093 drives_table[drives_table_idx].bus = bus_id;
6094 drives_table[drives_table_idx].unit = unit_id;
6095 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
6096 nb_drives++;
6098 switch(type) {
6099 case IF_IDE:
6100 case IF_SCSI:
6101 switch(media) {
6102 case MEDIA_DISK:
6103 if (cyls != 0) {
6104 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
6105 bdrv_set_translation_hint(bdrv, translation);
6107 break;
6108 case MEDIA_CDROM:
6109 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
6110 break;
6112 break;
6113 case IF_SD:
6114 /* FIXME: This isn't really a floppy, but it's a reasonable
6115 approximation. */
6116 case IF_FLOPPY:
6117 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
6118 break;
6119 case IF_PFLASH:
6120 case IF_MTD:
6121 case IF_VIRTIO:
6122 break;
6124 if (!file[0])
6125 return -2;
6126 bdrv_flags = 0;
6127 if (snapshot)
6128 bdrv_flags |= BDRV_O_SNAPSHOT;
6129 if (!cache)
6130 bdrv_flags |= BDRV_O_DIRECT;
6131 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
6132 fprintf(stderr, "qemu: could not open disk image %s\n",
6133 file);
6134 return -1;
6136 return drives_table_idx;
6139 /***********************************************************/
6140 /* USB devices */
6142 static USBPort *used_usb_ports;
6143 static USBPort *free_usb_ports;
6145 /* ??? Maybe change this to register a hub to keep track of the topology. */
6146 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
6147 usb_attachfn attach)
6149 port->opaque = opaque;
6150 port->index = index;
6151 port->attach = attach;
6152 port->next = free_usb_ports;
6153 free_usb_ports = port;
6156 int usb_device_add_dev(USBDevice *dev)
6158 USBPort *port;
6160 /* Find a USB port to add the device to. */
6161 port = free_usb_ports;
6162 if (!port->next) {
6163 USBDevice *hub;
6165 /* Create a new hub and chain it on. */
6166 free_usb_ports = NULL;
6167 port->next = used_usb_ports;
6168 used_usb_ports = port;
6170 hub = usb_hub_init(VM_USB_HUB_SIZE);
6171 usb_attach(port, hub);
6172 port = free_usb_ports;
6175 free_usb_ports = port->next;
6176 port->next = used_usb_ports;
6177 used_usb_ports = port;
6178 usb_attach(port, dev);
6179 return 0;
6182 static int usb_device_add(const char *devname)
6184 const char *p;
6185 USBDevice *dev;
6187 if (!free_usb_ports)
6188 return -1;
6190 if (strstart(devname, "host:", &p)) {
6191 dev = usb_host_device_open(p);
6192 } else if (!strcmp(devname, "mouse")) {
6193 dev = usb_mouse_init();
6194 } else if (!strcmp(devname, "tablet")) {
6195 dev = usb_tablet_init();
6196 } else if (!strcmp(devname, "keyboard")) {
6197 dev = usb_keyboard_init();
6198 } else if (strstart(devname, "disk:", &p)) {
6199 dev = usb_msd_init(p);
6200 } else if (!strcmp(devname, "wacom-tablet")) {
6201 dev = usb_wacom_init();
6202 } else if (strstart(devname, "serial:", &p)) {
6203 dev = usb_serial_init(p);
6204 #ifdef CONFIG_BRLAPI
6205 } else if (!strcmp(devname, "braille")) {
6206 dev = usb_baum_init();
6207 #endif
6208 } else if (strstart(devname, "net:", &p)) {
6209 int nic = nb_nics;
6211 if (net_client_init("nic", p) < 0)
6212 return -1;
6213 nd_table[nic].model = "usb";
6214 dev = usb_net_init(&nd_table[nic]);
6215 } else {
6216 return -1;
6218 if (!dev)
6219 return -1;
6221 return usb_device_add_dev(dev);
6224 int usb_device_del_addr(int bus_num, int addr)
6226 USBPort *port;
6227 USBPort **lastp;
6228 USBDevice *dev;
6230 if (!used_usb_ports)
6231 return -1;
6233 if (bus_num != 0)
6234 return -1;
6236 lastp = &used_usb_ports;
6237 port = used_usb_ports;
6238 while (port && port->dev->addr != addr) {
6239 lastp = &port->next;
6240 port = port->next;
6243 if (!port)
6244 return -1;
6246 dev = port->dev;
6247 *lastp = port->next;
6248 usb_attach(port, NULL);
6249 dev->handle_destroy(dev);
6250 port->next = free_usb_ports;
6251 free_usb_ports = port;
6252 return 0;
6255 static int usb_device_del(const char *devname)
6257 int bus_num, addr;
6258 const char *p;
6260 if (strstart(devname, "host:", &p))
6261 return usb_host_device_close(p);
6263 if (!used_usb_ports)
6264 return -1;
6266 p = strchr(devname, '.');
6267 if (!p)
6268 return -1;
6269 bus_num = strtoul(devname, NULL, 0);
6270 addr = strtoul(p + 1, NULL, 0);
6272 return usb_device_del_addr(bus_num, addr);
6275 void do_usb_add(const char *devname)
6277 usb_device_add(devname);
6280 void do_usb_del(const char *devname)
6282 usb_device_del(devname);
6285 void usb_info(void)
6287 USBDevice *dev;
6288 USBPort *port;
6289 const char *speed_str;
6291 if (!usb_enabled) {
6292 term_printf("USB support not enabled\n");
6293 return;
6296 for (port = used_usb_ports; port; port = port->next) {
6297 dev = port->dev;
6298 if (!dev)
6299 continue;
6300 switch(dev->speed) {
6301 case USB_SPEED_LOW:
6302 speed_str = "1.5";
6303 break;
6304 case USB_SPEED_FULL:
6305 speed_str = "12";
6306 break;
6307 case USB_SPEED_HIGH:
6308 speed_str = "480";
6309 break;
6310 default:
6311 speed_str = "?";
6312 break;
6314 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6315 0, dev->addr, speed_str, dev->devname);
6319 /***********************************************************/
6320 /* PCMCIA/Cardbus */
6322 static struct pcmcia_socket_entry_s {
6323 struct pcmcia_socket_s *socket;
6324 struct pcmcia_socket_entry_s *next;
6325 } *pcmcia_sockets = 0;
6327 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
6329 struct pcmcia_socket_entry_s *entry;
6331 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
6332 entry->socket = socket;
6333 entry->next = pcmcia_sockets;
6334 pcmcia_sockets = entry;
6337 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
6339 struct pcmcia_socket_entry_s *entry, **ptr;
6341 ptr = &pcmcia_sockets;
6342 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
6343 if (entry->socket == socket) {
6344 *ptr = entry->next;
6345 qemu_free(entry);
6349 void pcmcia_info(void)
6351 struct pcmcia_socket_entry_s *iter;
6352 if (!pcmcia_sockets)
6353 term_printf("No PCMCIA sockets\n");
6355 for (iter = pcmcia_sockets; iter; iter = iter->next)
6356 term_printf("%s: %s\n", iter->socket->slot_string,
6357 iter->socket->attached ? iter->socket->card_string :
6358 "Empty");
6361 /***********************************************************/
6362 /* dumb display */
6364 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
6368 static void dumb_resize(DisplayState *ds, int w, int h)
6372 static void dumb_refresh(DisplayState *ds)
6374 #if defined(CONFIG_SDL)
6375 vga_hw_update();
6376 #endif
6379 static void dumb_display_init(DisplayState *ds)
6381 ds->data = NULL;
6382 ds->linesize = 0;
6383 ds->depth = 0;
6384 ds->dpy_update = dumb_update;
6385 ds->dpy_resize = dumb_resize;
6386 ds->dpy_refresh = dumb_refresh;
6387 ds->gui_timer_interval = 500;
6388 ds->idle = 1;
6391 /***********************************************************/
6392 /* I/O handling */
6394 #define MAX_IO_HANDLERS 64
6396 typedef struct IOHandlerRecord {
6397 int fd;
6398 IOCanRWHandler *fd_read_poll;
6399 IOHandler *fd_read;
6400 IOHandler *fd_write;
6401 int deleted;
6402 void *opaque;
6403 /* temporary data */
6404 struct pollfd *ufd;
6405 struct IOHandlerRecord *next;
6406 } IOHandlerRecord;
6408 static IOHandlerRecord *first_io_handler;
6410 /* XXX: fd_read_poll should be suppressed, but an API change is
6411 necessary in the character devices to suppress fd_can_read(). */
6412 int qemu_set_fd_handler2(int fd,
6413 IOCanRWHandler *fd_read_poll,
6414 IOHandler *fd_read,
6415 IOHandler *fd_write,
6416 void *opaque)
6418 IOHandlerRecord **pioh, *ioh;
6420 if (!fd_read && !fd_write) {
6421 pioh = &first_io_handler;
6422 for(;;) {
6423 ioh = *pioh;
6424 if (ioh == NULL)
6425 break;
6426 if (ioh->fd == fd) {
6427 ioh->deleted = 1;
6428 break;
6430 pioh = &ioh->next;
6432 } else {
6433 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6434 if (ioh->fd == fd)
6435 goto found;
6437 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6438 if (!ioh)
6439 return -1;
6440 ioh->next = first_io_handler;
6441 first_io_handler = ioh;
6442 found:
6443 ioh->fd = fd;
6444 ioh->fd_read_poll = fd_read_poll;
6445 ioh->fd_read = fd_read;
6446 ioh->fd_write = fd_write;
6447 ioh->opaque = opaque;
6448 ioh->deleted = 0;
6450 main_loop_break();
6451 return 0;
6454 int qemu_set_fd_handler(int fd,
6455 IOHandler *fd_read,
6456 IOHandler *fd_write,
6457 void *opaque)
6459 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6462 /***********************************************************/
6463 /* Polling handling */
6465 typedef struct PollingEntry {
6466 PollingFunc *func;
6467 void *opaque;
6468 struct PollingEntry *next;
6469 } PollingEntry;
6471 static PollingEntry *first_polling_entry;
6473 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6475 PollingEntry **ppe, *pe;
6476 pe = qemu_mallocz(sizeof(PollingEntry));
6477 if (!pe)
6478 return -1;
6479 pe->func = func;
6480 pe->opaque = opaque;
6481 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6482 *ppe = pe;
6483 return 0;
6486 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6488 PollingEntry **ppe, *pe;
6489 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6490 pe = *ppe;
6491 if (pe->func == func && pe->opaque == opaque) {
6492 *ppe = pe->next;
6493 qemu_free(pe);
6494 break;
6499 #ifdef _WIN32
6500 /***********************************************************/
6501 /* Wait objects support */
6502 typedef struct WaitObjects {
6503 int num;
6504 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6505 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6506 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6507 } WaitObjects;
6509 static WaitObjects wait_objects = {0};
6511 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6513 WaitObjects *w = &wait_objects;
6515 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6516 return -1;
6517 w->events[w->num] = handle;
6518 w->func[w->num] = func;
6519 w->opaque[w->num] = opaque;
6520 w->num++;
6521 return 0;
6524 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6526 int i, found;
6527 WaitObjects *w = &wait_objects;
6529 found = 0;
6530 for (i = 0; i < w->num; i++) {
6531 if (w->events[i] == handle)
6532 found = 1;
6533 if (found) {
6534 w->events[i] = w->events[i + 1];
6535 w->func[i] = w->func[i + 1];
6536 w->opaque[i] = w->opaque[i + 1];
6539 if (found)
6540 w->num--;
6542 #endif
6544 #define SELF_ANNOUNCE_ROUNDS 5
6545 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6546 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6547 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6549 static int announce_self_create(uint8_t *buf,
6550 uint8_t *mac_addr)
6552 uint32_t magic = EXPERIMENTAL_MAGIC;
6553 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
6555 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6557 memset(buf, 0xff, 6); /* h_dst */
6558 memcpy(buf + 6, mac_addr, 6); /* h_src */
6559 memcpy(buf + 12, &proto, 2); /* h_proto */
6560 memcpy(buf + 14, &magic, 4); /* magic */
6562 return 18; /* len */
6565 static void qemu_announce_self(void)
6567 int i, j, len;
6568 VLANState *vlan;
6569 VLANClientState *vc;
6570 uint8_t buf[256];
6572 for (i = 0; i < nb_nics; i++) {
6573 len = announce_self_create(buf, nd_table[i].macaddr);
6574 vlan = nd_table[i].vlan;
6575 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
6576 if (vc->fd_read == tap_receive) /* send only if tap */
6577 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
6578 vc->fd_read(vc->opaque, buf, len);
6583 /***********************************************************/
6584 /* savevm/loadvm support */
6586 #define IO_BUF_SIZE 32768
6588 struct QEMUFile {
6589 QEMUFilePutBufferFunc *put_buffer;
6590 QEMUFileGetBufferFunc *get_buffer;
6591 QEMUFileCloseFunc *close;
6592 void *opaque;
6594 int64_t buf_offset; /* start of buffer when writing, end of buffer
6595 when reading */
6596 int buf_index;
6597 int buf_size; /* 0 when writing */
6598 uint8_t buf[IO_BUF_SIZE];
6601 typedef struct QEMUFileFD
6603 int fd;
6604 } QEMUFileFD;
6606 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6608 QEMUFileFD *s = opaque;
6609 int offset = 0;
6610 ssize_t len;
6612 again:
6613 len = read(s->fd, buf + offset, size - offset);
6614 if (len == -1) {
6615 if (errno == EINTR || errno == EAGAIN)
6616 goto again;
6619 return len;
6622 QEMUFile *qemu_fopen_fd(int fd)
6624 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
6625 s->fd = fd;
6626 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
6629 typedef struct QEMUFileUnix
6631 FILE *outfile;
6632 } QEMUFileUnix;
6634 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6636 QEMUFileUnix *s = opaque;
6637 fseek(s->outfile, pos, SEEK_SET);
6638 fwrite(buf, 1, size, s->outfile);
6641 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6643 QEMUFileUnix *s = opaque;
6644 fseek(s->outfile, pos, SEEK_SET);
6645 return fread(buf, 1, size, s->outfile);
6648 static void file_close(void *opaque)
6650 QEMUFileUnix *s = opaque;
6651 fclose(s->outfile);
6652 qemu_free(s);
6655 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
6657 QEMUFileUnix *s;
6659 s = qemu_mallocz(sizeof(QEMUFileUnix));
6660 if (!s)
6661 return NULL;
6663 s->outfile = fopen(filename, mode);
6664 if (!s->outfile)
6665 goto fail;
6667 if (!strcmp(mode, "wb"))
6668 return qemu_fopen(s, file_put_buffer, NULL, file_close);
6669 else if (!strcmp(mode, "rb"))
6670 return qemu_fopen(s, NULL, file_get_buffer, file_close);
6672 fail:
6673 if (s->outfile)
6674 fclose(s->outfile);
6675 qemu_free(s);
6676 return NULL;
6679 typedef struct QEMUFileBdrv
6681 BlockDriverState *bs;
6682 int64_t base_offset;
6683 } QEMUFileBdrv;
6685 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6687 QEMUFileBdrv *s = opaque;
6688 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
6691 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6693 QEMUFileBdrv *s = opaque;
6694 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6697 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6699 QEMUFileBdrv *s;
6701 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6702 if (!s)
6703 return NULL;
6705 s->bs = bs;
6706 s->base_offset = offset;
6708 if (is_writable)
6709 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
6711 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
6714 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6715 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
6717 QEMUFile *f;
6719 f = qemu_mallocz(sizeof(QEMUFile));
6720 if (!f)
6721 return NULL;
6723 f->opaque = opaque;
6724 f->put_buffer = put_buffer;
6725 f->get_buffer = get_buffer;
6726 f->close = close;
6728 return f;
6731 void qemu_fflush(QEMUFile *f)
6733 if (!f->put_buffer)
6734 return;
6736 if (f->buf_index > 0) {
6737 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
6738 f->buf_offset += f->buf_index;
6739 f->buf_index = 0;
6743 static void qemu_fill_buffer(QEMUFile *f)
6745 int len;
6747 if (!f->get_buffer)
6748 return;
6750 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6751 if (len < 0)
6752 len = 0;
6754 f->buf_index = 0;
6755 f->buf_size = len;
6756 f->buf_offset += len;
6759 void qemu_fclose(QEMUFile *f)
6761 qemu_fflush(f);
6762 if (f->close)
6763 f->close(f->opaque);
6764 qemu_free(f);
6767 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6769 int l;
6770 while (size > 0) {
6771 l = IO_BUF_SIZE - f->buf_index;
6772 if (l > size)
6773 l = size;
6774 memcpy(f->buf + f->buf_index, buf, l);
6775 f->buf_index += l;
6776 buf += l;
6777 size -= l;
6778 if (f->buf_index >= IO_BUF_SIZE)
6779 qemu_fflush(f);
6783 void qemu_put_byte(QEMUFile *f, int v)
6785 f->buf[f->buf_index++] = v;
6786 if (f->buf_index >= IO_BUF_SIZE)
6787 qemu_fflush(f);
6790 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6792 int size, l;
6794 size = size1;
6795 while (size > 0) {
6796 l = f->buf_size - f->buf_index;
6797 if (l == 0) {
6798 qemu_fill_buffer(f);
6799 l = f->buf_size - f->buf_index;
6800 if (l == 0)
6801 break;
6803 if (l > size)
6804 l = size;
6805 memcpy(buf, f->buf + f->buf_index, l);
6806 f->buf_index += l;
6807 buf += l;
6808 size -= l;
6810 return size1 - size;
6813 int qemu_get_byte(QEMUFile *f)
6815 if (f->buf_index >= f->buf_size) {
6816 qemu_fill_buffer(f);
6817 if (f->buf_index >= f->buf_size)
6818 return 0;
6820 return f->buf[f->buf_index++];
6823 int64_t qemu_ftell(QEMUFile *f)
6825 return f->buf_offset - f->buf_size + f->buf_index;
6828 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6830 if (whence == SEEK_SET) {
6831 /* nothing to do */
6832 } else if (whence == SEEK_CUR) {
6833 pos += qemu_ftell(f);
6834 } else {
6835 /* SEEK_END not supported */
6836 return -1;
6838 if (f->put_buffer) {
6839 qemu_fflush(f);
6840 f->buf_offset = pos;
6841 } else {
6842 f->buf_offset = pos;
6843 f->buf_index = 0;
6844 f->buf_size = 0;
6846 return pos;
6849 void qemu_put_be16(QEMUFile *f, unsigned int v)
6851 qemu_put_byte(f, v >> 8);
6852 qemu_put_byte(f, v);
6855 void qemu_put_be32(QEMUFile *f, unsigned int v)
6857 qemu_put_byte(f, v >> 24);
6858 qemu_put_byte(f, v >> 16);
6859 qemu_put_byte(f, v >> 8);
6860 qemu_put_byte(f, v);
6863 void qemu_put_be64(QEMUFile *f, uint64_t v)
6865 qemu_put_be32(f, v >> 32);
6866 qemu_put_be32(f, v);
6869 unsigned int qemu_get_be16(QEMUFile *f)
6871 unsigned int v;
6872 v = qemu_get_byte(f) << 8;
6873 v |= qemu_get_byte(f);
6874 return v;
6877 unsigned int qemu_get_be32(QEMUFile *f)
6879 unsigned int v;
6880 v = qemu_get_byte(f) << 24;
6881 v |= qemu_get_byte(f) << 16;
6882 v |= qemu_get_byte(f) << 8;
6883 v |= qemu_get_byte(f);
6884 return v;
6887 uint64_t qemu_get_be64(QEMUFile *f)
6889 uint64_t v;
6890 v = (uint64_t)qemu_get_be32(f) << 32;
6891 v |= qemu_get_be32(f);
6892 return v;
6895 typedef struct SaveStateEntry {
6896 char idstr[256];
6897 int instance_id;
6898 int version_id;
6899 SaveStateHandler *save_state;
6900 LoadStateHandler *load_state;
6901 void *opaque;
6902 struct SaveStateEntry *next;
6903 } SaveStateEntry;
6905 static SaveStateEntry *first_se;
6907 /* TODO: Individual devices generally have very little idea about the rest
6908 of the system, so instance_id should be removed/replaced.
6909 Meanwhile pass -1 as instance_id if you do not already have a clearly
6910 distinguishing id for all instances of your device class. */
6911 int register_savevm(const char *idstr,
6912 int instance_id,
6913 int version_id,
6914 SaveStateHandler *save_state,
6915 LoadStateHandler *load_state,
6916 void *opaque)
6918 SaveStateEntry *se, **pse;
6920 se = qemu_malloc(sizeof(SaveStateEntry));
6921 if (!se)
6922 return -1;
6923 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6924 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6925 se->version_id = version_id;
6926 se->save_state = save_state;
6927 se->load_state = load_state;
6928 se->opaque = opaque;
6929 se->next = NULL;
6931 /* add at the end of list */
6932 pse = &first_se;
6933 while (*pse != NULL) {
6934 if (instance_id == -1
6935 && strcmp(se->idstr, (*pse)->idstr) == 0
6936 && se->instance_id <= (*pse)->instance_id)
6937 se->instance_id = (*pse)->instance_id + 1;
6938 pse = &(*pse)->next;
6940 *pse = se;
6941 return 0;
6944 #define QEMU_VM_FILE_MAGIC 0x5145564d
6945 #define QEMU_VM_FILE_VERSION 0x00000002
6947 static int qemu_savevm_state(QEMUFile *f)
6949 SaveStateEntry *se;
6950 int len, ret;
6951 int64_t cur_pos, len_pos, total_len_pos;
6953 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6954 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6955 total_len_pos = qemu_ftell(f);
6956 qemu_put_be64(f, 0); /* total size */
6958 for(se = first_se; se != NULL; se = se->next) {
6959 if (se->save_state == NULL)
6960 /* this one has a loader only, for backwards compatibility */
6961 continue;
6963 /* ID string */
6964 len = strlen(se->idstr);
6965 qemu_put_byte(f, len);
6966 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6968 qemu_put_be32(f, se->instance_id);
6969 qemu_put_be32(f, se->version_id);
6971 /* record size: filled later */
6972 len_pos = qemu_ftell(f);
6973 qemu_put_be32(f, 0);
6974 se->save_state(f, se->opaque);
6976 /* fill record size */
6977 cur_pos = qemu_ftell(f);
6978 len = cur_pos - len_pos - 4;
6979 qemu_fseek(f, len_pos, SEEK_SET);
6980 qemu_put_be32(f, len);
6981 qemu_fseek(f, cur_pos, SEEK_SET);
6983 cur_pos = qemu_ftell(f);
6984 qemu_fseek(f, total_len_pos, SEEK_SET);
6985 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6986 qemu_fseek(f, cur_pos, SEEK_SET);
6988 ret = 0;
6989 return ret;
6992 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6994 SaveStateEntry *se;
6996 for(se = first_se; se != NULL; se = se->next) {
6997 if (!strcmp(se->idstr, idstr) &&
6998 instance_id == se->instance_id)
6999 return se;
7001 return NULL;
7004 static int qemu_loadvm_state(QEMUFile *f)
7006 SaveStateEntry *se;
7007 int len, ret, instance_id, record_len, version_id;
7008 int64_t total_len, end_pos, cur_pos;
7009 unsigned int v;
7010 char idstr[256];
7012 v = qemu_get_be32(f);
7013 if (v != QEMU_VM_FILE_MAGIC)
7014 goto fail;
7015 v = qemu_get_be32(f);
7016 if (v != QEMU_VM_FILE_VERSION) {
7017 fail:
7018 ret = -1;
7019 goto the_end;
7021 total_len = qemu_get_be64(f);
7022 end_pos = total_len + qemu_ftell(f);
7023 for(;;) {
7024 if (qemu_ftell(f) >= end_pos)
7025 break;
7026 len = qemu_get_byte(f);
7027 qemu_get_buffer(f, (uint8_t *)idstr, len);
7028 idstr[len] = '\0';
7029 instance_id = qemu_get_be32(f);
7030 version_id = qemu_get_be32(f);
7031 record_len = qemu_get_be32(f);
7032 #if 0
7033 printf("idstr=%s instance=0x%x version=%d len=%d\n",
7034 idstr, instance_id, version_id, record_len);
7035 #endif
7036 cur_pos = qemu_ftell(f);
7037 se = find_se(idstr, instance_id);
7038 if (!se) {
7039 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7040 instance_id, idstr);
7041 } else {
7042 ret = se->load_state(f, se->opaque, version_id);
7043 if (ret < 0) {
7044 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7045 instance_id, idstr);
7046 goto the_end;
7049 /* always seek to exact end of record */
7050 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
7052 ret = 0;
7053 the_end:
7054 return ret;
7057 int qemu_live_savevm_state(QEMUFile *f)
7059 SaveStateEntry *se;
7060 int len, ret;
7062 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
7063 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
7065 for(se = first_se; se != NULL; se = se->next) {
7066 len = strlen(se->idstr);
7068 qemu_put_byte(f, len);
7069 qemu_put_buffer(f, se->idstr, len);
7070 qemu_put_be32(f, se->instance_id);
7071 qemu_put_be32(f, se->version_id);
7073 se->save_state(f, se->opaque);
7076 qemu_put_byte(f, 0);
7078 ret = 0;
7079 return ret;
7082 int qemu_live_loadvm_state(QEMUFile *f)
7084 SaveStateEntry *se;
7085 int len, ret, instance_id, version_id;
7086 unsigned int v;
7087 char idstr[256];
7089 v = qemu_get_be32(f);
7090 if (v != QEMU_VM_FILE_MAGIC)
7091 goto fail;
7092 v = qemu_get_be32(f);
7093 if (v != QEMU_VM_FILE_VERSION) {
7094 fail:
7095 ret = -1;
7096 goto the_end;
7099 for(;;) {
7100 len = qemu_get_byte(f);
7101 if (len == 0)
7102 break;
7103 qemu_get_buffer(f, idstr, len);
7104 idstr[len] = '\0';
7105 instance_id = qemu_get_be32(f);
7106 version_id = qemu_get_be32(f);
7107 se = find_se(idstr, instance_id);
7108 if (!se) {
7109 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7110 instance_id, idstr);
7111 } else {
7112 if (version_id > se->version_id) { /* src version > dst version */
7113 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7114 idstr, version_id, se->version_id);
7115 ret = -1;
7116 goto the_end;
7118 ret = se->load_state(f, se->opaque, version_id);
7119 if (ret < 0) {
7120 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7121 instance_id, idstr);
7122 goto the_end;
7126 ret = 0;
7128 qemu_announce_self();
7130 the_end:
7131 return ret;
7134 /* device can contain snapshots */
7135 static int bdrv_can_snapshot(BlockDriverState *bs)
7137 return (bs &&
7138 !bdrv_is_removable(bs) &&
7139 !bdrv_is_read_only(bs));
7142 /* device must be snapshots in order to have a reliable snapshot */
7143 static int bdrv_has_snapshot(BlockDriverState *bs)
7145 return (bs &&
7146 !bdrv_is_removable(bs) &&
7147 !bdrv_is_read_only(bs));
7150 static BlockDriverState *get_bs_snapshots(void)
7152 BlockDriverState *bs;
7153 int i;
7155 if (bs_snapshots)
7156 return bs_snapshots;
7157 for(i = 0; i <= nb_drives; i++) {
7158 bs = drives_table[i].bdrv;
7159 if (bdrv_can_snapshot(bs))
7160 goto ok;
7162 return NULL;
7164 bs_snapshots = bs;
7165 return bs;
7168 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
7169 const char *name)
7171 QEMUSnapshotInfo *sn_tab, *sn;
7172 int nb_sns, i, ret;
7174 ret = -ENOENT;
7175 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7176 if (nb_sns < 0)
7177 return ret;
7178 for(i = 0; i < nb_sns; i++) {
7179 sn = &sn_tab[i];
7180 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
7181 *sn_info = *sn;
7182 ret = 0;
7183 break;
7186 qemu_free(sn_tab);
7187 return ret;
7190 void do_savevm(const char *name)
7192 BlockDriverState *bs, *bs1;
7193 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
7194 int must_delete, ret, i;
7195 BlockDriverInfo bdi1, *bdi = &bdi1;
7196 QEMUFile *f;
7197 int saved_vm_running;
7198 #ifdef _WIN32
7199 struct _timeb tb;
7200 #else
7201 struct timeval tv;
7202 #endif
7204 bs = get_bs_snapshots();
7205 if (!bs) {
7206 term_printf("No block device can accept snapshots\n");
7207 return;
7210 /* ??? Should this occur after vm_stop? */
7211 qemu_aio_flush();
7213 saved_vm_running = vm_running;
7214 vm_stop(0);
7216 must_delete = 0;
7217 if (name) {
7218 ret = bdrv_snapshot_find(bs, old_sn, name);
7219 if (ret >= 0) {
7220 must_delete = 1;
7223 memset(sn, 0, sizeof(*sn));
7224 if (must_delete) {
7225 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
7226 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
7227 } else {
7228 if (name)
7229 pstrcpy(sn->name, sizeof(sn->name), name);
7232 /* fill auxiliary fields */
7233 #ifdef _WIN32
7234 _ftime(&tb);
7235 sn->date_sec = tb.time;
7236 sn->date_nsec = tb.millitm * 1000000;
7237 #else
7238 gettimeofday(&tv, NULL);
7239 sn->date_sec = tv.tv_sec;
7240 sn->date_nsec = tv.tv_usec * 1000;
7241 #endif
7242 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
7244 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7245 term_printf("Device %s does not support VM state snapshots\n",
7246 bdrv_get_device_name(bs));
7247 goto the_end;
7250 /* save the VM state */
7251 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
7252 if (!f) {
7253 term_printf("Could not open VM state file\n");
7254 goto the_end;
7256 ret = qemu_savevm_state(f);
7257 sn->vm_state_size = qemu_ftell(f);
7258 qemu_fclose(f);
7259 if (ret < 0) {
7260 term_printf("Error %d while writing VM\n", ret);
7261 goto the_end;
7264 /* create the snapshots */
7266 for(i = 0; i < nb_drives; i++) {
7267 bs1 = drives_table[i].bdrv;
7268 if (bdrv_has_snapshot(bs1)) {
7269 if (must_delete) {
7270 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
7271 if (ret < 0) {
7272 term_printf("Error while deleting snapshot on '%s'\n",
7273 bdrv_get_device_name(bs1));
7276 ret = bdrv_snapshot_create(bs1, sn);
7277 if (ret < 0) {
7278 term_printf("Error while creating snapshot on '%s'\n",
7279 bdrv_get_device_name(bs1));
7284 the_end:
7285 if (saved_vm_running)
7286 vm_start();
7289 void do_loadvm(const char *name)
7291 BlockDriverState *bs, *bs1;
7292 BlockDriverInfo bdi1, *bdi = &bdi1;
7293 QEMUFile *f;
7294 int i, ret;
7295 int saved_vm_running;
7297 bs = get_bs_snapshots();
7298 if (!bs) {
7299 term_printf("No block device supports snapshots\n");
7300 return;
7303 /* Flush all IO requests so they don't interfere with the new state. */
7304 qemu_aio_flush();
7306 saved_vm_running = vm_running;
7307 vm_stop(0);
7309 for(i = 0; i <= nb_drives; i++) {
7310 bs1 = drives_table[i].bdrv;
7311 if (bdrv_has_snapshot(bs1)) {
7312 ret = bdrv_snapshot_goto(bs1, name);
7313 if (ret < 0) {
7314 if (bs != bs1)
7315 term_printf("Warning: ");
7316 switch(ret) {
7317 case -ENOTSUP:
7318 term_printf("Snapshots not supported on device '%s'\n",
7319 bdrv_get_device_name(bs1));
7320 break;
7321 case -ENOENT:
7322 term_printf("Could not find snapshot '%s' on device '%s'\n",
7323 name, bdrv_get_device_name(bs1));
7324 break;
7325 default:
7326 term_printf("Error %d while activating snapshot on '%s'\n",
7327 ret, bdrv_get_device_name(bs1));
7328 break;
7330 /* fatal on snapshot block device */
7331 if (bs == bs1)
7332 goto the_end;
7337 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7338 term_printf("Device %s does not support VM state snapshots\n",
7339 bdrv_get_device_name(bs));
7340 return;
7343 /* restore the VM state */
7344 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
7345 if (!f) {
7346 term_printf("Could not open VM state file\n");
7347 goto the_end;
7349 ret = qemu_loadvm_state(f);
7350 qemu_fclose(f);
7351 if (ret < 0) {
7352 term_printf("Error %d while loading VM state\n", ret);
7354 the_end:
7355 if (saved_vm_running)
7356 vm_start();
7359 void do_delvm(const char *name)
7361 BlockDriverState *bs, *bs1;
7362 int i, ret;
7364 bs = get_bs_snapshots();
7365 if (!bs) {
7366 term_printf("No block device supports snapshots\n");
7367 return;
7370 for(i = 0; i <= nb_drives; i++) {
7371 bs1 = drives_table[i].bdrv;
7372 if (bdrv_has_snapshot(bs1)) {
7373 ret = bdrv_snapshot_delete(bs1, name);
7374 if (ret < 0) {
7375 if (ret == -ENOTSUP)
7376 term_printf("Snapshots not supported on device '%s'\n",
7377 bdrv_get_device_name(bs1));
7378 else
7379 term_printf("Error %d while deleting snapshot on '%s'\n",
7380 ret, bdrv_get_device_name(bs1));
7386 void do_info_snapshots(void)
7388 BlockDriverState *bs, *bs1;
7389 QEMUSnapshotInfo *sn_tab, *sn;
7390 int nb_sns, i;
7391 char buf[256];
7393 bs = get_bs_snapshots();
7394 if (!bs) {
7395 term_printf("No available block device supports snapshots\n");
7396 return;
7398 term_printf("Snapshot devices:");
7399 for(i = 0; i <= nb_drives; i++) {
7400 bs1 = drives_table[i].bdrv;
7401 if (bdrv_has_snapshot(bs1)) {
7402 if (bs == bs1)
7403 term_printf(" %s", bdrv_get_device_name(bs1));
7406 term_printf("\n");
7408 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7409 if (nb_sns < 0) {
7410 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
7411 return;
7413 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
7414 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
7415 for(i = 0; i < nb_sns; i++) {
7416 sn = &sn_tab[i];
7417 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
7419 qemu_free(sn_tab);
7422 /***********************************************************/
7423 /* ram save/restore */
7425 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7427 int v;
7429 v = qemu_get_byte(f);
7430 switch(v) {
7431 case 0:
7432 if (qemu_get_buffer(f, buf, len) != len)
7433 return -EIO;
7434 break;
7435 case 1:
7436 v = qemu_get_byte(f);
7437 memset(buf, v, len);
7438 break;
7439 default:
7440 return -EINVAL;
7442 return 0;
7445 static int ram_load_v1(QEMUFile *f, void *opaque)
7447 int ret;
7448 ram_addr_t i;
7450 if (qemu_get_be32(f) != phys_ram_size)
7451 return -EINVAL;
7452 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7453 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7454 continue;
7455 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7456 if (ret)
7457 return ret;
7459 return 0;
7462 #define BDRV_HASH_BLOCK_SIZE 1024
7463 #define IOBUF_SIZE 4096
7464 #define RAM_CBLOCK_MAGIC 0xfabe
7466 typedef struct RamCompressState {
7467 z_stream zstream;
7468 QEMUFile *f;
7469 uint8_t buf[IOBUF_SIZE];
7470 } RamCompressState;
7472 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7474 int ret;
7475 memset(s, 0, sizeof(*s));
7476 s->f = f;
7477 ret = deflateInit2(&s->zstream, 1,
7478 Z_DEFLATED, 15,
7479 9, Z_DEFAULT_STRATEGY);
7480 if (ret != Z_OK)
7481 return -1;
7482 s->zstream.avail_out = IOBUF_SIZE;
7483 s->zstream.next_out = s->buf;
7484 return 0;
7487 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7489 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7490 qemu_put_be16(s->f, len);
7491 qemu_put_buffer(s->f, buf, len);
7494 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7496 int ret;
7498 s->zstream.avail_in = len;
7499 s->zstream.next_in = (uint8_t *)buf;
7500 while (s->zstream.avail_in > 0) {
7501 ret = deflate(&s->zstream, Z_NO_FLUSH);
7502 if (ret != Z_OK)
7503 return -1;
7504 if (s->zstream.avail_out == 0) {
7505 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7506 s->zstream.avail_out = IOBUF_SIZE;
7507 s->zstream.next_out = s->buf;
7510 return 0;
7513 static void ram_compress_close(RamCompressState *s)
7515 int len, ret;
7517 /* compress last bytes */
7518 for(;;) {
7519 ret = deflate(&s->zstream, Z_FINISH);
7520 if (ret == Z_OK || ret == Z_STREAM_END) {
7521 len = IOBUF_SIZE - s->zstream.avail_out;
7522 if (len > 0) {
7523 ram_put_cblock(s, s->buf, len);
7525 s->zstream.avail_out = IOBUF_SIZE;
7526 s->zstream.next_out = s->buf;
7527 if (ret == Z_STREAM_END)
7528 break;
7529 } else {
7530 goto fail;
7533 fail:
7534 deflateEnd(&s->zstream);
7537 typedef struct RamDecompressState {
7538 z_stream zstream;
7539 QEMUFile *f;
7540 uint8_t buf[IOBUF_SIZE];
7541 } RamDecompressState;
7543 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7545 int ret;
7546 memset(s, 0, sizeof(*s));
7547 s->f = f;
7548 ret = inflateInit(&s->zstream);
7549 if (ret != Z_OK)
7550 return -1;
7551 return 0;
7554 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7556 int ret, clen;
7558 s->zstream.avail_out = len;
7559 s->zstream.next_out = buf;
7560 while (s->zstream.avail_out > 0) {
7561 if (s->zstream.avail_in == 0) {
7562 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7563 return -1;
7564 clen = qemu_get_be16(s->f);
7565 if (clen > IOBUF_SIZE)
7566 return -1;
7567 qemu_get_buffer(s->f, s->buf, clen);
7568 s->zstream.avail_in = clen;
7569 s->zstream.next_in = s->buf;
7571 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7572 if (ret != Z_OK && ret != Z_STREAM_END) {
7573 return -1;
7576 return 0;
7579 static void ram_decompress_close(RamDecompressState *s)
7581 inflateEnd(&s->zstream);
7584 static void ram_save_live(QEMUFile *f, void *opaque)
7586 target_ulong addr;
7588 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7589 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7590 continue;
7591 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7592 qemu_put_be32(f, addr);
7593 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7596 qemu_put_be32(f, 1);
7599 static void ram_save_static(QEMUFile *f, void *opaque)
7601 ram_addr_t i;
7602 RamCompressState s1, *s = &s1;
7603 uint8_t buf[10];
7605 qemu_put_be32(f, phys_ram_size);
7606 if (ram_compress_open(s, f) < 0)
7607 return;
7608 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7609 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7610 continue;
7611 #if 0
7612 if (tight_savevm_enabled) {
7613 int64_t sector_num;
7614 int j;
7616 /* find if the memory block is available on a virtual
7617 block device */
7618 sector_num = -1;
7619 for(j = 0; j < nb_drives; j++) {
7620 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7621 phys_ram_base + i,
7622 BDRV_HASH_BLOCK_SIZE);
7623 if (sector_num >= 0)
7624 break;
7626 if (j == nb_drives)
7627 goto normal_compress;
7628 buf[0] = 1;
7629 buf[1] = j;
7630 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7631 ram_compress_buf(s, buf, 10);
7632 } else
7633 #endif
7635 // normal_compress:
7636 buf[0] = 0;
7637 ram_compress_buf(s, buf, 1);
7638 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7641 ram_compress_close(s);
7644 static void ram_save(QEMUFile *f, void *opaque)
7646 int in_migration = cpu_physical_memory_get_dirty_tracking();
7648 qemu_put_byte(f, in_migration);
7650 if (in_migration)
7651 ram_save_live(f, opaque);
7652 else
7653 ram_save_static(f, opaque);
7656 static int ram_load_live(QEMUFile *f, void *opaque)
7658 target_ulong addr;
7660 do {
7661 addr = qemu_get_be32(f);
7662 if (addr == 1)
7663 break;
7665 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7666 } while (1);
7668 return 0;
7671 static int ram_load_static(QEMUFile *f, void *opaque)
7673 RamDecompressState s1, *s = &s1;
7674 uint8_t buf[10];
7675 ram_addr_t i;
7677 if (qemu_get_be32(f) != phys_ram_size)
7678 return -EINVAL;
7679 if (ram_decompress_open(s, f) < 0)
7680 return -EINVAL;
7681 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7682 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7683 continue;
7684 if (ram_decompress_buf(s, buf, 1) < 0) {
7685 fprintf(stderr, "Error while reading ram block header\n");
7686 goto error;
7688 if (buf[0] == 0) {
7689 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7690 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7691 goto error;
7693 } else
7694 #if 0
7695 if (buf[0] == 1) {
7696 int bs_index;
7697 int64_t sector_num;
7699 ram_decompress_buf(s, buf + 1, 9);
7700 bs_index = buf[1];
7701 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7702 if (bs_index >= nb_drives) {
7703 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7704 goto error;
7706 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7707 phys_ram_base + i,
7708 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7709 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7710 bs_index, sector_num);
7711 goto error;
7713 } else
7714 #endif
7716 error:
7717 printf("Error block header\n");
7718 return -EINVAL;
7721 ram_decompress_close(s);
7722 return 0;
7725 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7727 int ret;
7729 switch (version_id) {
7730 case 1:
7731 ret = ram_load_v1(f, opaque);
7732 break;
7733 case 3:
7734 if (qemu_get_byte(f)) {
7735 ret = ram_load_live(f, opaque);
7736 break;
7738 case 2:
7739 ret = ram_load_static(f, opaque);
7740 break;
7741 default:
7742 ret = -EINVAL;
7743 break;
7746 return ret;
7749 /***********************************************************/
7750 /* bottom halves (can be seen as timers which expire ASAP) */
7752 struct QEMUBH {
7753 QEMUBHFunc *cb;
7754 void *opaque;
7755 int scheduled;
7756 QEMUBH *next;
7759 static QEMUBH *first_bh = NULL;
7761 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7763 QEMUBH *bh;
7764 bh = qemu_mallocz(sizeof(QEMUBH));
7765 if (!bh)
7766 return NULL;
7767 bh->cb = cb;
7768 bh->opaque = opaque;
7769 return bh;
7772 int qemu_bh_poll(void)
7774 QEMUBH *bh, **pbh;
7775 int ret;
7777 ret = 0;
7778 for(;;) {
7779 pbh = &first_bh;
7780 bh = *pbh;
7781 if (!bh)
7782 break;
7783 ret = 1;
7784 *pbh = bh->next;
7785 bh->scheduled = 0;
7786 bh->cb(bh->opaque);
7788 return ret;
7791 void qemu_bh_schedule(QEMUBH *bh)
7793 CPUState *env = cpu_single_env;
7794 if (bh->scheduled)
7795 return;
7796 bh->scheduled = 1;
7797 bh->next = first_bh;
7798 first_bh = bh;
7800 /* stop the currently executing CPU to execute the BH ASAP */
7801 if (env) {
7802 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7804 main_loop_break();
7807 void qemu_bh_cancel(QEMUBH *bh)
7809 QEMUBH **pbh;
7810 if (bh->scheduled) {
7811 pbh = &first_bh;
7812 while (*pbh != bh)
7813 pbh = &(*pbh)->next;
7814 *pbh = bh->next;
7815 bh->scheduled = 0;
7819 void qemu_bh_delete(QEMUBH *bh)
7821 qemu_bh_cancel(bh);
7822 qemu_free(bh);
7825 /***********************************************************/
7826 /* machine registration */
7828 QEMUMachine *first_machine = NULL;
7829 QEMUMachine *current_machine = NULL;
7831 int qemu_register_machine(QEMUMachine *m)
7833 QEMUMachine **pm;
7834 pm = &first_machine;
7835 while (*pm != NULL)
7836 pm = &(*pm)->next;
7837 m->next = NULL;
7838 *pm = m;
7839 return 0;
7842 static QEMUMachine *find_machine(const char *name)
7844 QEMUMachine *m;
7846 for(m = first_machine; m != NULL; m = m->next) {
7847 if (!strcmp(m->name, name))
7848 return m;
7850 return NULL;
7853 /***********************************************************/
7854 /* main execution loop */
7856 static void gui_update(void *opaque)
7858 DisplayState *ds = opaque;
7859 ds->dpy_refresh(ds);
7860 qemu_mod_timer(ds->gui_timer,
7861 (ds->gui_timer_interval ?
7862 ds->gui_timer_interval :
7863 GUI_REFRESH_INTERVAL)
7864 + qemu_get_clock(rt_clock));
7867 struct vm_change_state_entry {
7868 VMChangeStateHandler *cb;
7869 void *opaque;
7870 LIST_ENTRY (vm_change_state_entry) entries;
7873 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7875 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7876 void *opaque)
7878 VMChangeStateEntry *e;
7880 e = qemu_mallocz(sizeof (*e));
7881 if (!e)
7882 return NULL;
7884 e->cb = cb;
7885 e->opaque = opaque;
7886 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7887 return e;
7890 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7892 LIST_REMOVE (e, entries);
7893 qemu_free (e);
7896 static void vm_state_notify(int running)
7898 VMChangeStateEntry *e;
7900 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7901 e->cb(e->opaque, running);
7905 /* XXX: support several handlers */
7906 static VMStopHandler *vm_stop_cb;
7907 static void *vm_stop_opaque;
7909 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7911 vm_stop_cb = cb;
7912 vm_stop_opaque = opaque;
7913 return 0;
7916 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7918 vm_stop_cb = NULL;
7921 void vm_start(void)
7923 if (!vm_running) {
7924 cpu_enable_ticks();
7925 vm_running = 1;
7926 vm_state_notify(1);
7927 qemu_rearm_alarm_timer(alarm_timer);
7931 void vm_stop(int reason)
7933 if (vm_running) {
7934 cpu_disable_ticks();
7935 vm_running = 0;
7936 if (reason != 0) {
7937 if (vm_stop_cb) {
7938 vm_stop_cb(vm_stop_opaque, reason);
7941 vm_state_notify(0);
7945 /* reset/shutdown handler */
7947 typedef struct QEMUResetEntry {
7948 QEMUResetHandler *func;
7949 void *opaque;
7950 struct QEMUResetEntry *next;
7951 } QEMUResetEntry;
7953 static QEMUResetEntry *first_reset_entry;
7954 static int reset_requested;
7955 static int shutdown_requested;
7956 static int powerdown_requested;
7958 int qemu_shutdown_requested(void)
7960 int r = shutdown_requested;
7961 shutdown_requested = 0;
7962 return r;
7965 int qemu_reset_requested(void)
7967 int r = reset_requested;
7968 reset_requested = 0;
7969 return r;
7972 int qemu_powerdown_requested(void)
7974 int r = powerdown_requested;
7975 powerdown_requested = 0;
7976 return r;
7979 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7981 QEMUResetEntry **pre, *re;
7983 pre = &first_reset_entry;
7984 while (*pre != NULL)
7985 pre = &(*pre)->next;
7986 re = qemu_mallocz(sizeof(QEMUResetEntry));
7987 re->func = func;
7988 re->opaque = opaque;
7989 re->next = NULL;
7990 *pre = re;
7993 void qemu_system_reset(void)
7995 QEMUResetEntry *re;
7997 /* reset all devices */
7998 for(re = first_reset_entry; re != NULL; re = re->next) {
7999 re->func(re->opaque);
8003 void qemu_system_reset_request(void)
8005 if (no_reboot) {
8006 shutdown_requested = 1;
8007 } else {
8008 reset_requested = 1;
8010 if (cpu_single_env)
8011 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
8012 main_loop_break();
8015 void qemu_system_shutdown_request(void)
8017 shutdown_requested = 1;
8018 if (cpu_single_env)
8019 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
8022 void qemu_system_powerdown_request(void)
8024 powerdown_requested = 1;
8025 if (cpu_single_env)
8026 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
8029 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
8030 struct timeval *tv)
8032 int ret;
8034 /* KVM holds a mutex while QEMU code is running, we need hooks to
8035 release the mutex whenever QEMU code sleeps. */
8037 kvm_sleep_begin();
8039 ret = select(max_fd, rfds, wfds, xfds, tv);
8041 kvm_sleep_end();
8043 return ret;
8046 void main_loop_wait(int timeout)
8048 IOHandlerRecord *ioh;
8049 fd_set rfds, wfds, xfds;
8050 int ret, nfds;
8051 #ifdef _WIN32
8052 int ret2, i;
8053 #endif
8054 struct timeval tv;
8055 PollingEntry *pe;
8058 /* XXX: need to suppress polling by better using win32 events */
8059 ret = 0;
8060 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
8061 ret |= pe->func(pe->opaque);
8063 #ifdef _WIN32
8064 if (ret == 0) {
8065 int err;
8066 WaitObjects *w = &wait_objects;
8068 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
8069 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
8070 if (w->func[ret - WAIT_OBJECT_0])
8071 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
8073 /* Check for additional signaled events */
8074 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
8076 /* Check if event is signaled */
8077 ret2 = WaitForSingleObject(w->events[i], 0);
8078 if(ret2 == WAIT_OBJECT_0) {
8079 if (w->func[i])
8080 w->func[i](w->opaque[i]);
8081 } else if (ret2 == WAIT_TIMEOUT) {
8082 } else {
8083 err = GetLastError();
8084 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
8087 } else if (ret == WAIT_TIMEOUT) {
8088 } else {
8089 err = GetLastError();
8090 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
8093 #endif
8094 /* poll any events */
8095 /* XXX: separate device handlers from system ones */
8096 nfds = -1;
8097 FD_ZERO(&rfds);
8098 FD_ZERO(&wfds);
8099 FD_ZERO(&xfds);
8100 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
8101 if (ioh->deleted)
8102 continue;
8103 if (ioh->fd_read &&
8104 (!ioh->fd_read_poll ||
8105 ioh->fd_read_poll(ioh->opaque) != 0)) {
8106 FD_SET(ioh->fd, &rfds);
8107 if (ioh->fd > nfds)
8108 nfds = ioh->fd;
8110 if (ioh->fd_write) {
8111 FD_SET(ioh->fd, &wfds);
8112 if (ioh->fd > nfds)
8113 nfds = ioh->fd;
8117 #ifdef _WIN32
8118 tv.tv_sec = 0;
8119 tv.tv_usec = 0;
8120 #else
8121 tv.tv_sec = timeout / 1000;
8122 tv.tv_usec = (timeout % 1000) * 1000;
8123 #endif
8124 #if defined(CONFIG_SLIRP)
8125 if (slirp_inited) {
8126 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
8128 #endif
8129 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
8130 if (ret > 0) {
8131 IOHandlerRecord **pioh;
8133 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
8134 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
8135 ioh->fd_read(ioh->opaque);
8136 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
8137 FD_CLR(ioh->fd, &rfds);
8139 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
8140 ioh->fd_write(ioh->opaque);
8144 /* remove deleted IO handlers */
8145 pioh = &first_io_handler;
8146 while (*pioh) {
8147 ioh = *pioh;
8148 if (ioh->deleted) {
8149 *pioh = ioh->next;
8150 qemu_free(ioh);
8151 } else
8152 pioh = &ioh->next;
8155 #if defined(CONFIG_SLIRP)
8156 if (slirp_inited) {
8157 if (ret < 0) {
8158 FD_ZERO(&rfds);
8159 FD_ZERO(&wfds);
8160 FD_ZERO(&xfds);
8162 slirp_select_poll(&rfds, &wfds, &xfds);
8164 #endif
8166 if (vm_running) {
8167 if (likely(!cur_cpu || !(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
8168 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
8169 qemu_get_clock(vm_clock));
8170 /* run dma transfers, if any */
8171 DMA_run();
8174 /* real time timers */
8175 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
8176 qemu_get_clock(rt_clock));
8178 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
8179 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
8180 qemu_rearm_alarm_timer(alarm_timer);
8183 /* Check bottom-halves last in case any of the earlier events triggered
8184 them. */
8185 qemu_bh_poll();
8189 static int main_loop(void)
8191 int ret, timeout;
8192 #ifdef CONFIG_PROFILER
8193 int64_t ti;
8194 #endif
8195 CPUState *env;
8198 if (kvm_enabled()) {
8199 kvm_main_loop();
8200 cpu_disable_ticks();
8201 return 0;
8204 cur_cpu = first_cpu;
8205 next_cpu = cur_cpu->next_cpu ?: first_cpu;
8206 for(;;) {
8207 if (vm_running) {
8209 for(;;) {
8210 /* get next cpu */
8211 env = next_cpu;
8212 #ifdef CONFIG_PROFILER
8213 ti = profile_getclock();
8214 #endif
8215 if (use_icount) {
8216 int64_t count;
8217 int decr;
8218 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
8219 env->icount_decr.u16.low = 0;
8220 env->icount_extra = 0;
8221 count = qemu_next_deadline();
8222 count = (count + (1 << icount_time_shift) - 1)
8223 >> icount_time_shift;
8224 qemu_icount += count;
8225 decr = (count > 0xffff) ? 0xffff : count;
8226 count -= decr;
8227 env->icount_decr.u16.low = decr;
8228 env->icount_extra = count;
8230 ret = cpu_exec(env);
8231 #ifdef CONFIG_PROFILER
8232 qemu_time += profile_getclock() - ti;
8233 #endif
8234 if (use_icount) {
8235 /* Fold pending instructions back into the
8236 instruction counter, and clear the interrupt flag. */
8237 qemu_icount -= (env->icount_decr.u16.low
8238 + env->icount_extra);
8239 env->icount_decr.u32 = 0;
8240 env->icount_extra = 0;
8242 next_cpu = env->next_cpu ?: first_cpu;
8243 if (event_pending && likely(ret != EXCP_DEBUG)) {
8244 ret = EXCP_INTERRUPT;
8245 event_pending = 0;
8246 break;
8248 if (ret == EXCP_HLT) {
8249 /* Give the next CPU a chance to run. */
8250 cur_cpu = env;
8251 continue;
8253 if (ret != EXCP_HALTED)
8254 break;
8255 /* all CPUs are halted ? */
8256 if (env == cur_cpu)
8257 break;
8259 cur_cpu = env;
8261 if (shutdown_requested) {
8262 ret = EXCP_INTERRUPT;
8263 if (no_shutdown) {
8264 vm_stop(0);
8265 no_shutdown = 0;
8267 else
8268 break;
8270 if (reset_requested) {
8271 reset_requested = 0;
8272 qemu_system_reset();
8273 if (kvm_enabled())
8274 kvm_load_registers(env);
8275 ret = EXCP_INTERRUPT;
8277 if (powerdown_requested) {
8278 powerdown_requested = 0;
8279 qemu_system_powerdown();
8280 ret = EXCP_INTERRUPT;
8282 if (unlikely(ret == EXCP_DEBUG)) {
8283 vm_stop(EXCP_DEBUG);
8285 /* If all cpus are halted then wait until the next IRQ */
8286 /* XXX: use timeout computed from timers */
8287 if (ret == EXCP_HALTED) {
8288 if (use_icount) {
8289 int64_t add;
8290 int64_t delta;
8291 /* Advance virtual time to the next event. */
8292 if (use_icount == 1) {
8293 /* When not using an adaptive execution frequency
8294 we tend to get badly out of sync with real time,
8295 so just delay for a reasonable amount of time. */
8296 delta = 0;
8297 } else {
8298 delta = cpu_get_icount() - cpu_get_clock();
8300 if (delta > 0) {
8301 /* If virtual time is ahead of real time then just
8302 wait for IO. */
8303 timeout = (delta / 1000000) + 1;
8304 } else {
8305 /* Wait for either IO to occur or the next
8306 timer event. */
8307 add = qemu_next_deadline();
8308 /* We advance the timer before checking for IO.
8309 Limit the amount we advance so that early IO
8310 activity won't get the guest too far ahead. */
8311 if (add > 10000000)
8312 add = 10000000;
8313 delta += add;
8314 add = (add + (1 << icount_time_shift) - 1)
8315 >> icount_time_shift;
8316 qemu_icount += add;
8317 timeout = delta / 1000000;
8318 if (timeout < 0)
8319 timeout = 0;
8321 } else {
8322 timeout = 10;
8324 } else {
8325 timeout = 0;
8327 } else {
8328 if (shutdown_requested)
8329 break;
8330 timeout = 10;
8332 #ifdef CONFIG_PROFILER
8333 ti = profile_getclock();
8334 #endif
8335 main_loop_wait(timeout);
8336 #ifdef CONFIG_PROFILER
8337 dev_time += profile_getclock() - ti;
8338 #endif
8340 cpu_disable_ticks();
8341 return ret;
8344 static void help(int exitcode)
8346 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
8347 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8348 "usage: %s [options] [disk_image]\n"
8349 "\n"
8350 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8351 "\n"
8352 "Standard options:\n"
8353 "-M machine select emulated machine (-M ? for list)\n"
8354 "-cpu cpu select CPU (-cpu ? for list)\n"
8355 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8356 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8357 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8358 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8359 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8360 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8361 " [,cache=on|off][,format=f][,boot=on|off]\n"
8362 " use 'file' as a drive image\n"
8363 "-mtdblock file use 'file' as on-board Flash memory image\n"
8364 "-sd file use 'file' as SecureDigital card image\n"
8365 "-pflash file use 'file' as a parallel flash image\n"
8366 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8367 "-snapshot write to temporary files instead of disk image files\n"
8368 #ifdef CONFIG_SDL
8369 "-no-frame open SDL window without a frame and window decorations\n"
8370 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8371 "-no-quit disable SDL window close capability\n"
8372 #endif
8373 #ifdef TARGET_I386
8374 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8375 #endif
8376 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8377 "-smp n set the number of CPUs to 'n' [default=1]\n"
8378 "-nographic disable graphical output and redirect serial I/Os to console\n"
8379 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8380 #ifndef _WIN32
8381 "-k language use keyboard layout (for example \"fr\" for French)\n"
8382 #endif
8383 #ifdef HAS_AUDIO
8384 "-audio-help print list of audio drivers and their options\n"
8385 "-soundhw c1,... enable audio support\n"
8386 " and only specified sound cards (comma separated list)\n"
8387 " use -soundhw ? to get the list of supported cards\n"
8388 " use -soundhw all to enable all of them\n"
8389 #endif
8390 "-localtime set the real time clock to local time [default=utc]\n"
8391 "-full-screen start in full screen\n"
8392 #ifdef TARGET_I386
8393 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8394 #endif
8395 "-usb enable the USB driver (will be the default soon)\n"
8396 "-usbdevice name add the host or guest USB device 'name'\n"
8397 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8398 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8399 #endif
8400 "-name string set the name of the guest\n"
8401 "\n"
8402 "Network options:\n"
8403 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8404 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8405 #ifdef CONFIG_SLIRP
8406 "-net user[,vlan=n][,hostname=host]\n"
8407 " connect the user mode network stack to VLAN 'n' and send\n"
8408 " hostname 'host' to DHCP clients\n"
8409 #endif
8410 #ifdef _WIN32
8411 "-net tap[,vlan=n],ifname=name\n"
8412 " connect the host TAP network interface to VLAN 'n'\n"
8413 #else
8414 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8415 " connect the host TAP network interface to VLAN 'n' and use the\n"
8416 " network scripts 'file' (default=%s)\n"
8417 " and 'dfile' (default=%s);\n"
8418 " use '[down]script=no' to disable script execution;\n"
8419 " use 'fd=h' to connect to an already opened TAP interface\n"
8420 #endif
8421 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8422 " connect the vlan 'n' to another VLAN using a socket connection\n"
8423 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8424 " connect the vlan 'n' to multicast maddr and port\n"
8425 #ifdef CONFIG_VDE
8426 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8427 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8428 " on host and listening for incoming connections on 'socketpath'.\n"
8429 " Use group 'groupname' and mode 'octalmode' to change default\n"
8430 " ownership and permissions for communication port.\n"
8431 #endif
8432 "-net none use it alone to have zero network devices; if no -net option\n"
8433 " is provided, the default is '-net nic -net user'\n"
8434 "\n"
8435 #ifdef CONFIG_SLIRP
8436 "-tftp dir allow tftp access to files in dir [-net user]\n"
8437 "-bootp file advertise file in BOOTP replies\n"
8438 #ifndef _WIN32
8439 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8440 #endif
8441 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8442 " redirect TCP or UDP connections from host to guest [-net user]\n"
8443 #endif
8444 "\n"
8445 "Linux boot specific:\n"
8446 "-kernel bzImage use 'bzImage' as kernel image\n"
8447 "-append cmdline use 'cmdline' as kernel command line\n"
8448 "-initrd file use 'file' as initial ram disk\n"
8449 "\n"
8450 "Debug/Expert options:\n"
8451 "-monitor dev redirect the monitor to char device 'dev'\n"
8452 "-serial dev redirect the serial port to char device 'dev'\n"
8453 "-parallel dev redirect the parallel port to char device 'dev'\n"
8454 "-pidfile file Write PID to 'file'\n"
8455 "-S freeze CPU at startup (use 'c' to start execution)\n"
8456 "-s wait gdb connection to port\n"
8457 "-p port set gdb connection port [default=%s]\n"
8458 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8459 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8460 " translation (t=none or lba) (usually qemu can guess them)\n"
8461 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8462 #ifdef USE_KQEMU
8463 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8464 "-no-kqemu disable KQEMU kernel module usage\n"
8465 #endif
8466 #ifdef USE_KVM
8467 #ifndef NO_CPU_EMULATION
8468 "-no-kvm disable KVM hardware virtualization\n"
8469 #endif
8470 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8471 "-no-kvm-pit disable KVM kernel mode PIT\n"
8472 #endif
8473 #ifdef TARGET_I386
8474 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8475 " (default is CL-GD5446 PCI VGA)\n"
8476 "-no-acpi disable ACPI\n"
8477 #endif
8478 #ifdef CONFIG_CURSES
8479 "-curses use a curses/ncurses interface instead of SDL\n"
8480 #endif
8481 "-no-reboot exit instead of rebooting\n"
8482 "-no-shutdown stop before shutdown\n"
8483 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8484 "-vnc display start a VNC server on display\n"
8485 #ifndef _WIN32
8486 "-daemonize daemonize QEMU after initializing\n"
8487 #endif
8488 "-tdf inject timer interrupts that got lost\n"
8489 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8490 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8491 "-option-rom rom load a file, rom, into the option ROM space\n"
8492 #ifdef TARGET_SPARC
8493 "-prom-env variable=value set OpenBIOS nvram variables\n"
8494 #endif
8495 "-clock force the use of the given methods for timer alarm.\n"
8496 " To see what timers are available use -clock ?\n"
8497 "-startdate select initial date of the clock\n"
8498 "-icount [N|auto]\n"
8499 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8500 "\n"
8501 "During emulation, the following keys are useful:\n"
8502 "ctrl-alt-f toggle full screen\n"
8503 "ctrl-alt-n switch to virtual console 'n'\n"
8504 "ctrl-alt toggle mouse and keyboard grab\n"
8505 "\n"
8506 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8508 "qemu",
8509 DEFAULT_RAM_SIZE,
8510 #ifndef _WIN32
8511 DEFAULT_NETWORK_SCRIPT,
8512 DEFAULT_NETWORK_DOWN_SCRIPT,
8513 #endif
8514 DEFAULT_GDBSTUB_PORT,
8515 "/tmp/qemu.log");
8516 exit(exitcode);
8519 #define HAS_ARG 0x0001
8521 enum {
8522 QEMU_OPTION_h,
8524 QEMU_OPTION_M,
8525 QEMU_OPTION_cpu,
8526 QEMU_OPTION_fda,
8527 QEMU_OPTION_fdb,
8528 QEMU_OPTION_hda,
8529 QEMU_OPTION_hdb,
8530 QEMU_OPTION_hdc,
8531 QEMU_OPTION_hdd,
8532 QEMU_OPTION_drive,
8533 QEMU_OPTION_cdrom,
8534 QEMU_OPTION_mtdblock,
8535 QEMU_OPTION_sd,
8536 QEMU_OPTION_pflash,
8537 QEMU_OPTION_boot,
8538 QEMU_OPTION_snapshot,
8539 #ifdef TARGET_I386
8540 QEMU_OPTION_no_fd_bootchk,
8541 #endif
8542 QEMU_OPTION_m,
8543 QEMU_OPTION_nographic,
8544 QEMU_OPTION_portrait,
8545 #ifdef HAS_AUDIO
8546 QEMU_OPTION_audio_help,
8547 QEMU_OPTION_soundhw,
8548 #endif
8550 QEMU_OPTION_net,
8551 QEMU_OPTION_tftp,
8552 QEMU_OPTION_bootp,
8553 QEMU_OPTION_smb,
8554 QEMU_OPTION_redir,
8556 QEMU_OPTION_kernel,
8557 QEMU_OPTION_append,
8558 QEMU_OPTION_initrd,
8560 QEMU_OPTION_S,
8561 QEMU_OPTION_s,
8562 QEMU_OPTION_p,
8563 QEMU_OPTION_d,
8564 QEMU_OPTION_hdachs,
8565 QEMU_OPTION_L,
8566 QEMU_OPTION_bios,
8567 QEMU_OPTION_k,
8568 QEMU_OPTION_localtime,
8569 QEMU_OPTION_cirrusvga,
8570 QEMU_OPTION_vmsvga,
8571 QEMU_OPTION_g,
8572 QEMU_OPTION_std_vga,
8573 QEMU_OPTION_echr,
8574 QEMU_OPTION_monitor,
8575 QEMU_OPTION_serial,
8576 QEMU_OPTION_parallel,
8577 QEMU_OPTION_loadvm,
8578 QEMU_OPTION_full_screen,
8579 QEMU_OPTION_no_frame,
8580 QEMU_OPTION_alt_grab,
8581 QEMU_OPTION_no_quit,
8582 QEMU_OPTION_pidfile,
8583 QEMU_OPTION_no_kqemu,
8584 QEMU_OPTION_kernel_kqemu,
8585 QEMU_OPTION_win2k_hack,
8586 QEMU_OPTION_usb,
8587 QEMU_OPTION_usbdevice,
8588 QEMU_OPTION_smp,
8589 QEMU_OPTION_vnc,
8590 QEMU_OPTION_no_acpi,
8591 QEMU_OPTION_curses,
8592 QEMU_OPTION_no_kvm,
8593 QEMU_OPTION_no_kvm_irqchip,
8594 QEMU_OPTION_no_kvm_pit,
8595 QEMU_OPTION_no_reboot,
8596 QEMU_OPTION_no_shutdown,
8597 QEMU_OPTION_show_cursor,
8598 QEMU_OPTION_daemonize,
8599 QEMU_OPTION_option_rom,
8600 QEMU_OPTION_semihosting,
8601 QEMU_OPTION_cpu_vendor,
8602 QEMU_OPTION_name,
8603 QEMU_OPTION_prom_env,
8604 QEMU_OPTION_old_param,
8605 QEMU_OPTION_clock,
8606 QEMU_OPTION_startdate,
8607 QEMU_OPTION_tb_size,
8608 QEMU_OPTION_icount,
8609 QEMU_OPTION_incoming,
8610 QEMU_OPTION_tdf,
8611 QEMU_OPTION_kvm_shadow_memory,
8612 QEMU_OPTION_mempath,
8615 typedef struct QEMUOption {
8616 const char *name;
8617 int flags;
8618 int index;
8619 } QEMUOption;
8621 const QEMUOption qemu_options[] = {
8622 { "h", 0, QEMU_OPTION_h },
8623 { "help", 0, QEMU_OPTION_h },
8625 { "M", HAS_ARG, QEMU_OPTION_M },
8626 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8627 { "fda", HAS_ARG, QEMU_OPTION_fda },
8628 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8629 { "hda", HAS_ARG, QEMU_OPTION_hda },
8630 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8631 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8632 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8633 { "drive", HAS_ARG, QEMU_OPTION_drive },
8634 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8635 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8636 { "sd", HAS_ARG, QEMU_OPTION_sd },
8637 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8638 { "boot", HAS_ARG, QEMU_OPTION_boot },
8639 { "snapshot", 0, QEMU_OPTION_snapshot },
8640 #ifdef TARGET_I386
8641 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8642 #endif
8643 { "m", HAS_ARG, QEMU_OPTION_m },
8644 { "nographic", 0, QEMU_OPTION_nographic },
8645 { "portrait", 0, QEMU_OPTION_portrait },
8646 { "k", HAS_ARG, QEMU_OPTION_k },
8647 #ifdef HAS_AUDIO
8648 { "audio-help", 0, QEMU_OPTION_audio_help },
8649 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8650 #endif
8652 { "net", HAS_ARG, QEMU_OPTION_net},
8653 #ifdef CONFIG_SLIRP
8654 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8655 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8656 #ifndef _WIN32
8657 { "smb", HAS_ARG, QEMU_OPTION_smb },
8658 #endif
8659 { "redir", HAS_ARG, QEMU_OPTION_redir },
8660 #endif
8662 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8663 { "append", HAS_ARG, QEMU_OPTION_append },
8664 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8666 { "S", 0, QEMU_OPTION_S },
8667 { "s", 0, QEMU_OPTION_s },
8668 { "p", HAS_ARG, QEMU_OPTION_p },
8669 { "d", HAS_ARG, QEMU_OPTION_d },
8670 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8671 { "L", HAS_ARG, QEMU_OPTION_L },
8672 { "bios", HAS_ARG, QEMU_OPTION_bios },
8673 #ifdef USE_KQEMU
8674 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8675 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8676 #endif
8677 #ifdef USE_KVM
8678 #ifndef NO_CPU_EMULATION
8679 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8680 #endif
8681 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8682 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8683 #endif
8684 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8685 { "g", 1, QEMU_OPTION_g },
8686 #endif
8687 { "localtime", 0, QEMU_OPTION_localtime },
8688 { "std-vga", 0, QEMU_OPTION_std_vga },
8689 { "echr", HAS_ARG, QEMU_OPTION_echr },
8690 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8691 { "serial", HAS_ARG, QEMU_OPTION_serial },
8692 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8693 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8694 { "incoming", 1, QEMU_OPTION_incoming },
8695 { "full-screen", 0, QEMU_OPTION_full_screen },
8696 #ifdef CONFIG_SDL
8697 { "no-frame", 0, QEMU_OPTION_no_frame },
8698 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8699 { "no-quit", 0, QEMU_OPTION_no_quit },
8700 #endif
8701 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8702 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8703 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8704 { "smp", HAS_ARG, QEMU_OPTION_smp },
8705 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8706 #ifdef CONFIG_CURSES
8707 { "curses", 0, QEMU_OPTION_curses },
8708 #endif
8710 /* temporary options */
8711 { "usb", 0, QEMU_OPTION_usb },
8712 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8713 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8714 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8715 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8716 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8717 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8718 { "daemonize", 0, QEMU_OPTION_daemonize },
8719 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8720 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8721 { "semihosting", 0, QEMU_OPTION_semihosting },
8722 #endif
8723 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8724 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8725 { "name", HAS_ARG, QEMU_OPTION_name },
8726 #if defined(TARGET_SPARC)
8727 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8728 #endif
8729 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8730 #if defined(TARGET_ARM)
8731 { "old-param", 0, QEMU_OPTION_old_param },
8732 #endif
8733 { "clock", HAS_ARG, QEMU_OPTION_clock },
8734 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8735 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8736 { "icount", HAS_ARG, QEMU_OPTION_icount },
8737 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8738 { NULL },
8741 /* password input */
8743 int qemu_key_check(BlockDriverState *bs, const char *name)
8745 char password[256];
8746 int i;
8748 if (!bdrv_is_encrypted(bs))
8749 return 0;
8751 term_printf("%s is encrypted.\n", name);
8752 for(i = 0; i < 3; i++) {
8753 monitor_readline("Password: ", 1, password, sizeof(password));
8754 if (bdrv_set_key(bs, password) == 0)
8755 return 0;
8756 term_printf("invalid password\n");
8758 return -EPERM;
8761 static BlockDriverState *get_bdrv(int index)
8763 if (index > nb_drives)
8764 return NULL;
8765 return drives_table[index].bdrv;
8768 static void read_passwords(void)
8770 BlockDriverState *bs;
8771 int i;
8773 for(i = 0; i < 6; i++) {
8774 bs = get_bdrv(i);
8775 if (bs)
8776 qemu_key_check(bs, bdrv_get_device_name(bs));
8780 #ifdef HAS_AUDIO
8781 struct soundhw soundhw[] = {
8782 #ifdef HAS_AUDIO_CHOICE
8783 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8785 "pcspk",
8786 "PC speaker",
8789 { .init_isa = pcspk_audio_init }
8791 #endif
8793 "sb16",
8794 "Creative Sound Blaster 16",
8797 { .init_isa = SB16_init }
8800 #ifdef CONFIG_CS4231A
8802 "cs4231a",
8803 "CS4231A",
8806 { .init_isa = cs4231a_init }
8808 #endif
8810 #ifdef CONFIG_ADLIB
8812 "adlib",
8813 #ifdef HAS_YMF262
8814 "Yamaha YMF262 (OPL3)",
8815 #else
8816 "Yamaha YM3812 (OPL2)",
8817 #endif
8820 { .init_isa = Adlib_init }
8822 #endif
8824 #ifdef CONFIG_GUS
8826 "gus",
8827 "Gravis Ultrasound GF1",
8830 { .init_isa = GUS_init }
8832 #endif
8834 #ifdef CONFIG_AC97
8836 "ac97",
8837 "Intel 82801AA AC97 Audio",
8840 { .init_pci = ac97_init }
8842 #endif
8845 "es1370",
8846 "ENSONIQ AudioPCI ES1370",
8849 { .init_pci = es1370_init }
8851 #endif
8853 { NULL, NULL, 0, 0, { NULL } }
8856 static void select_soundhw (const char *optarg)
8858 struct soundhw *c;
8860 if (*optarg == '?') {
8861 show_valid_cards:
8863 printf ("Valid sound card names (comma separated):\n");
8864 for (c = soundhw; c->name; ++c) {
8865 printf ("%-11s %s\n", c->name, c->descr);
8867 printf ("\n-soundhw all will enable all of the above\n");
8868 exit (*optarg != '?');
8870 else {
8871 size_t l;
8872 const char *p;
8873 char *e;
8874 int bad_card = 0;
8876 if (!strcmp (optarg, "all")) {
8877 for (c = soundhw; c->name; ++c) {
8878 c->enabled = 1;
8880 return;
8883 p = optarg;
8884 while (*p) {
8885 e = strchr (p, ',');
8886 l = !e ? strlen (p) : (size_t) (e - p);
8888 for (c = soundhw; c->name; ++c) {
8889 if (!strncmp (c->name, p, l)) {
8890 c->enabled = 1;
8891 break;
8895 if (!c->name) {
8896 if (l > 80) {
8897 fprintf (stderr,
8898 "Unknown sound card name (too big to show)\n");
8900 else {
8901 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8902 (int) l, p);
8904 bad_card = 1;
8906 p += l + (e != NULL);
8909 if (bad_card)
8910 goto show_valid_cards;
8913 #endif
8915 #ifdef _WIN32
8916 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8918 exit(STATUS_CONTROL_C_EXIT);
8919 return TRUE;
8921 #endif
8923 #define MAX_NET_CLIENTS 32
8925 static int saved_argc;
8926 static char **saved_argv;
8928 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8930 *argc = saved_argc;
8931 *argv = saved_argv;
8932 *opt_daemonize = daemonize;
8933 *opt_incoming = incoming;
8937 static int gethugepagesize(void)
8939 int ret, fd;
8940 char buf[4096];
8941 char *needle = "Hugepagesize:";
8942 char *size;
8943 unsigned long hugepagesize;
8945 fd = open("/proc/meminfo", O_RDONLY);
8946 if (fd < 0) {
8947 perror("open");
8948 exit(0);
8951 ret = read(fd, buf, sizeof(buf));
8952 if (ret < 0) {
8953 perror("read");
8954 exit(0);
8957 size = strstr(buf, needle);
8958 if (!size)
8959 return 0;
8960 size += strlen(needle);
8961 hugepagesize = strtol(size, NULL, 0);
8962 return hugepagesize;
8965 void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
8967 char *filename;
8968 void *area;
8969 int fd;
8971 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8972 return NULL;
8974 hpagesize = gethugepagesize() * 1024;
8975 if (!hpagesize)
8976 return NULL;
8978 fd = mkstemp(filename);
8979 if (fd < 0) {
8980 perror("mkstemp");
8981 free(filename);
8982 return NULL;
8984 unlink(filename);
8985 free(filename);
8987 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8990 * ftruncate is not supported by hugetlbfs in older
8991 * hosts, so don't bother checking for errors.
8992 * If anything goes wrong with it under other filesystems,
8993 * mmap will fail.
8995 ftruncate(fd, memory);
8997 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8998 if (area == MAP_FAILED) {
8999 perror("mmap");
9000 close(fd);
9001 return NULL;
9004 *len = memory;
9005 return area;
9008 void *qemu_alloc_physram(unsigned long memory)
9010 void *area = NULL;
9011 unsigned long map_len = memory;
9013 #ifdef USE_KVM
9014 if (mem_path)
9015 area = alloc_mem_area(memory, &map_len, mem_path);
9016 #endif
9017 if (!area)
9018 area = qemu_vmalloc(memory);
9019 #ifdef USE_KVM
9020 if (kvm_setup_guest_memory(area, map_len))
9021 area = NULL;
9022 #endif
9023 return area;
9026 #ifndef _WIN32
9028 static void termsig_handler(int signal)
9030 qemu_system_shutdown_request();
9033 static void termsig_setup(void)
9035 struct sigaction act;
9037 memset(&act, 0, sizeof(act));
9038 act.sa_handler = termsig_handler;
9039 sigaction(SIGINT, &act, NULL);
9040 sigaction(SIGHUP, &act, NULL);
9041 sigaction(SIGTERM, &act, NULL);
9044 #endif
9046 int main(int argc, char **argv)
9048 #ifdef CONFIG_GDBSTUB
9049 int use_gdbstub;
9050 const char *gdbstub_port;
9051 #endif
9052 uint32_t boot_devices_bitmap = 0;
9053 int i;
9054 int snapshot, linux_boot, net_boot;
9055 const char *initrd_filename;
9056 const char *kernel_filename, *kernel_cmdline;
9057 const char *boot_devices = "";
9058 DisplayState *ds = &display_state;
9059 int cyls, heads, secs, translation;
9060 const char *net_clients[MAX_NET_CLIENTS];
9061 int nb_net_clients;
9062 int hda_index;
9063 int optind;
9064 const char *r, *optarg;
9065 CharDriverState *monitor_hd;
9066 const char *monitor_device;
9067 const char *serial_devices[MAX_SERIAL_PORTS];
9068 int serial_device_index;
9069 const char *parallel_devices[MAX_PARALLEL_PORTS];
9070 int parallel_device_index;
9071 const char *loadvm = NULL;
9072 QEMUMachine *machine;
9073 const char *cpu_model;
9074 const char *usb_devices[MAX_USB_CMDLINE];
9075 int usb_devices_index;
9076 int fds[2];
9077 int tb_size;
9078 const char *pid_file = NULL;
9079 VLANState *vlan;
9081 saved_argc = argc;
9082 saved_argv = argv;
9084 LIST_INIT (&vm_change_state_head);
9085 #ifndef _WIN32
9087 struct sigaction act;
9088 sigfillset(&act.sa_mask);
9089 act.sa_flags = 0;
9090 act.sa_handler = SIG_IGN;
9091 sigaction(SIGPIPE, &act, NULL);
9093 #else
9094 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
9095 /* Note: cpu_interrupt() is currently not SMP safe, so we force
9096 QEMU to run on a single CPU */
9098 HANDLE h;
9099 DWORD mask, smask;
9100 int i;
9101 h = GetCurrentProcess();
9102 if (GetProcessAffinityMask(h, &mask, &smask)) {
9103 for(i = 0; i < 32; i++) {
9104 if (mask & (1 << i))
9105 break;
9107 if (i != 32) {
9108 mask = 1 << i;
9109 SetProcessAffinityMask(h, mask);
9113 #endif
9115 register_machines();
9116 machine = first_machine;
9117 cpu_model = NULL;
9118 initrd_filename = NULL;
9119 ram_size = 0;
9120 vga_ram_size = VGA_RAM_SIZE;
9121 #ifdef CONFIG_GDBSTUB
9122 use_gdbstub = 0;
9123 gdbstub_port = DEFAULT_GDBSTUB_PORT;
9124 #endif
9125 snapshot = 0;
9126 nographic = 0;
9127 curses = 0;
9128 kernel_filename = NULL;
9129 kernel_cmdline = "";
9130 cyls = heads = secs = 0;
9131 translation = BIOS_ATA_TRANSLATION_AUTO;
9132 monitor_device = "vc";
9134 serial_devices[0] = "vc:80Cx24C";
9135 for(i = 1; i < MAX_SERIAL_PORTS; i++)
9136 serial_devices[i] = NULL;
9137 serial_device_index = 0;
9139 parallel_devices[0] = "vc:640x480";
9140 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
9141 parallel_devices[i] = NULL;
9142 parallel_device_index = 0;
9144 usb_devices_index = 0;
9146 nb_net_clients = 0;
9147 nb_drives = 0;
9148 nb_drives_opt = 0;
9149 hda_index = -1;
9151 nb_nics = 0;
9153 tb_size = 0;
9155 optind = 1;
9156 for(;;) {
9157 if (optind >= argc)
9158 break;
9159 r = argv[optind];
9160 if (r[0] != '-') {
9161 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
9162 } else {
9163 const QEMUOption *popt;
9165 optind++;
9166 /* Treat --foo the same as -foo. */
9167 if (r[1] == '-')
9168 r++;
9169 popt = qemu_options;
9170 for(;;) {
9171 if (!popt->name) {
9172 fprintf(stderr, "%s: invalid option -- '%s'\n",
9173 argv[0], r);
9174 exit(1);
9176 if (!strcmp(popt->name, r + 1))
9177 break;
9178 popt++;
9180 if (popt->flags & HAS_ARG) {
9181 if (optind >= argc) {
9182 fprintf(stderr, "%s: option '%s' requires an argument\n",
9183 argv[0], r);
9184 exit(1);
9186 optarg = argv[optind++];
9187 } else {
9188 optarg = NULL;
9191 switch(popt->index) {
9192 case QEMU_OPTION_M:
9193 machine = find_machine(optarg);
9194 if (!machine) {
9195 QEMUMachine *m;
9196 printf("Supported machines are:\n");
9197 for(m = first_machine; m != NULL; m = m->next) {
9198 printf("%-10s %s%s\n",
9199 m->name, m->desc,
9200 m == first_machine ? " (default)" : "");
9202 exit(*optarg != '?');
9204 break;
9205 case QEMU_OPTION_cpu:
9206 /* hw initialization will check this */
9207 if (*optarg == '?') {
9208 /* XXX: implement xxx_cpu_list for targets that still miss it */
9209 #if defined(cpu_list)
9210 cpu_list(stdout, &fprintf);
9211 #endif
9212 exit(0);
9213 } else {
9214 cpu_model = optarg;
9216 break;
9217 case QEMU_OPTION_initrd:
9218 initrd_filename = optarg;
9219 break;
9220 case QEMU_OPTION_hda:
9221 if (cyls == 0)
9222 hda_index = drive_add(optarg, HD_ALIAS, 0);
9223 else
9224 hda_index = drive_add(optarg, HD_ALIAS
9225 ",cyls=%d,heads=%d,secs=%d%s",
9226 0, cyls, heads, secs,
9227 translation == BIOS_ATA_TRANSLATION_LBA ?
9228 ",trans=lba" :
9229 translation == BIOS_ATA_TRANSLATION_NONE ?
9230 ",trans=none" : "");
9231 break;
9232 case QEMU_OPTION_hdb:
9233 case QEMU_OPTION_hdc:
9234 case QEMU_OPTION_hdd:
9235 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
9236 break;
9237 case QEMU_OPTION_drive:
9238 drive_add(NULL, "%s", optarg);
9239 break;
9240 case QEMU_OPTION_mtdblock:
9241 drive_add(optarg, MTD_ALIAS);
9242 break;
9243 case QEMU_OPTION_sd:
9244 drive_add(optarg, SD_ALIAS);
9245 break;
9246 case QEMU_OPTION_pflash:
9247 drive_add(optarg, PFLASH_ALIAS);
9248 break;
9249 case QEMU_OPTION_snapshot:
9250 snapshot = 1;
9251 break;
9252 case QEMU_OPTION_hdachs:
9254 const char *p;
9255 p = optarg;
9256 cyls = strtol(p, (char **)&p, 0);
9257 if (cyls < 1 || cyls > 16383)
9258 goto chs_fail;
9259 if (*p != ',')
9260 goto chs_fail;
9261 p++;
9262 heads = strtol(p, (char **)&p, 0);
9263 if (heads < 1 || heads > 16)
9264 goto chs_fail;
9265 if (*p != ',')
9266 goto chs_fail;
9267 p++;
9268 secs = strtol(p, (char **)&p, 0);
9269 if (secs < 1 || secs > 63)
9270 goto chs_fail;
9271 if (*p == ',') {
9272 p++;
9273 if (!strcmp(p, "none"))
9274 translation = BIOS_ATA_TRANSLATION_NONE;
9275 else if (!strcmp(p, "lba"))
9276 translation = BIOS_ATA_TRANSLATION_LBA;
9277 else if (!strcmp(p, "auto"))
9278 translation = BIOS_ATA_TRANSLATION_AUTO;
9279 else
9280 goto chs_fail;
9281 } else if (*p != '\0') {
9282 chs_fail:
9283 fprintf(stderr, "qemu: invalid physical CHS format\n");
9284 exit(1);
9286 if (hda_index != -1)
9287 snprintf(drives_opt[hda_index].opt,
9288 sizeof(drives_opt[hda_index].opt),
9289 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
9290 0, cyls, heads, secs,
9291 translation == BIOS_ATA_TRANSLATION_LBA ?
9292 ",trans=lba" :
9293 translation == BIOS_ATA_TRANSLATION_NONE ?
9294 ",trans=none" : "");
9296 break;
9297 case QEMU_OPTION_nographic:
9298 nographic = 1;
9299 break;
9300 #ifdef CONFIG_CURSES
9301 case QEMU_OPTION_curses:
9302 curses = 1;
9303 break;
9304 #endif
9305 case QEMU_OPTION_portrait:
9306 graphic_rotate = 1;
9307 break;
9308 case QEMU_OPTION_kernel:
9309 kernel_filename = optarg;
9310 break;
9311 case QEMU_OPTION_append:
9312 kernel_cmdline = optarg;
9313 break;
9314 case QEMU_OPTION_cdrom:
9315 drive_add(optarg, CDROM_ALIAS);
9316 break;
9317 case QEMU_OPTION_boot:
9318 boot_devices = optarg;
9319 /* We just do some generic consistency checks */
9321 /* Could easily be extended to 64 devices if needed */
9322 const char *p;
9324 boot_devices_bitmap = 0;
9325 for (p = boot_devices; *p != '\0'; p++) {
9326 /* Allowed boot devices are:
9327 * a b : floppy disk drives
9328 * c ... f : IDE disk drives
9329 * g ... m : machine implementation dependant drives
9330 * n ... p : network devices
9331 * It's up to each machine implementation to check
9332 * if the given boot devices match the actual hardware
9333 * implementation and firmware features.
9335 if (*p < 'a' || *p > 'q') {
9336 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9337 exit(1);
9339 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9340 fprintf(stderr,
9341 "Boot device '%c' was given twice\n",*p);
9342 exit(1);
9344 boot_devices_bitmap |= 1 << (*p - 'a');
9347 break;
9348 case QEMU_OPTION_fda:
9349 case QEMU_OPTION_fdb:
9350 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9351 break;
9352 #ifdef TARGET_I386
9353 case QEMU_OPTION_no_fd_bootchk:
9354 fd_bootchk = 0;
9355 break;
9356 #endif
9357 case QEMU_OPTION_net:
9358 if (nb_net_clients >= MAX_NET_CLIENTS) {
9359 fprintf(stderr, "qemu: too many network clients\n");
9360 exit(1);
9362 net_clients[nb_net_clients] = optarg;
9363 nb_net_clients++;
9364 break;
9365 #ifdef CONFIG_SLIRP
9366 case QEMU_OPTION_tftp:
9367 tftp_prefix = optarg;
9368 break;
9369 case QEMU_OPTION_bootp:
9370 bootp_filename = optarg;
9371 break;
9372 #ifndef _WIN32
9373 case QEMU_OPTION_smb:
9374 net_slirp_smb(optarg);
9375 break;
9376 #endif
9377 case QEMU_OPTION_redir:
9378 net_slirp_redir(optarg);
9379 break;
9380 #endif
9381 #ifdef HAS_AUDIO
9382 case QEMU_OPTION_audio_help:
9383 AUD_help ();
9384 exit (0);
9385 break;
9386 case QEMU_OPTION_soundhw:
9387 select_soundhw (optarg);
9388 break;
9389 #endif
9390 case QEMU_OPTION_h:
9391 help(0);
9392 break;
9393 case QEMU_OPTION_m: {
9394 uint64_t value;
9395 char *ptr;
9397 value = strtoul(optarg, &ptr, 10);
9398 switch (*ptr) {
9399 case 0: case 'M': case 'm':
9400 value <<= 20;
9401 break;
9402 case 'G': case 'g':
9403 value <<= 30;
9404 break;
9405 default:
9406 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
9407 exit(1);
9410 /* On 32-bit hosts, QEMU is limited by virtual address space */
9411 if (value > (2047 << 20)
9412 #ifndef USE_KQEMU
9413 && HOST_LONG_BITS == 32
9414 #endif
9416 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
9417 exit(1);
9419 if (value != (uint64_t)(ram_addr_t)value) {
9420 fprintf(stderr, "qemu: ram size too large\n");
9421 exit(1);
9423 ram_size = value;
9424 break;
9426 case QEMU_OPTION_d:
9428 int mask;
9429 CPULogItem *item;
9431 mask = cpu_str_to_log_mask(optarg);
9432 if (!mask) {
9433 printf("Log items (comma separated):\n");
9434 for(item = cpu_log_items; item->mask != 0; item++) {
9435 printf("%-10s %s\n", item->name, item->help);
9437 exit(1);
9439 cpu_set_log(mask);
9441 break;
9442 #ifdef CONFIG_GDBSTUB
9443 case QEMU_OPTION_s:
9444 use_gdbstub = 1;
9445 break;
9446 case QEMU_OPTION_p:
9447 gdbstub_port = optarg;
9448 break;
9449 #endif
9450 case QEMU_OPTION_L:
9451 bios_dir = optarg;
9452 break;
9453 case QEMU_OPTION_bios:
9454 bios_name = optarg;
9455 break;
9456 case QEMU_OPTION_S:
9457 autostart = 0;
9458 break;
9459 case QEMU_OPTION_k:
9460 keyboard_layout = optarg;
9461 break;
9462 case QEMU_OPTION_localtime:
9463 rtc_utc = 0;
9464 break;
9465 case QEMU_OPTION_cirrusvga:
9466 cirrus_vga_enabled = 1;
9467 vmsvga_enabled = 0;
9468 break;
9469 case QEMU_OPTION_vmsvga:
9470 cirrus_vga_enabled = 0;
9471 vmsvga_enabled = 1;
9472 break;
9473 case QEMU_OPTION_std_vga:
9474 cirrus_vga_enabled = 0;
9475 vmsvga_enabled = 0;
9476 break;
9477 case QEMU_OPTION_g:
9479 const char *p;
9480 int w, h, depth;
9481 p = optarg;
9482 w = strtol(p, (char **)&p, 10);
9483 if (w <= 0) {
9484 graphic_error:
9485 fprintf(stderr, "qemu: invalid resolution or depth\n");
9486 exit(1);
9488 if (*p != 'x')
9489 goto graphic_error;
9490 p++;
9491 h = strtol(p, (char **)&p, 10);
9492 if (h <= 0)
9493 goto graphic_error;
9494 if (*p == 'x') {
9495 p++;
9496 depth = strtol(p, (char **)&p, 10);
9497 if (depth != 8 && depth != 15 && depth != 16 &&
9498 depth != 24 && depth != 32)
9499 goto graphic_error;
9500 } else if (*p == '\0') {
9501 depth = graphic_depth;
9502 } else {
9503 goto graphic_error;
9506 graphic_width = w;
9507 graphic_height = h;
9508 graphic_depth = depth;
9510 break;
9511 case QEMU_OPTION_echr:
9513 char *r;
9514 term_escape_char = strtol(optarg, &r, 0);
9515 if (r == optarg)
9516 printf("Bad argument to echr\n");
9517 break;
9519 case QEMU_OPTION_monitor:
9520 monitor_device = optarg;
9521 break;
9522 case QEMU_OPTION_serial:
9523 if (serial_device_index >= MAX_SERIAL_PORTS) {
9524 fprintf(stderr, "qemu: too many serial ports\n");
9525 exit(1);
9527 serial_devices[serial_device_index] = optarg;
9528 serial_device_index++;
9529 break;
9530 case QEMU_OPTION_parallel:
9531 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9532 fprintf(stderr, "qemu: too many parallel ports\n");
9533 exit(1);
9535 parallel_devices[parallel_device_index] = optarg;
9536 parallel_device_index++;
9537 break;
9538 case QEMU_OPTION_loadvm:
9539 loadvm = optarg;
9540 break;
9541 case QEMU_OPTION_incoming:
9542 incoming = optarg;
9543 break;
9544 case QEMU_OPTION_full_screen:
9545 full_screen = 1;
9546 break;
9547 #ifdef CONFIG_SDL
9548 case QEMU_OPTION_no_frame:
9549 no_frame = 1;
9550 break;
9551 case QEMU_OPTION_alt_grab:
9552 alt_grab = 1;
9553 break;
9554 case QEMU_OPTION_no_quit:
9555 no_quit = 1;
9556 break;
9557 #endif
9558 case QEMU_OPTION_pidfile:
9559 pid_file = optarg;
9560 break;
9561 #ifdef TARGET_I386
9562 case QEMU_OPTION_win2k_hack:
9563 win2k_install_hack = 1;
9564 break;
9565 #endif
9566 #ifdef USE_KQEMU
9567 case QEMU_OPTION_no_kqemu:
9568 kqemu_allowed = 0;
9569 break;
9570 case QEMU_OPTION_kernel_kqemu:
9571 kqemu_allowed = 2;
9572 break;
9573 #endif
9574 #ifdef USE_KVM
9575 case QEMU_OPTION_no_kvm:
9576 kvm_allowed = 0;
9577 break;
9578 case QEMU_OPTION_no_kvm_irqchip: {
9579 extern int kvm_irqchip, kvm_pit;
9580 kvm_irqchip = 0;
9581 kvm_pit = 0;
9582 break;
9584 case QEMU_OPTION_no_kvm_pit: {
9585 extern int kvm_pit;
9586 kvm_pit = 0;
9587 break;
9589 #endif
9590 case QEMU_OPTION_usb:
9591 usb_enabled = 1;
9592 break;
9593 case QEMU_OPTION_usbdevice:
9594 usb_enabled = 1;
9595 if (usb_devices_index >= MAX_USB_CMDLINE) {
9596 fprintf(stderr, "Too many USB devices\n");
9597 exit(1);
9599 usb_devices[usb_devices_index] = optarg;
9600 usb_devices_index++;
9601 break;
9602 case QEMU_OPTION_smp:
9603 smp_cpus = atoi(optarg);
9604 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9605 fprintf(stderr, "Invalid number of CPUs\n");
9606 exit(1);
9608 break;
9609 case QEMU_OPTION_vnc:
9610 vnc_display = optarg;
9611 break;
9612 case QEMU_OPTION_no_acpi:
9613 acpi_enabled = 0;
9614 break;
9615 case QEMU_OPTION_no_reboot:
9616 no_reboot = 1;
9617 break;
9618 case QEMU_OPTION_no_shutdown:
9619 no_shutdown = 1;
9620 break;
9621 case QEMU_OPTION_show_cursor:
9622 cursor_hide = 0;
9623 break;
9624 case QEMU_OPTION_daemonize:
9625 daemonize = 1;
9626 break;
9627 case QEMU_OPTION_option_rom:
9628 if (nb_option_roms >= MAX_OPTION_ROMS) {
9629 fprintf(stderr, "Too many option ROMs\n");
9630 exit(1);
9632 option_rom[nb_option_roms] = optarg;
9633 nb_option_roms++;
9634 break;
9635 case QEMU_OPTION_semihosting:
9636 semihosting_enabled = 1;
9637 break;
9638 case QEMU_OPTION_tdf:
9639 time_drift_fix = 1;
9640 break;
9641 case QEMU_OPTION_kvm_shadow_memory:
9642 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9643 break;
9644 case QEMU_OPTION_mempath:
9645 mem_path = optarg;
9646 break;
9647 case QEMU_OPTION_name:
9648 qemu_name = optarg;
9649 break;
9650 #ifdef TARGET_SPARC
9651 case QEMU_OPTION_prom_env:
9652 if (nb_prom_envs >= MAX_PROM_ENVS) {
9653 fprintf(stderr, "Too many prom variables\n");
9654 exit(1);
9656 prom_envs[nb_prom_envs] = optarg;
9657 nb_prom_envs++;
9658 break;
9659 #endif
9660 case QEMU_OPTION_cpu_vendor:
9661 cpu_vendor_string = optarg;
9662 break;
9663 #ifdef TARGET_ARM
9664 case QEMU_OPTION_old_param:
9665 old_param = 1;
9666 break;
9667 #endif
9668 case QEMU_OPTION_clock:
9669 configure_alarms(optarg);
9670 break;
9671 case QEMU_OPTION_startdate:
9673 struct tm tm;
9674 time_t rtc_start_date;
9675 if (!strcmp(optarg, "now")) {
9676 rtc_date_offset = -1;
9677 } else {
9678 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9679 &tm.tm_year,
9680 &tm.tm_mon,
9681 &tm.tm_mday,
9682 &tm.tm_hour,
9683 &tm.tm_min,
9684 &tm.tm_sec) == 6) {
9685 /* OK */
9686 } else if (sscanf(optarg, "%d-%d-%d",
9687 &tm.tm_year,
9688 &tm.tm_mon,
9689 &tm.tm_mday) == 3) {
9690 tm.tm_hour = 0;
9691 tm.tm_min = 0;
9692 tm.tm_sec = 0;
9693 } else {
9694 goto date_fail;
9696 tm.tm_year -= 1900;
9697 tm.tm_mon--;
9698 rtc_start_date = mktimegm(&tm);
9699 if (rtc_start_date == -1) {
9700 date_fail:
9701 fprintf(stderr, "Invalid date format. Valid format are:\n"
9702 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9703 exit(1);
9705 rtc_date_offset = time(NULL) - rtc_start_date;
9708 break;
9709 case QEMU_OPTION_tb_size:
9710 tb_size = strtol(optarg, NULL, 0);
9711 if (tb_size < 0)
9712 tb_size = 0;
9713 break;
9714 case QEMU_OPTION_icount:
9715 use_icount = 1;
9716 if (strcmp(optarg, "auto") == 0) {
9717 icount_time_shift = -1;
9718 } else {
9719 icount_time_shift = strtol(optarg, NULL, 0);
9721 break;
9726 if (nographic) {
9727 if (serial_device_index == 0)
9728 serial_devices[0] = "stdio";
9729 if (parallel_device_index == 0)
9730 parallel_devices[0] = "null";
9731 if (strncmp(monitor_device, "vc", 2) == 0)
9732 monitor_device = "stdio";
9735 #ifndef _WIN32
9736 if (daemonize) {
9737 pid_t pid;
9739 if (pipe(fds) == -1)
9740 exit(1);
9742 pid = fork();
9743 if (pid > 0) {
9744 uint8_t status;
9745 ssize_t len;
9747 close(fds[1]);
9749 again:
9750 len = read(fds[0], &status, 1);
9751 if (len == -1 && (errno == EINTR))
9752 goto again;
9754 if (len != 1)
9755 exit(1);
9756 else if (status == 1) {
9757 fprintf(stderr, "Could not acquire pidfile\n");
9758 exit(1);
9759 } else
9760 exit(0);
9761 } else if (pid < 0)
9762 exit(1);
9764 setsid();
9766 pid = fork();
9767 if (pid > 0)
9768 exit(0);
9769 else if (pid < 0)
9770 exit(1);
9772 umask(027);
9774 signal(SIGTSTP, SIG_IGN);
9775 signal(SIGTTOU, SIG_IGN);
9776 signal(SIGTTIN, SIG_IGN);
9778 #endif
9780 #if USE_KVM
9781 if (kvm_enabled()) {
9782 if (kvm_qemu_init() < 0) {
9783 extern int kvm_allowed;
9784 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9785 #ifdef NO_CPU_EMULATION
9786 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9787 exit(1);
9788 #endif
9789 kvm_allowed = 0;
9792 #endif
9794 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9795 if (daemonize) {
9796 uint8_t status = 1;
9797 write(fds[1], &status, 1);
9798 } else
9799 fprintf(stderr, "Could not acquire pid file\n");
9800 exit(1);
9803 #ifdef USE_KQEMU
9804 if (smp_cpus > 1)
9805 kqemu_allowed = 0;
9806 #endif
9807 linux_boot = (kernel_filename != NULL);
9808 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9810 if (!linux_boot && net_boot == 0 &&
9811 !machine->nodisk_ok && nb_drives_opt == 0)
9812 help(1);
9814 if (!linux_boot && *kernel_cmdline != '\0') {
9815 fprintf(stderr, "-append only allowed with -kernel option\n");
9816 exit(1);
9819 if (!linux_boot && initrd_filename != NULL) {
9820 fprintf(stderr, "-initrd only allowed with -kernel option\n");
9821 exit(1);
9824 /* boot to floppy or the default cd if no hard disk defined yet */
9825 if (!boot_devices[0]) {
9826 boot_devices = "cad";
9828 setvbuf(stdout, NULL, _IOLBF, 0);
9830 init_timers();
9831 init_timer_alarm();
9832 qemu_aio_init();
9833 if (use_icount && icount_time_shift < 0) {
9834 use_icount = 2;
9835 /* 125MIPS seems a reasonable initial guess at the guest speed.
9836 It will be corrected fairly quickly anyway. */
9837 icount_time_shift = 3;
9838 init_icount_adjust();
9841 #ifdef _WIN32
9842 socket_init();
9843 #endif
9845 /* init network clients */
9846 if (nb_net_clients == 0) {
9847 /* if no clients, we use a default config */
9848 net_clients[nb_net_clients++] = "nic";
9849 #ifdef CONFIG_SLIRP
9850 net_clients[nb_net_clients++] = "user";
9851 #endif
9854 for(i = 0;i < nb_net_clients; i++) {
9855 if (net_client_parse(net_clients[i]) < 0)
9856 exit(1);
9858 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9859 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9860 continue;
9861 if (vlan->nb_guest_devs == 0)
9862 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9863 if (vlan->nb_host_devs == 0)
9864 fprintf(stderr,
9865 "Warning: vlan %d is not connected to host network\n",
9866 vlan->id);
9869 #ifdef TARGET_I386
9870 /* XXX: this should be moved in the PC machine instantiation code */
9871 if (net_boot != 0) {
9872 int netroms = 0;
9873 for (i = 0; i < nb_nics && i < 4; i++) {
9874 const char *model = nd_table[i].model;
9875 char buf[1024];
9876 if (net_boot & (1 << i)) {
9877 if (model == NULL)
9878 model = "rtl8139";
9879 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9880 if (get_image_size(buf) > 0) {
9881 if (nb_option_roms >= MAX_OPTION_ROMS) {
9882 fprintf(stderr, "Too many option ROMs\n");
9883 exit(1);
9885 option_rom[nb_option_roms] = strdup(buf);
9886 nb_option_roms++;
9887 netroms++;
9891 if (netroms == 0) {
9892 fprintf(stderr, "No valid PXE rom found for network device\n");
9893 exit(1);
9896 #endif
9898 /* init the memory */
9899 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9901 if (machine->ram_require & RAMSIZE_FIXED) {
9902 if (ram_size > 0) {
9903 if (ram_size < phys_ram_size) {
9904 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9905 machine->name, (unsigned long long) phys_ram_size);
9906 exit(-1);
9909 phys_ram_size = ram_size;
9910 } else
9911 ram_size = phys_ram_size;
9912 } else {
9913 if (ram_size == 0)
9914 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9916 phys_ram_size += ram_size;
9919 /* Initialize kvm */
9920 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9921 #define KVM_EXTRA_PAGES 3
9922 #else
9923 #define KVM_EXTRA_PAGES 0
9924 #endif
9925 if (kvm_enabled()) {
9926 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9927 if (kvm_qemu_create_context() < 0) {
9928 fprintf(stderr, "Could not create KVM context\n");
9929 exit(1);
9933 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9934 if (!phys_ram_base) {
9935 fprintf(stderr, "Could not allocate physical memory\n");
9936 exit(1);
9939 /* init the dynamic translator */
9940 cpu_exec_init_all(tb_size * 1024 * 1024);
9942 bdrv_init();
9944 /* we always create the cdrom drive, even if no disk is there */
9946 if (nb_drives_opt < MAX_DRIVES)
9947 drive_add(NULL, CDROM_ALIAS);
9949 /* we always create at least one floppy */
9951 if (nb_drives_opt < MAX_DRIVES)
9952 drive_add(NULL, FD_ALIAS, 0);
9954 /* we always create one sd slot, even if no card is in it */
9956 if (nb_drives_opt < MAX_DRIVES)
9957 drive_add(NULL, SD_ALIAS);
9959 /* open the virtual block devices
9960 * note that migration with device
9961 * hot add/remove is broken.
9963 for(i = 0; i < nb_drives_opt; i++)
9964 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9965 exit(1);
9967 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9968 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9970 /* terminal init */
9971 memset(&display_state, 0, sizeof(display_state));
9972 if (nographic) {
9973 if (curses) {
9974 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9975 exit(1);
9977 /* nearly nothing to do */
9978 dumb_display_init(ds);
9979 } else if (vnc_display != NULL) {
9980 vnc_display_init(ds);
9981 if (vnc_display_open(ds, vnc_display) < 0)
9982 exit(1);
9983 } else
9984 #if defined(CONFIG_CURSES)
9985 if (curses) {
9986 curses_display_init(ds, full_screen);
9987 } else
9988 #endif
9990 #if defined(CONFIG_SDL)
9991 sdl_display_init(ds, full_screen, no_frame);
9992 #elif defined(CONFIG_COCOA)
9993 cocoa_display_init(ds, full_screen);
9994 #else
9995 dumb_display_init(ds);
9996 #endif
9999 #ifndef _WIN32
10000 /* must be after terminal init, SDL library changes signal handlers */
10001 termsig_setup();
10002 #endif
10004 /* Maintain compatibility with multiple stdio monitors */
10005 if (!strcmp(monitor_device,"stdio")) {
10006 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
10007 const char *devname = serial_devices[i];
10008 if (devname && !strcmp(devname,"mon:stdio")) {
10009 monitor_device = NULL;
10010 break;
10011 } else if (devname && !strcmp(devname,"stdio")) {
10012 monitor_device = NULL;
10013 serial_devices[i] = "mon:stdio";
10014 break;
10018 if (monitor_device) {
10019 monitor_hd = qemu_chr_open(monitor_device);
10020 if (!monitor_hd) {
10021 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
10022 exit(1);
10024 monitor_init(monitor_hd, !nographic);
10027 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
10028 const char *devname = serial_devices[i];
10029 if (devname && strcmp(devname, "none")) {
10030 serial_hds[i] = qemu_chr_open(devname);
10031 if (!serial_hds[i]) {
10032 fprintf(stderr, "qemu: could not open serial device '%s'\n",
10033 devname);
10034 exit(1);
10036 if (strstart(devname, "vc", 0))
10037 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
10041 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
10042 const char *devname = parallel_devices[i];
10043 if (devname && strcmp(devname, "none")) {
10044 parallel_hds[i] = qemu_chr_open(devname);
10045 if (!parallel_hds[i]) {
10046 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
10047 devname);
10048 exit(1);
10050 if (strstart(devname, "vc", 0))
10051 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
10055 if (kvm_enabled())
10056 kvm_init_ap();
10058 machine->init(ram_size, vga_ram_size, boot_devices, ds,
10059 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
10061 current_machine = machine;
10063 /* init USB devices */
10064 if (usb_enabled) {
10065 for(i = 0; i < usb_devices_index; i++) {
10066 if (usb_device_add(usb_devices[i]) < 0) {
10067 fprintf(stderr, "Warning: could not add USB device %s\n",
10068 usb_devices[i]);
10073 if (display_state.dpy_refresh) {
10074 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
10075 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
10078 #ifdef CONFIG_GDBSTUB
10079 if (use_gdbstub) {
10080 /* XXX: use standard host:port notation and modify options
10081 accordingly. */
10082 if (gdbserver_start(gdbstub_port) < 0) {
10083 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
10084 gdbstub_port);
10085 exit(1);
10088 #endif
10090 if (loadvm)
10091 do_loadvm(loadvm);
10093 if (incoming) {
10094 int rc;
10096 rc = migrate_incoming(incoming);
10097 if (rc != 0) {
10098 fprintf(stderr, "Migration failed rc=%d\n", rc);
10099 exit(rc);
10104 /* XXX: simplify init */
10105 read_passwords();
10106 if (autostart) {
10107 vm_start();
10111 if (daemonize) {
10112 uint8_t status = 0;
10113 ssize_t len;
10114 int fd;
10116 again1:
10117 len = write(fds[1], &status, 1);
10118 if (len == -1 && (errno == EINTR))
10119 goto again1;
10121 if (len != 1)
10122 exit(1);
10124 chdir("/");
10125 TFR(fd = open("/dev/null", O_RDWR));
10126 if (fd == -1)
10127 exit(1);
10129 dup2(fd, 0);
10130 dup2(fd, 1);
10131 dup2(fd, 2);
10133 close(fd);
10136 main_loop();
10137 quit_timers();
10139 #if !defined(_WIN32)
10140 /* close network clients */
10141 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
10142 VLANClientState *vc;
10144 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
10145 if (vc->fd_read == tap_receive) {
10146 char ifname[64];
10147 TAPState *s = vc->opaque;
10149 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
10150 s->down_script[0])
10151 launch_script(s->down_script, ifname, s->fd);
10153 #if defined(CONFIG_VDE)
10154 if (vc->fd_read == vde_from_qemu) {
10155 VDEState *s = vc->opaque;
10156 vde_close(s->vde);
10158 #endif
10161 #endif
10162 return 0;