I440fx: do change ISA mappings under KVM
[qemu-kvm/fedora.git] / vl.c
blob022b3b8f598315a7dca66fb85dd65727ed52d3fc
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 #else
107 #include <winsock2.h>
108 int inet_aton(const char *cp, struct in_addr *ia);
109 #endif
111 #if defined(CONFIG_SLIRP)
112 #include "libslirp.h"
113 #endif
115 #if defined(__OpenBSD__)
116 #include <util.h>
117 #endif
119 #if defined(CONFIG_VDE)
120 #include <libvdeplug.h>
121 #endif
123 #ifdef _WIN32
124 #include <malloc.h>
125 #include <sys/timeb.h>
126 #include <mmsystem.h>
127 #define getopt_long_only getopt_long
128 #define memalign(align, size) malloc(size)
129 #endif
131 #include "qemu_socket.h"
133 #ifdef CONFIG_SDL
134 #ifdef __APPLE__
135 #include <SDL/SDL.h>
136 #endif
137 #endif /* CONFIG_SDL */
139 #ifdef CONFIG_COCOA
140 #undef main
141 #define main qemu_main
142 #endif /* CONFIG_COCOA */
144 #include "disas.h"
146 #include "exec-all.h"
148 #include "qemu-kvm.h"
150 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
151 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
152 #ifdef __sun__
153 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
154 #else
155 #define SMBD_COMMAND "/usr/sbin/smbd"
156 #endif
158 //#define DEBUG_UNUSED_IOPORT
159 //#define DEBUG_IOPORT
161 #ifdef TARGET_PPC
162 #define DEFAULT_RAM_SIZE 144
163 #else
164 #define DEFAULT_RAM_SIZE 128
165 #endif
167 /* Max number of USB devices that can be specified on the commandline. */
168 #define MAX_USB_CMDLINE 8
170 /* XXX: use a two level table to limit memory usage */
171 #define MAX_IOPORTS 65536
173 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
174 const char *bios_name = NULL;
175 void *ioport_opaque[MAX_IOPORTS];
176 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
177 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 DriveInfo drives_table[MAX_DRIVES+1];
181 int nb_drives;
182 int extboot_drive = -1;
183 /* point to the block driver where the snapshots are managed */
184 BlockDriverState *bs_snapshots;
185 int vga_ram_size;
186 static DisplayState display_state;
187 int nographic;
188 int curses;
189 const char* keyboard_layout = NULL;
190 int64_t ticks_per_sec;
191 ram_addr_t ram_size;
192 int pit_min_timer_count = 0;
193 int nb_nics;
194 NICInfo nd_table[MAX_NICS];
195 int vm_running;
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 int cirrus_vga_enabled = 1;
199 int vmsvga_enabled = 0;
200 #ifdef TARGET_SPARC
201 int graphic_width = 1024;
202 int graphic_height = 768;
203 int graphic_depth = 8;
204 #else
205 int graphic_width = 800;
206 int graphic_height = 600;
207 int graphic_depth = 15;
208 #endif
209 int full_screen = 0;
210 int no_frame = 0;
211 int no_quit = 0;
212 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
213 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
214 #ifdef TARGET_I386
215 int win2k_install_hack = 0;
216 #endif
217 int usb_enabled = 0;
218 static VLANState *first_vlan;
219 int smp_cpus = 1;
220 const char *vnc_display;
221 #if defined(TARGET_SPARC)
222 #define MAX_CPUS 16
223 #elif defined(TARGET_I386)
224 #define MAX_CPUS 255
225 #elif defined(TARGET_IA64)
226 #define MAX_CPUS 4
227 #else
228 #define MAX_CPUS 1
229 #endif
230 int acpi_enabled = 1;
231 int fd_bootchk = 1;
232 int no_reboot = 0;
233 int no_shutdown = 0;
234 int cursor_hide = 1;
235 int graphic_rotate = 0;
236 int daemonize = 0;
237 const char *incoming;
238 const char *option_rom[MAX_OPTION_ROMS];
239 int nb_option_roms;
240 int semihosting_enabled = 0;
241 int autostart = 1;
242 int time_drift_fix = 0;
243 unsigned int kvm_shadow_memory = 0;
244 const char *mem_path = NULL;
245 int hpagesize = 0;
246 const char *cpu_vendor_string;
247 #ifdef TARGET_ARM
248 int old_param = 0;
249 #endif
250 const char *qemu_name;
251 int alt_grab = 0;
252 #ifdef TARGET_SPARC
253 unsigned int nb_prom_envs = 0;
254 const char *prom_envs[MAX_PROM_ENVS];
255 #endif
256 int nb_drives_opt;
257 struct drive_opt drives_opt[MAX_DRIVES];
259 static CPUState *cur_cpu;
260 static CPUState *next_cpu;
261 static int event_pending = 1;
262 /* Conversion factor from emulated instructions to virtual clock ticks. */
263 static int icount_time_shift;
264 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
265 #define MAX_ICOUNT_SHIFT 10
266 /* Compensate for varying guest execution speed. */
267 static int64_t qemu_icount_bias;
268 QEMUTimer *icount_rt_timer;
269 QEMUTimer *icount_vm_timer;
271 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
273 /* KVM runs the main loop in a separate thread. If we update one of the lists
274 * that are polled before or after select(), we need to make sure to break out
275 * of the select() to ensure the new item is serviced.
277 static void main_loop_break(void)
279 if (kvm_enabled())
280 qemu_kvm_notify_work();
283 /***********************************************************/
284 /* x86 ISA bus support */
286 target_phys_addr_t isa_mem_base = 0;
287 PicState2 *isa_pic;
289 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
290 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
292 static uint32_t ioport_read(int index, uint32_t address)
294 static IOPortReadFunc *default_func[3] = {
295 default_ioport_readb,
296 default_ioport_readw,
297 default_ioport_readl
299 IOPortReadFunc *func = ioport_read_table[index][address];
300 if (!func)
301 func = default_func[index];
302 return func(ioport_opaque[address], address);
305 static void ioport_write(int index, uint32_t address, uint32_t data)
307 static IOPortWriteFunc *default_func[3] = {
308 default_ioport_writeb,
309 default_ioport_writew,
310 default_ioport_writel
312 IOPortWriteFunc *func = ioport_write_table[index][address];
313 if (!func)
314 func = default_func[index];
315 func(ioport_opaque[address], address, data);
318 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
320 #ifdef DEBUG_UNUSED_IOPORT
321 fprintf(stderr, "unused inb: port=0x%04x\n", address);
322 #endif
323 return 0xff;
326 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
328 #ifdef DEBUG_UNUSED_IOPORT
329 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
330 #endif
333 /* default is to make two byte accesses */
334 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
336 uint32_t data;
337 data = ioport_read(0, address);
338 address = (address + 1) & (MAX_IOPORTS - 1);
339 data |= ioport_read(0, address) << 8;
340 return data;
343 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
345 ioport_write(0, address, data & 0xff);
346 address = (address + 1) & (MAX_IOPORTS - 1);
347 ioport_write(0, address, (data >> 8) & 0xff);
350 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
352 #ifdef DEBUG_UNUSED_IOPORT
353 fprintf(stderr, "unused inl: port=0x%04x\n", address);
354 #endif
355 return 0xffffffff;
358 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
360 #ifdef DEBUG_UNUSED_IOPORT
361 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
362 #endif
365 /* size is the word size in byte */
366 int register_ioport_read(int start, int length, int size,
367 IOPortReadFunc *func, void *opaque)
369 int i, bsize;
371 if (size == 1) {
372 bsize = 0;
373 } else if (size == 2) {
374 bsize = 1;
375 } else if (size == 4) {
376 bsize = 2;
377 } else {
378 hw_error("register_ioport_read: invalid size");
379 return -1;
381 for(i = start; i < start + length; i += size) {
382 ioport_read_table[bsize][i] = func;
383 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
384 hw_error("register_ioport_read: invalid opaque");
385 ioport_opaque[i] = opaque;
387 return 0;
390 /* size is the word size in byte */
391 int register_ioport_write(int start, int length, int size,
392 IOPortWriteFunc *func, void *opaque)
394 int i, bsize;
396 if (size == 1) {
397 bsize = 0;
398 } else if (size == 2) {
399 bsize = 1;
400 } else if (size == 4) {
401 bsize = 2;
402 } else {
403 hw_error("register_ioport_write: invalid size");
404 return -1;
406 for(i = start; i < start + length; i += size) {
407 ioport_write_table[bsize][i] = func;
408 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
409 hw_error("register_ioport_write: invalid opaque");
410 ioport_opaque[i] = opaque;
412 return 0;
415 void isa_unassign_ioport(int start, int length)
417 int i;
419 for(i = start; i < start + length; i++) {
420 ioport_read_table[0][i] = default_ioport_readb;
421 ioport_read_table[1][i] = default_ioport_readw;
422 ioport_read_table[2][i] = default_ioport_readl;
424 ioport_write_table[0][i] = default_ioport_writeb;
425 ioport_write_table[1][i] = default_ioport_writew;
426 ioport_write_table[2][i] = default_ioport_writel;
428 ioport_opaque[i] = NULL;
432 /***********************************************************/
434 void cpu_outb(CPUState *env, int addr, int val)
436 #ifdef DEBUG_IOPORT
437 if (loglevel & CPU_LOG_IOPORT)
438 fprintf(logfile, "outb: %04x %02x\n", addr, val);
439 #endif
440 ioport_write(0, addr, val);
441 #ifdef USE_KQEMU
442 if (env)
443 env->last_io_time = cpu_get_time_fast();
444 #endif
447 void cpu_outw(CPUState *env, int addr, int val)
449 #ifdef DEBUG_IOPORT
450 if (loglevel & CPU_LOG_IOPORT)
451 fprintf(logfile, "outw: %04x %04x\n", addr, val);
452 #endif
453 ioport_write(1, addr, val);
454 #ifdef USE_KQEMU
455 if (env)
456 env->last_io_time = cpu_get_time_fast();
457 #endif
460 void cpu_outl(CPUState *env, int addr, int val)
462 #ifdef DEBUG_IOPORT
463 if (loglevel & CPU_LOG_IOPORT)
464 fprintf(logfile, "outl: %04x %08x\n", addr, val);
465 #endif
466 ioport_write(2, addr, val);
467 #ifdef USE_KQEMU
468 if (env)
469 env->last_io_time = cpu_get_time_fast();
470 #endif
473 int cpu_inb(CPUState *env, int addr)
475 int val;
476 val = ioport_read(0, addr);
477 #ifdef DEBUG_IOPORT
478 if (loglevel & CPU_LOG_IOPORT)
479 fprintf(logfile, "inb : %04x %02x\n", addr, val);
480 #endif
481 #ifdef USE_KQEMU
482 if (env)
483 env->last_io_time = cpu_get_time_fast();
484 #endif
485 return val;
488 int cpu_inw(CPUState *env, int addr)
490 int val;
491 val = ioport_read(1, addr);
492 #ifdef DEBUG_IOPORT
493 if (loglevel & CPU_LOG_IOPORT)
494 fprintf(logfile, "inw : %04x %04x\n", addr, val);
495 #endif
496 #ifdef USE_KQEMU
497 if (env)
498 env->last_io_time = cpu_get_time_fast();
499 #endif
500 return val;
503 int cpu_inl(CPUState *env, int addr)
505 int val;
506 val = ioport_read(2, addr);
507 #ifdef DEBUG_IOPORT
508 if (loglevel & CPU_LOG_IOPORT)
509 fprintf(logfile, "inl : %04x %08x\n", addr, val);
510 #endif
511 #ifdef USE_KQEMU
512 if (env)
513 env->last_io_time = cpu_get_time_fast();
514 #endif
515 return val;
518 /***********************************************************/
519 void hw_error(const char *fmt, ...)
521 va_list ap;
522 CPUState *env;
524 va_start(ap, fmt);
525 fprintf(stderr, "qemu: hardware error: ");
526 vfprintf(stderr, fmt, ap);
527 fprintf(stderr, "\n");
528 for(env = first_cpu; env != NULL; env = env->next_cpu) {
529 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
530 #ifdef TARGET_I386
531 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
532 #else
533 cpu_dump_state(env, stderr, fprintf, 0);
534 #endif
536 va_end(ap);
537 abort();
540 /***************/
541 /* ballooning */
543 static QEMUBalloonEvent *qemu_balloon_event;
544 void *qemu_balloon_event_opaque;
546 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
548 qemu_balloon_event = func;
549 qemu_balloon_event_opaque = opaque;
552 void qemu_balloon(ram_addr_t target)
554 if (qemu_balloon_event)
555 qemu_balloon_event(qemu_balloon_event_opaque, target);
558 ram_addr_t qemu_balloon_status(void)
560 if (qemu_balloon_event)
561 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
562 return 0;
565 /***********************************************************/
566 /* keyboard/mouse */
568 static QEMUPutKBDEvent *qemu_put_kbd_event;
569 static void *qemu_put_kbd_event_opaque;
570 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
571 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
573 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
575 qemu_put_kbd_event_opaque = opaque;
576 qemu_put_kbd_event = func;
579 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
580 void *opaque, int absolute,
581 const char *name)
583 QEMUPutMouseEntry *s, *cursor;
585 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
586 if (!s)
587 return NULL;
589 s->qemu_put_mouse_event = func;
590 s->qemu_put_mouse_event_opaque = opaque;
591 s->qemu_put_mouse_event_absolute = absolute;
592 s->qemu_put_mouse_event_name = qemu_strdup(name);
593 s->next = NULL;
595 if (!qemu_put_mouse_event_head) {
596 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
597 return s;
600 cursor = qemu_put_mouse_event_head;
601 while (cursor->next != NULL)
602 cursor = cursor->next;
604 cursor->next = s;
605 qemu_put_mouse_event_current = s;
607 return s;
610 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
612 QEMUPutMouseEntry *prev = NULL, *cursor;
614 if (!qemu_put_mouse_event_head || entry == NULL)
615 return;
617 cursor = qemu_put_mouse_event_head;
618 while (cursor != NULL && cursor != entry) {
619 prev = cursor;
620 cursor = cursor->next;
623 if (cursor == NULL) // does not exist or list empty
624 return;
625 else if (prev == NULL) { // entry is head
626 qemu_put_mouse_event_head = cursor->next;
627 if (qemu_put_mouse_event_current == entry)
628 qemu_put_mouse_event_current = cursor->next;
629 qemu_free(entry->qemu_put_mouse_event_name);
630 qemu_free(entry);
631 return;
634 prev->next = entry->next;
636 if (qemu_put_mouse_event_current == entry)
637 qemu_put_mouse_event_current = prev;
639 qemu_free(entry->qemu_put_mouse_event_name);
640 qemu_free(entry);
643 void kbd_put_keycode(int keycode)
645 if (qemu_put_kbd_event) {
646 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
650 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
652 QEMUPutMouseEvent *mouse_event;
653 void *mouse_event_opaque;
654 int width;
656 if (!qemu_put_mouse_event_current) {
657 return;
660 mouse_event =
661 qemu_put_mouse_event_current->qemu_put_mouse_event;
662 mouse_event_opaque =
663 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
665 if (mouse_event) {
666 if (graphic_rotate) {
667 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
668 width = 0x7fff;
669 else
670 width = graphic_width - 1;
671 mouse_event(mouse_event_opaque,
672 width - dy, dx, dz, buttons_state);
673 } else
674 mouse_event(mouse_event_opaque,
675 dx, dy, dz, buttons_state);
679 int kbd_mouse_is_absolute(void)
681 if (!qemu_put_mouse_event_current)
682 return 0;
684 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
687 void do_info_mice(void)
689 QEMUPutMouseEntry *cursor;
690 int index = 0;
692 if (!qemu_put_mouse_event_head) {
693 term_printf("No mouse devices connected\n");
694 return;
697 term_printf("Mouse devices available:\n");
698 cursor = qemu_put_mouse_event_head;
699 while (cursor != NULL) {
700 term_printf("%c Mouse #%d: %s\n",
701 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
702 index, cursor->qemu_put_mouse_event_name);
703 index++;
704 cursor = cursor->next;
708 void do_mouse_set(int index)
710 QEMUPutMouseEntry *cursor;
711 int i = 0;
713 if (!qemu_put_mouse_event_head) {
714 term_printf("No mouse devices connected\n");
715 return;
718 cursor = qemu_put_mouse_event_head;
719 while (cursor != NULL && index != i) {
720 i++;
721 cursor = cursor->next;
724 if (cursor != NULL)
725 qemu_put_mouse_event_current = cursor;
726 else
727 term_printf("Mouse at given index not found\n");
730 /* compute with 96 bit intermediate result: (a*b)/c */
731 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
733 union {
734 uint64_t ll;
735 struct {
736 #ifdef WORDS_BIGENDIAN
737 uint32_t high, low;
738 #else
739 uint32_t low, high;
740 #endif
741 } l;
742 } u, res;
743 uint64_t rl, rh;
745 u.ll = a;
746 rl = (uint64_t)u.l.low * (uint64_t)b;
747 rh = (uint64_t)u.l.high * (uint64_t)b;
748 rh += (rl >> 32);
749 res.l.high = rh / c;
750 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
751 return res.ll;
754 /***********************************************************/
755 /* real time host monotonic timer */
757 #define QEMU_TIMER_BASE 1000000000LL
759 #ifdef WIN32
761 static int64_t clock_freq;
763 static void init_get_clock(void)
765 LARGE_INTEGER freq;
766 int ret;
767 ret = QueryPerformanceFrequency(&freq);
768 if (ret == 0) {
769 fprintf(stderr, "Could not calibrate ticks\n");
770 exit(1);
772 clock_freq = freq.QuadPart;
775 static int64_t get_clock(void)
777 LARGE_INTEGER ti;
778 QueryPerformanceCounter(&ti);
779 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
782 #else
784 static int use_rt_clock;
786 static void init_get_clock(void)
788 use_rt_clock = 0;
789 #if defined(__linux__)
791 struct timespec ts;
792 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
793 use_rt_clock = 1;
796 #endif
799 static int64_t get_clock(void)
801 #if defined(__linux__)
802 if (use_rt_clock) {
803 struct timespec ts;
804 clock_gettime(CLOCK_MONOTONIC, &ts);
805 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
806 } else
807 #endif
809 /* XXX: using gettimeofday leads to problems if the date
810 changes, so it should be avoided. */
811 struct timeval tv;
812 gettimeofday(&tv, NULL);
813 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
816 #endif
818 /* Return the virtual CPU time, based on the instruction counter. */
819 static int64_t cpu_get_icount(void)
821 int64_t icount;
822 CPUState *env = cpu_single_env;;
823 icount = qemu_icount;
824 if (env) {
825 if (!can_do_io(env))
826 fprintf(stderr, "Bad clock read\n");
827 icount -= (env->icount_decr.u16.low + env->icount_extra);
829 return qemu_icount_bias + (icount << icount_time_shift);
832 /***********************************************************/
833 /* guest cycle counter */
835 static int64_t cpu_ticks_prev;
836 static int64_t cpu_ticks_offset;
837 static int64_t cpu_clock_offset;
838 static int cpu_ticks_enabled;
840 /* return the host CPU cycle counter and handle stop/restart */
841 int64_t cpu_get_ticks(void)
843 if (use_icount) {
844 return cpu_get_icount();
846 if (!cpu_ticks_enabled) {
847 return cpu_ticks_offset;
848 } else {
849 int64_t ticks;
850 ticks = cpu_get_real_ticks();
851 if (cpu_ticks_prev > ticks) {
852 /* Note: non increasing ticks may happen if the host uses
853 software suspend */
854 cpu_ticks_offset += cpu_ticks_prev - ticks;
856 cpu_ticks_prev = ticks;
857 return ticks + cpu_ticks_offset;
861 /* return the host CPU monotonic timer and handle stop/restart */
862 static int64_t cpu_get_clock(void)
864 int64_t ti;
865 if (!cpu_ticks_enabled) {
866 return cpu_clock_offset;
867 } else {
868 ti = get_clock();
869 return ti + cpu_clock_offset;
873 /* enable cpu_get_ticks() */
874 void cpu_enable_ticks(void)
876 if (!cpu_ticks_enabled) {
877 cpu_ticks_offset -= cpu_get_real_ticks();
878 cpu_clock_offset -= get_clock();
879 cpu_ticks_enabled = 1;
883 /* disable cpu_get_ticks() : the clock is stopped. You must not call
884 cpu_get_ticks() after that. */
885 void cpu_disable_ticks(void)
887 if (cpu_ticks_enabled) {
888 cpu_ticks_offset = cpu_get_ticks();
889 cpu_clock_offset = cpu_get_clock();
890 cpu_ticks_enabled = 0;
894 /***********************************************************/
895 /* timers */
897 #define QEMU_TIMER_REALTIME 0
898 #define QEMU_TIMER_VIRTUAL 1
900 struct QEMUClock {
901 int type;
902 /* XXX: add frequency */
905 struct QEMUTimer {
906 QEMUClock *clock;
907 int64_t expire_time;
908 QEMUTimerCB *cb;
909 void *opaque;
910 struct QEMUTimer *next;
913 struct qemu_alarm_timer {
914 char const *name;
915 unsigned int flags;
917 int (*start)(struct qemu_alarm_timer *t);
918 void (*stop)(struct qemu_alarm_timer *t);
919 void (*rearm)(struct qemu_alarm_timer *t);
920 void *priv;
923 #define ALARM_FLAG_DYNTICKS 0x1
924 #define ALARM_FLAG_EXPIRED 0x2
926 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
928 return t->flags & ALARM_FLAG_DYNTICKS;
931 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
933 if (!alarm_has_dynticks(t))
934 return;
936 t->rearm(t);
939 /* TODO: MIN_TIMER_REARM_US should be optimized */
940 #define MIN_TIMER_REARM_US 250
942 static struct qemu_alarm_timer *alarm_timer;
944 #ifdef _WIN32
946 struct qemu_alarm_win32 {
947 MMRESULT timerId;
948 HANDLE host_alarm;
949 unsigned int period;
950 } alarm_win32_data = {0, NULL, -1};
952 static int win32_start_timer(struct qemu_alarm_timer *t);
953 static void win32_stop_timer(struct qemu_alarm_timer *t);
954 static void win32_rearm_timer(struct qemu_alarm_timer *t);
956 #else
958 static int unix_start_timer(struct qemu_alarm_timer *t);
959 static void unix_stop_timer(struct qemu_alarm_timer *t);
961 #ifdef __linux__
963 static int dynticks_start_timer(struct qemu_alarm_timer *t);
964 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
965 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
967 static int hpet_start_timer(struct qemu_alarm_timer *t);
968 static void hpet_stop_timer(struct qemu_alarm_timer *t);
970 static int rtc_start_timer(struct qemu_alarm_timer *t);
971 static void rtc_stop_timer(struct qemu_alarm_timer *t);
973 #endif /* __linux__ */
975 #endif /* _WIN32 */
977 /* Correlation between real and virtual time is always going to be
978 fairly approximate, so ignore small variation.
979 When the guest is idle real and virtual time will be aligned in
980 the IO wait loop. */
981 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
983 static void icount_adjust(void)
985 int64_t cur_time;
986 int64_t cur_icount;
987 int64_t delta;
988 static int64_t last_delta;
989 /* If the VM is not running, then do nothing. */
990 if (!vm_running)
991 return;
993 cur_time = cpu_get_clock();
994 cur_icount = qemu_get_clock(vm_clock);
995 delta = cur_icount - cur_time;
996 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
997 if (delta > 0
998 && last_delta + ICOUNT_WOBBLE < delta * 2
999 && icount_time_shift > 0) {
1000 /* The guest is getting too far ahead. Slow time down. */
1001 icount_time_shift--;
1003 if (delta < 0
1004 && last_delta - ICOUNT_WOBBLE > delta * 2
1005 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1006 /* The guest is getting too far behind. Speed time up. */
1007 icount_time_shift++;
1009 last_delta = delta;
1010 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1013 static void icount_adjust_rt(void * opaque)
1015 qemu_mod_timer(icount_rt_timer,
1016 qemu_get_clock(rt_clock) + 1000);
1017 icount_adjust();
1020 static void icount_adjust_vm(void * opaque)
1022 qemu_mod_timer(icount_vm_timer,
1023 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1024 icount_adjust();
1027 static void init_icount_adjust(void)
1029 /* Have both realtime and virtual time triggers for speed adjustment.
1030 The realtime trigger catches emulated time passing too slowly,
1031 the virtual time trigger catches emulated time passing too fast.
1032 Realtime triggers occur even when idle, so use them less frequently
1033 than VM triggers. */
1034 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1035 qemu_mod_timer(icount_rt_timer,
1036 qemu_get_clock(rt_clock) + 1000);
1037 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1038 qemu_mod_timer(icount_vm_timer,
1039 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1042 static struct qemu_alarm_timer alarm_timers[] = {
1043 #ifndef _WIN32
1044 #ifdef __linux__
1045 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1046 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1047 /* HPET - if available - is preferred */
1048 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1049 /* ...otherwise try RTC */
1050 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1051 #endif
1052 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1053 #else
1054 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1055 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1056 {"win32", 0, win32_start_timer,
1057 win32_stop_timer, NULL, &alarm_win32_data},
1058 #endif
1059 {NULL, }
1062 static void show_available_alarms(void)
1064 int i;
1066 printf("Available alarm timers, in order of precedence:\n");
1067 for (i = 0; alarm_timers[i].name; i++)
1068 printf("%s\n", alarm_timers[i].name);
1071 static void configure_alarms(char const *opt)
1073 int i;
1074 int cur = 0;
1075 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1076 char *arg;
1077 char *name;
1078 struct qemu_alarm_timer tmp;
1080 if (!strcmp(opt, "?")) {
1081 show_available_alarms();
1082 exit(0);
1085 arg = strdup(opt);
1087 /* Reorder the array */
1088 name = strtok(arg, ",");
1089 while (name) {
1090 for (i = 0; i < count && alarm_timers[i].name; i++) {
1091 if (!strcmp(alarm_timers[i].name, name))
1092 break;
1095 if (i == count) {
1096 fprintf(stderr, "Unknown clock %s\n", name);
1097 goto next;
1100 if (i < cur)
1101 /* Ignore */
1102 goto next;
1104 /* Swap */
1105 tmp = alarm_timers[i];
1106 alarm_timers[i] = alarm_timers[cur];
1107 alarm_timers[cur] = tmp;
1109 cur++;
1110 next:
1111 name = strtok(NULL, ",");
1114 free(arg);
1116 if (cur) {
1117 /* Disable remaining timers */
1118 for (i = cur; i < count; i++)
1119 alarm_timers[i].name = NULL;
1120 } else {
1121 show_available_alarms();
1122 exit(1);
1126 QEMUClock *rt_clock;
1127 QEMUClock *vm_clock;
1129 static QEMUTimer *active_timers[2];
1131 static QEMUClock *qemu_new_clock(int type)
1133 QEMUClock *clock;
1134 clock = qemu_mallocz(sizeof(QEMUClock));
1135 if (!clock)
1136 return NULL;
1137 clock->type = type;
1138 return clock;
1141 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1143 QEMUTimer *ts;
1145 ts = qemu_mallocz(sizeof(QEMUTimer));
1146 ts->clock = clock;
1147 ts->cb = cb;
1148 ts->opaque = opaque;
1149 return ts;
1152 void qemu_free_timer(QEMUTimer *ts)
1154 qemu_free(ts);
1157 /* stop a timer, but do not dealloc it */
1158 void qemu_del_timer(QEMUTimer *ts)
1160 QEMUTimer **pt, *t;
1162 /* NOTE: this code must be signal safe because
1163 qemu_timer_expired() can be called from a signal. */
1164 pt = &active_timers[ts->clock->type];
1165 for(;;) {
1166 t = *pt;
1167 if (!t)
1168 break;
1169 if (t == ts) {
1170 *pt = t->next;
1171 break;
1173 pt = &t->next;
1177 /* modify the current timer so that it will be fired when current_time
1178 >= expire_time. The corresponding callback will be called. */
1179 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1181 QEMUTimer **pt, *t;
1183 qemu_del_timer(ts);
1185 /* add the timer in the sorted list */
1186 /* NOTE: this code must be signal safe because
1187 qemu_timer_expired() can be called from a signal. */
1188 pt = &active_timers[ts->clock->type];
1189 for(;;) {
1190 t = *pt;
1191 if (!t)
1192 break;
1193 if (t->expire_time > expire_time)
1194 break;
1195 pt = &t->next;
1197 ts->expire_time = expire_time;
1198 ts->next = *pt;
1199 *pt = ts;
1201 /* Rearm if necessary */
1202 if (pt == &active_timers[ts->clock->type]) {
1203 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1204 qemu_rearm_alarm_timer(alarm_timer);
1206 /* Interrupt execution to force deadline recalculation. */
1207 if (use_icount && cpu_single_env) {
1208 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1213 int qemu_timer_pending(QEMUTimer *ts)
1215 QEMUTimer *t;
1216 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1217 if (t == ts)
1218 return 1;
1220 return 0;
1223 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1225 if (!timer_head)
1226 return 0;
1227 return (timer_head->expire_time <= current_time);
1230 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1232 QEMUTimer *ts;
1234 for(;;) {
1235 ts = *ptimer_head;
1236 if (!ts || ts->expire_time > current_time)
1237 break;
1238 /* remove timer from the list before calling the callback */
1239 *ptimer_head = ts->next;
1240 ts->next = NULL;
1242 /* run the callback (the timer list can be modified) */
1243 ts->cb(ts->opaque);
1247 int64_t qemu_get_clock(QEMUClock *clock)
1249 switch(clock->type) {
1250 case QEMU_TIMER_REALTIME:
1251 return get_clock() / 1000000;
1252 default:
1253 case QEMU_TIMER_VIRTUAL:
1254 if (use_icount) {
1255 return cpu_get_icount();
1256 } else {
1257 return cpu_get_clock();
1262 static void init_timers(void)
1264 init_get_clock();
1265 ticks_per_sec = QEMU_TIMER_BASE;
1266 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1267 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1270 /* save a timer */
1271 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1273 uint64_t expire_time;
1275 if (qemu_timer_pending(ts)) {
1276 expire_time = ts->expire_time;
1277 } else {
1278 expire_time = -1;
1280 qemu_put_be64(f, expire_time);
1283 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1285 uint64_t expire_time;
1287 expire_time = qemu_get_be64(f);
1288 if (expire_time != -1) {
1289 qemu_mod_timer(ts, expire_time);
1290 } else {
1291 qemu_del_timer(ts);
1295 static void timer_save(QEMUFile *f, void *opaque)
1297 if (cpu_ticks_enabled) {
1298 hw_error("cannot save state if virtual timers are running");
1300 qemu_put_be64(f, cpu_ticks_offset);
1301 qemu_put_be64(f, ticks_per_sec);
1302 qemu_put_be64(f, cpu_clock_offset);
1305 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1307 if (version_id != 1 && version_id != 2)
1308 return -EINVAL;
1309 if (cpu_ticks_enabled) {
1310 return -EINVAL;
1312 cpu_ticks_offset=qemu_get_be64(f);
1313 ticks_per_sec=qemu_get_be64(f);
1314 if (version_id == 2) {
1315 cpu_clock_offset=qemu_get_be64(f);
1317 return 0;
1320 #ifdef _WIN32
1321 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1322 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1323 #else
1324 static void host_alarm_handler(int host_signum)
1325 #endif
1327 #if 0
1328 #define DISP_FREQ 1000
1330 static int64_t delta_min = INT64_MAX;
1331 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1332 static int count;
1333 ti = qemu_get_clock(vm_clock);
1334 if (last_clock != 0) {
1335 delta = ti - last_clock;
1336 if (delta < delta_min)
1337 delta_min = delta;
1338 if (delta > delta_max)
1339 delta_max = delta;
1340 delta_cum += delta;
1341 if (++count == DISP_FREQ) {
1342 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1343 muldiv64(delta_min, 1000000, ticks_per_sec),
1344 muldiv64(delta_max, 1000000, ticks_per_sec),
1345 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1346 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1347 count = 0;
1348 delta_min = INT64_MAX;
1349 delta_max = 0;
1350 delta_cum = 0;
1353 last_clock = ti;
1355 #endif
1356 if (1 ||
1357 alarm_has_dynticks(alarm_timer) ||
1358 (!use_icount &&
1359 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1360 qemu_get_clock(vm_clock))) ||
1361 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1362 qemu_get_clock(rt_clock))) {
1363 #ifdef _WIN32
1364 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1365 SetEvent(data->host_alarm);
1366 #endif
1367 CPUState *env = next_cpu;
1369 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1371 if (env) {
1372 /* stop the currently executing cpu because a timer occured */
1373 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1374 #ifdef USE_KQEMU
1375 if (env->kqemu_enabled) {
1376 kqemu_cpu_interrupt(env);
1378 #endif
1380 event_pending = 1;
1384 static int64_t qemu_next_deadline(void)
1386 int64_t delta;
1388 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1389 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1390 qemu_get_clock(vm_clock);
1391 } else {
1392 /* To avoid problems with overflow limit this to 2^32. */
1393 delta = INT32_MAX;
1396 if (delta < 0)
1397 delta = 0;
1399 return delta;
1402 static uint64_t qemu_next_deadline_dyntick(void)
1404 int64_t delta;
1405 int64_t rtdelta;
1407 if (use_icount)
1408 delta = INT32_MAX;
1409 else
1410 delta = (qemu_next_deadline() + 999) / 1000;
1412 if (active_timers[QEMU_TIMER_REALTIME]) {
1413 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1414 qemu_get_clock(rt_clock))*1000;
1415 if (rtdelta < delta)
1416 delta = rtdelta;
1419 if (delta < MIN_TIMER_REARM_US)
1420 delta = MIN_TIMER_REARM_US;
1422 return delta;
1425 #ifndef _WIN32
1427 #if defined(__linux__)
1429 #define RTC_FREQ 1024
1431 static void enable_sigio_timer(int fd)
1433 struct sigaction act;
1435 /* timer signal */
1436 sigfillset(&act.sa_mask);
1437 act.sa_flags = 0;
1438 act.sa_handler = host_alarm_handler;
1440 sigaction(SIGIO, &act, NULL);
1441 fcntl(fd, F_SETFL, O_ASYNC);
1442 fcntl(fd, F_SETOWN, getpid());
1445 static int hpet_start_timer(struct qemu_alarm_timer *t)
1447 struct hpet_info info;
1448 int r, fd;
1450 fd = open("/dev/hpet", O_RDONLY);
1451 if (fd < 0)
1452 return -1;
1454 /* Set frequency */
1455 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1456 if (r < 0) {
1457 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1458 "error, but for better emulation accuracy type:\n"
1459 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1460 goto fail;
1463 /* Check capabilities */
1464 r = ioctl(fd, HPET_INFO, &info);
1465 if (r < 0)
1466 goto fail;
1468 /* Enable periodic mode */
1469 r = ioctl(fd, HPET_EPI, 0);
1470 if (info.hi_flags && (r < 0))
1471 goto fail;
1473 /* Enable interrupt */
1474 r = ioctl(fd, HPET_IE_ON, 0);
1475 if (r < 0)
1476 goto fail;
1478 enable_sigio_timer(fd);
1479 t->priv = (void *)(long)fd;
1481 return 0;
1482 fail:
1483 close(fd);
1484 return -1;
1487 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1489 int fd = (long)t->priv;
1491 close(fd);
1494 static int rtc_start_timer(struct qemu_alarm_timer *t)
1496 int rtc_fd;
1497 unsigned long current_rtc_freq = 0;
1499 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1500 if (rtc_fd < 0)
1501 return -1;
1502 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1503 if (current_rtc_freq != RTC_FREQ &&
1504 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1505 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1506 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1507 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1508 goto fail;
1510 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1511 fail:
1512 close(rtc_fd);
1513 return -1;
1516 enable_sigio_timer(rtc_fd);
1518 t->priv = (void *)(long)rtc_fd;
1520 return 0;
1523 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1525 int rtc_fd = (long)t->priv;
1527 close(rtc_fd);
1530 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1532 struct sigevent ev;
1533 timer_t host_timer;
1534 struct sigaction act;
1536 sigfillset(&act.sa_mask);
1537 act.sa_flags = 0;
1538 act.sa_handler = host_alarm_handler;
1540 sigaction(SIGALRM, &act, NULL);
1542 ev.sigev_value.sival_int = 0;
1543 ev.sigev_notify = SIGEV_SIGNAL;
1544 ev.sigev_signo = SIGALRM;
1546 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1547 perror("timer_create");
1549 /* disable dynticks */
1550 fprintf(stderr, "Dynamic Ticks disabled\n");
1552 return -1;
1555 t->priv = (void *)host_timer;
1557 return 0;
1560 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1562 timer_t host_timer = (timer_t)t->priv;
1564 timer_delete(host_timer);
1567 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1569 timer_t host_timer = (timer_t)t->priv;
1570 struct itimerspec timeout;
1571 int64_t nearest_delta_us = INT64_MAX;
1572 int64_t current_us;
1574 if (!active_timers[QEMU_TIMER_REALTIME] &&
1575 !active_timers[QEMU_TIMER_VIRTUAL])
1576 return;
1578 nearest_delta_us = qemu_next_deadline_dyntick();
1580 /* check whether a timer is already running */
1581 if (timer_gettime(host_timer, &timeout)) {
1582 perror("gettime");
1583 fprintf(stderr, "Internal timer error: aborting\n");
1584 exit(1);
1586 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1587 if (current_us && current_us <= nearest_delta_us)
1588 return;
1590 timeout.it_interval.tv_sec = 0;
1591 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1592 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1593 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1594 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1595 perror("settime");
1596 fprintf(stderr, "Internal timer error: aborting\n");
1597 exit(1);
1601 #endif /* defined(__linux__) */
1603 static int unix_start_timer(struct qemu_alarm_timer *t)
1605 struct sigaction act;
1606 struct itimerval itv;
1607 int err;
1609 /* timer signal */
1610 sigfillset(&act.sa_mask);
1611 act.sa_flags = 0;
1612 act.sa_handler = host_alarm_handler;
1614 sigaction(SIGALRM, &act, NULL);
1616 itv.it_interval.tv_sec = 0;
1617 /* for i386 kernel 2.6 to get 1 ms */
1618 itv.it_interval.tv_usec = 999;
1619 itv.it_value.tv_sec = 0;
1620 itv.it_value.tv_usec = 10 * 1000;
1622 err = setitimer(ITIMER_REAL, &itv, NULL);
1623 if (err)
1624 return -1;
1626 return 0;
1629 static void unix_stop_timer(struct qemu_alarm_timer *t)
1631 struct itimerval itv;
1633 memset(&itv, 0, sizeof(itv));
1634 setitimer(ITIMER_REAL, &itv, NULL);
1637 #endif /* !defined(_WIN32) */
1639 #ifdef _WIN32
1641 static int win32_start_timer(struct qemu_alarm_timer *t)
1643 TIMECAPS tc;
1644 struct qemu_alarm_win32 *data = t->priv;
1645 UINT flags;
1647 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1648 if (!data->host_alarm) {
1649 perror("Failed CreateEvent");
1650 return -1;
1653 memset(&tc, 0, sizeof(tc));
1654 timeGetDevCaps(&tc, sizeof(tc));
1656 if (data->period < tc.wPeriodMin)
1657 data->period = tc.wPeriodMin;
1659 timeBeginPeriod(data->period);
1661 flags = TIME_CALLBACK_FUNCTION;
1662 if (alarm_has_dynticks(t))
1663 flags |= TIME_ONESHOT;
1664 else
1665 flags |= TIME_PERIODIC;
1667 data->timerId = timeSetEvent(1, // interval (ms)
1668 data->period, // resolution
1669 host_alarm_handler, // function
1670 (DWORD)t, // parameter
1671 flags);
1673 if (!data->timerId) {
1674 perror("Failed to initialize win32 alarm timer");
1676 timeEndPeriod(data->period);
1677 CloseHandle(data->host_alarm);
1678 return -1;
1681 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1683 return 0;
1686 static void win32_stop_timer(struct qemu_alarm_timer *t)
1688 struct qemu_alarm_win32 *data = t->priv;
1690 timeKillEvent(data->timerId);
1691 timeEndPeriod(data->period);
1693 CloseHandle(data->host_alarm);
1696 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1698 struct qemu_alarm_win32 *data = t->priv;
1699 uint64_t nearest_delta_us;
1701 if (!active_timers[QEMU_TIMER_REALTIME] &&
1702 !active_timers[QEMU_TIMER_VIRTUAL])
1703 return;
1705 nearest_delta_us = qemu_next_deadline_dyntick();
1706 nearest_delta_us /= 1000;
1708 timeKillEvent(data->timerId);
1710 data->timerId = timeSetEvent(1,
1711 data->period,
1712 host_alarm_handler,
1713 (DWORD)t,
1714 TIME_ONESHOT | TIME_PERIODIC);
1716 if (!data->timerId) {
1717 perror("Failed to re-arm win32 alarm timer");
1719 timeEndPeriod(data->period);
1720 CloseHandle(data->host_alarm);
1721 exit(1);
1725 #endif /* _WIN32 */
1727 static void init_timer_alarm(void)
1729 struct qemu_alarm_timer *t;
1730 int i, err = -1;
1732 for (i = 0; alarm_timers[i].name; i++) {
1733 t = &alarm_timers[i];
1735 err = t->start(t);
1736 if (!err)
1737 break;
1740 if (err) {
1741 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1742 fprintf(stderr, "Terminating\n");
1743 exit(1);
1746 alarm_timer = t;
1749 static void quit_timers(void)
1751 alarm_timer->stop(alarm_timer);
1752 alarm_timer = NULL;
1755 /***********************************************************/
1756 /* host time/date access */
1757 void qemu_get_timedate(struct tm *tm, int offset)
1759 time_t ti;
1760 struct tm *ret;
1762 time(&ti);
1763 ti += offset;
1764 if (rtc_date_offset == -1) {
1765 if (rtc_utc)
1766 ret = gmtime(&ti);
1767 else
1768 ret = localtime(&ti);
1769 } else {
1770 ti -= rtc_date_offset;
1771 ret = gmtime(&ti);
1774 memcpy(tm, ret, sizeof(struct tm));
1777 int qemu_timedate_diff(struct tm *tm)
1779 time_t seconds;
1781 if (rtc_date_offset == -1)
1782 if (rtc_utc)
1783 seconds = mktimegm(tm);
1784 else
1785 seconds = mktime(tm);
1786 else
1787 seconds = mktimegm(tm) + rtc_date_offset;
1789 return seconds - time(NULL);
1792 /***********************************************************/
1793 /* character device */
1795 static void qemu_chr_event(CharDriverState *s, int event)
1797 if (!s->chr_event)
1798 return;
1799 s->chr_event(s->handler_opaque, event);
1802 static void qemu_chr_reset_bh(void *opaque)
1804 CharDriverState *s = opaque;
1805 qemu_chr_event(s, CHR_EVENT_RESET);
1806 qemu_bh_delete(s->bh);
1807 s->bh = NULL;
1810 void qemu_chr_reset(CharDriverState *s)
1812 if (s->bh == NULL) {
1813 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1814 qemu_bh_schedule(s->bh);
1818 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1820 return s->chr_write(s, buf, len);
1823 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1825 if (!s->chr_ioctl)
1826 return -ENOTSUP;
1827 return s->chr_ioctl(s, cmd, arg);
1830 int qemu_chr_can_read(CharDriverState *s)
1832 if (!s->chr_can_read)
1833 return 0;
1834 return s->chr_can_read(s->handler_opaque);
1837 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1839 s->chr_read(s->handler_opaque, buf, len);
1842 void qemu_chr_accept_input(CharDriverState *s)
1844 if (s->chr_accept_input)
1845 s->chr_accept_input(s);
1848 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1850 char buf[4096];
1851 va_list ap;
1852 va_start(ap, fmt);
1853 vsnprintf(buf, sizeof(buf), fmt, ap);
1854 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1855 va_end(ap);
1858 void qemu_chr_send_event(CharDriverState *s, int event)
1860 if (s->chr_send_event)
1861 s->chr_send_event(s, event);
1864 void qemu_chr_add_handlers(CharDriverState *s,
1865 IOCanRWHandler *fd_can_read,
1866 IOReadHandler *fd_read,
1867 IOEventHandler *fd_event,
1868 void *opaque)
1870 s->chr_can_read = fd_can_read;
1871 s->chr_read = fd_read;
1872 s->chr_event = fd_event;
1873 s->handler_opaque = opaque;
1874 if (s->chr_update_read_handler)
1875 s->chr_update_read_handler(s);
1878 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1880 return len;
1883 static CharDriverState *qemu_chr_open_null(void)
1885 CharDriverState *chr;
1887 chr = qemu_mallocz(sizeof(CharDriverState));
1888 if (!chr)
1889 return NULL;
1890 chr->chr_write = null_chr_write;
1891 return chr;
1894 /* MUX driver for serial I/O splitting */
1895 static int term_timestamps;
1896 static int64_t term_timestamps_start;
1897 #define MAX_MUX 4
1898 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1899 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1900 typedef struct {
1901 IOCanRWHandler *chr_can_read[MAX_MUX];
1902 IOReadHandler *chr_read[MAX_MUX];
1903 IOEventHandler *chr_event[MAX_MUX];
1904 void *ext_opaque[MAX_MUX];
1905 CharDriverState *drv;
1906 unsigned char buffer[MUX_BUFFER_SIZE];
1907 int prod;
1908 int cons;
1909 int mux_cnt;
1910 int term_got_escape;
1911 int max_size;
1912 } MuxDriver;
1915 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1917 MuxDriver *d = chr->opaque;
1918 int ret;
1919 if (!term_timestamps) {
1920 ret = d->drv->chr_write(d->drv, buf, len);
1921 } else {
1922 int i;
1924 ret = 0;
1925 for(i = 0; i < len; i++) {
1926 ret += d->drv->chr_write(d->drv, buf+i, 1);
1927 if (buf[i] == '\n') {
1928 char buf1[64];
1929 int64_t ti;
1930 int secs;
1932 ti = get_clock();
1933 if (term_timestamps_start == -1)
1934 term_timestamps_start = ti;
1935 ti -= term_timestamps_start;
1936 secs = ti / 1000000000;
1937 snprintf(buf1, sizeof(buf1),
1938 "[%02d:%02d:%02d.%03d] ",
1939 secs / 3600,
1940 (secs / 60) % 60,
1941 secs % 60,
1942 (int)((ti / 1000000) % 1000));
1943 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1947 return ret;
1950 static char *mux_help[] = {
1951 "% h print this help\n\r",
1952 "% x exit emulator\n\r",
1953 "% s save disk data back to file (if -snapshot)\n\r",
1954 "% t toggle console timestamps\n\r"
1955 "% b send break (magic sysrq)\n\r",
1956 "% c switch between console and monitor\n\r",
1957 "% % sends %\n\r",
1958 NULL
1961 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1962 static void mux_print_help(CharDriverState *chr)
1964 int i, j;
1965 char ebuf[15] = "Escape-Char";
1966 char cbuf[50] = "\n\r";
1968 if (term_escape_char > 0 && term_escape_char < 26) {
1969 snprintf(cbuf, sizeof(cbuf), "\n\r");
1970 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1971 } else {
1972 snprintf(cbuf, sizeof(cbuf),
1973 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1974 term_escape_char);
1976 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1977 for (i = 0; mux_help[i] != NULL; i++) {
1978 for (j=0; mux_help[i][j] != '\0'; j++) {
1979 if (mux_help[i][j] == '%')
1980 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1981 else
1982 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1987 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1989 if (d->term_got_escape) {
1990 d->term_got_escape = 0;
1991 if (ch == term_escape_char)
1992 goto send_char;
1993 switch(ch) {
1994 case '?':
1995 case 'h':
1996 mux_print_help(chr);
1997 break;
1998 case 'x':
2000 char *term = "QEMU: Terminated\n\r";
2001 chr->chr_write(chr,(uint8_t *)term,strlen(term));
2002 exit(0);
2003 break;
2005 case 's':
2007 int i;
2008 for (i = 0; i < nb_drives; i++) {
2009 bdrv_commit(drives_table[i].bdrv);
2012 break;
2013 case 'b':
2014 qemu_chr_event(chr, CHR_EVENT_BREAK);
2015 break;
2016 case 'c':
2017 /* Switch to the next registered device */
2018 chr->focus++;
2019 if (chr->focus >= d->mux_cnt)
2020 chr->focus = 0;
2021 break;
2022 case 't':
2023 term_timestamps = !term_timestamps;
2024 term_timestamps_start = -1;
2025 break;
2027 } else if (ch == term_escape_char) {
2028 d->term_got_escape = 1;
2029 } else {
2030 send_char:
2031 return 1;
2033 return 0;
2036 static void mux_chr_accept_input(CharDriverState *chr)
2038 int m = chr->focus;
2039 MuxDriver *d = chr->opaque;
2041 while (d->prod != d->cons &&
2042 d->chr_can_read[m] &&
2043 d->chr_can_read[m](d->ext_opaque[m])) {
2044 d->chr_read[m](d->ext_opaque[m],
2045 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
2049 static int mux_chr_can_read(void *opaque)
2051 CharDriverState *chr = opaque;
2052 MuxDriver *d = chr->opaque;
2054 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2055 return 1;
2056 if (d->chr_can_read[chr->focus])
2057 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2058 return 0;
2061 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2063 CharDriverState *chr = opaque;
2064 MuxDriver *d = chr->opaque;
2065 int m = chr->focus;
2066 int i;
2068 mux_chr_accept_input (opaque);
2070 for(i = 0; i < size; i++)
2071 if (mux_proc_byte(chr, d, buf[i])) {
2072 if (d->prod == d->cons &&
2073 d->chr_can_read[m] &&
2074 d->chr_can_read[m](d->ext_opaque[m]))
2075 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2076 else
2077 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2081 static void mux_chr_event(void *opaque, int event)
2083 CharDriverState *chr = opaque;
2084 MuxDriver *d = chr->opaque;
2085 int i;
2087 /* Send the event to all registered listeners */
2088 for (i = 0; i < d->mux_cnt; i++)
2089 if (d->chr_event[i])
2090 d->chr_event[i](d->ext_opaque[i], event);
2093 static void mux_chr_update_read_handler(CharDriverState *chr)
2095 MuxDriver *d = chr->opaque;
2097 if (d->mux_cnt >= MAX_MUX) {
2098 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2099 return;
2101 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2102 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2103 d->chr_read[d->mux_cnt] = chr->chr_read;
2104 d->chr_event[d->mux_cnt] = chr->chr_event;
2105 /* Fix up the real driver with mux routines */
2106 if (d->mux_cnt == 0) {
2107 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2108 mux_chr_event, chr);
2110 chr->focus = d->mux_cnt;
2111 d->mux_cnt++;
2114 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2116 CharDriverState *chr;
2117 MuxDriver *d;
2119 chr = qemu_mallocz(sizeof(CharDriverState));
2120 if (!chr)
2121 return NULL;
2122 d = qemu_mallocz(sizeof(MuxDriver));
2123 if (!d) {
2124 free(chr);
2125 return NULL;
2128 chr->opaque = d;
2129 d->drv = drv;
2130 chr->focus = -1;
2131 chr->chr_write = mux_chr_write;
2132 chr->chr_update_read_handler = mux_chr_update_read_handler;
2133 chr->chr_accept_input = mux_chr_accept_input;
2134 return chr;
2138 #ifdef _WIN32
2140 static void socket_cleanup(void)
2142 WSACleanup();
2145 static int socket_init(void)
2147 WSADATA Data;
2148 int ret, err;
2150 ret = WSAStartup(MAKEWORD(2,2), &Data);
2151 if (ret != 0) {
2152 err = WSAGetLastError();
2153 fprintf(stderr, "WSAStartup: %d\n", err);
2154 return -1;
2156 atexit(socket_cleanup);
2157 return 0;
2160 static int send_all(int fd, const uint8_t *buf, int len1)
2162 int ret, len;
2164 len = len1;
2165 while (len > 0) {
2166 ret = send(fd, buf, len, 0);
2167 if (ret < 0) {
2168 int errno;
2169 errno = WSAGetLastError();
2170 if (errno != WSAEWOULDBLOCK) {
2171 return -1;
2173 } else if (ret == 0) {
2174 break;
2175 } else {
2176 buf += ret;
2177 len -= ret;
2180 return len1 - len;
2183 void socket_set_nonblock(int fd)
2185 unsigned long opt = 1;
2186 ioctlsocket(fd, FIONBIO, &opt);
2189 #else
2191 static int unix_write(int fd, const uint8_t *buf, int len1)
2193 int ret, len;
2195 len = len1;
2196 while (len > 0) {
2197 ret = write(fd, buf, len);
2198 if (ret < 0) {
2199 if (errno != EINTR && errno != EAGAIN)
2200 return -1;
2201 } else if (ret == 0) {
2202 break;
2203 } else {
2204 buf += ret;
2205 len -= ret;
2208 return len1 - len;
2211 static inline int send_all(int fd, const uint8_t *buf, int len1)
2213 return unix_write(fd, buf, len1);
2216 void socket_set_nonblock(int fd)
2218 int f;
2219 f = fcntl(fd, F_GETFL);
2220 fcntl(fd, F_SETFL, f | O_NONBLOCK);
2222 #endif /* !_WIN32 */
2224 #ifndef _WIN32
2226 typedef struct {
2227 int fd_in, fd_out;
2228 int max_size;
2229 } FDCharDriver;
2231 #define STDIO_MAX_CLIENTS 1
2232 static int stdio_nb_clients = 0;
2234 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2236 FDCharDriver *s = chr->opaque;
2237 return unix_write(s->fd_out, buf, len);
2240 static int fd_chr_read_poll(void *opaque)
2242 CharDriverState *chr = opaque;
2243 FDCharDriver *s = chr->opaque;
2245 s->max_size = qemu_chr_can_read(chr);
2246 return s->max_size;
2249 static void fd_chr_read(void *opaque)
2251 CharDriverState *chr = opaque;
2252 FDCharDriver *s = chr->opaque;
2253 int size, len;
2254 uint8_t buf[1024];
2256 len = sizeof(buf);
2257 if (len > s->max_size)
2258 len = s->max_size;
2259 if (len == 0)
2260 return;
2261 size = read(s->fd_in, buf, len);
2262 if (size == 0) {
2263 /* FD has been closed. Remove it from the active list. */
2264 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2265 return;
2267 if (size > 0) {
2268 qemu_chr_read(chr, buf, size);
2272 static void fd_chr_update_read_handler(CharDriverState *chr)
2274 FDCharDriver *s = chr->opaque;
2276 if (s->fd_in >= 0) {
2277 if (nographic && s->fd_in == 0) {
2278 } else {
2279 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2280 fd_chr_read, NULL, chr);
2285 static void fd_chr_close(struct CharDriverState *chr)
2287 FDCharDriver *s = chr->opaque;
2289 if (s->fd_in >= 0) {
2290 if (nographic && s->fd_in == 0) {
2291 } else {
2292 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2296 qemu_free(s);
2299 /* open a character device to a unix fd */
2300 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2302 CharDriverState *chr;
2303 FDCharDriver *s;
2305 chr = qemu_mallocz(sizeof(CharDriverState));
2306 if (!chr)
2307 return NULL;
2308 s = qemu_mallocz(sizeof(FDCharDriver));
2309 if (!s) {
2310 free(chr);
2311 return NULL;
2313 s->fd_in = fd_in;
2314 s->fd_out = fd_out;
2315 chr->opaque = s;
2316 chr->chr_write = fd_chr_write;
2317 chr->chr_update_read_handler = fd_chr_update_read_handler;
2318 chr->chr_close = fd_chr_close;
2320 qemu_chr_reset(chr);
2322 return chr;
2325 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2327 int fd_out;
2329 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2330 if (fd_out < 0)
2331 return NULL;
2332 return qemu_chr_open_fd(-1, fd_out);
2335 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2337 int fd_in, fd_out;
2338 char filename_in[256], filename_out[256];
2340 snprintf(filename_in, 256, "%s.in", filename);
2341 snprintf(filename_out, 256, "%s.out", filename);
2342 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2343 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2344 if (fd_in < 0 || fd_out < 0) {
2345 if (fd_in >= 0)
2346 close(fd_in);
2347 if (fd_out >= 0)
2348 close(fd_out);
2349 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2350 if (fd_in < 0)
2351 return NULL;
2353 return qemu_chr_open_fd(fd_in, fd_out);
2357 /* for STDIO, we handle the case where several clients use it
2358 (nographic mode) */
2360 #define TERM_FIFO_MAX_SIZE 1
2362 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2363 static int term_fifo_size;
2365 static int stdio_read_poll(void *opaque)
2367 CharDriverState *chr = opaque;
2369 /* try to flush the queue if needed */
2370 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2371 qemu_chr_read(chr, term_fifo, 1);
2372 term_fifo_size = 0;
2374 /* see if we can absorb more chars */
2375 if (term_fifo_size == 0)
2376 return 1;
2377 else
2378 return 0;
2381 static void stdio_read(void *opaque)
2383 int size;
2384 uint8_t buf[1];
2385 CharDriverState *chr = opaque;
2387 size = read(0, buf, 1);
2388 if (size == 0) {
2389 /* stdin has been closed. Remove it from the active list. */
2390 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2391 return;
2393 if (size > 0) {
2394 if (qemu_chr_can_read(chr) > 0) {
2395 qemu_chr_read(chr, buf, 1);
2396 } else if (term_fifo_size == 0) {
2397 term_fifo[term_fifo_size++] = buf[0];
2402 /* init terminal so that we can grab keys */
2403 static struct termios oldtty;
2404 static int old_fd0_flags;
2405 static int term_atexit_done;
2407 static void term_exit(void)
2409 tcsetattr (0, TCSANOW, &oldtty);
2410 fcntl(0, F_SETFL, old_fd0_flags);
2413 static void term_init(void)
2415 struct termios tty;
2417 tcgetattr (0, &tty);
2418 oldtty = tty;
2419 old_fd0_flags = fcntl(0, F_GETFL);
2421 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2422 |INLCR|IGNCR|ICRNL|IXON);
2423 tty.c_oflag |= OPOST;
2424 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2425 /* if graphical mode, we allow Ctrl-C handling */
2426 if (nographic)
2427 tty.c_lflag &= ~ISIG;
2428 tty.c_cflag &= ~(CSIZE|PARENB);
2429 tty.c_cflag |= CS8;
2430 tty.c_cc[VMIN] = 1;
2431 tty.c_cc[VTIME] = 0;
2433 tcsetattr (0, TCSANOW, &tty);
2435 if (!term_atexit_done++)
2436 atexit(term_exit);
2438 fcntl(0, F_SETFL, O_NONBLOCK);
2441 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2443 term_exit();
2444 stdio_nb_clients--;
2445 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2446 fd_chr_close(chr);
2449 static CharDriverState *qemu_chr_open_stdio(void)
2451 CharDriverState *chr;
2453 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2454 return NULL;
2455 chr = qemu_chr_open_fd(0, 1);
2456 chr->chr_close = qemu_chr_close_stdio;
2457 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2458 stdio_nb_clients++;
2459 term_init();
2461 return chr;
2464 #ifdef __sun__
2465 /* Once Solaris has openpty(), this is going to be removed. */
2466 int openpty(int *amaster, int *aslave, char *name,
2467 struct termios *termp, struct winsize *winp)
2469 const char *slave;
2470 int mfd = -1, sfd = -1;
2472 *amaster = *aslave = -1;
2474 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2475 if (mfd < 0)
2476 goto err;
2478 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2479 goto err;
2481 if ((slave = ptsname(mfd)) == NULL)
2482 goto err;
2484 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2485 goto err;
2487 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2488 (termp != NULL && tcgetattr(sfd, termp) < 0))
2489 goto err;
2491 if (amaster)
2492 *amaster = mfd;
2493 if (aslave)
2494 *aslave = sfd;
2495 if (winp)
2496 ioctl(sfd, TIOCSWINSZ, winp);
2498 return 0;
2500 err:
2501 if (sfd != -1)
2502 close(sfd);
2503 close(mfd);
2504 return -1;
2507 void cfmakeraw (struct termios *termios_p)
2509 termios_p->c_iflag &=
2510 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2511 termios_p->c_oflag &= ~OPOST;
2512 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2513 termios_p->c_cflag &= ~(CSIZE|PARENB);
2514 termios_p->c_cflag |= CS8;
2516 termios_p->c_cc[VMIN] = 0;
2517 termios_p->c_cc[VTIME] = 0;
2519 #endif
2521 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2522 || defined(__NetBSD__) || defined(__OpenBSD__)
2524 typedef struct {
2525 int fd;
2526 int connected;
2527 int polling;
2528 int read_bytes;
2529 QEMUTimer *timer;
2530 } PtyCharDriver;
2532 static void pty_chr_update_read_handler(CharDriverState *chr);
2533 static void pty_chr_state(CharDriverState *chr, int connected);
2535 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2537 PtyCharDriver *s = chr->opaque;
2539 if (!s->connected) {
2540 /* guest sends data, check for (re-)connect */
2541 pty_chr_update_read_handler(chr);
2542 return 0;
2544 return unix_write(s->fd, buf, len);
2547 static int pty_chr_read_poll(void *opaque)
2549 CharDriverState *chr = opaque;
2550 PtyCharDriver *s = chr->opaque;
2552 s->read_bytes = qemu_chr_can_read(chr);
2553 return s->read_bytes;
2556 static void pty_chr_read(void *opaque)
2558 CharDriverState *chr = opaque;
2559 PtyCharDriver *s = chr->opaque;
2560 int size, len;
2561 uint8_t buf[1024];
2563 len = sizeof(buf);
2564 if (len > s->read_bytes)
2565 len = s->read_bytes;
2566 if (len == 0)
2567 return;
2568 size = read(s->fd, buf, len);
2569 if ((size == -1 && errno == EIO) ||
2570 (size == 0)) {
2571 pty_chr_state(chr, 0);
2572 return;
2574 if (size > 0) {
2575 pty_chr_state(chr, 1);
2576 qemu_chr_read(chr, buf, size);
2580 static void pty_chr_update_read_handler(CharDriverState *chr)
2582 PtyCharDriver *s = chr->opaque;
2584 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2585 pty_chr_read, NULL, chr);
2586 s->polling = 1;
2588 * Short timeout here: just need wait long enougth that qemu makes
2589 * it through the poll loop once. When reconnected we want a
2590 * short timeout so we notice it almost instantly. Otherwise
2591 * read() gives us -EIO instantly, making pty_chr_state() reset the
2592 * timeout to the normal (much longer) poll interval before the
2593 * timer triggers.
2595 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2598 static void pty_chr_state(CharDriverState *chr, int connected)
2600 PtyCharDriver *s = chr->opaque;
2602 if (!connected) {
2603 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2604 s->connected = 0;
2605 s->polling = 0;
2606 /* (re-)connect poll interval for idle guests: once per second.
2607 * We check more frequently in case the guests sends data to
2608 * the virtual device linked to our pty. */
2609 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2610 } else {
2611 if (!s->connected)
2612 qemu_chr_reset(chr);
2613 s->connected = 1;
2617 static void pty_chr_timer(void *opaque)
2619 struct CharDriverState *chr = opaque;
2620 PtyCharDriver *s = chr->opaque;
2622 if (s->connected)
2623 return;
2624 if (s->polling) {
2625 /* If we arrive here without polling being cleared due
2626 * read returning -EIO, then we are (re-)connected */
2627 pty_chr_state(chr, 1);
2628 return;
2631 /* Next poll ... */
2632 pty_chr_update_read_handler(chr);
2635 static void pty_chr_close(struct CharDriverState *chr)
2637 PtyCharDriver *s = chr->opaque;
2639 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2640 close(s->fd);
2641 qemu_free(s);
2644 static CharDriverState *qemu_chr_open_pty(void)
2646 CharDriverState *chr;
2647 PtyCharDriver *s;
2648 struct termios tty;
2649 int slave_fd;
2650 #if defined(__OpenBSD__)
2651 char pty_name[PATH_MAX];
2652 #define q_ptsname(x) pty_name
2653 #else
2654 char *pty_name = NULL;
2655 #define q_ptsname(x) ptsname(x)
2656 #endif
2658 chr = qemu_mallocz(sizeof(CharDriverState));
2659 if (!chr)
2660 return NULL;
2661 s = qemu_mallocz(sizeof(PtyCharDriver));
2662 if (!s) {
2663 qemu_free(chr);
2664 return NULL;
2667 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2668 return NULL;
2671 /* Set raw attributes on the pty. */
2672 cfmakeraw(&tty);
2673 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2674 close(slave_fd);
2676 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2678 chr->opaque = s;
2679 chr->chr_write = pty_chr_write;
2680 chr->chr_update_read_handler = pty_chr_update_read_handler;
2681 chr->chr_close = pty_chr_close;
2683 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2685 return chr;
2688 static void tty_serial_init(int fd, int speed,
2689 int parity, int data_bits, int stop_bits)
2691 struct termios tty;
2692 speed_t spd;
2694 #if 0
2695 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2696 speed, parity, data_bits, stop_bits);
2697 #endif
2698 tcgetattr (fd, &tty);
2700 #define MARGIN 1.1
2701 if (speed <= 50 * MARGIN)
2702 spd = B50;
2703 else if (speed <= 75 * MARGIN)
2704 spd = B75;
2705 else if (speed <= 300 * MARGIN)
2706 spd = B300;
2707 else if (speed <= 600 * MARGIN)
2708 spd = B600;
2709 else if (speed <= 1200 * MARGIN)
2710 spd = B1200;
2711 else if (speed <= 2400 * MARGIN)
2712 spd = B2400;
2713 else if (speed <= 4800 * MARGIN)
2714 spd = B4800;
2715 else if (speed <= 9600 * MARGIN)
2716 spd = B9600;
2717 else if (speed <= 19200 * MARGIN)
2718 spd = B19200;
2719 else if (speed <= 38400 * MARGIN)
2720 spd = B38400;
2721 else if (speed <= 57600 * MARGIN)
2722 spd = B57600;
2723 else if (speed <= 115200 * MARGIN)
2724 spd = B115200;
2725 else
2726 spd = B115200;
2728 cfsetispeed(&tty, spd);
2729 cfsetospeed(&tty, spd);
2731 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2732 |INLCR|IGNCR|ICRNL|IXON);
2733 tty.c_oflag |= OPOST;
2734 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2735 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2736 switch(data_bits) {
2737 default:
2738 case 8:
2739 tty.c_cflag |= CS8;
2740 break;
2741 case 7:
2742 tty.c_cflag |= CS7;
2743 break;
2744 case 6:
2745 tty.c_cflag |= CS6;
2746 break;
2747 case 5:
2748 tty.c_cflag |= CS5;
2749 break;
2751 switch(parity) {
2752 default:
2753 case 'N':
2754 break;
2755 case 'E':
2756 tty.c_cflag |= PARENB;
2757 break;
2758 case 'O':
2759 tty.c_cflag |= PARENB | PARODD;
2760 break;
2762 if (stop_bits == 2)
2763 tty.c_cflag |= CSTOPB;
2765 tcsetattr (fd, TCSANOW, &tty);
2768 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2770 FDCharDriver *s = chr->opaque;
2772 switch(cmd) {
2773 case CHR_IOCTL_SERIAL_SET_PARAMS:
2775 QEMUSerialSetParams *ssp = arg;
2776 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2777 ssp->data_bits, ssp->stop_bits);
2779 break;
2780 case CHR_IOCTL_SERIAL_SET_BREAK:
2782 int enable = *(int *)arg;
2783 if (enable)
2784 tcsendbreak(s->fd_in, 1);
2786 break;
2787 case CHR_IOCTL_SERIAL_GET_TIOCM:
2789 int sarg = 0;
2790 int *targ = (int *)arg;
2791 ioctl(s->fd_in, TIOCMGET, &sarg);
2792 *targ = 0;
2793 if (sarg | TIOCM_CTS)
2794 *targ |= CHR_TIOCM_CTS;
2795 if (sarg | TIOCM_CAR)
2796 *targ |= CHR_TIOCM_CAR;
2797 if (sarg | TIOCM_DSR)
2798 *targ |= CHR_TIOCM_DSR;
2799 if (sarg | TIOCM_RI)
2800 *targ |= CHR_TIOCM_RI;
2801 if (sarg | TIOCM_DTR)
2802 *targ |= CHR_TIOCM_DTR;
2803 if (sarg | TIOCM_RTS)
2804 *targ |= CHR_TIOCM_RTS;
2806 break;
2807 case CHR_IOCTL_SERIAL_SET_TIOCM:
2809 int sarg = *(int *)arg;
2810 int targ = 0;
2811 if (sarg | CHR_TIOCM_DTR)
2812 targ |= TIOCM_DTR;
2813 if (sarg | CHR_TIOCM_RTS)
2814 targ |= TIOCM_RTS;
2815 ioctl(s->fd_in, TIOCMSET, &targ);
2817 break;
2818 default:
2819 return -ENOTSUP;
2821 return 0;
2824 static CharDriverState *qemu_chr_open_tty(const char *filename)
2826 CharDriverState *chr;
2827 int fd;
2829 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2830 tty_serial_init(fd, 115200, 'N', 8, 1);
2831 chr = qemu_chr_open_fd(fd, fd);
2832 if (!chr) {
2833 close(fd);
2834 return NULL;
2836 chr->chr_ioctl = tty_serial_ioctl;
2837 qemu_chr_reset(chr);
2838 return chr;
2840 #else /* ! __linux__ && ! __sun__ */
2841 static CharDriverState *qemu_chr_open_pty(void)
2843 return NULL;
2845 #endif /* __linux__ || __sun__ */
2847 #if defined(__linux__)
2848 typedef struct {
2849 int fd;
2850 int mode;
2851 } ParallelCharDriver;
2853 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2855 if (s->mode != mode) {
2856 int m = mode;
2857 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2858 return 0;
2859 s->mode = mode;
2861 return 1;
2864 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2866 ParallelCharDriver *drv = chr->opaque;
2867 int fd = drv->fd;
2868 uint8_t b;
2870 switch(cmd) {
2871 case CHR_IOCTL_PP_READ_DATA:
2872 if (ioctl(fd, PPRDATA, &b) < 0)
2873 return -ENOTSUP;
2874 *(uint8_t *)arg = b;
2875 break;
2876 case CHR_IOCTL_PP_WRITE_DATA:
2877 b = *(uint8_t *)arg;
2878 if (ioctl(fd, PPWDATA, &b) < 0)
2879 return -ENOTSUP;
2880 break;
2881 case CHR_IOCTL_PP_READ_CONTROL:
2882 if (ioctl(fd, PPRCONTROL, &b) < 0)
2883 return -ENOTSUP;
2884 /* Linux gives only the lowest bits, and no way to know data
2885 direction! For better compatibility set the fixed upper
2886 bits. */
2887 *(uint8_t *)arg = b | 0xc0;
2888 break;
2889 case CHR_IOCTL_PP_WRITE_CONTROL:
2890 b = *(uint8_t *)arg;
2891 if (ioctl(fd, PPWCONTROL, &b) < 0)
2892 return -ENOTSUP;
2893 break;
2894 case CHR_IOCTL_PP_READ_STATUS:
2895 if (ioctl(fd, PPRSTATUS, &b) < 0)
2896 return -ENOTSUP;
2897 *(uint8_t *)arg = b;
2898 break;
2899 case CHR_IOCTL_PP_DATA_DIR:
2900 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2901 return -ENOTSUP;
2902 break;
2903 case CHR_IOCTL_PP_EPP_READ_ADDR:
2904 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2905 struct ParallelIOArg *parg = arg;
2906 int n = read(fd, parg->buffer, parg->count);
2907 if (n != parg->count) {
2908 return -EIO;
2911 break;
2912 case CHR_IOCTL_PP_EPP_READ:
2913 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2914 struct ParallelIOArg *parg = arg;
2915 int n = read(fd, parg->buffer, parg->count);
2916 if (n != parg->count) {
2917 return -EIO;
2920 break;
2921 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2922 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2923 struct ParallelIOArg *parg = arg;
2924 int n = write(fd, parg->buffer, parg->count);
2925 if (n != parg->count) {
2926 return -EIO;
2929 break;
2930 case CHR_IOCTL_PP_EPP_WRITE:
2931 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2932 struct ParallelIOArg *parg = arg;
2933 int n = write(fd, parg->buffer, parg->count);
2934 if (n != parg->count) {
2935 return -EIO;
2938 break;
2939 default:
2940 return -ENOTSUP;
2942 return 0;
2945 static void pp_close(CharDriverState *chr)
2947 ParallelCharDriver *drv = chr->opaque;
2948 int fd = drv->fd;
2950 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2951 ioctl(fd, PPRELEASE);
2952 close(fd);
2953 qemu_free(drv);
2956 static CharDriverState *qemu_chr_open_pp(const char *filename)
2958 CharDriverState *chr;
2959 ParallelCharDriver *drv;
2960 int fd;
2962 TFR(fd = open(filename, O_RDWR));
2963 if (fd < 0)
2964 return NULL;
2966 if (ioctl(fd, PPCLAIM) < 0) {
2967 close(fd);
2968 return NULL;
2971 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2972 if (!drv) {
2973 close(fd);
2974 return NULL;
2976 drv->fd = fd;
2977 drv->mode = IEEE1284_MODE_COMPAT;
2979 chr = qemu_mallocz(sizeof(CharDriverState));
2980 if (!chr) {
2981 qemu_free(drv);
2982 close(fd);
2983 return NULL;
2985 chr->chr_write = null_chr_write;
2986 chr->chr_ioctl = pp_ioctl;
2987 chr->chr_close = pp_close;
2988 chr->opaque = drv;
2990 qemu_chr_reset(chr);
2992 return chr;
2994 #endif /* __linux__ */
2996 #else /* _WIN32 */
2998 typedef struct {
2999 int max_size;
3000 HANDLE hcom, hrecv, hsend;
3001 OVERLAPPED orecv, osend;
3002 BOOL fpipe;
3003 DWORD len;
3004 } WinCharState;
3006 #define NSENDBUF 2048
3007 #define NRECVBUF 2048
3008 #define MAXCONNECT 1
3009 #define NTIMEOUT 5000
3011 static int win_chr_poll(void *opaque);
3012 static int win_chr_pipe_poll(void *opaque);
3014 static void win_chr_close(CharDriverState *chr)
3016 WinCharState *s = chr->opaque;
3018 if (s->hsend) {
3019 CloseHandle(s->hsend);
3020 s->hsend = NULL;
3022 if (s->hrecv) {
3023 CloseHandle(s->hrecv);
3024 s->hrecv = NULL;
3026 if (s->hcom) {
3027 CloseHandle(s->hcom);
3028 s->hcom = NULL;
3030 if (s->fpipe)
3031 qemu_del_polling_cb(win_chr_pipe_poll, chr);
3032 else
3033 qemu_del_polling_cb(win_chr_poll, chr);
3036 static int win_chr_init(CharDriverState *chr, const char *filename)
3038 WinCharState *s = chr->opaque;
3039 COMMCONFIG comcfg;
3040 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
3041 COMSTAT comstat;
3042 DWORD size;
3043 DWORD err;
3045 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3046 if (!s->hsend) {
3047 fprintf(stderr, "Failed CreateEvent\n");
3048 goto fail;
3050 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3051 if (!s->hrecv) {
3052 fprintf(stderr, "Failed CreateEvent\n");
3053 goto fail;
3056 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
3057 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
3058 if (s->hcom == INVALID_HANDLE_VALUE) {
3059 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
3060 s->hcom = NULL;
3061 goto fail;
3064 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3065 fprintf(stderr, "Failed SetupComm\n");
3066 goto fail;
3069 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3070 size = sizeof(COMMCONFIG);
3071 GetDefaultCommConfig(filename, &comcfg, &size);
3072 comcfg.dcb.DCBlength = sizeof(DCB);
3073 CommConfigDialog(filename, NULL, &comcfg);
3075 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3076 fprintf(stderr, "Failed SetCommState\n");
3077 goto fail;
3080 if (!SetCommMask(s->hcom, EV_ERR)) {
3081 fprintf(stderr, "Failed SetCommMask\n");
3082 goto fail;
3085 cto.ReadIntervalTimeout = MAXDWORD;
3086 if (!SetCommTimeouts(s->hcom, &cto)) {
3087 fprintf(stderr, "Failed SetCommTimeouts\n");
3088 goto fail;
3091 if (!ClearCommError(s->hcom, &err, &comstat)) {
3092 fprintf(stderr, "Failed ClearCommError\n");
3093 goto fail;
3095 qemu_add_polling_cb(win_chr_poll, chr);
3096 return 0;
3098 fail:
3099 win_chr_close(chr);
3100 return -1;
3103 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3105 WinCharState *s = chr->opaque;
3106 DWORD len, ret, size, err;
3108 len = len1;
3109 ZeroMemory(&s->osend, sizeof(s->osend));
3110 s->osend.hEvent = s->hsend;
3111 while (len > 0) {
3112 if (s->hsend)
3113 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3114 else
3115 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3116 if (!ret) {
3117 err = GetLastError();
3118 if (err == ERROR_IO_PENDING) {
3119 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3120 if (ret) {
3121 buf += size;
3122 len -= size;
3123 } else {
3124 break;
3126 } else {
3127 break;
3129 } else {
3130 buf += size;
3131 len -= size;
3134 return len1 - len;
3137 static int win_chr_read_poll(CharDriverState *chr)
3139 WinCharState *s = chr->opaque;
3141 s->max_size = qemu_chr_can_read(chr);
3142 return s->max_size;
3145 static void win_chr_readfile(CharDriverState *chr)
3147 WinCharState *s = chr->opaque;
3148 int ret, err;
3149 uint8_t buf[1024];
3150 DWORD size;
3152 ZeroMemory(&s->orecv, sizeof(s->orecv));
3153 s->orecv.hEvent = s->hrecv;
3154 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3155 if (!ret) {
3156 err = GetLastError();
3157 if (err == ERROR_IO_PENDING) {
3158 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3162 if (size > 0) {
3163 qemu_chr_read(chr, buf, size);
3167 static void win_chr_read(CharDriverState *chr)
3169 WinCharState *s = chr->opaque;
3171 if (s->len > s->max_size)
3172 s->len = s->max_size;
3173 if (s->len == 0)
3174 return;
3176 win_chr_readfile(chr);
3179 static int win_chr_poll(void *opaque)
3181 CharDriverState *chr = opaque;
3182 WinCharState *s = chr->opaque;
3183 COMSTAT status;
3184 DWORD comerr;
3186 ClearCommError(s->hcom, &comerr, &status);
3187 if (status.cbInQue > 0) {
3188 s->len = status.cbInQue;
3189 win_chr_read_poll(chr);
3190 win_chr_read(chr);
3191 return 1;
3193 return 0;
3196 static CharDriverState *qemu_chr_open_win(const char *filename)
3198 CharDriverState *chr;
3199 WinCharState *s;
3201 chr = qemu_mallocz(sizeof(CharDriverState));
3202 if (!chr)
3203 return NULL;
3204 s = qemu_mallocz(sizeof(WinCharState));
3205 if (!s) {
3206 free(chr);
3207 return NULL;
3209 chr->opaque = s;
3210 chr->chr_write = win_chr_write;
3211 chr->chr_close = win_chr_close;
3213 if (win_chr_init(chr, filename) < 0) {
3214 free(s);
3215 free(chr);
3216 return NULL;
3218 qemu_chr_reset(chr);
3219 return chr;
3222 static int win_chr_pipe_poll(void *opaque)
3224 CharDriverState *chr = opaque;
3225 WinCharState *s = chr->opaque;
3226 DWORD size;
3228 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3229 if (size > 0) {
3230 s->len = size;
3231 win_chr_read_poll(chr);
3232 win_chr_read(chr);
3233 return 1;
3235 return 0;
3238 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3240 WinCharState *s = chr->opaque;
3241 OVERLAPPED ov;
3242 int ret;
3243 DWORD size;
3244 char openname[256];
3246 s->fpipe = TRUE;
3248 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3249 if (!s->hsend) {
3250 fprintf(stderr, "Failed CreateEvent\n");
3251 goto fail;
3253 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3254 if (!s->hrecv) {
3255 fprintf(stderr, "Failed CreateEvent\n");
3256 goto fail;
3259 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3260 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3261 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3262 PIPE_WAIT,
3263 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3264 if (s->hcom == INVALID_HANDLE_VALUE) {
3265 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3266 s->hcom = NULL;
3267 goto fail;
3270 ZeroMemory(&ov, sizeof(ov));
3271 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3272 ret = ConnectNamedPipe(s->hcom, &ov);
3273 if (ret) {
3274 fprintf(stderr, "Failed ConnectNamedPipe\n");
3275 goto fail;
3278 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3279 if (!ret) {
3280 fprintf(stderr, "Failed GetOverlappedResult\n");
3281 if (ov.hEvent) {
3282 CloseHandle(ov.hEvent);
3283 ov.hEvent = NULL;
3285 goto fail;
3288 if (ov.hEvent) {
3289 CloseHandle(ov.hEvent);
3290 ov.hEvent = NULL;
3292 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3293 return 0;
3295 fail:
3296 win_chr_close(chr);
3297 return -1;
3301 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3303 CharDriverState *chr;
3304 WinCharState *s;
3306 chr = qemu_mallocz(sizeof(CharDriverState));
3307 if (!chr)
3308 return NULL;
3309 s = qemu_mallocz(sizeof(WinCharState));
3310 if (!s) {
3311 free(chr);
3312 return NULL;
3314 chr->opaque = s;
3315 chr->chr_write = win_chr_write;
3316 chr->chr_close = win_chr_close;
3318 if (win_chr_pipe_init(chr, filename) < 0) {
3319 free(s);
3320 free(chr);
3321 return NULL;
3323 qemu_chr_reset(chr);
3324 return chr;
3327 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3329 CharDriverState *chr;
3330 WinCharState *s;
3332 chr = qemu_mallocz(sizeof(CharDriverState));
3333 if (!chr)
3334 return NULL;
3335 s = qemu_mallocz(sizeof(WinCharState));
3336 if (!s) {
3337 free(chr);
3338 return NULL;
3340 s->hcom = fd_out;
3341 chr->opaque = s;
3342 chr->chr_write = win_chr_write;
3343 qemu_chr_reset(chr);
3344 return chr;
3347 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3349 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3352 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3354 HANDLE fd_out;
3356 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3357 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3358 if (fd_out == INVALID_HANDLE_VALUE)
3359 return NULL;
3361 return qemu_chr_open_win_file(fd_out);
3363 #endif /* !_WIN32 */
3365 /***********************************************************/
3366 /* UDP Net console */
3368 typedef struct {
3369 int fd;
3370 struct sockaddr_in daddr;
3371 uint8_t buf[1024];
3372 int bufcnt;
3373 int bufptr;
3374 int max_size;
3375 } NetCharDriver;
3377 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3379 NetCharDriver *s = chr->opaque;
3381 return sendto(s->fd, buf, len, 0,
3382 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3385 static int udp_chr_read_poll(void *opaque)
3387 CharDriverState *chr = opaque;
3388 NetCharDriver *s = chr->opaque;
3390 s->max_size = qemu_chr_can_read(chr);
3392 /* If there were any stray characters in the queue process them
3393 * first
3395 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3396 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3397 s->bufptr++;
3398 s->max_size = qemu_chr_can_read(chr);
3400 return s->max_size;
3403 static void udp_chr_read(void *opaque)
3405 CharDriverState *chr = opaque;
3406 NetCharDriver *s = chr->opaque;
3408 if (s->max_size == 0)
3409 return;
3410 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3411 s->bufptr = s->bufcnt;
3412 if (s->bufcnt <= 0)
3413 return;
3415 s->bufptr = 0;
3416 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3417 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3418 s->bufptr++;
3419 s->max_size = qemu_chr_can_read(chr);
3423 static void udp_chr_update_read_handler(CharDriverState *chr)
3425 NetCharDriver *s = chr->opaque;
3427 if (s->fd >= 0) {
3428 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3429 udp_chr_read, NULL, chr);
3433 #ifndef _WIN32
3434 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3435 #endif
3436 int parse_host_src_port(struct sockaddr_in *haddr,
3437 struct sockaddr_in *saddr,
3438 const char *str);
3440 static CharDriverState *qemu_chr_open_udp(const char *def)
3442 CharDriverState *chr = NULL;
3443 NetCharDriver *s = NULL;
3444 int fd = -1;
3445 struct sockaddr_in saddr;
3447 chr = qemu_mallocz(sizeof(CharDriverState));
3448 if (!chr)
3449 goto return_err;
3450 s = qemu_mallocz(sizeof(NetCharDriver));
3451 if (!s)
3452 goto return_err;
3454 fd = socket(PF_INET, SOCK_DGRAM, 0);
3455 if (fd < 0) {
3456 perror("socket(PF_INET, SOCK_DGRAM)");
3457 goto return_err;
3460 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3461 printf("Could not parse: %s\n", def);
3462 goto return_err;
3465 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3467 perror("bind");
3468 goto return_err;
3471 s->fd = fd;
3472 s->bufcnt = 0;
3473 s->bufptr = 0;
3474 chr->opaque = s;
3475 chr->chr_write = udp_chr_write;
3476 chr->chr_update_read_handler = udp_chr_update_read_handler;
3477 return chr;
3479 return_err:
3480 if (chr)
3481 free(chr);
3482 if (s)
3483 free(s);
3484 if (fd >= 0)
3485 closesocket(fd);
3486 return NULL;
3489 /***********************************************************/
3490 /* TCP Net console */
3492 typedef struct {
3493 int fd, listen_fd;
3494 int connected;
3495 int max_size;
3496 int do_telnetopt;
3497 int do_nodelay;
3498 int is_unix;
3499 } TCPCharDriver;
3501 static void tcp_chr_accept(void *opaque);
3503 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3505 TCPCharDriver *s = chr->opaque;
3506 if (s->connected) {
3507 return send_all(s->fd, buf, len);
3508 } else {
3509 /* XXX: indicate an error ? */
3510 return len;
3514 static int tcp_chr_read_poll(void *opaque)
3516 CharDriverState *chr = opaque;
3517 TCPCharDriver *s = chr->opaque;
3518 if (!s->connected)
3519 return 0;
3520 s->max_size = qemu_chr_can_read(chr);
3521 return s->max_size;
3524 #define IAC 255
3525 #define IAC_BREAK 243
3526 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3527 TCPCharDriver *s,
3528 uint8_t *buf, int *size)
3530 /* Handle any telnet client's basic IAC options to satisfy char by
3531 * char mode with no echo. All IAC options will be removed from
3532 * the buf and the do_telnetopt variable will be used to track the
3533 * state of the width of the IAC information.
3535 * IAC commands come in sets of 3 bytes with the exception of the
3536 * "IAC BREAK" command and the double IAC.
3539 int i;
3540 int j = 0;
3542 for (i = 0; i < *size; i++) {
3543 if (s->do_telnetopt > 1) {
3544 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3545 /* Double IAC means send an IAC */
3546 if (j != i)
3547 buf[j] = buf[i];
3548 j++;
3549 s->do_telnetopt = 1;
3550 } else {
3551 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3552 /* Handle IAC break commands by sending a serial break */
3553 qemu_chr_event(chr, CHR_EVENT_BREAK);
3554 s->do_telnetopt++;
3556 s->do_telnetopt++;
3558 if (s->do_telnetopt >= 4) {
3559 s->do_telnetopt = 1;
3561 } else {
3562 if ((unsigned char)buf[i] == IAC) {
3563 s->do_telnetopt = 2;
3564 } else {
3565 if (j != i)
3566 buf[j] = buf[i];
3567 j++;
3571 *size = j;
3574 static void tcp_chr_read(void *opaque)
3576 CharDriverState *chr = opaque;
3577 TCPCharDriver *s = chr->opaque;
3578 uint8_t buf[1024];
3579 int len, size;
3581 if (!s->connected || s->max_size <= 0)
3582 return;
3583 len = sizeof(buf);
3584 if (len > s->max_size)
3585 len = s->max_size;
3586 size = recv(s->fd, buf, len, 0);
3587 if (size == 0) {
3588 /* connection closed */
3589 s->connected = 0;
3590 if (s->listen_fd >= 0) {
3591 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3593 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3594 closesocket(s->fd);
3595 s->fd = -1;
3596 } else if (size > 0) {
3597 if (s->do_telnetopt)
3598 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3599 if (size > 0)
3600 qemu_chr_read(chr, buf, size);
3604 static void tcp_chr_connect(void *opaque)
3606 CharDriverState *chr = opaque;
3607 TCPCharDriver *s = chr->opaque;
3609 s->connected = 1;
3610 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3611 tcp_chr_read, NULL, chr);
3612 qemu_chr_reset(chr);
3615 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3616 static void tcp_chr_telnet_init(int fd)
3618 char buf[3];
3619 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3620 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3621 send(fd, (char *)buf, 3, 0);
3622 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3623 send(fd, (char *)buf, 3, 0);
3624 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3625 send(fd, (char *)buf, 3, 0);
3626 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3627 send(fd, (char *)buf, 3, 0);
3630 static void socket_set_nodelay(int fd)
3632 int val = 1;
3633 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3636 static void tcp_chr_accept(void *opaque)
3638 CharDriverState *chr = opaque;
3639 TCPCharDriver *s = chr->opaque;
3640 struct sockaddr_in saddr;
3641 #ifndef _WIN32
3642 struct sockaddr_un uaddr;
3643 #endif
3644 struct sockaddr *addr;
3645 socklen_t len;
3646 int fd;
3648 for(;;) {
3649 #ifndef _WIN32
3650 if (s->is_unix) {
3651 len = sizeof(uaddr);
3652 addr = (struct sockaddr *)&uaddr;
3653 } else
3654 #endif
3656 len = sizeof(saddr);
3657 addr = (struct sockaddr *)&saddr;
3659 fd = accept(s->listen_fd, addr, &len);
3660 if (fd < 0 && errno != EINTR) {
3661 return;
3662 } else if (fd >= 0) {
3663 if (s->do_telnetopt)
3664 tcp_chr_telnet_init(fd);
3665 break;
3668 socket_set_nonblock(fd);
3669 if (s->do_nodelay)
3670 socket_set_nodelay(fd);
3671 s->fd = fd;
3672 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3673 tcp_chr_connect(chr);
3676 static void tcp_chr_close(CharDriverState *chr)
3678 TCPCharDriver *s = chr->opaque;
3679 if (s->fd >= 0)
3680 closesocket(s->fd);
3681 if (s->listen_fd >= 0)
3682 closesocket(s->listen_fd);
3683 qemu_free(s);
3686 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3687 int is_telnet,
3688 int is_unix)
3690 CharDriverState *chr = NULL;
3691 TCPCharDriver *s = NULL;
3692 int fd = -1, ret, err, val;
3693 int is_listen = 0;
3694 int is_waitconnect = 1;
3695 int do_nodelay = 0;
3696 const char *ptr;
3697 struct sockaddr_in saddr;
3698 #ifndef _WIN32
3699 struct sockaddr_un uaddr;
3700 #endif
3701 struct sockaddr *addr;
3702 socklen_t addrlen;
3704 #ifndef _WIN32
3705 if (is_unix) {
3706 addr = (struct sockaddr *)&uaddr;
3707 addrlen = sizeof(uaddr);
3708 if (parse_unix_path(&uaddr, host_str) < 0)
3709 goto fail;
3710 } else
3711 #endif
3713 addr = (struct sockaddr *)&saddr;
3714 addrlen = sizeof(saddr);
3715 if (parse_host_port(&saddr, host_str) < 0)
3716 goto fail;
3719 ptr = host_str;
3720 while((ptr = strchr(ptr,','))) {
3721 ptr++;
3722 if (!strncmp(ptr,"server",6)) {
3723 is_listen = 1;
3724 } else if (!strncmp(ptr,"nowait",6)) {
3725 is_waitconnect = 0;
3726 } else if (!strncmp(ptr,"nodelay",6)) {
3727 do_nodelay = 1;
3728 } else {
3729 printf("Unknown option: %s\n", ptr);
3730 goto fail;
3733 if (!is_listen)
3734 is_waitconnect = 0;
3736 chr = qemu_mallocz(sizeof(CharDriverState));
3737 if (!chr)
3738 goto fail;
3739 s = qemu_mallocz(sizeof(TCPCharDriver));
3740 if (!s)
3741 goto fail;
3743 #ifndef _WIN32
3744 if (is_unix)
3745 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3746 else
3747 #endif
3748 fd = socket(PF_INET, SOCK_STREAM, 0);
3750 if (fd < 0)
3751 goto fail;
3753 if (!is_waitconnect)
3754 socket_set_nonblock(fd);
3756 s->connected = 0;
3757 s->fd = -1;
3758 s->listen_fd = -1;
3759 s->is_unix = is_unix;
3760 s->do_nodelay = do_nodelay && !is_unix;
3762 chr->opaque = s;
3763 chr->chr_write = tcp_chr_write;
3764 chr->chr_close = tcp_chr_close;
3766 if (is_listen) {
3767 /* allow fast reuse */
3768 #ifndef _WIN32
3769 if (is_unix) {
3770 char path[109];
3771 pstrcpy(path, sizeof(path), uaddr.sun_path);
3772 unlink(path);
3773 } else
3774 #endif
3776 val = 1;
3777 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3780 ret = bind(fd, addr, addrlen);
3781 if (ret < 0)
3782 goto fail;
3784 ret = listen(fd, 0);
3785 if (ret < 0)
3786 goto fail;
3788 s->listen_fd = fd;
3789 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3790 if (is_telnet)
3791 s->do_telnetopt = 1;
3792 } else {
3793 for(;;) {
3794 ret = connect(fd, addr, addrlen);
3795 if (ret < 0) {
3796 err = socket_error();
3797 if (err == EINTR || err == EWOULDBLOCK) {
3798 } else if (err == EINPROGRESS) {
3799 break;
3800 #ifdef _WIN32
3801 } else if (err == WSAEALREADY) {
3802 break;
3803 #endif
3804 } else {
3805 goto fail;
3807 } else {
3808 s->connected = 1;
3809 break;
3812 s->fd = fd;
3813 socket_set_nodelay(fd);
3814 if (s->connected)
3815 tcp_chr_connect(chr);
3816 else
3817 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3820 if (is_listen && is_waitconnect) {
3821 printf("QEMU waiting for connection on: %s\n", host_str);
3822 tcp_chr_accept(chr);
3823 socket_set_nonblock(s->listen_fd);
3826 return chr;
3827 fail:
3828 if (fd >= 0)
3829 closesocket(fd);
3830 qemu_free(s);
3831 qemu_free(chr);
3832 return NULL;
3835 CharDriverState *qemu_chr_open(const char *filename)
3837 const char *p;
3839 if (!strcmp(filename, "vc")) {
3840 return text_console_init(&display_state, 0);
3841 } else if (strstart(filename, "vc:", &p)) {
3842 return text_console_init(&display_state, p);
3843 } else if (!strcmp(filename, "null")) {
3844 return qemu_chr_open_null();
3845 } else
3846 if (strstart(filename, "tcp:", &p)) {
3847 return qemu_chr_open_tcp(p, 0, 0);
3848 } else
3849 if (strstart(filename, "telnet:", &p)) {
3850 return qemu_chr_open_tcp(p, 1, 0);
3851 } else
3852 if (strstart(filename, "udp:", &p)) {
3853 return qemu_chr_open_udp(p);
3854 } else
3855 if (strstart(filename, "mon:", &p)) {
3856 CharDriverState *drv = qemu_chr_open(p);
3857 if (drv) {
3858 drv = qemu_chr_open_mux(drv);
3859 monitor_init(drv, !nographic);
3860 return drv;
3862 printf("Unable to open driver: %s\n", p);
3863 return 0;
3864 } else
3865 #ifndef _WIN32
3866 if (strstart(filename, "unix:", &p)) {
3867 return qemu_chr_open_tcp(p, 0, 1);
3868 } else if (strstart(filename, "file:", &p)) {
3869 return qemu_chr_open_file_out(p);
3870 } else if (strstart(filename, "pipe:", &p)) {
3871 return qemu_chr_open_pipe(p);
3872 } else if (!strcmp(filename, "pty")) {
3873 return qemu_chr_open_pty();
3874 } else if (!strcmp(filename, "stdio")) {
3875 return qemu_chr_open_stdio();
3876 } else
3877 #if defined(__linux__)
3878 if (strstart(filename, "/dev/parport", NULL)) {
3879 return qemu_chr_open_pp(filename);
3880 } else
3881 #endif
3882 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3883 || defined(__NetBSD__) || defined(__OpenBSD__)
3884 if (strstart(filename, "/dev/", NULL)) {
3885 return qemu_chr_open_tty(filename);
3886 } else
3887 #endif
3888 #else /* !_WIN32 */
3889 if (strstart(filename, "COM", NULL)) {
3890 return qemu_chr_open_win(filename);
3891 } else
3892 if (strstart(filename, "pipe:", &p)) {
3893 return qemu_chr_open_win_pipe(p);
3894 } else
3895 if (strstart(filename, "con:", NULL)) {
3896 return qemu_chr_open_win_con(filename);
3897 } else
3898 if (strstart(filename, "file:", &p)) {
3899 return qemu_chr_open_win_file_out(p);
3900 } else
3901 #endif
3902 #ifdef CONFIG_BRLAPI
3903 if (!strcmp(filename, "braille")) {
3904 return chr_baum_init();
3905 } else
3906 #endif
3908 return NULL;
3912 void qemu_chr_close(CharDriverState *chr)
3914 if (chr->chr_close)
3915 chr->chr_close(chr);
3916 qemu_free(chr);
3919 /***********************************************************/
3920 /* network device redirectors */
3922 __attribute__ (( unused ))
3923 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3925 int len, i, j, c;
3927 for(i=0;i<size;i+=16) {
3928 len = size - i;
3929 if (len > 16)
3930 len = 16;
3931 fprintf(f, "%08x ", i);
3932 for(j=0;j<16;j++) {
3933 if (j < len)
3934 fprintf(f, " %02x", buf[i+j]);
3935 else
3936 fprintf(f, " ");
3938 fprintf(f, " ");
3939 for(j=0;j<len;j++) {
3940 c = buf[i+j];
3941 if (c < ' ' || c > '~')
3942 c = '.';
3943 fprintf(f, "%c", c);
3945 fprintf(f, "\n");
3949 static int parse_macaddr(uint8_t *macaddr, const char *p)
3951 int i;
3952 char *last_char;
3953 long int offset;
3955 errno = 0;
3956 offset = strtol(p, &last_char, 0);
3957 if (0 == errno && '\0' == *last_char &&
3958 offset >= 0 && offset <= 0xFFFFFF) {
3959 macaddr[3] = (offset & 0xFF0000) >> 16;
3960 macaddr[4] = (offset & 0xFF00) >> 8;
3961 macaddr[5] = offset & 0xFF;
3962 return 0;
3963 } else {
3964 for(i = 0; i < 6; i++) {
3965 macaddr[i] = strtol(p, (char **)&p, 16);
3966 if (i == 5) {
3967 if (*p != '\0')
3968 return -1;
3969 } else {
3970 if (*p != ':' && *p != '-')
3971 return -1;
3972 p++;
3975 return 0;
3978 return -1;
3981 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3983 const char *p, *p1;
3984 int len;
3985 p = *pp;
3986 p1 = strchr(p, sep);
3987 if (!p1)
3988 return -1;
3989 len = p1 - p;
3990 p1++;
3991 if (buf_size > 0) {
3992 if (len > buf_size - 1)
3993 len = buf_size - 1;
3994 memcpy(buf, p, len);
3995 buf[len] = '\0';
3997 *pp = p1;
3998 return 0;
4001 int parse_host_src_port(struct sockaddr_in *haddr,
4002 struct sockaddr_in *saddr,
4003 const char *input_str)
4005 char *str = strdup(input_str);
4006 char *host_str = str;
4007 char *src_str;
4008 char *ptr;
4011 * Chop off any extra arguments at the end of the string which
4012 * would start with a comma, then fill in the src port information
4013 * if it was provided else use the "any address" and "any port".
4015 if ((ptr = strchr(str,',')))
4016 *ptr = '\0';
4018 if ((src_str = strchr(input_str,'@'))) {
4019 *src_str = '\0';
4020 src_str++;
4023 if (parse_host_port(haddr, host_str) < 0)
4024 goto fail;
4026 if (!src_str || *src_str == '\0')
4027 src_str = ":0";
4029 if (parse_host_port(saddr, src_str) < 0)
4030 goto fail;
4032 free(str);
4033 return(0);
4035 fail:
4036 free(str);
4037 return -1;
4040 int parse_host_port(struct sockaddr_in *saddr, const char *str)
4042 char buf[512];
4043 struct hostent *he;
4044 const char *p, *r;
4045 int port;
4047 p = str;
4048 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4049 return -1;
4050 saddr->sin_family = AF_INET;
4051 if (buf[0] == '\0') {
4052 saddr->sin_addr.s_addr = 0;
4053 } else {
4054 if (isdigit(buf[0])) {
4055 if (!inet_aton(buf, &saddr->sin_addr))
4056 return -1;
4057 } else {
4058 if ((he = gethostbyname(buf)) == NULL)
4059 return - 1;
4060 saddr->sin_addr = *(struct in_addr *)he->h_addr;
4063 port = strtol(p, (char **)&r, 0);
4064 if (r == p)
4065 return -1;
4066 saddr->sin_port = htons(port);
4067 return 0;
4070 #ifndef _WIN32
4071 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4073 const char *p;
4074 int len;
4076 len = MIN(108, strlen(str));
4077 p = strchr(str, ',');
4078 if (p)
4079 len = MIN(len, p - str);
4081 memset(uaddr, 0, sizeof(*uaddr));
4083 uaddr->sun_family = AF_UNIX;
4084 memcpy(uaddr->sun_path, str, len);
4086 return 0;
4088 #endif
4090 /* find or alloc a new VLAN */
4091 VLANState *qemu_find_vlan(int id)
4093 VLANState **pvlan, *vlan;
4094 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4095 if (vlan->id == id)
4096 return vlan;
4098 vlan = qemu_mallocz(sizeof(VLANState));
4099 if (!vlan)
4100 return NULL;
4101 vlan->id = id;
4102 vlan->next = NULL;
4103 pvlan = &first_vlan;
4104 while (*pvlan != NULL)
4105 pvlan = &(*pvlan)->next;
4106 *pvlan = vlan;
4107 return vlan;
4110 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4111 IOReadHandler *fd_read,
4112 IOCanRWHandler *fd_can_read,
4113 void *opaque)
4115 VLANClientState *vc, **pvc;
4116 vc = qemu_mallocz(sizeof(VLANClientState));
4117 if (!vc)
4118 return NULL;
4119 vc->fd_read = fd_read;
4120 vc->fd_can_read = fd_can_read;
4121 vc->opaque = opaque;
4122 vc->vlan = vlan;
4124 vc->next = NULL;
4125 pvc = &vlan->first_client;
4126 while (*pvc != NULL)
4127 pvc = &(*pvc)->next;
4128 *pvc = vc;
4129 return vc;
4132 void qemu_del_vlan_client(VLANClientState *vc)
4134 VLANClientState **pvc = &vc->vlan->first_client;
4136 while (*pvc != NULL)
4137 if (*pvc == vc) {
4138 *pvc = vc->next;
4139 free(vc);
4140 break;
4141 } else
4142 pvc = &(*pvc)->next;
4145 int qemu_can_send_packet(VLANClientState *vc1)
4147 VLANState *vlan = vc1->vlan;
4148 VLANClientState *vc;
4150 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4151 if (vc != vc1) {
4152 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4153 return 1;
4156 return 0;
4159 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4161 VLANState *vlan = vc1->vlan;
4162 VLANClientState *vc;
4163 int ret = -EAGAIN;
4165 #if 0
4166 printf("vlan %d send:\n", vlan->id);
4167 hex_dump(stdout, buf, size);
4168 #endif
4169 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4170 if (vc != vc1) {
4171 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
4172 vc->fd_read(vc->opaque, buf, size);
4173 ret = 0;
4178 return ret;
4181 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
4182 int iovcnt)
4184 char buffer[4096];
4185 size_t offset = 0;
4186 int i;
4188 for (i = 0; i < iovcnt; i++) {
4189 size_t len;
4191 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
4192 memcpy(buffer + offset, iov[i].iov_base, len);
4193 offset += len;
4196 vc->fd_read(vc->opaque, buffer, offset);
4198 return offset;
4201 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
4202 int iovcnt)
4204 VLANState *vlan = vc1->vlan;
4205 VLANClientState *vc;
4206 ssize_t max_len = 0;
4208 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
4209 ssize_t len = 0;
4211 if (vc == vc1)
4212 continue;
4214 if (vc->fd_readv)
4215 len = vc->fd_readv(vc->opaque, iov, iovcnt);
4216 else if (vc->fd_read)
4217 len = vc_sendv_compat(vc, iov, iovcnt);
4219 max_len = MAX(max_len, len);
4222 return max_len;
4225 #if defined(CONFIG_SLIRP)
4227 /* slirp network adapter */
4229 static int slirp_inited;
4230 static VLANClientState *slirp_vc;
4232 int slirp_can_output(void)
4234 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4237 void slirp_output(const uint8_t *pkt, int pkt_len)
4239 #if 0
4240 printf("slirp output:\n");
4241 hex_dump(stdout, pkt, pkt_len);
4242 #endif
4243 if (!slirp_vc)
4244 return;
4245 qemu_send_packet(slirp_vc, pkt, pkt_len);
4248 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4250 #if 0
4251 printf("slirp input:\n");
4252 hex_dump(stdout, buf, size);
4253 #endif
4254 slirp_input(buf, size);
4257 static int net_slirp_init(VLANState *vlan)
4259 if (!slirp_inited) {
4260 slirp_inited = 1;
4261 slirp_init();
4263 slirp_vc = qemu_new_vlan_client(vlan,
4264 slirp_receive, NULL, NULL);
4265 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4266 return 0;
4269 static void net_slirp_redir(const char *redir_str)
4271 int is_udp;
4272 char buf[256], *r;
4273 const char *p;
4274 struct in_addr guest_addr;
4275 int host_port, guest_port;
4277 if (!slirp_inited) {
4278 slirp_inited = 1;
4279 slirp_init();
4282 p = redir_str;
4283 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4284 goto fail;
4285 if (!strcmp(buf, "tcp")) {
4286 is_udp = 0;
4287 } else if (!strcmp(buf, "udp")) {
4288 is_udp = 1;
4289 } else {
4290 goto fail;
4293 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4294 goto fail;
4295 host_port = strtol(buf, &r, 0);
4296 if (r == buf)
4297 goto fail;
4299 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4300 goto fail;
4301 if (buf[0] == '\0') {
4302 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4304 if (!inet_aton(buf, &guest_addr))
4305 goto fail;
4307 guest_port = strtol(p, &r, 0);
4308 if (r == p)
4309 goto fail;
4311 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4312 fprintf(stderr, "qemu: could not set up redirection\n");
4313 exit(1);
4315 return;
4316 fail:
4317 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4318 exit(1);
4321 #ifndef _WIN32
4323 char smb_dir[1024];
4325 static void erase_dir(char *dir_name)
4327 DIR *d;
4328 struct dirent *de;
4329 char filename[1024];
4331 /* erase all the files in the directory */
4332 if ((d = opendir(dir_name)) != 0) {
4333 for(;;) {
4334 de = readdir(d);
4335 if (!de)
4336 break;
4337 if (strcmp(de->d_name, ".") != 0 &&
4338 strcmp(de->d_name, "..") != 0) {
4339 snprintf(filename, sizeof(filename), "%s/%s",
4340 smb_dir, de->d_name);
4341 if (unlink(filename) != 0) /* is it a directory? */
4342 erase_dir(filename);
4345 closedir(d);
4346 rmdir(dir_name);
4350 /* automatic user mode samba server configuration */
4351 static void smb_exit(void)
4353 erase_dir(smb_dir);
4356 /* automatic user mode samba server configuration */
4357 static void net_slirp_smb(const char *exported_dir)
4359 char smb_conf[1024];
4360 char smb_cmdline[1024];
4361 FILE *f;
4363 if (!slirp_inited) {
4364 slirp_inited = 1;
4365 slirp_init();
4368 /* XXX: better tmp dir construction */
4369 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4370 if (mkdir(smb_dir, 0700) < 0) {
4371 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4372 exit(1);
4374 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4376 f = fopen(smb_conf, "w");
4377 if (!f) {
4378 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4379 exit(1);
4381 fprintf(f,
4382 "[global]\n"
4383 "private dir=%s\n"
4384 "smb ports=0\n"
4385 "socket address=127.0.0.1\n"
4386 "pid directory=%s\n"
4387 "lock directory=%s\n"
4388 "log file=%s/log.smbd\n"
4389 "smb passwd file=%s/smbpasswd\n"
4390 "security = share\n"
4391 "[qemu]\n"
4392 "path=%s\n"
4393 "read only=no\n"
4394 "guest ok=yes\n",
4395 smb_dir,
4396 smb_dir,
4397 smb_dir,
4398 smb_dir,
4399 smb_dir,
4400 exported_dir
4402 fclose(f);
4403 atexit(smb_exit);
4405 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4406 SMBD_COMMAND, smb_conf);
4408 slirp_add_exec(0, smb_cmdline, 4, 139);
4411 #endif /* !defined(_WIN32) */
4412 void do_info_slirp(void)
4414 slirp_stats();
4417 #endif /* CONFIG_SLIRP */
4419 #ifdef _WIN32
4421 int tap_has_vnet_hdr(void *opaque)
4423 return 0;
4426 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
4430 #else /* !defined(_WIN32) */
4432 #ifndef IFF_VNET_HDR
4433 #define TAP_BUFSIZE 4096
4434 #else
4435 #include <linux/virtio_net.h>
4436 #define ETH_HLEN 14
4437 #define ETH_DATA_LEN 1500
4438 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4439 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4440 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4441 #endif
4443 typedef struct TAPState {
4444 VLANClientState *vc;
4445 int fd;
4446 char down_script[1024];
4447 char buf[TAP_BUFSIZE];
4448 int size;
4449 unsigned int has_vnet_hdr : 1;
4450 unsigned int using_vnet_hdr : 1;
4451 } TAPState;
4453 static ssize_t tap_writev(void *opaque, const struct iovec *iov,
4454 int iovcnt)
4456 TAPState *s = opaque;
4457 ssize_t len;
4459 do {
4460 len = writev(s->fd, iov, iovcnt);
4461 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
4463 return len;
4466 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
4467 int iovcnt)
4469 #ifdef IFF_VNET_HDR
4470 TAPState *s = opaque;
4472 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4473 struct iovec *iov_copy;
4474 struct virtio_net_hdr hdr = { 0, };
4476 iov_copy = alloca(sizeof(struct iovec) * (iovcnt + 1));
4478 iov_copy[0].iov_base = &hdr;
4479 iov_copy[0].iov_len = sizeof(hdr);
4481 memcpy(&iov_copy[1], iov, sizeof(struct iovec) * iovcnt);
4483 return tap_writev(opaque, iov_copy, iovcnt + 1);
4485 #endif
4487 return tap_writev(opaque, iov, iovcnt);
4490 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4492 struct iovec iov[2];
4493 int i = 0;
4495 #ifdef IFF_VNET_HDR
4496 TAPState *s = opaque;
4497 struct virtio_net_hdr hdr = { 0, };
4499 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4500 iov[i].iov_base = &hdr;
4501 iov[i].iov_len = sizeof(hdr);
4502 i++;
4504 #endif
4506 iov[i].iov_base = (char *) buf;
4507 iov[i].iov_len = size;
4508 i++;
4510 tap_writev(opaque, iov, i);
4513 static int tap_can_send(void *opaque)
4515 TAPState *s = opaque;
4516 VLANClientState *vc;
4517 int can_receive = 0;
4519 /* Check to see if any of our clients can receive a packet */
4520 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
4521 /* Skip ourselves */
4522 if (vc == s->vc)
4523 continue;
4525 if (!vc->fd_can_read) {
4526 /* no fd_can_read handler, they always can receive */
4527 can_receive = 1;
4528 } else
4529 can_receive = vc->fd_can_read(vc->opaque);
4531 /* Once someone can receive, we try to send a packet */
4532 if (can_receive)
4533 break;
4536 return can_receive;
4539 static int tap_send_packet(TAPState *s)
4541 uint8_t *buf = s->buf;
4542 int size = s->size;
4544 #ifdef IFF_VNET_HDR
4545 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
4546 buf += sizeof(struct virtio_net_hdr);
4547 size -= sizeof(struct virtio_net_hdr);
4549 #endif
4551 return qemu_send_packet(s->vc, buf, size);
4554 static void tap_send(void *opaque)
4556 TAPState *s = opaque;
4558 /* First try to send any buffered packet */
4559 if (s->size > 0) {
4560 int err;
4562 /* If noone can receive the packet, buffer it */
4563 err = tap_send_packet(s);
4564 if (err == -EAGAIN)
4565 return;
4568 /* Read packets until we hit EAGAIN */
4569 do {
4570 #ifdef __sun__
4571 struct strbuf sbuf;
4572 int f = 0;
4573 sbuf.maxlen = sizeof(s->buf);
4574 sbuf.buf = s->buf;
4575 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4576 #else
4577 kvm_sleep_begin();
4578 s->size = read(s->fd, s->buf, sizeof(s->buf));
4579 kvm_sleep_end();
4580 #endif
4582 if (s->size == -1 && errno == EINTR)
4583 continue;
4585 if (s->size > 0) {
4586 int err;
4588 /* If noone can receive the packet, buffer it */
4589 err = tap_send_packet(s);
4590 if (err == -EAGAIN)
4591 break;
4593 } while (s->size > 0);
4596 int tap_has_vnet_hdr(void *opaque)
4598 VLANClientState *vc = opaque;
4599 TAPState *s = vc->opaque;
4601 return s ? s->has_vnet_hdr : 0;
4604 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
4606 VLANClientState *vc = opaque;
4607 TAPState *s = vc->opaque;
4609 if (!s || !s->has_vnet_hdr)
4610 return;
4612 s->using_vnet_hdr = using_vnet_hdr != 0;
4615 static int tap_probe_vnet_hdr(int fd)
4617 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
4618 struct ifreq ifr;
4620 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
4621 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
4622 return 0;
4625 return ifr.ifr_flags & IFF_VNET_HDR;
4626 #else
4627 return 0;
4628 #endif
4631 #ifdef TUNSETOFFLOAD
4632 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
4633 int ecn)
4635 TAPState *s = vc->opaque;
4636 unsigned int offload = 0;
4638 if (csum) {
4639 offload |= TUN_F_CSUM;
4640 if (tso4)
4641 offload |= TUN_F_TSO4;
4642 if (tso6)
4643 offload |= TUN_F_TSO6;
4644 if ((tso4 || tso6) && ecn)
4645 offload |= TUN_F_TSO_ECN;
4648 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
4649 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
4650 strerror(errno));
4652 #endif /* TUNSETOFFLOAD */
4654 /* fd support */
4656 static TAPState *net_tap_fd_init(VLANState *vlan, int fd, int vnet_hdr)
4658 TAPState *s;
4660 s = qemu_mallocz(sizeof(TAPState));
4661 if (!s)
4662 return NULL;
4663 s->fd = fd;
4664 s->has_vnet_hdr = vnet_hdr != 0;
4665 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4666 s->vc->fd_readv = tap_receive_iov;
4667 #ifdef TUNSETOFFLOAD
4668 s->vc->set_offload = tap_set_offload;
4669 #endif
4670 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
4671 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4672 return s;
4675 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4676 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4678 int fd;
4679 char *dev;
4680 struct stat s;
4682 TFR(fd = open("/dev/tap", O_RDWR));
4683 if (fd < 0) {
4684 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4685 return -1;
4688 fstat(fd, &s);
4689 dev = devname(s.st_rdev, S_IFCHR);
4690 pstrcpy(ifname, ifname_size, dev);
4692 fcntl(fd, F_SETFL, O_NONBLOCK);
4693 return fd;
4695 #elif defined(__sun__)
4696 #define TUNNEWPPA (('T'<<16) | 0x0001)
4698 * Allocate TAP device, returns opened fd.
4699 * Stores dev name in the first arg(must be large enough).
4701 int tap_alloc(char *dev, size_t dev_size)
4703 int tap_fd, if_fd, ppa = -1;
4704 static int ip_fd = 0;
4705 char *ptr;
4707 static int arp_fd = 0;
4708 int ip_muxid, arp_muxid;
4709 struct strioctl strioc_if, strioc_ppa;
4710 int link_type = I_PLINK;;
4711 struct lifreq ifr;
4712 char actual_name[32] = "";
4714 memset(&ifr, 0x0, sizeof(ifr));
4716 if( *dev ){
4717 ptr = dev;
4718 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4719 ppa = atoi(ptr);
4722 /* Check if IP device was opened */
4723 if( ip_fd )
4724 close(ip_fd);
4726 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4727 if (ip_fd < 0) {
4728 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4729 return -1;
4732 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4733 if (tap_fd < 0) {
4734 syslog(LOG_ERR, "Can't open /dev/tap");
4735 return -1;
4738 /* Assign a new PPA and get its unit number. */
4739 strioc_ppa.ic_cmd = TUNNEWPPA;
4740 strioc_ppa.ic_timout = 0;
4741 strioc_ppa.ic_len = sizeof(ppa);
4742 strioc_ppa.ic_dp = (char *)&ppa;
4743 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4744 syslog (LOG_ERR, "Can't assign new interface");
4746 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4747 if (if_fd < 0) {
4748 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4749 return -1;
4751 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4752 syslog(LOG_ERR, "Can't push IP module");
4753 return -1;
4756 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4757 syslog(LOG_ERR, "Can't get flags\n");
4759 snprintf (actual_name, 32, "tap%d", ppa);
4760 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4762 ifr.lifr_ppa = ppa;
4763 /* Assign ppa according to the unit number returned by tun device */
4765 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4766 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4767 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4768 syslog (LOG_ERR, "Can't get flags\n");
4769 /* Push arp module to if_fd */
4770 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4771 syslog (LOG_ERR, "Can't push ARP module (2)");
4773 /* Push arp module to ip_fd */
4774 if (ioctl (ip_fd, I_POP, NULL) < 0)
4775 syslog (LOG_ERR, "I_POP failed\n");
4776 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4777 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4778 /* Open arp_fd */
4779 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4780 if (arp_fd < 0)
4781 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4783 /* Set ifname to arp */
4784 strioc_if.ic_cmd = SIOCSLIFNAME;
4785 strioc_if.ic_timout = 0;
4786 strioc_if.ic_len = sizeof(ifr);
4787 strioc_if.ic_dp = (char *)&ifr;
4788 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4789 syslog (LOG_ERR, "Can't set ifname to arp\n");
4792 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4793 syslog(LOG_ERR, "Can't link TAP device to IP");
4794 return -1;
4797 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4798 syslog (LOG_ERR, "Can't link TAP device to ARP");
4800 close (if_fd);
4802 memset(&ifr, 0x0, sizeof(ifr));
4803 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4804 ifr.lifr_ip_muxid = ip_muxid;
4805 ifr.lifr_arp_muxid = arp_muxid;
4807 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4809 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4810 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4811 syslog (LOG_ERR, "Can't set multiplexor id");
4814 snprintf(dev, dev_size, "tap%d", ppa);
4815 return tap_fd;
4818 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4820 char dev[10]="";
4821 int fd;
4822 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4823 fprintf(stderr, "Cannot allocate TAP device\n");
4824 return -1;
4826 pstrcpy(ifname, ifname_size, dev);
4827 fcntl(fd, F_SETFL, O_NONBLOCK);
4828 return fd;
4830 #else
4831 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
4833 struct ifreq ifr;
4834 int fd, ret;
4836 TFR(fd = open("/dev/net/tun", O_RDWR));
4837 if (fd < 0) {
4838 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4839 return -1;
4841 memset(&ifr, 0, sizeof(ifr));
4842 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4844 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4846 unsigned int features;
4848 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
4849 features & IFF_VNET_HDR) {
4850 *vnet_hdr = 1;
4851 ifr.ifr_flags |= IFF_VNET_HDR;
4854 #endif
4856 if (ifname[0] != '\0')
4857 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4858 else
4859 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4860 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4861 if (ret != 0) {
4862 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4863 close(fd);
4864 return -1;
4866 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4867 fcntl(fd, F_SETFL, O_NONBLOCK);
4868 return fd;
4870 #endif
4872 static int launch_script(const char *setup_script, const char *ifname, int fd)
4874 int pid, status;
4875 char *args[3];
4876 char **parg;
4878 /* try to launch network script */
4879 pid = fork();
4880 if (pid >= 0) {
4881 if (pid == 0) {
4882 int open_max = sysconf (_SC_OPEN_MAX), i;
4883 for (i = 0; i < open_max; i++)
4884 if (i != STDIN_FILENO &&
4885 i != STDOUT_FILENO &&
4886 i != STDERR_FILENO &&
4887 i != fd)
4888 close(i);
4890 parg = args;
4891 *parg++ = (char *)setup_script;
4892 *parg++ = (char *)ifname;
4893 *parg++ = NULL;
4894 execv(setup_script, args);
4895 _exit(1);
4897 while (waitpid(pid, &status, 0) != pid);
4898 if (!WIFEXITED(status) ||
4899 WEXITSTATUS(status) != 0) {
4900 fprintf(stderr, "%s: could not launch network script\n",
4901 setup_script);
4902 return -1;
4905 return 0;
4908 static int net_tap_init(VLANState *vlan, const char *ifname1,
4909 const char *setup_script, const char *down_script)
4911 TAPState *s;
4912 int fd;
4913 int vnet_hdr;
4914 char ifname[128];
4916 if (ifname1 != NULL)
4917 pstrcpy(ifname, sizeof(ifname), ifname1);
4918 else
4919 ifname[0] = '\0';
4920 vnet_hdr = 0;
4921 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
4922 if (fd < 0)
4923 return -1;
4925 if (!setup_script || !strcmp(setup_script, "no"))
4926 setup_script = "";
4927 if (setup_script[0] != '\0') {
4928 if (launch_script(setup_script, ifname, fd))
4929 return -1;
4931 s = net_tap_fd_init(vlan, fd, vnet_hdr);
4932 if (!s)
4933 return -1;
4935 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4936 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4937 if (down_script && strcmp(down_script, "no"))
4938 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4939 return 0;
4942 #endif /* !_WIN32 */
4944 #if defined(CONFIG_VDE)
4945 typedef struct VDEState {
4946 VLANClientState *vc;
4947 VDECONN *vde;
4948 } VDEState;
4950 static void vde_to_qemu(void *opaque)
4952 VDEState *s = opaque;
4953 uint8_t buf[4096];
4954 int size;
4956 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4957 if (size > 0) {
4958 qemu_send_packet(s->vc, buf, size);
4962 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4964 VDEState *s = opaque;
4965 int ret;
4966 for(;;) {
4967 ret = vde_send(s->vde, buf, size, 0);
4968 if (ret < 0 && errno == EINTR) {
4969 } else {
4970 break;
4975 static int net_vde_init(VLANState *vlan, const char *sock, int port,
4976 const char *group, int mode)
4978 VDEState *s;
4979 char *init_group = strlen(group) ? (char *)group : NULL;
4980 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4982 struct vde_open_args args = {
4983 .port = port,
4984 .group = init_group,
4985 .mode = mode,
4988 s = qemu_mallocz(sizeof(VDEState));
4989 if (!s)
4990 return -1;
4991 s->vde = vde_open(init_sock, "QEMU", &args);
4992 if (!s->vde){
4993 free(s);
4994 return -1;
4996 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4997 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4998 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4999 sock, vde_datafd(s->vde));
5000 return 0;
5002 #endif
5004 /* network connection */
5005 typedef struct NetSocketState {
5006 VLANClientState *vc;
5007 int fd;
5008 int state; /* 0 = getting length, 1 = getting data */
5009 int index;
5010 int packet_len;
5011 uint8_t buf[4096];
5012 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
5013 } NetSocketState;
5015 typedef struct NetSocketListenState {
5016 VLANState *vlan;
5017 int fd;
5018 } NetSocketListenState;
5020 /* XXX: we consider we can send the whole packet without blocking */
5021 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
5023 NetSocketState *s = opaque;
5024 uint32_t len;
5025 len = htonl(size);
5027 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
5028 send_all(s->fd, buf, size);
5031 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
5033 NetSocketState *s = opaque;
5034 sendto(s->fd, buf, size, 0,
5035 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
5038 static void net_socket_send(void *opaque)
5040 NetSocketState *s = opaque;
5041 int l, size, err;
5042 uint8_t buf1[4096];
5043 const uint8_t *buf;
5045 size = recv(s->fd, buf1, sizeof(buf1), 0);
5046 if (size < 0) {
5047 err = socket_error();
5048 if (err != EWOULDBLOCK)
5049 goto eoc;
5050 } else if (size == 0) {
5051 /* end of connection */
5052 eoc:
5053 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
5054 closesocket(s->fd);
5055 return;
5057 buf = buf1;
5058 while (size > 0) {
5059 /* reassemble a packet from the network */
5060 switch(s->state) {
5061 case 0:
5062 l = 4 - s->index;
5063 if (l > size)
5064 l = size;
5065 memcpy(s->buf + s->index, buf, l);
5066 buf += l;
5067 size -= l;
5068 s->index += l;
5069 if (s->index == 4) {
5070 /* got length */
5071 s->packet_len = ntohl(*(uint32_t *)s->buf);
5072 s->index = 0;
5073 s->state = 1;
5075 break;
5076 case 1:
5077 l = s->packet_len - s->index;
5078 if (l > size)
5079 l = size;
5080 memcpy(s->buf + s->index, buf, l);
5081 s->index += l;
5082 buf += l;
5083 size -= l;
5084 if (s->index >= s->packet_len) {
5085 qemu_send_packet(s->vc, s->buf, s->packet_len);
5086 s->index = 0;
5087 s->state = 0;
5089 break;
5094 static void net_socket_send_dgram(void *opaque)
5096 NetSocketState *s = opaque;
5097 int size;
5099 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
5100 if (size < 0)
5101 return;
5102 if (size == 0) {
5103 /* end of connection */
5104 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
5105 return;
5107 qemu_send_packet(s->vc, s->buf, size);
5110 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
5112 struct ip_mreq imr;
5113 int fd;
5114 int val, ret;
5115 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
5116 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5117 inet_ntoa(mcastaddr->sin_addr),
5118 (int)ntohl(mcastaddr->sin_addr.s_addr));
5119 return -1;
5122 fd = socket(PF_INET, SOCK_DGRAM, 0);
5123 if (fd < 0) {
5124 perror("socket(PF_INET, SOCK_DGRAM)");
5125 return -1;
5128 val = 1;
5129 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
5130 (const char *)&val, sizeof(val));
5131 if (ret < 0) {
5132 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5133 goto fail;
5136 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
5137 if (ret < 0) {
5138 perror("bind");
5139 goto fail;
5142 /* Add host to multicast group */
5143 imr.imr_multiaddr = mcastaddr->sin_addr;
5144 imr.imr_interface.s_addr = htonl(INADDR_ANY);
5146 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
5147 (const char *)&imr, sizeof(struct ip_mreq));
5148 if (ret < 0) {
5149 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5150 goto fail;
5153 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5154 val = 1;
5155 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
5156 (const char *)&val, sizeof(val));
5157 if (ret < 0) {
5158 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5159 goto fail;
5162 socket_set_nonblock(fd);
5163 return fd;
5164 fail:
5165 if (fd >= 0)
5166 closesocket(fd);
5167 return -1;
5170 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
5171 int is_connected)
5173 struct sockaddr_in saddr;
5174 int newfd;
5175 socklen_t saddr_len;
5176 NetSocketState *s;
5178 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5179 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5180 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5183 if (is_connected) {
5184 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
5185 /* must be bound */
5186 if (saddr.sin_addr.s_addr==0) {
5187 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5188 fd);
5189 return NULL;
5191 /* clone dgram socket */
5192 newfd = net_socket_mcast_create(&saddr);
5193 if (newfd < 0) {
5194 /* error already reported by net_socket_mcast_create() */
5195 close(fd);
5196 return NULL;
5198 /* clone newfd to fd, close newfd */
5199 dup2(newfd, fd);
5200 close(newfd);
5202 } else {
5203 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5204 fd, strerror(errno));
5205 return NULL;
5209 s = qemu_mallocz(sizeof(NetSocketState));
5210 if (!s)
5211 return NULL;
5212 s->fd = fd;
5214 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
5215 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
5217 /* mcast: save bound address as dst */
5218 if (is_connected) s->dgram_dst=saddr;
5220 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5221 "socket: fd=%d (%s mcast=%s:%d)",
5222 fd, is_connected? "cloned" : "",
5223 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5224 return s;
5227 static void net_socket_connect(void *opaque)
5229 NetSocketState *s = opaque;
5230 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
5233 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
5234 int is_connected)
5236 NetSocketState *s;
5237 s = qemu_mallocz(sizeof(NetSocketState));
5238 if (!s)
5239 return NULL;
5240 s->fd = fd;
5241 s->vc = qemu_new_vlan_client(vlan,
5242 net_socket_receive, NULL, s);
5243 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5244 "socket: fd=%d", fd);
5245 if (is_connected) {
5246 net_socket_connect(s);
5247 } else {
5248 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
5250 return s;
5253 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
5254 int is_connected)
5256 int so_type=-1, optlen=sizeof(so_type);
5258 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
5259 (socklen_t *)&optlen)< 0) {
5260 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
5261 return NULL;
5263 switch(so_type) {
5264 case SOCK_DGRAM:
5265 return net_socket_fd_init_dgram(vlan, fd, is_connected);
5266 case SOCK_STREAM:
5267 return net_socket_fd_init_stream(vlan, fd, is_connected);
5268 default:
5269 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5270 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
5271 return net_socket_fd_init_stream(vlan, fd, is_connected);
5273 return NULL;
5276 static void net_socket_accept(void *opaque)
5278 NetSocketListenState *s = opaque;
5279 NetSocketState *s1;
5280 struct sockaddr_in saddr;
5281 socklen_t len;
5282 int fd;
5284 for(;;) {
5285 len = sizeof(saddr);
5286 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
5287 if (fd < 0 && errno != EINTR) {
5288 return;
5289 } else if (fd >= 0) {
5290 break;
5293 s1 = net_socket_fd_init(s->vlan, fd, 1);
5294 if (!s1) {
5295 closesocket(fd);
5296 } else {
5297 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
5298 "socket: connection from %s:%d",
5299 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5303 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
5305 NetSocketListenState *s;
5306 int fd, val, ret;
5307 struct sockaddr_in saddr;
5309 if (parse_host_port(&saddr, host_str) < 0)
5310 return -1;
5312 s = qemu_mallocz(sizeof(NetSocketListenState));
5313 if (!s)
5314 return -1;
5316 fd = socket(PF_INET, SOCK_STREAM, 0);
5317 if (fd < 0) {
5318 perror("socket");
5319 return -1;
5321 socket_set_nonblock(fd);
5323 /* allow fast reuse */
5324 val = 1;
5325 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5327 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5328 if (ret < 0) {
5329 perror("bind");
5330 return -1;
5332 ret = listen(fd, 0);
5333 if (ret < 0) {
5334 perror("listen");
5335 return -1;
5337 s->vlan = vlan;
5338 s->fd = fd;
5339 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5340 return 0;
5343 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5345 NetSocketState *s;
5346 int fd, connected, ret, err;
5347 struct sockaddr_in saddr;
5349 if (parse_host_port(&saddr, host_str) < 0)
5350 return -1;
5352 fd = socket(PF_INET, SOCK_STREAM, 0);
5353 if (fd < 0) {
5354 perror("socket");
5355 return -1;
5357 socket_set_nonblock(fd);
5359 connected = 0;
5360 for(;;) {
5361 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5362 if (ret < 0) {
5363 err = socket_error();
5364 if (err == EINTR || err == EWOULDBLOCK) {
5365 } else if (err == EINPROGRESS) {
5366 break;
5367 #ifdef _WIN32
5368 } else if (err == WSAEALREADY) {
5369 break;
5370 #endif
5371 } else {
5372 perror("connect");
5373 closesocket(fd);
5374 return -1;
5376 } else {
5377 connected = 1;
5378 break;
5381 s = net_socket_fd_init(vlan, fd, connected);
5382 if (!s)
5383 return -1;
5384 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5385 "socket: connect to %s:%d",
5386 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5387 return 0;
5390 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5392 NetSocketState *s;
5393 int fd;
5394 struct sockaddr_in saddr;
5396 if (parse_host_port(&saddr, host_str) < 0)
5397 return -1;
5400 fd = net_socket_mcast_create(&saddr);
5401 if (fd < 0)
5402 return -1;
5404 s = net_socket_fd_init(vlan, fd, 0);
5405 if (!s)
5406 return -1;
5408 s->dgram_dst = saddr;
5410 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5411 "socket: mcast=%s:%d",
5412 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5413 return 0;
5417 static const char *get_opt_name(char *buf, int buf_size, const char *p)
5419 char *q;
5421 q = buf;
5422 while (*p != '\0' && *p != '=') {
5423 if (q && (q - buf) < buf_size - 1)
5424 *q++ = *p;
5425 p++;
5427 if (q)
5428 *q = '\0';
5430 return p;
5433 static const char *get_opt_value(char *buf, int buf_size, const char *p)
5435 char *q;
5437 q = buf;
5438 while (*p != '\0') {
5439 if (*p == ',') {
5440 if (*(p + 1) != ',')
5441 break;
5442 p++;
5444 if (q && (q - buf) < buf_size - 1)
5445 *q++ = *p;
5446 p++;
5448 if (q)
5449 *q = '\0';
5451 return p;
5454 int get_param_value(char *buf, int buf_size,
5455 const char *tag, const char *str)
5457 const char *p;
5458 char option[128];
5460 p = str;
5461 for(;;) {
5462 p = get_opt_name(option, sizeof(option), p);
5463 if (*p != '=')
5464 break;
5465 p++;
5466 if (!strcmp(tag, option)) {
5467 (void)get_opt_value(buf, buf_size, p);
5468 return strlen(buf);
5469 } else {
5470 p = get_opt_value(NULL, 0, p);
5472 if (*p != ',')
5473 break;
5474 p++;
5476 return 0;
5479 int check_params(char *buf, int buf_size,
5480 char **params, const char *str)
5482 const char *p;
5483 int i;
5485 p = str;
5486 for(;;) {
5487 p = get_opt_name(buf, buf_size, p);
5488 if (*p != '=')
5489 return -1;
5490 p++;
5491 for(i = 0; params[i] != NULL; i++)
5492 if (!strcmp(params[i], buf))
5493 break;
5494 if (params[i] == NULL)
5495 return -1;
5496 p = get_opt_value(NULL, 0, p);
5497 if (*p != ',')
5498 break;
5499 p++;
5501 return 0;
5504 static int nic_get_free_idx(void)
5506 int index;
5508 for (index = 0; index < MAX_NICS; index++)
5509 if (!nd_table[index].used)
5510 return index;
5511 return -1;
5514 int net_client_init(const char *device, const char *p)
5516 char buf[1024];
5517 int vlan_id, ret;
5518 VLANState *vlan;
5520 vlan_id = 0;
5521 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5522 vlan_id = strtol(buf, NULL, 0);
5524 vlan = qemu_find_vlan(vlan_id);
5525 if (!vlan) {
5526 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5527 return -1;
5529 if (!strcmp(device, "nic")) {
5530 NICInfo *nd;
5531 uint8_t *macaddr;
5532 int idx = nic_get_free_idx();
5534 if (idx == -1 || nb_nics >= MAX_NICS) {
5535 fprintf(stderr, "Too Many NICs\n");
5536 return -1;
5538 nd = &nd_table[idx];
5539 macaddr = nd->macaddr;
5540 macaddr[0] = 0x52;
5541 macaddr[1] = 0x54;
5542 macaddr[2] = 0x00;
5543 macaddr[3] = 0x12;
5544 macaddr[4] = 0x34;
5545 macaddr[5] = 0x56 + idx;
5547 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5548 if (parse_macaddr(macaddr, buf) < 0) {
5549 fprintf(stderr, "invalid syntax for ethernet address\n");
5550 return -1;
5553 if (get_param_value(buf, sizeof(buf), "model", p)) {
5554 nd->model = strdup(buf);
5556 nd->vlan = vlan;
5557 nd->used = 1;
5558 nb_nics++;
5559 vlan->nb_guest_devs++;
5560 ret = idx;
5561 } else
5562 if (!strcmp(device, "none")) {
5563 /* does nothing. It is needed to signal that no network cards
5564 are wanted */
5565 ret = 0;
5566 } else
5567 #ifdef CONFIG_SLIRP
5568 if (!strcmp(device, "user")) {
5569 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5570 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5572 vlan->nb_host_devs++;
5573 ret = net_slirp_init(vlan);
5574 } else
5575 #endif
5576 #ifdef _WIN32
5577 if (!strcmp(device, "tap")) {
5578 char ifname[64];
5579 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5580 fprintf(stderr, "tap: no interface name\n");
5581 return -1;
5583 vlan->nb_host_devs++;
5584 ret = tap_win32_init(vlan, ifname);
5585 } else
5586 #else
5587 if (!strcmp(device, "tap")) {
5588 char ifname[64];
5589 char setup_script[1024], down_script[1024];
5590 int fd;
5591 vlan->nb_host_devs++;
5592 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5593 fd = strtol(buf, NULL, 0);
5594 fcntl(fd, F_SETFL, O_NONBLOCK);
5595 ret = -1;
5596 if (net_tap_fd_init(vlan, fd, tap_probe_vnet_hdr(fd)))
5597 ret = 0;
5598 } else {
5599 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5600 ifname[0] = '\0';
5602 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5603 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5605 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5606 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5608 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5610 } else
5611 #endif
5612 if (!strcmp(device, "socket")) {
5613 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5614 int fd;
5615 fd = strtol(buf, NULL, 0);
5616 ret = -1;
5617 if (net_socket_fd_init(vlan, fd, 1))
5618 ret = 0;
5619 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5620 ret = net_socket_listen_init(vlan, buf);
5621 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5622 ret = net_socket_connect_init(vlan, buf);
5623 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5624 ret = net_socket_mcast_init(vlan, buf);
5625 } else {
5626 fprintf(stderr, "Unknown socket options: %s\n", p);
5627 return -1;
5629 vlan->nb_host_devs++;
5630 } else
5631 #ifdef CONFIG_VDE
5632 if (!strcmp(device, "vde")) {
5633 char vde_sock[1024], vde_group[512];
5634 int vde_port, vde_mode;
5635 vlan->nb_host_devs++;
5636 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5637 vde_sock[0] = '\0';
5639 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5640 vde_port = strtol(buf, NULL, 10);
5641 } else {
5642 vde_port = 0;
5644 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5645 vde_group[0] = '\0';
5647 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5648 vde_mode = strtol(buf, NULL, 8);
5649 } else {
5650 vde_mode = 0700;
5652 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5653 } else
5654 #endif
5656 fprintf(stderr, "Unknown network device: %s\n", device);
5657 return -1;
5659 if (ret < 0) {
5660 fprintf(stderr, "Could not initialize device '%s'\n", device);
5663 return ret;
5666 void net_client_uninit(NICInfo *nd)
5668 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
5669 nb_nics--;
5670 nd->used = 0;
5671 free((void *)nd->model);
5674 static int net_client_parse(const char *str)
5676 const char *p;
5677 char *q;
5678 char device[64];
5680 p = str;
5681 q = device;
5682 while (*p != '\0' && *p != ',') {
5683 if ((q - device) < sizeof(device) - 1)
5684 *q++ = *p;
5685 p++;
5687 *q = '\0';
5688 if (*p == ',')
5689 p++;
5691 return net_client_init(device, p);
5694 void do_info_network(void)
5696 VLANState *vlan;
5697 VLANClientState *vc;
5699 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5700 term_printf("VLAN %d devices:\n", vlan->id);
5701 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5702 term_printf(" %s\n", vc->info_str);
5706 #define HD_ALIAS "index=%d,media=disk"
5707 #ifdef TARGET_PPC
5708 #define CDROM_ALIAS "index=1,media=cdrom"
5709 #else
5710 #define CDROM_ALIAS "index=2,media=cdrom"
5711 #endif
5712 #define FD_ALIAS "index=%d,if=floppy"
5713 #define PFLASH_ALIAS "if=pflash"
5714 #define MTD_ALIAS "if=mtd"
5715 #define SD_ALIAS "index=0,if=sd"
5717 static int drive_opt_get_free_idx(void)
5719 int index;
5721 for (index = 0; index < MAX_DRIVES; index++)
5722 if (!drives_opt[index].used) {
5723 drives_opt[index].used = 1;
5724 return index;
5727 return -1;
5730 static int drive_get_free_idx(void)
5732 int index;
5734 for (index = 0; index < MAX_DRIVES; index++)
5735 if (!drives_table[index].used) {
5736 drives_table[index].used = 1;
5737 return index;
5740 return -1;
5743 int drive_add(const char *file, const char *fmt, ...)
5745 va_list ap;
5746 int index = drive_opt_get_free_idx();
5748 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5749 fprintf(stderr, "qemu: too many drives\n");
5750 return -1;
5753 drives_opt[index].file = file;
5754 va_start(ap, fmt);
5755 vsnprintf(drives_opt[index].opt,
5756 sizeof(drives_opt[0].opt), fmt, ap);
5757 va_end(ap);
5759 nb_drives_opt++;
5760 return index;
5763 void drive_remove(int index)
5765 drives_opt[index].used = 0;
5766 nb_drives_opt--;
5769 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5771 int index;
5773 /* seek interface, bus and unit */
5775 for (index = 0; index < MAX_DRIVES; index++)
5776 if (drives_table[index].type == type &&
5777 drives_table[index].bus == bus &&
5778 drives_table[index].unit == unit &&
5779 drives_table[index].used)
5780 return index;
5782 return -1;
5785 int drive_get_max_bus(BlockInterfaceType type)
5787 int max_bus;
5788 int index;
5790 max_bus = -1;
5791 for (index = 0; index < nb_drives; index++) {
5792 if(drives_table[index].type == type &&
5793 drives_table[index].bus > max_bus)
5794 max_bus = drives_table[index].bus;
5796 return max_bus;
5799 static void bdrv_format_print(void *opaque, const char *name)
5801 fprintf(stderr, " %s", name);
5804 void drive_uninit(BlockDriverState *bdrv)
5806 int i;
5808 for (i = 0; i < MAX_DRIVES; i++)
5809 if (drives_table[i].bdrv == bdrv) {
5810 drives_table[i].bdrv = NULL;
5811 drives_table[i].used = 0;
5812 drive_remove(drives_table[i].drive_opt_idx);
5813 nb_drives--;
5814 break;
5818 int drive_init(struct drive_opt *arg, int snapshot,
5819 QEMUMachine *machine)
5821 char buf[128];
5822 char file[1024];
5823 char devname[128];
5824 const char *mediastr = "";
5825 BlockInterfaceType type;
5826 enum { MEDIA_DISK, MEDIA_CDROM } media;
5827 int bus_id, unit_id;
5828 int cyls, heads, secs, translation;
5829 BlockDriverState *bdrv;
5830 BlockDriver *drv = NULL;
5831 int max_devs;
5832 int index;
5833 int cache;
5834 int bdrv_flags;
5835 int drives_table_idx;
5836 char *str = arg->opt;
5837 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5838 "secs", "trans", "media", "snapshot", "file",
5839 "cache", "format", "boot", NULL };
5841 if (check_params(buf, sizeof(buf), params, str) < 0) {
5842 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5843 buf, str);
5844 return -1;
5847 file[0] = 0;
5848 cyls = heads = secs = 0;
5849 bus_id = 0;
5850 unit_id = -1;
5851 translation = BIOS_ATA_TRANSLATION_AUTO;
5852 index = -1;
5853 cache = 1;
5855 if (!strcmp(machine->name, "realview") ||
5856 !strcmp(machine->name, "SS-5") ||
5857 !strcmp(machine->name, "SS-10") ||
5858 !strcmp(machine->name, "SS-600MP") ||
5859 !strcmp(machine->name, "versatilepb") ||
5860 !strcmp(machine->name, "versatileab")) {
5861 type = IF_SCSI;
5862 max_devs = MAX_SCSI_DEVS;
5863 pstrcpy(devname, sizeof(devname), "scsi");
5864 } else {
5865 type = IF_IDE;
5866 max_devs = MAX_IDE_DEVS;
5867 pstrcpy(devname, sizeof(devname), "ide");
5869 media = MEDIA_DISK;
5871 /* extract parameters */
5873 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5874 bus_id = strtol(buf, NULL, 0);
5875 if (bus_id < 0) {
5876 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5877 return -1;
5881 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5882 unit_id = strtol(buf, NULL, 0);
5883 if (unit_id < 0) {
5884 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5885 return -1;
5889 if (get_param_value(buf, sizeof(buf), "if", str)) {
5890 pstrcpy(devname, sizeof(devname), buf);
5891 if (!strcmp(buf, "ide")) {
5892 type = IF_IDE;
5893 max_devs = MAX_IDE_DEVS;
5894 } else if (!strcmp(buf, "scsi")) {
5895 type = IF_SCSI;
5896 max_devs = MAX_SCSI_DEVS;
5897 } else if (!strcmp(buf, "floppy")) {
5898 type = IF_FLOPPY;
5899 max_devs = 0;
5900 } else if (!strcmp(buf, "pflash")) {
5901 type = IF_PFLASH;
5902 max_devs = 0;
5903 } else if (!strcmp(buf, "mtd")) {
5904 type = IF_MTD;
5905 max_devs = 0;
5906 } else if (!strcmp(buf, "sd")) {
5907 type = IF_SD;
5908 max_devs = 0;
5909 } else if (!strcmp(buf, "virtio")) {
5910 type = IF_VIRTIO;
5911 max_devs = 0;
5912 } else {
5913 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5914 return -1;
5918 if (get_param_value(buf, sizeof(buf), "index", str)) {
5919 index = strtol(buf, NULL, 0);
5920 if (index < 0) {
5921 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5922 return -1;
5926 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5927 cyls = strtol(buf, NULL, 0);
5930 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5931 heads = strtol(buf, NULL, 0);
5934 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5935 secs = strtol(buf, NULL, 0);
5938 if (cyls || heads || secs) {
5939 if (cyls < 1 || cyls > 16383) {
5940 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5941 return -1;
5943 if (heads < 1 || heads > 16) {
5944 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5945 return -1;
5947 if (secs < 1 || secs > 63) {
5948 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5949 return -1;
5953 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5954 if (!cyls) {
5955 fprintf(stderr,
5956 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5957 str);
5958 return -1;
5960 if (!strcmp(buf, "none"))
5961 translation = BIOS_ATA_TRANSLATION_NONE;
5962 else if (!strcmp(buf, "lba"))
5963 translation = BIOS_ATA_TRANSLATION_LBA;
5964 else if (!strcmp(buf, "auto"))
5965 translation = BIOS_ATA_TRANSLATION_AUTO;
5966 else {
5967 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5968 return -1;
5972 if (get_param_value(buf, sizeof(buf), "media", str)) {
5973 if (!strcmp(buf, "disk")) {
5974 media = MEDIA_DISK;
5975 } else if (!strcmp(buf, "cdrom")) {
5976 if (cyls || secs || heads) {
5977 fprintf(stderr,
5978 "qemu: '%s' invalid physical CHS format\n", str);
5979 return -1;
5981 media = MEDIA_CDROM;
5982 } else {
5983 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5984 return -1;
5988 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5989 if (!strcmp(buf, "on"))
5990 snapshot = 1;
5991 else if (!strcmp(buf, "off"))
5992 snapshot = 0;
5993 else {
5994 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5995 return -1;
5999 if (get_param_value(buf, sizeof(buf), "cache", str)) {
6000 if (!strcmp(buf, "off"))
6001 cache = 0;
6002 else if (!strcmp(buf, "on"))
6003 cache = 1;
6004 else {
6005 fprintf(stderr, "qemu: invalid cache option\n");
6006 return -1;
6010 if (get_param_value(buf, sizeof(buf), "format", str)) {
6011 if (strcmp(buf, "?") == 0) {
6012 fprintf(stderr, "qemu: Supported formats:");
6013 bdrv_iterate_format(bdrv_format_print, NULL);
6014 fprintf(stderr, "\n");
6015 return -1;
6017 drv = bdrv_find_format(buf);
6018 if (!drv) {
6019 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
6020 return -1;
6024 if (get_param_value(buf, sizeof(buf), "boot", str)) {
6025 if (!strcmp(buf, "on")) {
6026 if (extboot_drive != -1) {
6027 fprintf(stderr, "qemu: two bootable drives specified\n");
6028 return -1;
6030 extboot_drive = nb_drives;
6031 } else if (strcmp(buf, "off")) {
6032 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
6033 return -1;
6037 if (arg->file == NULL)
6038 get_param_value(file, sizeof(file), "file", str);
6039 else
6040 pstrcpy(file, sizeof(file), arg->file);
6042 /* compute bus and unit according index */
6044 if (index != -1) {
6045 if (bus_id != 0 || unit_id != -1) {
6046 fprintf(stderr,
6047 "qemu: '%s' index cannot be used with bus and unit\n", str);
6048 return -1;
6050 if (max_devs == 0)
6052 unit_id = index;
6053 bus_id = 0;
6054 } else {
6055 unit_id = index % max_devs;
6056 bus_id = index / max_devs;
6060 /* if user doesn't specify a unit_id,
6061 * try to find the first free
6064 if (unit_id == -1) {
6065 unit_id = 0;
6066 while (drive_get_index(type, bus_id, unit_id) != -1) {
6067 unit_id++;
6068 if (max_devs && unit_id >= max_devs) {
6069 unit_id -= max_devs;
6070 bus_id++;
6075 /* check unit id */
6077 if (max_devs && unit_id >= max_devs) {
6078 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
6079 str, unit_id, max_devs - 1);
6080 return -1;
6084 * ignore multiple definitions
6087 if (drive_get_index(type, bus_id, unit_id) != -1)
6088 return -2;
6090 /* init */
6092 if (type == IF_IDE || type == IF_SCSI)
6093 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
6094 if (max_devs)
6095 snprintf(buf, sizeof(buf), "%s%i%s%i",
6096 devname, bus_id, mediastr, unit_id);
6097 else
6098 snprintf(buf, sizeof(buf), "%s%s%i",
6099 devname, mediastr, unit_id);
6100 bdrv = bdrv_new(buf);
6101 drives_table_idx = drive_get_free_idx();
6102 drives_table[drives_table_idx].bdrv = bdrv;
6103 drives_table[drives_table_idx].type = type;
6104 drives_table[drives_table_idx].bus = bus_id;
6105 drives_table[drives_table_idx].unit = unit_id;
6106 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
6107 nb_drives++;
6109 switch(type) {
6110 case IF_IDE:
6111 case IF_SCSI:
6112 switch(media) {
6113 case MEDIA_DISK:
6114 if (cyls != 0) {
6115 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
6116 bdrv_set_translation_hint(bdrv, translation);
6118 break;
6119 case MEDIA_CDROM:
6120 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
6121 break;
6123 break;
6124 case IF_SD:
6125 /* FIXME: This isn't really a floppy, but it's a reasonable
6126 approximation. */
6127 case IF_FLOPPY:
6128 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
6129 break;
6130 case IF_PFLASH:
6131 case IF_MTD:
6132 case IF_VIRTIO:
6133 break;
6135 if (!file[0])
6136 return -2;
6137 bdrv_flags = 0;
6138 if (snapshot)
6139 bdrv_flags |= BDRV_O_SNAPSHOT;
6140 if (!cache)
6141 bdrv_flags |= BDRV_O_DIRECT;
6142 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
6143 fprintf(stderr, "qemu: could not open disk image %s\n",
6144 file);
6145 return -1;
6147 return drives_table_idx;
6150 /***********************************************************/
6151 /* USB devices */
6153 static USBPort *used_usb_ports;
6154 static USBPort *free_usb_ports;
6156 /* ??? Maybe change this to register a hub to keep track of the topology. */
6157 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
6158 usb_attachfn attach)
6160 port->opaque = opaque;
6161 port->index = index;
6162 port->attach = attach;
6163 port->next = free_usb_ports;
6164 free_usb_ports = port;
6167 int usb_device_add_dev(USBDevice *dev)
6169 USBPort *port;
6171 /* Find a USB port to add the device to. */
6172 port = free_usb_ports;
6173 if (!port->next) {
6174 USBDevice *hub;
6176 /* Create a new hub and chain it on. */
6177 free_usb_ports = NULL;
6178 port->next = used_usb_ports;
6179 used_usb_ports = port;
6181 hub = usb_hub_init(VM_USB_HUB_SIZE);
6182 usb_attach(port, hub);
6183 port = free_usb_ports;
6186 free_usb_ports = port->next;
6187 port->next = used_usb_ports;
6188 used_usb_ports = port;
6189 usb_attach(port, dev);
6190 return 0;
6193 static int usb_device_add(const char *devname)
6195 const char *p;
6196 USBDevice *dev;
6197 USBPort *port;
6199 if (!free_usb_ports)
6200 return -1;
6202 if (strstart(devname, "host:", &p)) {
6203 dev = usb_host_device_open(p);
6204 } else if (!strcmp(devname, "mouse")) {
6205 dev = usb_mouse_init();
6206 } else if (!strcmp(devname, "tablet")) {
6207 dev = usb_tablet_init();
6208 } else if (!strcmp(devname, "keyboard")) {
6209 dev = usb_keyboard_init();
6210 } else if (strstart(devname, "disk:", &p)) {
6211 dev = usb_msd_init(p);
6212 } else if (!strcmp(devname, "wacom-tablet")) {
6213 dev = usb_wacom_init();
6214 } else if (strstart(devname, "serial:", &p)) {
6215 dev = usb_serial_init(p);
6216 #ifdef CONFIG_BRLAPI
6217 } else if (!strcmp(devname, "braille")) {
6218 dev = usb_baum_init();
6219 #endif
6220 } else if (strstart(devname, "net:", &p)) {
6221 int nic = nb_nics;
6223 if (net_client_init("nic", p) < 0)
6224 return -1;
6225 nd_table[nic].model = "usb";
6226 dev = usb_net_init(&nd_table[nic]);
6227 } else {
6228 return -1;
6230 if (!dev)
6231 return -1;
6233 return usb_device_add_dev(dev);
6236 int usb_device_del_addr(int bus_num, int addr)
6238 USBPort *port;
6239 USBPort **lastp;
6240 USBDevice *dev;
6242 if (!used_usb_ports)
6243 return -1;
6245 if (bus_num != 0)
6246 return -1;
6248 lastp = &used_usb_ports;
6249 port = used_usb_ports;
6250 while (port && port->dev->addr != addr) {
6251 lastp = &port->next;
6252 port = port->next;
6255 if (!port)
6256 return -1;
6258 dev = port->dev;
6259 *lastp = port->next;
6260 usb_attach(port, NULL);
6261 dev->handle_destroy(dev);
6262 port->next = free_usb_ports;
6263 free_usb_ports = port;
6264 return 0;
6267 static int usb_device_del(const char *devname)
6269 int bus_num, addr;
6270 const char *p;
6272 if (!used_usb_ports)
6273 return -1;
6275 p = strchr(devname, '.');
6276 if (!p)
6277 return -1;
6278 bus_num = strtoul(devname, NULL, 0);
6279 addr = strtoul(p + 1, NULL, 0);
6281 return usb_device_del_addr(bus_num, addr);
6284 void do_usb_add(const char *devname)
6286 usb_device_add(devname);
6289 void do_usb_del(const char *devname)
6291 usb_device_del(devname);
6294 void usb_info(void)
6296 USBDevice *dev;
6297 USBPort *port;
6298 const char *speed_str;
6300 if (!usb_enabled) {
6301 term_printf("USB support not enabled\n");
6302 return;
6305 for (port = used_usb_ports; port; port = port->next) {
6306 dev = port->dev;
6307 if (!dev)
6308 continue;
6309 switch(dev->speed) {
6310 case USB_SPEED_LOW:
6311 speed_str = "1.5";
6312 break;
6313 case USB_SPEED_FULL:
6314 speed_str = "12";
6315 break;
6316 case USB_SPEED_HIGH:
6317 speed_str = "480";
6318 break;
6319 default:
6320 speed_str = "?";
6321 break;
6323 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6324 0, dev->addr, speed_str, dev->devname);
6328 /***********************************************************/
6329 /* PCMCIA/Cardbus */
6331 static struct pcmcia_socket_entry_s {
6332 struct pcmcia_socket_s *socket;
6333 struct pcmcia_socket_entry_s *next;
6334 } *pcmcia_sockets = 0;
6336 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
6338 struct pcmcia_socket_entry_s *entry;
6340 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
6341 entry->socket = socket;
6342 entry->next = pcmcia_sockets;
6343 pcmcia_sockets = entry;
6346 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
6348 struct pcmcia_socket_entry_s *entry, **ptr;
6350 ptr = &pcmcia_sockets;
6351 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
6352 if (entry->socket == socket) {
6353 *ptr = entry->next;
6354 qemu_free(entry);
6358 void pcmcia_info(void)
6360 struct pcmcia_socket_entry_s *iter;
6361 if (!pcmcia_sockets)
6362 term_printf("No PCMCIA sockets\n");
6364 for (iter = pcmcia_sockets; iter; iter = iter->next)
6365 term_printf("%s: %s\n", iter->socket->slot_string,
6366 iter->socket->attached ? iter->socket->card_string :
6367 "Empty");
6370 /***********************************************************/
6371 /* dumb display */
6373 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
6377 static void dumb_resize(DisplayState *ds, int w, int h)
6381 static void dumb_refresh(DisplayState *ds)
6383 #if defined(CONFIG_SDL)
6384 vga_hw_update();
6385 #endif
6388 static void dumb_display_init(DisplayState *ds)
6390 ds->data = NULL;
6391 ds->linesize = 0;
6392 ds->depth = 0;
6393 ds->dpy_update = dumb_update;
6394 ds->dpy_resize = dumb_resize;
6395 ds->dpy_refresh = dumb_refresh;
6396 ds->gui_timer_interval = 500;
6397 ds->idle = 1;
6400 /***********************************************************/
6401 /* I/O handling */
6403 #define MAX_IO_HANDLERS 64
6405 typedef struct IOHandlerRecord {
6406 int fd;
6407 IOCanRWHandler *fd_read_poll;
6408 IOHandler *fd_read;
6409 IOHandler *fd_write;
6410 int deleted;
6411 void *opaque;
6412 /* temporary data */
6413 struct pollfd *ufd;
6414 struct IOHandlerRecord *next;
6415 } IOHandlerRecord;
6417 static IOHandlerRecord *first_io_handler;
6419 /* XXX: fd_read_poll should be suppressed, but an API change is
6420 necessary in the character devices to suppress fd_can_read(). */
6421 int qemu_set_fd_handler2(int fd,
6422 IOCanRWHandler *fd_read_poll,
6423 IOHandler *fd_read,
6424 IOHandler *fd_write,
6425 void *opaque)
6427 IOHandlerRecord **pioh, *ioh;
6429 if (!fd_read && !fd_write) {
6430 pioh = &first_io_handler;
6431 for(;;) {
6432 ioh = *pioh;
6433 if (ioh == NULL)
6434 break;
6435 if (ioh->fd == fd) {
6436 ioh->deleted = 1;
6437 break;
6439 pioh = &ioh->next;
6441 } else {
6442 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6443 if (ioh->fd == fd)
6444 goto found;
6446 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6447 if (!ioh)
6448 return -1;
6449 ioh->next = first_io_handler;
6450 first_io_handler = ioh;
6451 found:
6452 ioh->fd = fd;
6453 ioh->fd_read_poll = fd_read_poll;
6454 ioh->fd_read = fd_read;
6455 ioh->fd_write = fd_write;
6456 ioh->opaque = opaque;
6457 ioh->deleted = 0;
6459 main_loop_break();
6460 return 0;
6463 int qemu_set_fd_handler(int fd,
6464 IOHandler *fd_read,
6465 IOHandler *fd_write,
6466 void *opaque)
6468 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6471 /***********************************************************/
6472 /* Polling handling */
6474 typedef struct PollingEntry {
6475 PollingFunc *func;
6476 void *opaque;
6477 struct PollingEntry *next;
6478 } PollingEntry;
6480 static PollingEntry *first_polling_entry;
6482 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6484 PollingEntry **ppe, *pe;
6485 pe = qemu_mallocz(sizeof(PollingEntry));
6486 if (!pe)
6487 return -1;
6488 pe->func = func;
6489 pe->opaque = opaque;
6490 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6491 *ppe = pe;
6492 return 0;
6495 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6497 PollingEntry **ppe, *pe;
6498 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6499 pe = *ppe;
6500 if (pe->func == func && pe->opaque == opaque) {
6501 *ppe = pe->next;
6502 qemu_free(pe);
6503 break;
6508 #ifdef _WIN32
6509 /***********************************************************/
6510 /* Wait objects support */
6511 typedef struct WaitObjects {
6512 int num;
6513 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6514 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6515 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6516 } WaitObjects;
6518 static WaitObjects wait_objects = {0};
6520 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6522 WaitObjects *w = &wait_objects;
6524 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6525 return -1;
6526 w->events[w->num] = handle;
6527 w->func[w->num] = func;
6528 w->opaque[w->num] = opaque;
6529 w->num++;
6530 return 0;
6533 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6535 int i, found;
6536 WaitObjects *w = &wait_objects;
6538 found = 0;
6539 for (i = 0; i < w->num; i++) {
6540 if (w->events[i] == handle)
6541 found = 1;
6542 if (found) {
6543 w->events[i] = w->events[i + 1];
6544 w->func[i] = w->func[i + 1];
6545 w->opaque[i] = w->opaque[i + 1];
6548 if (found)
6549 w->num--;
6551 #endif
6553 #define SELF_ANNOUNCE_ROUNDS 5
6554 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6555 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6556 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6558 static int announce_self_create(uint8_t *buf,
6559 uint8_t *mac_addr)
6561 uint32_t magic = EXPERIMENTAL_MAGIC;
6562 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
6564 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6566 memset(buf, 0xff, 6); /* h_dst */
6567 memcpy(buf + 6, mac_addr, 6); /* h_src */
6568 memcpy(buf + 12, &proto, 2); /* h_proto */
6569 memcpy(buf + 14, &magic, 4); /* magic */
6571 return 18; /* len */
6574 static void qemu_announce_self(void)
6576 int i, j, len;
6577 VLANState *vlan;
6578 VLANClientState *vc;
6579 uint8_t buf[256];
6581 for (i = 0; i < nb_nics; i++) {
6582 len = announce_self_create(buf, nd_table[i].macaddr);
6583 vlan = nd_table[i].vlan;
6584 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
6585 if (vc->fd_read == tap_receive) /* send only if tap */
6586 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
6587 vc->fd_read(vc->opaque, buf, len);
6592 /***********************************************************/
6593 /* savevm/loadvm support */
6595 #define IO_BUF_SIZE 32768
6597 struct QEMUFile {
6598 QEMUFilePutBufferFunc *put_buffer;
6599 QEMUFileGetBufferFunc *get_buffer;
6600 QEMUFileCloseFunc *close;
6601 void *opaque;
6603 int64_t buf_offset; /* start of buffer when writing, end of buffer
6604 when reading */
6605 int buf_index;
6606 int buf_size; /* 0 when writing */
6607 uint8_t buf[IO_BUF_SIZE];
6610 typedef struct QEMUFileFD
6612 int fd;
6613 } QEMUFileFD;
6615 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6617 QEMUFileFD *s = opaque;
6618 int offset = 0;
6619 ssize_t len;
6621 again:
6622 len = read(s->fd, buf + offset, size - offset);
6623 if (len == -1) {
6624 if (errno == EINTR || errno == EAGAIN)
6625 goto again;
6628 return len;
6631 QEMUFile *qemu_fopen_fd(int fd)
6633 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
6634 s->fd = fd;
6635 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
6638 typedef struct QEMUFileUnix
6640 FILE *outfile;
6641 } QEMUFileUnix;
6643 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6645 QEMUFileUnix *s = opaque;
6646 fseek(s->outfile, pos, SEEK_SET);
6647 fwrite(buf, 1, size, s->outfile);
6650 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6652 QEMUFileUnix *s = opaque;
6653 fseek(s->outfile, pos, SEEK_SET);
6654 return fread(buf, 1, size, s->outfile);
6657 static void file_close(void *opaque)
6659 QEMUFileUnix *s = opaque;
6660 fclose(s->outfile);
6661 qemu_free(s);
6664 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
6666 QEMUFileUnix *s;
6668 s = qemu_mallocz(sizeof(QEMUFileUnix));
6669 if (!s)
6670 return NULL;
6672 s->outfile = fopen(filename, mode);
6673 if (!s->outfile)
6674 goto fail;
6676 if (!strcmp(mode, "wb"))
6677 return qemu_fopen(s, file_put_buffer, NULL, file_close);
6678 else if (!strcmp(mode, "rb"))
6679 return qemu_fopen(s, NULL, file_get_buffer, file_close);
6681 fail:
6682 if (s->outfile)
6683 fclose(s->outfile);
6684 qemu_free(s);
6685 return NULL;
6688 typedef struct QEMUFileBdrv
6690 BlockDriverState *bs;
6691 int64_t base_offset;
6692 } QEMUFileBdrv;
6694 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6696 QEMUFileBdrv *s = opaque;
6697 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
6700 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6702 QEMUFileBdrv *s = opaque;
6703 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6706 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6708 QEMUFileBdrv *s;
6710 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6711 if (!s)
6712 return NULL;
6714 s->bs = bs;
6715 s->base_offset = offset;
6717 if (is_writable)
6718 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
6720 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
6723 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6724 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
6726 QEMUFile *f;
6728 f = qemu_mallocz(sizeof(QEMUFile));
6729 if (!f)
6730 return NULL;
6732 f->opaque = opaque;
6733 f->put_buffer = put_buffer;
6734 f->get_buffer = get_buffer;
6735 f->close = close;
6737 return f;
6740 void qemu_fflush(QEMUFile *f)
6742 if (!f->put_buffer)
6743 return;
6745 if (f->buf_index > 0) {
6746 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
6747 f->buf_offset += f->buf_index;
6748 f->buf_index = 0;
6752 static void qemu_fill_buffer(QEMUFile *f)
6754 int len;
6756 if (!f->get_buffer)
6757 return;
6759 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6760 if (len < 0)
6761 len = 0;
6763 f->buf_index = 0;
6764 f->buf_size = len;
6765 f->buf_offset += len;
6768 void qemu_fclose(QEMUFile *f)
6770 qemu_fflush(f);
6771 if (f->close)
6772 f->close(f->opaque);
6773 qemu_free(f);
6776 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6778 int l;
6779 while (size > 0) {
6780 l = IO_BUF_SIZE - f->buf_index;
6781 if (l > size)
6782 l = size;
6783 memcpy(f->buf + f->buf_index, buf, l);
6784 f->buf_index += l;
6785 buf += l;
6786 size -= l;
6787 if (f->buf_index >= IO_BUF_SIZE)
6788 qemu_fflush(f);
6792 void qemu_put_byte(QEMUFile *f, int v)
6794 f->buf[f->buf_index++] = v;
6795 if (f->buf_index >= IO_BUF_SIZE)
6796 qemu_fflush(f);
6799 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6801 int size, l;
6803 size = size1;
6804 while (size > 0) {
6805 l = f->buf_size - f->buf_index;
6806 if (l == 0) {
6807 qemu_fill_buffer(f);
6808 l = f->buf_size - f->buf_index;
6809 if (l == 0)
6810 break;
6812 if (l > size)
6813 l = size;
6814 memcpy(buf, f->buf + f->buf_index, l);
6815 f->buf_index += l;
6816 buf += l;
6817 size -= l;
6819 return size1 - size;
6822 int qemu_get_byte(QEMUFile *f)
6824 if (f->buf_index >= f->buf_size) {
6825 qemu_fill_buffer(f);
6826 if (f->buf_index >= f->buf_size)
6827 return 0;
6829 return f->buf[f->buf_index++];
6832 int64_t qemu_ftell(QEMUFile *f)
6834 return f->buf_offset - f->buf_size + f->buf_index;
6837 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6839 if (whence == SEEK_SET) {
6840 /* nothing to do */
6841 } else if (whence == SEEK_CUR) {
6842 pos += qemu_ftell(f);
6843 } else {
6844 /* SEEK_END not supported */
6845 return -1;
6847 if (f->put_buffer) {
6848 qemu_fflush(f);
6849 f->buf_offset = pos;
6850 } else {
6851 f->buf_offset = pos;
6852 f->buf_index = 0;
6853 f->buf_size = 0;
6855 return pos;
6858 void qemu_put_be16(QEMUFile *f, unsigned int v)
6860 qemu_put_byte(f, v >> 8);
6861 qemu_put_byte(f, v);
6864 void qemu_put_be32(QEMUFile *f, unsigned int v)
6866 qemu_put_byte(f, v >> 24);
6867 qemu_put_byte(f, v >> 16);
6868 qemu_put_byte(f, v >> 8);
6869 qemu_put_byte(f, v);
6872 void qemu_put_be64(QEMUFile *f, uint64_t v)
6874 qemu_put_be32(f, v >> 32);
6875 qemu_put_be32(f, v);
6878 unsigned int qemu_get_be16(QEMUFile *f)
6880 unsigned int v;
6881 v = qemu_get_byte(f) << 8;
6882 v |= qemu_get_byte(f);
6883 return v;
6886 unsigned int qemu_get_be32(QEMUFile *f)
6888 unsigned int v;
6889 v = qemu_get_byte(f) << 24;
6890 v |= qemu_get_byte(f) << 16;
6891 v |= qemu_get_byte(f) << 8;
6892 v |= qemu_get_byte(f);
6893 return v;
6896 uint64_t qemu_get_be64(QEMUFile *f)
6898 uint64_t v;
6899 v = (uint64_t)qemu_get_be32(f) << 32;
6900 v |= qemu_get_be32(f);
6901 return v;
6904 typedef struct SaveStateEntry {
6905 char idstr[256];
6906 int instance_id;
6907 int version_id;
6908 SaveStateHandler *save_state;
6909 LoadStateHandler *load_state;
6910 void *opaque;
6911 struct SaveStateEntry *next;
6912 } SaveStateEntry;
6914 static SaveStateEntry *first_se;
6916 /* TODO: Individual devices generally have very little idea about the rest
6917 of the system, so instance_id should be removed/replaced.
6918 Meanwhile pass -1 as instance_id if you do not already have a clearly
6919 distinguishing id for all instances of your device class. */
6920 int register_savevm(const char *idstr,
6921 int instance_id,
6922 int version_id,
6923 SaveStateHandler *save_state,
6924 LoadStateHandler *load_state,
6925 void *opaque)
6927 SaveStateEntry *se, **pse;
6929 se = qemu_malloc(sizeof(SaveStateEntry));
6930 if (!se)
6931 return -1;
6932 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6933 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6934 se->version_id = version_id;
6935 se->save_state = save_state;
6936 se->load_state = load_state;
6937 se->opaque = opaque;
6938 se->next = NULL;
6940 /* add at the end of list */
6941 pse = &first_se;
6942 while (*pse != NULL) {
6943 if (instance_id == -1
6944 && strcmp(se->idstr, (*pse)->idstr) == 0
6945 && se->instance_id <= (*pse)->instance_id)
6946 se->instance_id = (*pse)->instance_id + 1;
6947 pse = &(*pse)->next;
6949 *pse = se;
6950 return 0;
6953 #define QEMU_VM_FILE_MAGIC 0x5145564d
6954 #define QEMU_VM_FILE_VERSION 0x00000002
6956 static int qemu_savevm_state(QEMUFile *f)
6958 SaveStateEntry *se;
6959 int len, ret;
6960 int64_t cur_pos, len_pos, total_len_pos;
6962 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6963 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6964 total_len_pos = qemu_ftell(f);
6965 qemu_put_be64(f, 0); /* total size */
6967 for(se = first_se; se != NULL; se = se->next) {
6968 if (se->save_state == NULL)
6969 /* this one has a loader only, for backwards compatibility */
6970 continue;
6972 /* ID string */
6973 len = strlen(se->idstr);
6974 qemu_put_byte(f, len);
6975 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6977 qemu_put_be32(f, se->instance_id);
6978 qemu_put_be32(f, se->version_id);
6980 /* record size: filled later */
6981 len_pos = qemu_ftell(f);
6982 qemu_put_be32(f, 0);
6983 se->save_state(f, se->opaque);
6985 /* fill record size */
6986 cur_pos = qemu_ftell(f);
6987 len = cur_pos - len_pos - 4;
6988 qemu_fseek(f, len_pos, SEEK_SET);
6989 qemu_put_be32(f, len);
6990 qemu_fseek(f, cur_pos, SEEK_SET);
6992 cur_pos = qemu_ftell(f);
6993 qemu_fseek(f, total_len_pos, SEEK_SET);
6994 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6995 qemu_fseek(f, cur_pos, SEEK_SET);
6997 ret = 0;
6998 return ret;
7001 static SaveStateEntry *find_se(const char *idstr, int instance_id)
7003 SaveStateEntry *se;
7005 for(se = first_se; se != NULL; se = se->next) {
7006 if (!strcmp(se->idstr, idstr) &&
7007 instance_id == se->instance_id)
7008 return se;
7010 return NULL;
7013 static int qemu_loadvm_state(QEMUFile *f)
7015 SaveStateEntry *se;
7016 int len, ret, instance_id, record_len, version_id;
7017 int64_t total_len, end_pos, cur_pos;
7018 unsigned int v;
7019 char idstr[256];
7021 v = qemu_get_be32(f);
7022 if (v != QEMU_VM_FILE_MAGIC)
7023 goto fail;
7024 v = qemu_get_be32(f);
7025 if (v != QEMU_VM_FILE_VERSION) {
7026 fail:
7027 ret = -1;
7028 goto the_end;
7030 total_len = qemu_get_be64(f);
7031 end_pos = total_len + qemu_ftell(f);
7032 for(;;) {
7033 if (qemu_ftell(f) >= end_pos)
7034 break;
7035 len = qemu_get_byte(f);
7036 qemu_get_buffer(f, (uint8_t *)idstr, len);
7037 idstr[len] = '\0';
7038 instance_id = qemu_get_be32(f);
7039 version_id = qemu_get_be32(f);
7040 record_len = qemu_get_be32(f);
7041 #if 0
7042 printf("idstr=%s instance=0x%x version=%d len=%d\n",
7043 idstr, instance_id, version_id, record_len);
7044 #endif
7045 cur_pos = qemu_ftell(f);
7046 se = find_se(idstr, instance_id);
7047 if (!se) {
7048 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7049 instance_id, idstr);
7050 } else {
7051 ret = se->load_state(f, se->opaque, version_id);
7052 if (ret < 0) {
7053 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7054 instance_id, idstr);
7055 goto the_end;
7058 /* always seek to exact end of record */
7059 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
7061 ret = 0;
7062 the_end:
7063 return ret;
7066 int qemu_live_savevm_state(QEMUFile *f)
7068 SaveStateEntry *se;
7069 int len, ret;
7071 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
7072 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
7074 for(se = first_se; se != NULL; se = se->next) {
7075 len = strlen(se->idstr);
7077 qemu_put_byte(f, len);
7078 qemu_put_buffer(f, se->idstr, len);
7079 qemu_put_be32(f, se->instance_id);
7080 qemu_put_be32(f, se->version_id);
7082 se->save_state(f, se->opaque);
7085 qemu_put_byte(f, 0);
7087 ret = 0;
7088 return ret;
7091 int qemu_live_loadvm_state(QEMUFile *f)
7093 SaveStateEntry *se;
7094 int len, ret, instance_id, version_id;
7095 unsigned int v;
7096 char idstr[256];
7098 v = qemu_get_be32(f);
7099 if (v != QEMU_VM_FILE_MAGIC)
7100 goto fail;
7101 v = qemu_get_be32(f);
7102 if (v != QEMU_VM_FILE_VERSION) {
7103 fail:
7104 ret = -1;
7105 goto the_end;
7108 for(;;) {
7109 len = qemu_get_byte(f);
7110 if (len == 0)
7111 break;
7112 qemu_get_buffer(f, idstr, len);
7113 idstr[len] = '\0';
7114 instance_id = qemu_get_be32(f);
7115 version_id = qemu_get_be32(f);
7116 se = find_se(idstr, instance_id);
7117 if (!se) {
7118 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7119 instance_id, idstr);
7120 } else {
7121 if (version_id > se->version_id) { /* src version > dst version */
7122 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7123 idstr, version_id, se->version_id);
7124 ret = -1;
7125 goto the_end;
7127 ret = se->load_state(f, se->opaque, version_id);
7128 if (ret < 0) {
7129 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7130 instance_id, idstr);
7131 goto the_end;
7135 ret = 0;
7137 qemu_announce_self();
7139 the_end:
7140 return ret;
7143 /* device can contain snapshots */
7144 static int bdrv_can_snapshot(BlockDriverState *bs)
7146 return (bs &&
7147 !bdrv_is_removable(bs) &&
7148 !bdrv_is_read_only(bs));
7151 /* device must be snapshots in order to have a reliable snapshot */
7152 static int bdrv_has_snapshot(BlockDriverState *bs)
7154 return (bs &&
7155 !bdrv_is_removable(bs) &&
7156 !bdrv_is_read_only(bs));
7159 static BlockDriverState *get_bs_snapshots(void)
7161 BlockDriverState *bs;
7162 int i;
7164 if (bs_snapshots)
7165 return bs_snapshots;
7166 for(i = 0; i <= nb_drives; i++) {
7167 bs = drives_table[i].bdrv;
7168 if (bdrv_can_snapshot(bs))
7169 goto ok;
7171 return NULL;
7173 bs_snapshots = bs;
7174 return bs;
7177 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
7178 const char *name)
7180 QEMUSnapshotInfo *sn_tab, *sn;
7181 int nb_sns, i, ret;
7183 ret = -ENOENT;
7184 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7185 if (nb_sns < 0)
7186 return ret;
7187 for(i = 0; i < nb_sns; i++) {
7188 sn = &sn_tab[i];
7189 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
7190 *sn_info = *sn;
7191 ret = 0;
7192 break;
7195 qemu_free(sn_tab);
7196 return ret;
7199 void do_savevm(const char *name)
7201 BlockDriverState *bs, *bs1;
7202 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
7203 int must_delete, ret, i;
7204 BlockDriverInfo bdi1, *bdi = &bdi1;
7205 QEMUFile *f;
7206 int saved_vm_running;
7207 #ifdef _WIN32
7208 struct _timeb tb;
7209 #else
7210 struct timeval tv;
7211 #endif
7213 bs = get_bs_snapshots();
7214 if (!bs) {
7215 term_printf("No block device can accept snapshots\n");
7216 return;
7219 /* ??? Should this occur after vm_stop? */
7220 qemu_aio_flush();
7222 saved_vm_running = vm_running;
7223 vm_stop(0);
7225 must_delete = 0;
7226 if (name) {
7227 ret = bdrv_snapshot_find(bs, old_sn, name);
7228 if (ret >= 0) {
7229 must_delete = 1;
7232 memset(sn, 0, sizeof(*sn));
7233 if (must_delete) {
7234 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
7235 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
7236 } else {
7237 if (name)
7238 pstrcpy(sn->name, sizeof(sn->name), name);
7241 /* fill auxiliary fields */
7242 #ifdef _WIN32
7243 _ftime(&tb);
7244 sn->date_sec = tb.time;
7245 sn->date_nsec = tb.millitm * 1000000;
7246 #else
7247 gettimeofday(&tv, NULL);
7248 sn->date_sec = tv.tv_sec;
7249 sn->date_nsec = tv.tv_usec * 1000;
7250 #endif
7251 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
7253 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7254 term_printf("Device %s does not support VM state snapshots\n",
7255 bdrv_get_device_name(bs));
7256 goto the_end;
7259 /* save the VM state */
7260 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
7261 if (!f) {
7262 term_printf("Could not open VM state file\n");
7263 goto the_end;
7265 ret = qemu_savevm_state(f);
7266 sn->vm_state_size = qemu_ftell(f);
7267 qemu_fclose(f);
7268 if (ret < 0) {
7269 term_printf("Error %d while writing VM\n", ret);
7270 goto the_end;
7273 /* create the snapshots */
7275 for(i = 0; i < nb_drives; i++) {
7276 bs1 = drives_table[i].bdrv;
7277 if (bdrv_has_snapshot(bs1)) {
7278 if (must_delete) {
7279 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
7280 if (ret < 0) {
7281 term_printf("Error while deleting snapshot on '%s'\n",
7282 bdrv_get_device_name(bs1));
7285 ret = bdrv_snapshot_create(bs1, sn);
7286 if (ret < 0) {
7287 term_printf("Error while creating snapshot on '%s'\n",
7288 bdrv_get_device_name(bs1));
7293 the_end:
7294 if (saved_vm_running)
7295 vm_start();
7298 void do_loadvm(const char *name)
7300 BlockDriverState *bs, *bs1;
7301 BlockDriverInfo bdi1, *bdi = &bdi1;
7302 QEMUFile *f;
7303 int i, ret;
7304 int saved_vm_running;
7306 bs = get_bs_snapshots();
7307 if (!bs) {
7308 term_printf("No block device supports snapshots\n");
7309 return;
7312 /* Flush all IO requests so they don't interfere with the new state. */
7313 qemu_aio_flush();
7315 saved_vm_running = vm_running;
7316 vm_stop(0);
7318 for(i = 0; i <= nb_drives; i++) {
7319 bs1 = drives_table[i].bdrv;
7320 if (bdrv_has_snapshot(bs1)) {
7321 ret = bdrv_snapshot_goto(bs1, name);
7322 if (ret < 0) {
7323 if (bs != bs1)
7324 term_printf("Warning: ");
7325 switch(ret) {
7326 case -ENOTSUP:
7327 term_printf("Snapshots not supported on device '%s'\n",
7328 bdrv_get_device_name(bs1));
7329 break;
7330 case -ENOENT:
7331 term_printf("Could not find snapshot '%s' on device '%s'\n",
7332 name, bdrv_get_device_name(bs1));
7333 break;
7334 default:
7335 term_printf("Error %d while activating snapshot on '%s'\n",
7336 ret, bdrv_get_device_name(bs1));
7337 break;
7339 /* fatal on snapshot block device */
7340 if (bs == bs1)
7341 goto the_end;
7346 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7347 term_printf("Device %s does not support VM state snapshots\n",
7348 bdrv_get_device_name(bs));
7349 return;
7352 /* restore the VM state */
7353 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
7354 if (!f) {
7355 term_printf("Could not open VM state file\n");
7356 goto the_end;
7358 ret = qemu_loadvm_state(f);
7359 qemu_fclose(f);
7360 if (ret < 0) {
7361 term_printf("Error %d while loading VM state\n", ret);
7363 the_end:
7364 if (saved_vm_running)
7365 vm_start();
7368 void do_delvm(const char *name)
7370 BlockDriverState *bs, *bs1;
7371 int i, ret;
7373 bs = get_bs_snapshots();
7374 if (!bs) {
7375 term_printf("No block device supports snapshots\n");
7376 return;
7379 for(i = 0; i <= nb_drives; i++) {
7380 bs1 = drives_table[i].bdrv;
7381 if (bdrv_has_snapshot(bs1)) {
7382 ret = bdrv_snapshot_delete(bs1, name);
7383 if (ret < 0) {
7384 if (ret == -ENOTSUP)
7385 term_printf("Snapshots not supported on device '%s'\n",
7386 bdrv_get_device_name(bs1));
7387 else
7388 term_printf("Error %d while deleting snapshot on '%s'\n",
7389 ret, bdrv_get_device_name(bs1));
7395 void do_info_snapshots(void)
7397 BlockDriverState *bs, *bs1;
7398 QEMUSnapshotInfo *sn_tab, *sn;
7399 int nb_sns, i;
7400 char buf[256];
7402 bs = get_bs_snapshots();
7403 if (!bs) {
7404 term_printf("No available block device supports snapshots\n");
7405 return;
7407 term_printf("Snapshot devices:");
7408 for(i = 0; i <= nb_drives; i++) {
7409 bs1 = drives_table[i].bdrv;
7410 if (bdrv_has_snapshot(bs1)) {
7411 if (bs == bs1)
7412 term_printf(" %s", bdrv_get_device_name(bs1));
7415 term_printf("\n");
7417 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7418 if (nb_sns < 0) {
7419 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
7420 return;
7422 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
7423 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
7424 for(i = 0; i < nb_sns; i++) {
7425 sn = &sn_tab[i];
7426 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
7428 qemu_free(sn_tab);
7431 /***********************************************************/
7432 /* ram save/restore */
7434 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7436 int v;
7438 v = qemu_get_byte(f);
7439 switch(v) {
7440 case 0:
7441 if (qemu_get_buffer(f, buf, len) != len)
7442 return -EIO;
7443 break;
7444 case 1:
7445 v = qemu_get_byte(f);
7446 memset(buf, v, len);
7447 break;
7448 default:
7449 return -EINVAL;
7451 return 0;
7454 static int ram_load_v1(QEMUFile *f, void *opaque)
7456 int ret;
7457 ram_addr_t i;
7459 if (qemu_get_be32(f) != phys_ram_size)
7460 return -EINVAL;
7461 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7462 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7463 continue;
7464 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7465 if (ret)
7466 return ret;
7468 return 0;
7471 #define BDRV_HASH_BLOCK_SIZE 1024
7472 #define IOBUF_SIZE 4096
7473 #define RAM_CBLOCK_MAGIC 0xfabe
7475 typedef struct RamCompressState {
7476 z_stream zstream;
7477 QEMUFile *f;
7478 uint8_t buf[IOBUF_SIZE];
7479 } RamCompressState;
7481 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7483 int ret;
7484 memset(s, 0, sizeof(*s));
7485 s->f = f;
7486 ret = deflateInit2(&s->zstream, 1,
7487 Z_DEFLATED, 15,
7488 9, Z_DEFAULT_STRATEGY);
7489 if (ret != Z_OK)
7490 return -1;
7491 s->zstream.avail_out = IOBUF_SIZE;
7492 s->zstream.next_out = s->buf;
7493 return 0;
7496 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7498 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7499 qemu_put_be16(s->f, len);
7500 qemu_put_buffer(s->f, buf, len);
7503 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7505 int ret;
7507 s->zstream.avail_in = len;
7508 s->zstream.next_in = (uint8_t *)buf;
7509 while (s->zstream.avail_in > 0) {
7510 ret = deflate(&s->zstream, Z_NO_FLUSH);
7511 if (ret != Z_OK)
7512 return -1;
7513 if (s->zstream.avail_out == 0) {
7514 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7515 s->zstream.avail_out = IOBUF_SIZE;
7516 s->zstream.next_out = s->buf;
7519 return 0;
7522 static void ram_compress_close(RamCompressState *s)
7524 int len, ret;
7526 /* compress last bytes */
7527 for(;;) {
7528 ret = deflate(&s->zstream, Z_FINISH);
7529 if (ret == Z_OK || ret == Z_STREAM_END) {
7530 len = IOBUF_SIZE - s->zstream.avail_out;
7531 if (len > 0) {
7532 ram_put_cblock(s, s->buf, len);
7534 s->zstream.avail_out = IOBUF_SIZE;
7535 s->zstream.next_out = s->buf;
7536 if (ret == Z_STREAM_END)
7537 break;
7538 } else {
7539 goto fail;
7542 fail:
7543 deflateEnd(&s->zstream);
7546 typedef struct RamDecompressState {
7547 z_stream zstream;
7548 QEMUFile *f;
7549 uint8_t buf[IOBUF_SIZE];
7550 } RamDecompressState;
7552 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7554 int ret;
7555 memset(s, 0, sizeof(*s));
7556 s->f = f;
7557 ret = inflateInit(&s->zstream);
7558 if (ret != Z_OK)
7559 return -1;
7560 return 0;
7563 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7565 int ret, clen;
7567 s->zstream.avail_out = len;
7568 s->zstream.next_out = buf;
7569 while (s->zstream.avail_out > 0) {
7570 if (s->zstream.avail_in == 0) {
7571 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7572 return -1;
7573 clen = qemu_get_be16(s->f);
7574 if (clen > IOBUF_SIZE)
7575 return -1;
7576 qemu_get_buffer(s->f, s->buf, clen);
7577 s->zstream.avail_in = clen;
7578 s->zstream.next_in = s->buf;
7580 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7581 if (ret != Z_OK && ret != Z_STREAM_END) {
7582 return -1;
7585 return 0;
7588 static void ram_decompress_close(RamDecompressState *s)
7590 inflateEnd(&s->zstream);
7593 static void ram_save_live(QEMUFile *f, void *opaque)
7595 target_ulong addr;
7597 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7598 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
7599 continue;
7600 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
7601 qemu_put_be32(f, addr);
7602 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7605 qemu_put_be32(f, 1);
7608 static void ram_save_static(QEMUFile *f, void *opaque)
7610 ram_addr_t i;
7611 RamCompressState s1, *s = &s1;
7612 uint8_t buf[10];
7614 qemu_put_be32(f, phys_ram_size);
7615 if (ram_compress_open(s, f) < 0)
7616 return;
7617 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7618 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7619 continue;
7620 #if 0
7621 if (tight_savevm_enabled) {
7622 int64_t sector_num;
7623 int j;
7625 /* find if the memory block is available on a virtual
7626 block device */
7627 sector_num = -1;
7628 for(j = 0; j < nb_drives; j++) {
7629 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7630 phys_ram_base + i,
7631 BDRV_HASH_BLOCK_SIZE);
7632 if (sector_num >= 0)
7633 break;
7635 if (j == nb_drives)
7636 goto normal_compress;
7637 buf[0] = 1;
7638 buf[1] = j;
7639 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7640 ram_compress_buf(s, buf, 10);
7641 } else
7642 #endif
7644 // normal_compress:
7645 buf[0] = 0;
7646 ram_compress_buf(s, buf, 1);
7647 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7650 ram_compress_close(s);
7653 static void ram_save(QEMUFile *f, void *opaque)
7655 int in_migration = cpu_physical_memory_get_dirty_tracking();
7657 qemu_put_byte(f, in_migration);
7659 if (in_migration)
7660 ram_save_live(f, opaque);
7661 else
7662 ram_save_static(f, opaque);
7665 static int ram_load_live(QEMUFile *f, void *opaque)
7667 target_ulong addr;
7669 do {
7670 addr = qemu_get_be32(f);
7671 if (addr == 1)
7672 break;
7674 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7675 } while (1);
7677 return 0;
7680 static int ram_load_static(QEMUFile *f, void *opaque)
7682 RamDecompressState s1, *s = &s1;
7683 uint8_t buf[10];
7684 ram_addr_t i;
7686 if (qemu_get_be32(f) != phys_ram_size)
7687 return -EINVAL;
7688 if (ram_decompress_open(s, f) < 0)
7689 return -EINVAL;
7690 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7691 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7692 continue;
7693 if (ram_decompress_buf(s, buf, 1) < 0) {
7694 fprintf(stderr, "Error while reading ram block header\n");
7695 goto error;
7697 if (buf[0] == 0) {
7698 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7699 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7700 goto error;
7702 } else
7703 #if 0
7704 if (buf[0] == 1) {
7705 int bs_index;
7706 int64_t sector_num;
7708 ram_decompress_buf(s, buf + 1, 9);
7709 bs_index = buf[1];
7710 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7711 if (bs_index >= nb_drives) {
7712 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7713 goto error;
7715 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7716 phys_ram_base + i,
7717 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7718 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7719 bs_index, sector_num);
7720 goto error;
7722 } else
7723 #endif
7725 error:
7726 printf("Error block header\n");
7727 return -EINVAL;
7730 ram_decompress_close(s);
7731 return 0;
7734 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7736 int ret;
7738 switch (version_id) {
7739 case 1:
7740 ret = ram_load_v1(f, opaque);
7741 break;
7742 case 3:
7743 if (qemu_get_byte(f)) {
7744 ret = ram_load_live(f, opaque);
7745 break;
7747 case 2:
7748 ret = ram_load_static(f, opaque);
7749 break;
7750 default:
7751 ret = -EINVAL;
7752 break;
7755 return ret;
7758 /***********************************************************/
7759 /* bottom halves (can be seen as timers which expire ASAP) */
7761 struct QEMUBH {
7762 QEMUBHFunc *cb;
7763 void *opaque;
7764 int scheduled;
7765 QEMUBH *next;
7768 static QEMUBH *first_bh = NULL;
7770 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7772 QEMUBH *bh;
7773 bh = qemu_mallocz(sizeof(QEMUBH));
7774 if (!bh)
7775 return NULL;
7776 bh->cb = cb;
7777 bh->opaque = opaque;
7778 return bh;
7781 int qemu_bh_poll(void)
7783 QEMUBH *bh, **pbh;
7784 int ret;
7786 ret = 0;
7787 for(;;) {
7788 pbh = &first_bh;
7789 bh = *pbh;
7790 if (!bh)
7791 break;
7792 ret = 1;
7793 *pbh = bh->next;
7794 bh->scheduled = 0;
7795 bh->cb(bh->opaque);
7797 return ret;
7800 void qemu_bh_schedule(QEMUBH *bh)
7802 CPUState *env = cpu_single_env;
7803 if (bh->scheduled)
7804 return;
7805 bh->scheduled = 1;
7806 bh->next = first_bh;
7807 first_bh = bh;
7809 /* stop the currently executing CPU to execute the BH ASAP */
7810 if (env) {
7811 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7813 main_loop_break();
7816 void qemu_bh_cancel(QEMUBH *bh)
7818 QEMUBH **pbh;
7819 if (bh->scheduled) {
7820 pbh = &first_bh;
7821 while (*pbh != bh)
7822 pbh = &(*pbh)->next;
7823 *pbh = bh->next;
7824 bh->scheduled = 0;
7828 void qemu_bh_delete(QEMUBH *bh)
7830 qemu_bh_cancel(bh);
7831 qemu_free(bh);
7834 /***********************************************************/
7835 /* machine registration */
7837 QEMUMachine *first_machine = NULL;
7838 QEMUMachine *current_machine = NULL;
7840 int qemu_register_machine(QEMUMachine *m)
7842 QEMUMachine **pm;
7843 pm = &first_machine;
7844 while (*pm != NULL)
7845 pm = &(*pm)->next;
7846 m->next = NULL;
7847 *pm = m;
7848 return 0;
7851 static QEMUMachine *find_machine(const char *name)
7853 QEMUMachine *m;
7855 for(m = first_machine; m != NULL; m = m->next) {
7856 if (!strcmp(m->name, name))
7857 return m;
7859 return NULL;
7862 /***********************************************************/
7863 /* main execution loop */
7865 static void gui_update(void *opaque)
7867 DisplayState *ds = opaque;
7868 ds->dpy_refresh(ds);
7869 qemu_mod_timer(ds->gui_timer,
7870 (ds->gui_timer_interval ?
7871 ds->gui_timer_interval :
7872 GUI_REFRESH_INTERVAL)
7873 + qemu_get_clock(rt_clock));
7876 struct vm_change_state_entry {
7877 VMChangeStateHandler *cb;
7878 void *opaque;
7879 LIST_ENTRY (vm_change_state_entry) entries;
7882 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7884 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7885 void *opaque)
7887 VMChangeStateEntry *e;
7889 e = qemu_mallocz(sizeof (*e));
7890 if (!e)
7891 return NULL;
7893 e->cb = cb;
7894 e->opaque = opaque;
7895 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7896 return e;
7899 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7901 LIST_REMOVE (e, entries);
7902 qemu_free (e);
7905 static void vm_state_notify(int running)
7907 VMChangeStateEntry *e;
7909 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7910 e->cb(e->opaque, running);
7914 /* XXX: support several handlers */
7915 static VMStopHandler *vm_stop_cb;
7916 static void *vm_stop_opaque;
7918 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7920 vm_stop_cb = cb;
7921 vm_stop_opaque = opaque;
7922 return 0;
7925 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7927 vm_stop_cb = NULL;
7930 void vm_start(void)
7932 if (!vm_running) {
7933 cpu_enable_ticks();
7934 vm_running = 1;
7935 vm_state_notify(1);
7936 qemu_rearm_alarm_timer(alarm_timer);
7940 void vm_stop(int reason)
7942 if (vm_running) {
7943 cpu_disable_ticks();
7944 vm_running = 0;
7945 if (reason != 0) {
7946 if (vm_stop_cb) {
7947 vm_stop_cb(vm_stop_opaque, reason);
7950 vm_state_notify(0);
7954 /* reset/shutdown handler */
7956 typedef struct QEMUResetEntry {
7957 QEMUResetHandler *func;
7958 void *opaque;
7959 struct QEMUResetEntry *next;
7960 } QEMUResetEntry;
7962 static QEMUResetEntry *first_reset_entry;
7963 static int reset_requested;
7964 static int shutdown_requested;
7965 static int powerdown_requested;
7967 int qemu_shutdown_requested(void)
7969 int r = shutdown_requested;
7970 shutdown_requested = 0;
7971 return r;
7974 int qemu_reset_requested(void)
7976 int r = reset_requested;
7977 reset_requested = 0;
7978 return r;
7981 int qemu_powerdown_requested(void)
7983 int r = powerdown_requested;
7984 powerdown_requested = 0;
7985 return r;
7988 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7990 QEMUResetEntry **pre, *re;
7992 pre = &first_reset_entry;
7993 while (*pre != NULL)
7994 pre = &(*pre)->next;
7995 re = qemu_mallocz(sizeof(QEMUResetEntry));
7996 re->func = func;
7997 re->opaque = opaque;
7998 re->next = NULL;
7999 *pre = re;
8002 void qemu_system_reset(void)
8004 QEMUResetEntry *re;
8006 /* reset all devices */
8007 for(re = first_reset_entry; re != NULL; re = re->next) {
8008 re->func(re->opaque);
8012 void qemu_system_reset_request(void)
8014 if (no_reboot) {
8015 shutdown_requested = 1;
8016 } else {
8017 reset_requested = 1;
8019 if (cpu_single_env)
8020 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
8021 main_loop_break();
8024 void qemu_system_shutdown_request(void)
8026 shutdown_requested = 1;
8027 if (cpu_single_env)
8028 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
8031 void qemu_system_powerdown_request(void)
8033 powerdown_requested = 1;
8034 if (cpu_single_env)
8035 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
8038 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
8039 struct timeval *tv)
8041 int ret;
8043 /* KVM holds a mutex while QEMU code is running, we need hooks to
8044 release the mutex whenever QEMU code sleeps. */
8046 kvm_sleep_begin();
8048 ret = select(max_fd, rfds, wfds, xfds, tv);
8050 kvm_sleep_end();
8052 return ret;
8055 void main_loop_wait(int timeout)
8057 IOHandlerRecord *ioh;
8058 fd_set rfds, wfds, xfds;
8059 int ret, nfds;
8060 #ifdef _WIN32
8061 int ret2, i;
8062 #endif
8063 struct timeval tv;
8064 PollingEntry *pe;
8067 /* XXX: need to suppress polling by better using win32 events */
8068 ret = 0;
8069 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
8070 ret |= pe->func(pe->opaque);
8072 #ifdef _WIN32
8073 if (ret == 0) {
8074 int err;
8075 WaitObjects *w = &wait_objects;
8077 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
8078 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
8079 if (w->func[ret - WAIT_OBJECT_0])
8080 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
8082 /* Check for additional signaled events */
8083 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
8085 /* Check if event is signaled */
8086 ret2 = WaitForSingleObject(w->events[i], 0);
8087 if(ret2 == WAIT_OBJECT_0) {
8088 if (w->func[i])
8089 w->func[i](w->opaque[i]);
8090 } else if (ret2 == WAIT_TIMEOUT) {
8091 } else {
8092 err = GetLastError();
8093 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
8096 } else if (ret == WAIT_TIMEOUT) {
8097 } else {
8098 err = GetLastError();
8099 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
8102 #endif
8103 /* poll any events */
8104 /* XXX: separate device handlers from system ones */
8105 nfds = -1;
8106 FD_ZERO(&rfds);
8107 FD_ZERO(&wfds);
8108 FD_ZERO(&xfds);
8109 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
8110 if (ioh->deleted)
8111 continue;
8112 if (ioh->fd_read &&
8113 (!ioh->fd_read_poll ||
8114 ioh->fd_read_poll(ioh->opaque) != 0)) {
8115 FD_SET(ioh->fd, &rfds);
8116 if (ioh->fd > nfds)
8117 nfds = ioh->fd;
8119 if (ioh->fd_write) {
8120 FD_SET(ioh->fd, &wfds);
8121 if (ioh->fd > nfds)
8122 nfds = ioh->fd;
8126 #ifdef _WIN32
8127 tv.tv_sec = 0;
8128 tv.tv_usec = 0;
8129 #else
8130 tv.tv_sec = timeout / 1000;
8131 tv.tv_usec = (timeout % 1000) * 1000;
8132 #endif
8133 #if defined(CONFIG_SLIRP)
8134 if (slirp_inited) {
8135 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
8137 #endif
8138 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
8139 if (ret > 0) {
8140 IOHandlerRecord **pioh;
8142 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
8143 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
8144 ioh->fd_read(ioh->opaque);
8145 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
8146 FD_CLR(ioh->fd, &rfds);
8148 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
8149 ioh->fd_write(ioh->opaque);
8153 /* remove deleted IO handlers */
8154 pioh = &first_io_handler;
8155 while (*pioh) {
8156 ioh = *pioh;
8157 if (ioh->deleted) {
8158 *pioh = ioh->next;
8159 qemu_free(ioh);
8160 } else
8161 pioh = &ioh->next;
8164 #if defined(CONFIG_SLIRP)
8165 if (slirp_inited) {
8166 if (ret < 0) {
8167 FD_ZERO(&rfds);
8168 FD_ZERO(&wfds);
8169 FD_ZERO(&xfds);
8171 slirp_select_poll(&rfds, &wfds, &xfds);
8173 #endif
8174 qemu_aio_poll();
8175 if (vm_running) {
8176 if (likely(!cur_cpu || !(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
8177 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
8178 qemu_get_clock(vm_clock));
8179 /* run dma transfers, if any */
8180 DMA_run();
8183 /* real time timers */
8184 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
8185 qemu_get_clock(rt_clock));
8187 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
8188 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
8189 qemu_rearm_alarm_timer(alarm_timer);
8192 /* Check bottom-halves last in case any of the earlier events triggered
8193 them. */
8194 qemu_bh_poll();
8198 static int main_loop(void)
8200 int ret, timeout;
8201 #ifdef CONFIG_PROFILER
8202 int64_t ti;
8203 #endif
8204 CPUState *env;
8207 if (kvm_enabled()) {
8208 kvm_main_loop();
8209 cpu_disable_ticks();
8210 return 0;
8213 cur_cpu = first_cpu;
8214 next_cpu = cur_cpu->next_cpu ?: first_cpu;
8215 for(;;) {
8216 if (vm_running) {
8218 for(;;) {
8219 /* get next cpu */
8220 env = next_cpu;
8221 #ifdef CONFIG_PROFILER
8222 ti = profile_getclock();
8223 #endif
8224 if (use_icount) {
8225 int64_t count;
8226 int decr;
8227 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
8228 env->icount_decr.u16.low = 0;
8229 env->icount_extra = 0;
8230 count = qemu_next_deadline();
8231 count = (count + (1 << icount_time_shift) - 1)
8232 >> icount_time_shift;
8233 qemu_icount += count;
8234 decr = (count > 0xffff) ? 0xffff : count;
8235 count -= decr;
8236 env->icount_decr.u16.low = decr;
8237 env->icount_extra = count;
8239 ret = cpu_exec(env);
8240 #ifdef CONFIG_PROFILER
8241 qemu_time += profile_getclock() - ti;
8242 #endif
8243 if (use_icount) {
8244 /* Fold pending instructions back into the
8245 instruction counter, and clear the interrupt flag. */
8246 qemu_icount -= (env->icount_decr.u16.low
8247 + env->icount_extra);
8248 env->icount_decr.u32 = 0;
8249 env->icount_extra = 0;
8251 next_cpu = env->next_cpu ?: first_cpu;
8252 if (event_pending && likely(ret != EXCP_DEBUG)) {
8253 ret = EXCP_INTERRUPT;
8254 event_pending = 0;
8255 break;
8257 if (ret == EXCP_HLT) {
8258 /* Give the next CPU a chance to run. */
8259 cur_cpu = env;
8260 continue;
8262 if (ret != EXCP_HALTED)
8263 break;
8264 /* all CPUs are halted ? */
8265 if (env == cur_cpu)
8266 break;
8268 cur_cpu = env;
8270 if (shutdown_requested) {
8271 ret = EXCP_INTERRUPT;
8272 if (no_shutdown) {
8273 vm_stop(0);
8274 no_shutdown = 0;
8276 else
8277 break;
8279 if (reset_requested) {
8280 reset_requested = 0;
8281 qemu_system_reset();
8282 if (kvm_enabled())
8283 kvm_load_registers(env);
8284 ret = EXCP_INTERRUPT;
8286 if (powerdown_requested) {
8287 powerdown_requested = 0;
8288 qemu_system_powerdown();
8289 ret = EXCP_INTERRUPT;
8291 if (unlikely(ret == EXCP_DEBUG)) {
8292 vm_stop(EXCP_DEBUG);
8294 /* If all cpus are halted then wait until the next IRQ */
8295 /* XXX: use timeout computed from timers */
8296 if (ret == EXCP_HALTED) {
8297 if (use_icount) {
8298 int64_t add;
8299 int64_t delta;
8300 /* Advance virtual time to the next event. */
8301 if (use_icount == 1) {
8302 /* When not using an adaptive execution frequency
8303 we tend to get badly out of sync with real time,
8304 so just delay for a reasonable amount of time. */
8305 delta = 0;
8306 } else {
8307 delta = cpu_get_icount() - cpu_get_clock();
8309 if (delta > 0) {
8310 /* If virtual time is ahead of real time then just
8311 wait for IO. */
8312 timeout = (delta / 1000000) + 1;
8313 } else {
8314 /* Wait for either IO to occur or the next
8315 timer event. */
8316 add = qemu_next_deadline();
8317 /* We advance the timer before checking for IO.
8318 Limit the amount we advance so that early IO
8319 activity won't get the guest too far ahead. */
8320 if (add > 10000000)
8321 add = 10000000;
8322 delta += add;
8323 add = (add + (1 << icount_time_shift) - 1)
8324 >> icount_time_shift;
8325 qemu_icount += add;
8326 timeout = delta / 1000000;
8327 if (timeout < 0)
8328 timeout = 0;
8330 } else {
8331 timeout = 10;
8333 } else {
8334 timeout = 0;
8336 } else {
8337 if (shutdown_requested)
8338 break;
8339 timeout = 10;
8341 #ifdef CONFIG_PROFILER
8342 ti = profile_getclock();
8343 #endif
8344 main_loop_wait(timeout);
8345 #ifdef CONFIG_PROFILER
8346 dev_time += profile_getclock() - ti;
8347 #endif
8349 cpu_disable_ticks();
8350 return ret;
8353 static void help(int exitcode)
8355 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
8356 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8357 "usage: %s [options] [disk_image]\n"
8358 "\n"
8359 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8360 "\n"
8361 "Standard options:\n"
8362 "-M machine select emulated machine (-M ? for list)\n"
8363 "-cpu cpu select CPU (-cpu ? for list)\n"
8364 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8365 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8366 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8367 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8368 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8369 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8370 " [,cache=on|off][,format=f][,boot=on|off]\n"
8371 " use 'file' as a drive image\n"
8372 "-mtdblock file use 'file' as on-board Flash memory image\n"
8373 "-sd file use 'file' as SecureDigital card image\n"
8374 "-pflash file use 'file' as a parallel flash image\n"
8375 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8376 "-snapshot write to temporary files instead of disk image files\n"
8377 #ifdef CONFIG_SDL
8378 "-no-frame open SDL window without a frame and window decorations\n"
8379 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8380 "-no-quit disable SDL window close capability\n"
8381 #endif
8382 #ifdef TARGET_I386
8383 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8384 #endif
8385 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8386 "-smp n set the number of CPUs to 'n' [default=1]\n"
8387 "-nographic disable graphical output and redirect serial I/Os to console\n"
8388 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8389 #ifndef _WIN32
8390 "-k language use keyboard layout (for example \"fr\" for French)\n"
8391 #endif
8392 #ifdef HAS_AUDIO
8393 "-audio-help print list of audio drivers and their options\n"
8394 "-soundhw c1,... enable audio support\n"
8395 " and only specified sound cards (comma separated list)\n"
8396 " use -soundhw ? to get the list of supported cards\n"
8397 " use -soundhw all to enable all of them\n"
8398 #endif
8399 "-localtime set the real time clock to local time [default=utc]\n"
8400 "-full-screen start in full screen\n"
8401 #ifdef TARGET_I386
8402 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8403 #endif
8404 "-usb enable the USB driver (will be the default soon)\n"
8405 "-usbdevice name add the host or guest USB device 'name'\n"
8406 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8407 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8408 #endif
8409 "-name string set the name of the guest\n"
8410 "\n"
8411 "Network options:\n"
8412 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8413 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8414 #ifdef CONFIG_SLIRP
8415 "-net user[,vlan=n][,hostname=host]\n"
8416 " connect the user mode network stack to VLAN 'n' and send\n"
8417 " hostname 'host' to DHCP clients\n"
8418 #endif
8419 #ifdef _WIN32
8420 "-net tap[,vlan=n],ifname=name\n"
8421 " connect the host TAP network interface to VLAN 'n'\n"
8422 #else
8423 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8424 " connect the host TAP network interface to VLAN 'n' and use the\n"
8425 " network scripts 'file' (default=%s)\n"
8426 " and 'dfile' (default=%s);\n"
8427 " use '[down]script=no' to disable script execution;\n"
8428 " use 'fd=h' to connect to an already opened TAP interface\n"
8429 #endif
8430 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8431 " connect the vlan 'n' to another VLAN using a socket connection\n"
8432 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8433 " connect the vlan 'n' to multicast maddr and port\n"
8434 #ifdef CONFIG_VDE
8435 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8436 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8437 " on host and listening for incoming connections on 'socketpath'.\n"
8438 " Use group 'groupname' and mode 'octalmode' to change default\n"
8439 " ownership and permissions for communication port.\n"
8440 #endif
8441 "-net none use it alone to have zero network devices; if no -net option\n"
8442 " is provided, the default is '-net nic -net user'\n"
8443 "\n"
8444 #ifdef CONFIG_SLIRP
8445 "-tftp dir allow tftp access to files in dir [-net user]\n"
8446 "-bootp file advertise file in BOOTP replies\n"
8447 #ifndef _WIN32
8448 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8449 #endif
8450 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8451 " redirect TCP or UDP connections from host to guest [-net user]\n"
8452 #endif
8453 "\n"
8454 "Linux boot specific:\n"
8455 "-kernel bzImage use 'bzImage' as kernel image\n"
8456 "-append cmdline use 'cmdline' as kernel command line\n"
8457 "-initrd file use 'file' as initial ram disk\n"
8458 "\n"
8459 "Debug/Expert options:\n"
8460 "-monitor dev redirect the monitor to char device 'dev'\n"
8461 "-serial dev redirect the serial port to char device 'dev'\n"
8462 "-parallel dev redirect the parallel port to char device 'dev'\n"
8463 "-pidfile file Write PID to 'file'\n"
8464 "-S freeze CPU at startup (use 'c' to start execution)\n"
8465 "-s wait gdb connection to port\n"
8466 "-p port set gdb connection port [default=%s]\n"
8467 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8468 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8469 " translation (t=none or lba) (usually qemu can guess them)\n"
8470 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8471 #ifdef USE_KQEMU
8472 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8473 "-no-kqemu disable KQEMU kernel module usage\n"
8474 #endif
8475 #ifdef USE_KVM
8476 #ifndef NO_CPU_EMULATION
8477 "-no-kvm disable KVM hardware virtualization\n"
8478 #endif
8479 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8480 "-no-kvm-pit disable KVM kernel mode PIT\n"
8481 #endif
8482 #ifdef TARGET_I386
8483 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8484 " (default is CL-GD5446 PCI VGA)\n"
8485 "-no-acpi disable ACPI\n"
8486 #endif
8487 #ifdef CONFIG_CURSES
8488 "-curses use a curses/ncurses interface instead of SDL\n"
8489 #endif
8490 "-no-reboot exit instead of rebooting\n"
8491 "-no-shutdown stop before shutdown\n"
8492 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8493 "-vnc display start a VNC server on display\n"
8494 #ifndef _WIN32
8495 "-daemonize daemonize QEMU after initializing\n"
8496 #endif
8497 "-tdf inject timer interrupts that got lost\n"
8498 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8499 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8500 "-option-rom rom load a file, rom, into the option ROM space\n"
8501 #ifdef TARGET_SPARC
8502 "-prom-env variable=value set OpenBIOS nvram variables\n"
8503 #endif
8504 "-clock force the use of the given methods for timer alarm.\n"
8505 " To see what timers are available use -clock ?\n"
8506 "-startdate select initial date of the clock\n"
8507 "-icount [N|auto]\n"
8508 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8509 "\n"
8510 "During emulation, the following keys are useful:\n"
8511 "ctrl-alt-f toggle full screen\n"
8512 "ctrl-alt-n switch to virtual console 'n'\n"
8513 "ctrl-alt toggle mouse and keyboard grab\n"
8514 "\n"
8515 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8517 "qemu",
8518 DEFAULT_RAM_SIZE,
8519 #ifndef _WIN32
8520 DEFAULT_NETWORK_SCRIPT,
8521 DEFAULT_NETWORK_DOWN_SCRIPT,
8522 #endif
8523 DEFAULT_GDBSTUB_PORT,
8524 "/tmp/qemu.log");
8525 exit(exitcode);
8528 #define HAS_ARG 0x0001
8530 enum {
8531 QEMU_OPTION_h,
8533 QEMU_OPTION_M,
8534 QEMU_OPTION_cpu,
8535 QEMU_OPTION_fda,
8536 QEMU_OPTION_fdb,
8537 QEMU_OPTION_hda,
8538 QEMU_OPTION_hdb,
8539 QEMU_OPTION_hdc,
8540 QEMU_OPTION_hdd,
8541 QEMU_OPTION_drive,
8542 QEMU_OPTION_cdrom,
8543 QEMU_OPTION_mtdblock,
8544 QEMU_OPTION_sd,
8545 QEMU_OPTION_pflash,
8546 QEMU_OPTION_boot,
8547 QEMU_OPTION_snapshot,
8548 #ifdef TARGET_I386
8549 QEMU_OPTION_no_fd_bootchk,
8550 #endif
8551 QEMU_OPTION_m,
8552 QEMU_OPTION_nographic,
8553 QEMU_OPTION_portrait,
8554 #ifdef HAS_AUDIO
8555 QEMU_OPTION_audio_help,
8556 QEMU_OPTION_soundhw,
8557 #endif
8559 QEMU_OPTION_net,
8560 QEMU_OPTION_tftp,
8561 QEMU_OPTION_bootp,
8562 QEMU_OPTION_smb,
8563 QEMU_OPTION_redir,
8565 QEMU_OPTION_kernel,
8566 QEMU_OPTION_append,
8567 QEMU_OPTION_initrd,
8569 QEMU_OPTION_S,
8570 QEMU_OPTION_s,
8571 QEMU_OPTION_p,
8572 QEMU_OPTION_d,
8573 QEMU_OPTION_hdachs,
8574 QEMU_OPTION_L,
8575 QEMU_OPTION_bios,
8576 QEMU_OPTION_k,
8577 QEMU_OPTION_localtime,
8578 QEMU_OPTION_cirrusvga,
8579 QEMU_OPTION_vmsvga,
8580 QEMU_OPTION_g,
8581 QEMU_OPTION_std_vga,
8582 QEMU_OPTION_echr,
8583 QEMU_OPTION_monitor,
8584 QEMU_OPTION_serial,
8585 QEMU_OPTION_parallel,
8586 QEMU_OPTION_loadvm,
8587 QEMU_OPTION_full_screen,
8588 QEMU_OPTION_no_frame,
8589 QEMU_OPTION_alt_grab,
8590 QEMU_OPTION_no_quit,
8591 QEMU_OPTION_pidfile,
8592 QEMU_OPTION_no_kqemu,
8593 QEMU_OPTION_kernel_kqemu,
8594 QEMU_OPTION_win2k_hack,
8595 QEMU_OPTION_usb,
8596 QEMU_OPTION_usbdevice,
8597 QEMU_OPTION_smp,
8598 QEMU_OPTION_vnc,
8599 QEMU_OPTION_no_acpi,
8600 QEMU_OPTION_curses,
8601 QEMU_OPTION_no_kvm,
8602 QEMU_OPTION_no_kvm_irqchip,
8603 QEMU_OPTION_no_kvm_pit,
8604 QEMU_OPTION_no_reboot,
8605 QEMU_OPTION_no_shutdown,
8606 QEMU_OPTION_show_cursor,
8607 QEMU_OPTION_daemonize,
8608 QEMU_OPTION_option_rom,
8609 QEMU_OPTION_semihosting,
8610 QEMU_OPTION_cpu_vendor,
8611 QEMU_OPTION_name,
8612 QEMU_OPTION_prom_env,
8613 QEMU_OPTION_old_param,
8614 QEMU_OPTION_clock,
8615 QEMU_OPTION_startdate,
8616 QEMU_OPTION_tb_size,
8617 QEMU_OPTION_icount,
8618 QEMU_OPTION_incoming,
8619 QEMU_OPTION_tdf,
8620 QEMU_OPTION_kvm_shadow_memory,
8621 QEMU_OPTION_mempath,
8624 typedef struct QEMUOption {
8625 const char *name;
8626 int flags;
8627 int index;
8628 } QEMUOption;
8630 const QEMUOption qemu_options[] = {
8631 { "h", 0, QEMU_OPTION_h },
8632 { "help", 0, QEMU_OPTION_h },
8634 { "M", HAS_ARG, QEMU_OPTION_M },
8635 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8636 { "fda", HAS_ARG, QEMU_OPTION_fda },
8637 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8638 { "hda", HAS_ARG, QEMU_OPTION_hda },
8639 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8640 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8641 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8642 { "drive", HAS_ARG, QEMU_OPTION_drive },
8643 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8644 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8645 { "sd", HAS_ARG, QEMU_OPTION_sd },
8646 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8647 { "boot", HAS_ARG, QEMU_OPTION_boot },
8648 { "snapshot", 0, QEMU_OPTION_snapshot },
8649 #ifdef TARGET_I386
8650 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8651 #endif
8652 { "m", HAS_ARG, QEMU_OPTION_m },
8653 { "nographic", 0, QEMU_OPTION_nographic },
8654 { "portrait", 0, QEMU_OPTION_portrait },
8655 { "k", HAS_ARG, QEMU_OPTION_k },
8656 #ifdef HAS_AUDIO
8657 { "audio-help", 0, QEMU_OPTION_audio_help },
8658 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8659 #endif
8661 { "net", HAS_ARG, QEMU_OPTION_net},
8662 #ifdef CONFIG_SLIRP
8663 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8664 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8665 #ifndef _WIN32
8666 { "smb", HAS_ARG, QEMU_OPTION_smb },
8667 #endif
8668 { "redir", HAS_ARG, QEMU_OPTION_redir },
8669 #endif
8671 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8672 { "append", HAS_ARG, QEMU_OPTION_append },
8673 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8675 { "S", 0, QEMU_OPTION_S },
8676 { "s", 0, QEMU_OPTION_s },
8677 { "p", HAS_ARG, QEMU_OPTION_p },
8678 { "d", HAS_ARG, QEMU_OPTION_d },
8679 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8680 { "L", HAS_ARG, QEMU_OPTION_L },
8681 { "bios", HAS_ARG, QEMU_OPTION_bios },
8682 #ifdef USE_KQEMU
8683 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8684 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8685 #endif
8686 #ifdef USE_KVM
8687 #ifndef NO_CPU_EMULATION
8688 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8689 #endif
8690 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8691 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8692 #endif
8693 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8694 { "g", 1, QEMU_OPTION_g },
8695 #endif
8696 { "localtime", 0, QEMU_OPTION_localtime },
8697 { "std-vga", 0, QEMU_OPTION_std_vga },
8698 { "echr", HAS_ARG, QEMU_OPTION_echr },
8699 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8700 { "serial", HAS_ARG, QEMU_OPTION_serial },
8701 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8702 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8703 { "incoming", 1, QEMU_OPTION_incoming },
8704 { "full-screen", 0, QEMU_OPTION_full_screen },
8705 #ifdef CONFIG_SDL
8706 { "no-frame", 0, QEMU_OPTION_no_frame },
8707 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8708 { "no-quit", 0, QEMU_OPTION_no_quit },
8709 #endif
8710 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8711 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8712 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8713 { "smp", HAS_ARG, QEMU_OPTION_smp },
8714 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8715 #ifdef CONFIG_CURSES
8716 { "curses", 0, QEMU_OPTION_curses },
8717 #endif
8719 /* temporary options */
8720 { "usb", 0, QEMU_OPTION_usb },
8721 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8722 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8723 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8724 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8725 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8726 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8727 { "daemonize", 0, QEMU_OPTION_daemonize },
8728 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8729 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8730 { "semihosting", 0, QEMU_OPTION_semihosting },
8731 #endif
8732 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8733 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8734 { "name", HAS_ARG, QEMU_OPTION_name },
8735 #if defined(TARGET_SPARC)
8736 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8737 #endif
8738 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8739 #if defined(TARGET_ARM)
8740 { "old-param", 0, QEMU_OPTION_old_param },
8741 #endif
8742 { "clock", HAS_ARG, QEMU_OPTION_clock },
8743 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8744 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8745 { "icount", HAS_ARG, QEMU_OPTION_icount },
8746 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8747 { NULL },
8750 /* password input */
8752 int qemu_key_check(BlockDriverState *bs, const char *name)
8754 char password[256];
8755 int i;
8757 if (!bdrv_is_encrypted(bs))
8758 return 0;
8760 term_printf("%s is encrypted.\n", name);
8761 for(i = 0; i < 3; i++) {
8762 monitor_readline("Password: ", 1, password, sizeof(password));
8763 if (bdrv_set_key(bs, password) == 0)
8764 return 0;
8765 term_printf("invalid password\n");
8767 return -EPERM;
8770 static BlockDriverState *get_bdrv(int index)
8772 if (index > nb_drives)
8773 return NULL;
8774 return drives_table[index].bdrv;
8777 static void read_passwords(void)
8779 BlockDriverState *bs;
8780 int i;
8782 for(i = 0; i < 6; i++) {
8783 bs = get_bdrv(i);
8784 if (bs)
8785 qemu_key_check(bs, bdrv_get_device_name(bs));
8789 #ifdef HAS_AUDIO
8790 struct soundhw soundhw[] = {
8791 #ifdef HAS_AUDIO_CHOICE
8792 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8794 "pcspk",
8795 "PC speaker",
8798 { .init_isa = pcspk_audio_init }
8800 #endif
8802 "sb16",
8803 "Creative Sound Blaster 16",
8806 { .init_isa = SB16_init }
8809 #ifdef CONFIG_CS4231A
8811 "cs4231a",
8812 "CS4231A",
8815 { .init_isa = cs4231a_init }
8817 #endif
8819 #ifdef CONFIG_ADLIB
8821 "adlib",
8822 #ifdef HAS_YMF262
8823 "Yamaha YMF262 (OPL3)",
8824 #else
8825 "Yamaha YM3812 (OPL2)",
8826 #endif
8829 { .init_isa = Adlib_init }
8831 #endif
8833 #ifdef CONFIG_GUS
8835 "gus",
8836 "Gravis Ultrasound GF1",
8839 { .init_isa = GUS_init }
8841 #endif
8843 #ifdef CONFIG_AC97
8845 "ac97",
8846 "Intel 82801AA AC97 Audio",
8849 { .init_pci = ac97_init }
8851 #endif
8854 "es1370",
8855 "ENSONIQ AudioPCI ES1370",
8858 { .init_pci = es1370_init }
8860 #endif
8862 { NULL, NULL, 0, 0, { NULL } }
8865 static void select_soundhw (const char *optarg)
8867 struct soundhw *c;
8869 if (*optarg == '?') {
8870 show_valid_cards:
8872 printf ("Valid sound card names (comma separated):\n");
8873 for (c = soundhw; c->name; ++c) {
8874 printf ("%-11s %s\n", c->name, c->descr);
8876 printf ("\n-soundhw all will enable all of the above\n");
8877 exit (*optarg != '?');
8879 else {
8880 size_t l;
8881 const char *p;
8882 char *e;
8883 int bad_card = 0;
8885 if (!strcmp (optarg, "all")) {
8886 for (c = soundhw; c->name; ++c) {
8887 c->enabled = 1;
8889 return;
8892 p = optarg;
8893 while (*p) {
8894 e = strchr (p, ',');
8895 l = !e ? strlen (p) : (size_t) (e - p);
8897 for (c = soundhw; c->name; ++c) {
8898 if (!strncmp (c->name, p, l)) {
8899 c->enabled = 1;
8900 break;
8904 if (!c->name) {
8905 if (l > 80) {
8906 fprintf (stderr,
8907 "Unknown sound card name (too big to show)\n");
8909 else {
8910 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8911 (int) l, p);
8913 bad_card = 1;
8915 p += l + (e != NULL);
8918 if (bad_card)
8919 goto show_valid_cards;
8922 #endif
8924 #ifdef _WIN32
8925 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8927 exit(STATUS_CONTROL_C_EXIT);
8928 return TRUE;
8930 #endif
8932 #define MAX_NET_CLIENTS 32
8934 static int saved_argc;
8935 static char **saved_argv;
8937 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8939 *argc = saved_argc;
8940 *argv = saved_argv;
8941 *opt_daemonize = daemonize;
8942 *opt_incoming = incoming;
8946 static int gethugepagesize(void)
8948 int ret, fd;
8949 char buf[4096];
8950 char *needle = "Hugepagesize:";
8951 char *size;
8952 unsigned long hugepagesize;
8954 fd = open("/proc/meminfo", O_RDONLY);
8955 if (fd < 0) {
8956 perror("open");
8957 exit(0);
8960 ret = read(fd, buf, sizeof(buf));
8961 if (ret < 0) {
8962 perror("read");
8963 exit(0);
8966 size = strstr(buf, needle);
8967 if (!size)
8968 return 0;
8969 size += strlen(needle);
8970 hugepagesize = strtol(size, NULL, 0);
8971 return hugepagesize;
8974 void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
8976 char *filename;
8977 void *area;
8978 int fd;
8980 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8981 return NULL;
8983 hpagesize = gethugepagesize() * 1024;
8984 if (!hpagesize)
8985 return NULL;
8987 fd = mkstemp(filename);
8988 if (fd < 0) {
8989 perror("mkstemp");
8990 free(filename);
8991 return NULL;
8993 unlink(filename);
8994 free(filename);
8996 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8999 * ftruncate is not supported by hugetlbfs in older
9000 * hosts, so don't bother checking for errors.
9001 * If anything goes wrong with it under other filesystems,
9002 * mmap will fail.
9004 ftruncate(fd, memory);
9006 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
9007 if (area == MAP_FAILED) {
9008 perror("mmap");
9009 close(fd);
9010 return NULL;
9013 *len = memory;
9014 return area;
9017 void *qemu_alloc_physram(unsigned long memory)
9019 void *area = NULL;
9020 unsigned long map_len = memory;
9022 #ifdef USE_KVM
9023 if (mem_path)
9024 area = alloc_mem_area(memory, &map_len, mem_path);
9025 #endif
9026 if (!area)
9027 area = qemu_vmalloc(memory);
9028 #ifdef USE_KVM
9029 if (kvm_setup_guest_memory(area, map_len))
9030 area = NULL;
9031 #endif
9032 return area;
9035 #ifndef _WIN32
9037 static void termsig_handler(int signal)
9039 qemu_system_shutdown_request();
9042 void termsig_setup(void)
9044 struct sigaction act;
9046 memset(&act, 0, sizeof(act));
9047 act.sa_handler = termsig_handler;
9048 sigaction(SIGINT, &act, NULL);
9049 sigaction(SIGHUP, &act, NULL);
9050 sigaction(SIGTERM, &act, NULL);
9053 #endif
9055 int main(int argc, char **argv)
9057 #ifdef CONFIG_GDBSTUB
9058 int use_gdbstub;
9059 const char *gdbstub_port;
9060 #endif
9061 uint32_t boot_devices_bitmap = 0;
9062 int i;
9063 int snapshot, linux_boot, net_boot;
9064 const char *initrd_filename;
9065 const char *kernel_filename, *kernel_cmdline;
9066 const char *boot_devices = "";
9067 DisplayState *ds = &display_state;
9068 int cyls, heads, secs, translation;
9069 const char *net_clients[MAX_NET_CLIENTS];
9070 int nb_net_clients;
9071 int hda_index;
9072 int optind;
9073 const char *r, *optarg;
9074 CharDriverState *monitor_hd;
9075 const char *monitor_device;
9076 const char *serial_devices[MAX_SERIAL_PORTS];
9077 int serial_device_index;
9078 const char *parallel_devices[MAX_PARALLEL_PORTS];
9079 int parallel_device_index;
9080 const char *loadvm = NULL;
9081 QEMUMachine *machine;
9082 const char *cpu_model;
9083 const char *usb_devices[MAX_USB_CMDLINE];
9084 int usb_devices_index;
9085 int fds[2];
9086 int tb_size;
9087 const char *pid_file = NULL;
9088 VLANState *vlan;
9090 saved_argc = argc;
9091 saved_argv = argv;
9093 LIST_INIT (&vm_change_state_head);
9094 #ifndef _WIN32
9096 struct sigaction act;
9097 sigfillset(&act.sa_mask);
9098 act.sa_flags = 0;
9099 act.sa_handler = SIG_IGN;
9100 sigaction(SIGPIPE, &act, NULL);
9102 #else
9103 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
9104 /* Note: cpu_interrupt() is currently not SMP safe, so we force
9105 QEMU to run on a single CPU */
9107 HANDLE h;
9108 DWORD mask, smask;
9109 int i;
9110 h = GetCurrentProcess();
9111 if (GetProcessAffinityMask(h, &mask, &smask)) {
9112 for(i = 0; i < 32; i++) {
9113 if (mask & (1 << i))
9114 break;
9116 if (i != 32) {
9117 mask = 1 << i;
9118 SetProcessAffinityMask(h, mask);
9122 #endif
9124 register_machines();
9125 machine = first_machine;
9126 cpu_model = NULL;
9127 initrd_filename = NULL;
9128 ram_size = 0;
9129 vga_ram_size = VGA_RAM_SIZE;
9130 #ifdef CONFIG_GDBSTUB
9131 use_gdbstub = 0;
9132 gdbstub_port = DEFAULT_GDBSTUB_PORT;
9133 #endif
9134 snapshot = 0;
9135 nographic = 0;
9136 curses = 0;
9137 kernel_filename = NULL;
9138 kernel_cmdline = "";
9139 cyls = heads = secs = 0;
9140 translation = BIOS_ATA_TRANSLATION_AUTO;
9141 monitor_device = "vc";
9143 serial_devices[0] = "vc:80Cx24C";
9144 for(i = 1; i < MAX_SERIAL_PORTS; i++)
9145 serial_devices[i] = NULL;
9146 serial_device_index = 0;
9148 parallel_devices[0] = "vc:640x480";
9149 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
9150 parallel_devices[i] = NULL;
9151 parallel_device_index = 0;
9153 usb_devices_index = 0;
9155 nb_net_clients = 0;
9156 nb_drives = 0;
9157 nb_drives_opt = 0;
9158 hda_index = -1;
9160 nb_nics = 0;
9162 tb_size = 0;
9164 optind = 1;
9165 for(;;) {
9166 if (optind >= argc)
9167 break;
9168 r = argv[optind];
9169 if (r[0] != '-') {
9170 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
9171 } else {
9172 const QEMUOption *popt;
9174 optind++;
9175 /* Treat --foo the same as -foo. */
9176 if (r[1] == '-')
9177 r++;
9178 popt = qemu_options;
9179 for(;;) {
9180 if (!popt->name) {
9181 fprintf(stderr, "%s: invalid option -- '%s'\n",
9182 argv[0], r);
9183 exit(1);
9185 if (!strcmp(popt->name, r + 1))
9186 break;
9187 popt++;
9189 if (popt->flags & HAS_ARG) {
9190 if (optind >= argc) {
9191 fprintf(stderr, "%s: option '%s' requires an argument\n",
9192 argv[0], r);
9193 exit(1);
9195 optarg = argv[optind++];
9196 } else {
9197 optarg = NULL;
9200 switch(popt->index) {
9201 case QEMU_OPTION_M:
9202 machine = find_machine(optarg);
9203 if (!machine) {
9204 QEMUMachine *m;
9205 printf("Supported machines are:\n");
9206 for(m = first_machine; m != NULL; m = m->next) {
9207 printf("%-10s %s%s\n",
9208 m->name, m->desc,
9209 m == first_machine ? " (default)" : "");
9211 exit(*optarg != '?');
9213 break;
9214 case QEMU_OPTION_cpu:
9215 /* hw initialization will check this */
9216 if (*optarg == '?') {
9217 /* XXX: implement xxx_cpu_list for targets that still miss it */
9218 #if defined(cpu_list)
9219 cpu_list(stdout, &fprintf);
9220 #endif
9221 exit(0);
9222 } else {
9223 cpu_model = optarg;
9225 break;
9226 case QEMU_OPTION_initrd:
9227 initrd_filename = optarg;
9228 break;
9229 case QEMU_OPTION_hda:
9230 if (cyls == 0)
9231 hda_index = drive_add(optarg, HD_ALIAS, 0);
9232 else
9233 hda_index = drive_add(optarg, HD_ALIAS
9234 ",cyls=%d,heads=%d,secs=%d%s",
9235 0, cyls, heads, secs,
9236 translation == BIOS_ATA_TRANSLATION_LBA ?
9237 ",trans=lba" :
9238 translation == BIOS_ATA_TRANSLATION_NONE ?
9239 ",trans=none" : "");
9240 break;
9241 case QEMU_OPTION_hdb:
9242 case QEMU_OPTION_hdc:
9243 case QEMU_OPTION_hdd:
9244 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
9245 break;
9246 case QEMU_OPTION_drive:
9247 drive_add(NULL, "%s", optarg);
9248 break;
9249 case QEMU_OPTION_mtdblock:
9250 drive_add(optarg, MTD_ALIAS);
9251 break;
9252 case QEMU_OPTION_sd:
9253 drive_add(optarg, SD_ALIAS);
9254 break;
9255 case QEMU_OPTION_pflash:
9256 drive_add(optarg, PFLASH_ALIAS);
9257 break;
9258 case QEMU_OPTION_snapshot:
9259 snapshot = 1;
9260 break;
9261 case QEMU_OPTION_hdachs:
9263 const char *p;
9264 p = optarg;
9265 cyls = strtol(p, (char **)&p, 0);
9266 if (cyls < 1 || cyls > 16383)
9267 goto chs_fail;
9268 if (*p != ',')
9269 goto chs_fail;
9270 p++;
9271 heads = strtol(p, (char **)&p, 0);
9272 if (heads < 1 || heads > 16)
9273 goto chs_fail;
9274 if (*p != ',')
9275 goto chs_fail;
9276 p++;
9277 secs = strtol(p, (char **)&p, 0);
9278 if (secs < 1 || secs > 63)
9279 goto chs_fail;
9280 if (*p == ',') {
9281 p++;
9282 if (!strcmp(p, "none"))
9283 translation = BIOS_ATA_TRANSLATION_NONE;
9284 else if (!strcmp(p, "lba"))
9285 translation = BIOS_ATA_TRANSLATION_LBA;
9286 else if (!strcmp(p, "auto"))
9287 translation = BIOS_ATA_TRANSLATION_AUTO;
9288 else
9289 goto chs_fail;
9290 } else if (*p != '\0') {
9291 chs_fail:
9292 fprintf(stderr, "qemu: invalid physical CHS format\n");
9293 exit(1);
9295 if (hda_index != -1)
9296 snprintf(drives_opt[hda_index].opt,
9297 sizeof(drives_opt[hda_index].opt),
9298 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
9299 0, cyls, heads, secs,
9300 translation == BIOS_ATA_TRANSLATION_LBA ?
9301 ",trans=lba" :
9302 translation == BIOS_ATA_TRANSLATION_NONE ?
9303 ",trans=none" : "");
9305 break;
9306 case QEMU_OPTION_nographic:
9307 nographic = 1;
9308 break;
9309 #ifdef CONFIG_CURSES
9310 case QEMU_OPTION_curses:
9311 curses = 1;
9312 break;
9313 #endif
9314 case QEMU_OPTION_portrait:
9315 graphic_rotate = 1;
9316 break;
9317 case QEMU_OPTION_kernel:
9318 kernel_filename = optarg;
9319 break;
9320 case QEMU_OPTION_append:
9321 kernel_cmdline = optarg;
9322 break;
9323 case QEMU_OPTION_cdrom:
9324 drive_add(optarg, CDROM_ALIAS);
9325 break;
9326 case QEMU_OPTION_boot:
9327 boot_devices = optarg;
9328 /* We just do some generic consistency checks */
9330 /* Could easily be extended to 64 devices if needed */
9331 const char *p;
9333 boot_devices_bitmap = 0;
9334 for (p = boot_devices; *p != '\0'; p++) {
9335 /* Allowed boot devices are:
9336 * a b : floppy disk drives
9337 * c ... f : IDE disk drives
9338 * g ... m : machine implementation dependant drives
9339 * n ... p : network devices
9340 * It's up to each machine implementation to check
9341 * if the given boot devices match the actual hardware
9342 * implementation and firmware features.
9344 if (*p < 'a' || *p > 'q') {
9345 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9346 exit(1);
9348 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9349 fprintf(stderr,
9350 "Boot device '%c' was given twice\n",*p);
9351 exit(1);
9353 boot_devices_bitmap |= 1 << (*p - 'a');
9356 break;
9357 case QEMU_OPTION_fda:
9358 case QEMU_OPTION_fdb:
9359 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9360 break;
9361 #ifdef TARGET_I386
9362 case QEMU_OPTION_no_fd_bootchk:
9363 fd_bootchk = 0;
9364 break;
9365 #endif
9366 case QEMU_OPTION_net:
9367 if (nb_net_clients >= MAX_NET_CLIENTS) {
9368 fprintf(stderr, "qemu: too many network clients\n");
9369 exit(1);
9371 net_clients[nb_net_clients] = optarg;
9372 nb_net_clients++;
9373 break;
9374 #ifdef CONFIG_SLIRP
9375 case QEMU_OPTION_tftp:
9376 tftp_prefix = optarg;
9377 break;
9378 case QEMU_OPTION_bootp:
9379 bootp_filename = optarg;
9380 break;
9381 #ifndef _WIN32
9382 case QEMU_OPTION_smb:
9383 net_slirp_smb(optarg);
9384 break;
9385 #endif
9386 case QEMU_OPTION_redir:
9387 net_slirp_redir(optarg);
9388 break;
9389 #endif
9390 #ifdef HAS_AUDIO
9391 case QEMU_OPTION_audio_help:
9392 AUD_help ();
9393 exit (0);
9394 break;
9395 case QEMU_OPTION_soundhw:
9396 select_soundhw (optarg);
9397 break;
9398 #endif
9399 case QEMU_OPTION_h:
9400 help(0);
9401 break;
9402 case QEMU_OPTION_m: {
9403 uint64_t value;
9404 char *ptr;
9406 value = strtoul(optarg, &ptr, 10);
9407 switch (*ptr) {
9408 case 0: case 'M': case 'm':
9409 value <<= 20;
9410 break;
9411 case 'G': case 'g':
9412 value <<= 30;
9413 break;
9414 default:
9415 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
9416 exit(1);
9419 /* On 32-bit hosts, QEMU is limited by virtual address space */
9420 if (value > (2047 << 20)
9421 #ifndef USE_KQEMU
9422 && HOST_LONG_BITS == 32
9423 #endif
9425 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
9426 exit(1);
9428 if (value != (uint64_t)(ram_addr_t)value) {
9429 fprintf(stderr, "qemu: ram size too large\n");
9430 exit(1);
9432 ram_size = value;
9433 break;
9435 case QEMU_OPTION_d:
9437 int mask;
9438 CPULogItem *item;
9440 mask = cpu_str_to_log_mask(optarg);
9441 if (!mask) {
9442 printf("Log items (comma separated):\n");
9443 for(item = cpu_log_items; item->mask != 0; item++) {
9444 printf("%-10s %s\n", item->name, item->help);
9446 exit(1);
9448 cpu_set_log(mask);
9450 break;
9451 #ifdef CONFIG_GDBSTUB
9452 case QEMU_OPTION_s:
9453 use_gdbstub = 1;
9454 break;
9455 case QEMU_OPTION_p:
9456 gdbstub_port = optarg;
9457 break;
9458 #endif
9459 case QEMU_OPTION_L:
9460 bios_dir = optarg;
9461 break;
9462 case QEMU_OPTION_bios:
9463 bios_name = optarg;
9464 break;
9465 case QEMU_OPTION_S:
9466 autostart = 0;
9467 break;
9468 case QEMU_OPTION_k:
9469 keyboard_layout = optarg;
9470 break;
9471 case QEMU_OPTION_localtime:
9472 rtc_utc = 0;
9473 break;
9474 case QEMU_OPTION_cirrusvga:
9475 cirrus_vga_enabled = 1;
9476 vmsvga_enabled = 0;
9477 break;
9478 case QEMU_OPTION_vmsvga:
9479 cirrus_vga_enabled = 0;
9480 vmsvga_enabled = 1;
9481 break;
9482 case QEMU_OPTION_std_vga:
9483 cirrus_vga_enabled = 0;
9484 vmsvga_enabled = 0;
9485 break;
9486 case QEMU_OPTION_g:
9488 const char *p;
9489 int w, h, depth;
9490 p = optarg;
9491 w = strtol(p, (char **)&p, 10);
9492 if (w <= 0) {
9493 graphic_error:
9494 fprintf(stderr, "qemu: invalid resolution or depth\n");
9495 exit(1);
9497 if (*p != 'x')
9498 goto graphic_error;
9499 p++;
9500 h = strtol(p, (char **)&p, 10);
9501 if (h <= 0)
9502 goto graphic_error;
9503 if (*p == 'x') {
9504 p++;
9505 depth = strtol(p, (char **)&p, 10);
9506 if (depth != 8 && depth != 15 && depth != 16 &&
9507 depth != 24 && depth != 32)
9508 goto graphic_error;
9509 } else if (*p == '\0') {
9510 depth = graphic_depth;
9511 } else {
9512 goto graphic_error;
9515 graphic_width = w;
9516 graphic_height = h;
9517 graphic_depth = depth;
9519 break;
9520 case QEMU_OPTION_echr:
9522 char *r;
9523 term_escape_char = strtol(optarg, &r, 0);
9524 if (r == optarg)
9525 printf("Bad argument to echr\n");
9526 break;
9528 case QEMU_OPTION_monitor:
9529 monitor_device = optarg;
9530 break;
9531 case QEMU_OPTION_serial:
9532 if (serial_device_index >= MAX_SERIAL_PORTS) {
9533 fprintf(stderr, "qemu: too many serial ports\n");
9534 exit(1);
9536 serial_devices[serial_device_index] = optarg;
9537 serial_device_index++;
9538 break;
9539 case QEMU_OPTION_parallel:
9540 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9541 fprintf(stderr, "qemu: too many parallel ports\n");
9542 exit(1);
9544 parallel_devices[parallel_device_index] = optarg;
9545 parallel_device_index++;
9546 break;
9547 case QEMU_OPTION_loadvm:
9548 loadvm = optarg;
9549 break;
9550 case QEMU_OPTION_incoming:
9551 incoming = optarg;
9552 break;
9553 case QEMU_OPTION_full_screen:
9554 full_screen = 1;
9555 break;
9556 #ifdef CONFIG_SDL
9557 case QEMU_OPTION_no_frame:
9558 no_frame = 1;
9559 break;
9560 case QEMU_OPTION_alt_grab:
9561 alt_grab = 1;
9562 break;
9563 case QEMU_OPTION_no_quit:
9564 no_quit = 1;
9565 break;
9566 #endif
9567 case QEMU_OPTION_pidfile:
9568 pid_file = optarg;
9569 break;
9570 #ifdef TARGET_I386
9571 case QEMU_OPTION_win2k_hack:
9572 win2k_install_hack = 1;
9573 break;
9574 #endif
9575 #ifdef USE_KQEMU
9576 case QEMU_OPTION_no_kqemu:
9577 kqemu_allowed = 0;
9578 break;
9579 case QEMU_OPTION_kernel_kqemu:
9580 kqemu_allowed = 2;
9581 break;
9582 #endif
9583 #ifdef USE_KVM
9584 case QEMU_OPTION_no_kvm:
9585 kvm_allowed = 0;
9586 break;
9587 case QEMU_OPTION_no_kvm_irqchip: {
9588 extern int kvm_irqchip, kvm_pit;
9589 kvm_irqchip = 0;
9590 kvm_pit = 0;
9591 break;
9593 case QEMU_OPTION_no_kvm_pit: {
9594 extern int kvm_pit;
9595 kvm_pit = 0;
9596 break;
9598 #endif
9599 case QEMU_OPTION_usb:
9600 usb_enabled = 1;
9601 break;
9602 case QEMU_OPTION_usbdevice:
9603 usb_enabled = 1;
9604 if (usb_devices_index >= MAX_USB_CMDLINE) {
9605 fprintf(stderr, "Too many USB devices\n");
9606 exit(1);
9608 usb_devices[usb_devices_index] = optarg;
9609 usb_devices_index++;
9610 break;
9611 case QEMU_OPTION_smp:
9612 smp_cpus = atoi(optarg);
9613 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9614 fprintf(stderr, "Invalid number of CPUs\n");
9615 exit(1);
9617 break;
9618 case QEMU_OPTION_vnc:
9619 vnc_display = optarg;
9620 break;
9621 case QEMU_OPTION_no_acpi:
9622 acpi_enabled = 0;
9623 break;
9624 case QEMU_OPTION_no_reboot:
9625 no_reboot = 1;
9626 break;
9627 case QEMU_OPTION_no_shutdown:
9628 no_shutdown = 1;
9629 break;
9630 case QEMU_OPTION_show_cursor:
9631 cursor_hide = 0;
9632 break;
9633 case QEMU_OPTION_daemonize:
9634 daemonize = 1;
9635 break;
9636 case QEMU_OPTION_option_rom:
9637 if (nb_option_roms >= MAX_OPTION_ROMS) {
9638 fprintf(stderr, "Too many option ROMs\n");
9639 exit(1);
9641 option_rom[nb_option_roms] = optarg;
9642 nb_option_roms++;
9643 break;
9644 case QEMU_OPTION_semihosting:
9645 semihosting_enabled = 1;
9646 break;
9647 case QEMU_OPTION_tdf:
9648 time_drift_fix = 1;
9649 break;
9650 case QEMU_OPTION_kvm_shadow_memory:
9651 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
9652 break;
9653 case QEMU_OPTION_mempath:
9654 mem_path = optarg;
9655 break;
9656 case QEMU_OPTION_name:
9657 qemu_name = optarg;
9658 break;
9659 #ifdef TARGET_SPARC
9660 case QEMU_OPTION_prom_env:
9661 if (nb_prom_envs >= MAX_PROM_ENVS) {
9662 fprintf(stderr, "Too many prom variables\n");
9663 exit(1);
9665 prom_envs[nb_prom_envs] = optarg;
9666 nb_prom_envs++;
9667 break;
9668 #endif
9669 case QEMU_OPTION_cpu_vendor:
9670 cpu_vendor_string = optarg;
9671 break;
9672 #ifdef TARGET_ARM
9673 case QEMU_OPTION_old_param:
9674 old_param = 1;
9675 break;
9676 #endif
9677 case QEMU_OPTION_clock:
9678 configure_alarms(optarg);
9679 break;
9680 case QEMU_OPTION_startdate:
9682 struct tm tm;
9683 time_t rtc_start_date;
9684 if (!strcmp(optarg, "now")) {
9685 rtc_date_offset = -1;
9686 } else {
9687 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9688 &tm.tm_year,
9689 &tm.tm_mon,
9690 &tm.tm_mday,
9691 &tm.tm_hour,
9692 &tm.tm_min,
9693 &tm.tm_sec) == 6) {
9694 /* OK */
9695 } else if (sscanf(optarg, "%d-%d-%d",
9696 &tm.tm_year,
9697 &tm.tm_mon,
9698 &tm.tm_mday) == 3) {
9699 tm.tm_hour = 0;
9700 tm.tm_min = 0;
9701 tm.tm_sec = 0;
9702 } else {
9703 goto date_fail;
9705 tm.tm_year -= 1900;
9706 tm.tm_mon--;
9707 rtc_start_date = mktimegm(&tm);
9708 if (rtc_start_date == -1) {
9709 date_fail:
9710 fprintf(stderr, "Invalid date format. Valid format are:\n"
9711 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9712 exit(1);
9714 rtc_date_offset = time(NULL) - rtc_start_date;
9717 break;
9718 case QEMU_OPTION_tb_size:
9719 tb_size = strtol(optarg, NULL, 0);
9720 if (tb_size < 0)
9721 tb_size = 0;
9722 break;
9723 case QEMU_OPTION_icount:
9724 use_icount = 1;
9725 if (strcmp(optarg, "auto") == 0) {
9726 icount_time_shift = -1;
9727 } else {
9728 icount_time_shift = strtol(optarg, NULL, 0);
9730 break;
9735 if (nographic) {
9736 if (serial_device_index == 0)
9737 serial_devices[0] = "stdio";
9738 if (parallel_device_index == 0)
9739 parallel_devices[0] = "null";
9740 if (strncmp(monitor_device, "vc", 2) == 0)
9741 monitor_device = "stdio";
9744 #ifndef _WIN32
9745 if (daemonize) {
9746 pid_t pid;
9748 if (pipe(fds) == -1)
9749 exit(1);
9751 pid = fork();
9752 if (pid > 0) {
9753 uint8_t status;
9754 ssize_t len;
9756 close(fds[1]);
9758 again:
9759 len = read(fds[0], &status, 1);
9760 if (len == -1 && (errno == EINTR))
9761 goto again;
9763 if (len != 1)
9764 exit(1);
9765 else if (status == 1) {
9766 fprintf(stderr, "Could not acquire pidfile\n");
9767 exit(1);
9768 } else
9769 exit(0);
9770 } else if (pid < 0)
9771 exit(1);
9773 setsid();
9775 pid = fork();
9776 if (pid > 0)
9777 exit(0);
9778 else if (pid < 0)
9779 exit(1);
9781 umask(027);
9783 signal(SIGTSTP, SIG_IGN);
9784 signal(SIGTTOU, SIG_IGN);
9785 signal(SIGTTIN, SIG_IGN);
9787 #endif
9789 #if USE_KVM
9790 if (kvm_enabled()) {
9791 if (kvm_qemu_init() < 0) {
9792 extern int kvm_allowed;
9793 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9794 #ifdef NO_CPU_EMULATION
9795 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9796 exit(1);
9797 #endif
9798 kvm_allowed = 0;
9801 #endif
9803 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9804 if (daemonize) {
9805 uint8_t status = 1;
9806 write(fds[1], &status, 1);
9807 } else
9808 fprintf(stderr, "Could not acquire pid file\n");
9809 exit(1);
9812 #ifdef USE_KQEMU
9813 if (smp_cpus > 1)
9814 kqemu_allowed = 0;
9815 #endif
9816 linux_boot = (kernel_filename != NULL);
9817 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9819 if (!linux_boot && net_boot == 0 &&
9820 !machine->nodisk_ok && nb_drives_opt == 0)
9821 help(1);
9823 if (!linux_boot && *kernel_cmdline != '\0') {
9824 fprintf(stderr, "-append only allowed with -kernel option\n");
9825 exit(1);
9828 if (!linux_boot && initrd_filename != NULL) {
9829 fprintf(stderr, "-initrd only allowed with -kernel option\n");
9830 exit(1);
9833 /* boot to floppy or the default cd if no hard disk defined yet */
9834 if (!boot_devices[0]) {
9835 boot_devices = "cad";
9837 setvbuf(stdout, NULL, _IOLBF, 0);
9839 init_timers();
9840 init_timer_alarm();
9841 qemu_aio_init();
9842 if (use_icount && icount_time_shift < 0) {
9843 use_icount = 2;
9844 /* 125MIPS seems a reasonable initial guess at the guest speed.
9845 It will be corrected fairly quickly anyway. */
9846 icount_time_shift = 3;
9847 init_icount_adjust();
9850 #ifdef _WIN32
9851 socket_init();
9852 #endif
9854 /* init network clients */
9855 if (nb_net_clients == 0) {
9856 /* if no clients, we use a default config */
9857 net_clients[0] = "nic";
9858 net_clients[1] = "user";
9859 nb_net_clients = 2;
9862 for(i = 0;i < nb_net_clients; i++) {
9863 if (net_client_parse(net_clients[i]) < 0)
9864 exit(1);
9866 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9867 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9868 continue;
9869 if (vlan->nb_guest_devs == 0)
9870 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9871 if (vlan->nb_host_devs == 0)
9872 fprintf(stderr,
9873 "Warning: vlan %d is not connected to host network\n",
9874 vlan->id);
9877 #ifdef TARGET_I386
9878 /* XXX: this should be moved in the PC machine instantiation code */
9879 if (net_boot != 0) {
9880 int netroms = 0;
9881 for (i = 0; i < nb_nics && i < 4; i++) {
9882 const char *model = nd_table[i].model;
9883 char buf[1024];
9884 if (net_boot & (1 << i)) {
9885 if (model == NULL)
9886 model = "rtl8139";
9887 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9888 if (get_image_size(buf) > 0) {
9889 if (nb_option_roms >= MAX_OPTION_ROMS) {
9890 fprintf(stderr, "Too many option ROMs\n");
9891 exit(1);
9893 option_rom[nb_option_roms] = strdup(buf);
9894 nb_option_roms++;
9895 netroms++;
9899 if (netroms == 0) {
9900 fprintf(stderr, "No valid PXE rom found for network device\n");
9901 exit(1);
9904 #endif
9906 /* init the memory */
9907 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9909 if (machine->ram_require & RAMSIZE_FIXED) {
9910 if (ram_size > 0) {
9911 if (ram_size < phys_ram_size) {
9912 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9913 machine->name, (unsigned long long) phys_ram_size);
9914 exit(-1);
9917 phys_ram_size = ram_size;
9918 } else
9919 ram_size = phys_ram_size;
9920 } else {
9921 if (ram_size == 0)
9922 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9924 phys_ram_size += ram_size;
9927 /* Initialize kvm */
9928 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9929 #define KVM_EXTRA_PAGES 3
9930 #else
9931 #define KVM_EXTRA_PAGES 0
9932 #endif
9933 if (kvm_enabled()) {
9934 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9935 if (kvm_qemu_create_context() < 0) {
9936 fprintf(stderr, "Could not create KVM context\n");
9937 exit(1);
9941 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9942 if (!phys_ram_base) {
9943 fprintf(stderr, "Could not allocate physical memory\n");
9944 exit(1);
9947 /* init the dynamic translator */
9948 cpu_exec_init_all(tb_size * 1024 * 1024);
9950 bdrv_init();
9952 /* we always create the cdrom drive, even if no disk is there */
9954 if (nb_drives_opt < MAX_DRIVES)
9955 drive_add(NULL, CDROM_ALIAS);
9957 /* we always create at least one floppy */
9959 if (nb_drives_opt < MAX_DRIVES)
9960 drive_add(NULL, FD_ALIAS, 0);
9962 /* we always create one sd slot, even if no card is in it */
9964 if (nb_drives_opt < MAX_DRIVES)
9965 drive_add(NULL, SD_ALIAS);
9967 /* open the virtual block devices
9968 * note that migration with device
9969 * hot add/remove is broken.
9971 for(i = 0; i < nb_drives_opt; i++)
9972 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9973 exit(1);
9975 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9976 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9978 /* terminal init */
9979 memset(&display_state, 0, sizeof(display_state));
9980 if (nographic) {
9981 if (curses) {
9982 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9983 exit(1);
9985 /* nearly nothing to do */
9986 dumb_display_init(ds);
9987 } else if (vnc_display != NULL) {
9988 vnc_display_init(ds);
9989 if (vnc_display_open(ds, vnc_display) < 0)
9990 exit(1);
9991 } else
9992 #if defined(CONFIG_CURSES)
9993 if (curses) {
9994 curses_display_init(ds, full_screen);
9995 } else
9996 #endif
9998 #if defined(CONFIG_SDL)
9999 sdl_display_init(ds, full_screen, no_frame);
10000 #elif defined(CONFIG_COCOA)
10001 cocoa_display_init(ds, full_screen);
10002 #else
10003 dumb_display_init(ds);
10004 #endif
10007 #ifndef _WIN32
10008 /* must be after terminal init, SDL library changes signal handlers */
10009 termsig_setup();
10010 #endif
10012 /* Maintain compatibility with multiple stdio monitors */
10013 if (!strcmp(monitor_device,"stdio")) {
10014 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
10015 const char *devname = serial_devices[i];
10016 if (devname && !strcmp(devname,"mon:stdio")) {
10017 monitor_device = NULL;
10018 break;
10019 } else if (devname && !strcmp(devname,"stdio")) {
10020 monitor_device = NULL;
10021 serial_devices[i] = "mon:stdio";
10022 break;
10026 if (monitor_device) {
10027 monitor_hd = qemu_chr_open(monitor_device);
10028 if (!monitor_hd) {
10029 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
10030 exit(1);
10032 monitor_init(monitor_hd, !nographic);
10035 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
10036 const char *devname = serial_devices[i];
10037 if (devname && strcmp(devname, "none")) {
10038 serial_hds[i] = qemu_chr_open(devname);
10039 if (!serial_hds[i]) {
10040 fprintf(stderr, "qemu: could not open serial device '%s'\n",
10041 devname);
10042 exit(1);
10044 if (strstart(devname, "vc", 0))
10045 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
10049 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
10050 const char *devname = parallel_devices[i];
10051 if (devname && strcmp(devname, "none")) {
10052 parallel_hds[i] = qemu_chr_open(devname);
10053 if (!parallel_hds[i]) {
10054 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
10055 devname);
10056 exit(1);
10058 if (strstart(devname, "vc", 0))
10059 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
10063 if (kvm_enabled())
10064 kvm_init_ap();
10066 machine->init(ram_size, vga_ram_size, boot_devices, ds,
10067 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
10069 current_machine = machine;
10071 /* init USB devices */
10072 if (usb_enabled) {
10073 for(i = 0; i < usb_devices_index; i++) {
10074 if (usb_device_add(usb_devices[i]) < 0) {
10075 fprintf(stderr, "Warning: could not add USB device %s\n",
10076 usb_devices[i]);
10081 if (display_state.dpy_refresh) {
10082 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
10083 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
10086 #ifdef CONFIG_GDBSTUB
10087 if (use_gdbstub) {
10088 /* XXX: use standard host:port notation and modify options
10089 accordingly. */
10090 if (gdbserver_start(gdbstub_port) < 0) {
10091 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
10092 gdbstub_port);
10093 exit(1);
10096 #endif
10098 if (loadvm)
10099 do_loadvm(loadvm);
10101 if (incoming) {
10102 int rc;
10104 rc = migrate_incoming(incoming);
10105 if (rc != 0) {
10106 fprintf(stderr, "Migration failed rc=%d\n", rc);
10107 exit(rc);
10112 /* XXX: simplify init */
10113 read_passwords();
10114 if (autostart) {
10115 vm_start();
10119 if (daemonize) {
10120 uint8_t status = 0;
10121 ssize_t len;
10122 int fd;
10124 again1:
10125 len = write(fds[1], &status, 1);
10126 if (len == -1 && (errno == EINTR))
10127 goto again1;
10129 if (len != 1)
10130 exit(1);
10132 chdir("/");
10133 TFR(fd = open("/dev/null", O_RDWR));
10134 if (fd == -1)
10135 exit(1);
10137 dup2(fd, 0);
10138 dup2(fd, 1);
10139 dup2(fd, 2);
10141 close(fd);
10144 main_loop();
10145 quit_timers();
10147 #if !defined(_WIN32)
10148 /* close network clients */
10149 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
10150 VLANClientState *vc;
10152 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
10153 if (vc->fd_read == tap_receive) {
10154 char ifname[64];
10155 TAPState *s = vc->opaque;
10157 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
10158 s->down_script[0])
10159 launch_script(s->down_script, ifname, s->fd);
10161 #if defined(CONFIG_VDE)
10162 if (vc->fd_read == vde_from_qemu) {
10163 VDEState *s = vc->opaque;
10164 vde_close(s->vde);
10166 #endif
10169 #endif
10170 return 0;