kvm: external module: sles10 32bit compat fix
[qemu-kvm/markmc.git] / vl.c
blob7e4dce1d2c55ac9580988f77173591d9a15973ac
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "net.h"
33 #include "console.h"
34 #include "sysemu.h"
35 #include "gdbstub.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
38 #include "block.h"
39 #include "audio/audio.h"
40 #include "migration.h"
41 #include "qemu-kvm.h"
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <time.h>
47 #include <errno.h>
48 #include <sys/time.h>
49 #include <zlib.h>
51 #ifndef _WIN32
52 #include <sys/times.h>
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <sys/poll.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <dirent.h>
61 #include <netdb.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
64 #ifdef _BSD
65 #include <sys/stat.h>
66 #ifndef __APPLE__
67 #include <libutil.h>
68 #endif
69 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
70 #include <freebsd/stdlib.h>
71 #else
72 #ifndef __sun__
73 #include <linux/if.h>
74 #include <linux/if_tun.h>
75 #include <pty.h>
76 #include <malloc.h>
77 #include <linux/rtc.h>
79 /* For the benefit of older linux systems which don't supply it,
80 we use a local copy of hpet.h. */
81 /* #include <linux/hpet.h> */
82 #include "hpet.h"
84 #include <linux/ppdev.h>
85 #include <linux/parport.h>
86 #else
87 #include <sys/stat.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
97 #include <net/if.h>
98 #include <syslog.h>
99 #include <stropts.h>
100 #endif
101 #endif
102 #else
103 #include <winsock2.h>
104 int inet_aton(const char *cp, struct in_addr *ia);
105 #endif
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
109 #endif
111 #ifdef _WIN32
112 #include <malloc.h>
113 #include <sys/timeb.h>
114 #include <mmsystem.h>
115 #define getopt_long_only getopt_long
116 #define memalign(align, size) malloc(size)
117 #endif
119 #include "qemu_socket.h"
121 #ifdef CONFIG_SDL
122 #ifdef __APPLE__
123 #include <SDL/SDL.h>
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "disas.h"
134 #include "exec-all.h"
136 #include "qemu-kvm.h"
138 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
140 #ifdef __sun__
141 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
142 #else
143 #define SMBD_COMMAND "/usr/sbin/smbd"
144 #endif
146 //#define DEBUG_UNUSED_IOPORT
147 //#define DEBUG_IOPORT
149 #ifdef TARGET_PPC
150 #define DEFAULT_RAM_SIZE 144
151 #else
152 #define DEFAULT_RAM_SIZE 128
153 #endif
154 /* in ms */
155 #define GUI_REFRESH_INTERVAL 30
157 /* Max number of USB devices that can be specified on the commandline. */
158 #define MAX_USB_CMDLINE 8
160 /* XXX: use a two level table to limit memory usage */
161 #define MAX_IOPORTS 65536
163 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
164 const char *bios_name = NULL;
165 void *ioport_opaque[MAX_IOPORTS];
166 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
167 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
168 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
169 to store the VM snapshots */
170 DriveInfo drives_table[MAX_DRIVES+1];
171 int nb_drives;
172 int extboot_drive = -1;
173 /* point to the block driver where the snapshots are managed */
174 BlockDriverState *bs_snapshots;
175 int vga_ram_size;
176 static DisplayState display_state;
177 int nographic;
178 int curses;
179 const char* keyboard_layout = NULL;
180 int64_t ticks_per_sec;
181 ram_addr_t ram_size;
182 int pit_min_timer_count = 0;
183 int nb_nics;
184 NICInfo nd_table[MAX_NICS];
185 int vm_running;
186 static int rtc_utc = 1;
187 static int rtc_date_offset = -1; /* -1 means no change */
188 int cirrus_vga_enabled = 1;
189 int vmsvga_enabled = 0;
190 #ifdef TARGET_SPARC
191 int graphic_width = 1024;
192 int graphic_height = 768;
193 int graphic_depth = 8;
194 #else
195 int graphic_width = 800;
196 int graphic_height = 600;
197 int graphic_depth = 15;
198 #endif
199 int full_screen = 0;
200 int no_frame = 0;
201 int no_quit = 0;
202 int balloon_used = 0;
203 CharDriverState *vmchannel_hds[MAX_VMCHANNEL_DEVICES];
204 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
205 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
206 #ifdef TARGET_I386
207 int win2k_install_hack = 0;
208 #endif
209 int usb_enabled = 0;
210 static VLANState *first_vlan;
211 int smp_cpus = 1;
212 const char *vnc_display;
213 #if defined(TARGET_SPARC)
214 #define MAX_CPUS 16
215 #elif defined(TARGET_I386)
216 #define MAX_CPUS 255
217 #elif defined(TARGET_IA64)
218 #define MAX_CPUS 4
219 #else
220 #define MAX_CPUS 1
221 #endif
222 int acpi_enabled = 1;
223 int fd_bootchk = 1;
224 int no_reboot = 0;
225 int no_shutdown = 0;
226 int cursor_hide = 1;
227 int graphic_rotate = 0;
228 int daemonize = 0;
229 const char *incoming;
230 const char *option_rom[MAX_OPTION_ROMS];
231 int nb_option_roms;
232 int semihosting_enabled = 0;
233 int autostart = 1;
234 int time_drift_fix = 0;
235 unsigned int kvm_shadow_memory = 0;
236 const char *mem_path = NULL;
237 int hpagesize = 0;
238 const char *cpu_vendor_string;
239 #ifdef TARGET_ARM
240 int old_param = 0;
241 #endif
242 const char *qemu_name;
243 int alt_grab = 0;
244 #ifdef TARGET_SPARC
245 unsigned int nb_prom_envs = 0;
246 const char *prom_envs[MAX_PROM_ENVS];
247 #endif
248 int nb_drives_opt;
249 struct drive_opt drives_opt[MAX_DRIVES];
251 static CPUState *cur_cpu;
252 static CPUState *next_cpu;
253 static int event_pending = 1;
255 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
257 /* KVM runs the main loop in a separate thread. If we update one of the lists
258 * that are polled before or after select(), we need to make sure to break out
259 * of the select() to ensure the new item is serviced.
261 static void main_loop_break(void)
263 if (kvm_enabled())
264 qemu_kvm_notify_work();
267 void decorate_application_name(char *appname, int max_len)
269 if (kvm_enabled())
271 int remain = max_len - strlen(appname) - 1;
273 if (remain > 0)
274 strncat(appname, "/KVM", remain);
278 /***********************************************************/
279 /* x86 ISA bus support */
281 target_phys_addr_t isa_mem_base = 0;
282 PicState2 *isa_pic;
284 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
286 #ifdef DEBUG_UNUSED_IOPORT
287 fprintf(stderr, "unused inb: port=0x%04x\n", address);
288 #endif
289 return 0xff;
292 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
294 #ifdef DEBUG_UNUSED_IOPORT
295 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
296 #endif
299 /* default is to make two byte accesses */
300 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
302 uint32_t data;
303 data = ioport_read_table[0][address](ioport_opaque[address], address);
304 address = (address + 1) & (MAX_IOPORTS - 1);
305 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
306 return data;
309 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
311 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
312 address = (address + 1) & (MAX_IOPORTS - 1);
313 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
316 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
318 #ifdef DEBUG_UNUSED_IOPORT
319 fprintf(stderr, "unused inl: port=0x%04x\n", address);
320 #endif
321 return 0xffffffff;
324 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
326 #ifdef DEBUG_UNUSED_IOPORT
327 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
328 #endif
331 static void init_ioports(void)
333 int i;
335 for(i = 0; i < MAX_IOPORTS; i++) {
336 ioport_read_table[0][i] = default_ioport_readb;
337 ioport_write_table[0][i] = default_ioport_writeb;
338 ioport_read_table[1][i] = default_ioport_readw;
339 ioport_write_table[1][i] = default_ioport_writew;
340 ioport_read_table[2][i] = default_ioport_readl;
341 ioport_write_table[2][i] = default_ioport_writel;
345 /* size is the word size in byte */
346 int register_ioport_read(int start, int length, int size,
347 IOPortReadFunc *func, void *opaque)
349 int i, bsize;
351 if (size == 1) {
352 bsize = 0;
353 } else if (size == 2) {
354 bsize = 1;
355 } else if (size == 4) {
356 bsize = 2;
357 } else {
358 hw_error("register_ioport_read: invalid size");
359 return -1;
361 for(i = start; i < start + length; i += size) {
362 ioport_read_table[bsize][i] = func;
363 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
364 hw_error("register_ioport_read: invalid opaque");
365 ioport_opaque[i] = opaque;
367 return 0;
370 /* size is the word size in byte */
371 int register_ioport_write(int start, int length, int size,
372 IOPortWriteFunc *func, void *opaque)
374 int i, bsize;
376 if (size == 1) {
377 bsize = 0;
378 } else if (size == 2) {
379 bsize = 1;
380 } else if (size == 4) {
381 bsize = 2;
382 } else {
383 hw_error("register_ioport_write: invalid size");
384 return -1;
386 for(i = start; i < start + length; i += size) {
387 ioport_write_table[bsize][i] = func;
388 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
389 hw_error("register_ioport_write: invalid opaque");
390 ioport_opaque[i] = opaque;
392 return 0;
395 void isa_unassign_ioport(int start, int length)
397 int i;
399 for(i = start; i < start + length; i++) {
400 ioport_read_table[0][i] = default_ioport_readb;
401 ioport_read_table[1][i] = default_ioport_readw;
402 ioport_read_table[2][i] = default_ioport_readl;
404 ioport_write_table[0][i] = default_ioport_writeb;
405 ioport_write_table[1][i] = default_ioport_writew;
406 ioport_write_table[2][i] = default_ioport_writel;
408 ioport_opaque[i] = NULL;
412 /***********************************************************/
414 void cpu_outb(CPUState *env, int addr, int val)
416 #ifdef DEBUG_IOPORT
417 if (loglevel & CPU_LOG_IOPORT)
418 fprintf(logfile, "outb: %04x %02x\n", addr, val);
419 #endif
420 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
421 #ifdef USE_KQEMU
422 if (env)
423 env->last_io_time = cpu_get_time_fast();
424 #endif
427 void cpu_outw(CPUState *env, int addr, int val)
429 #ifdef DEBUG_IOPORT
430 if (loglevel & CPU_LOG_IOPORT)
431 fprintf(logfile, "outw: %04x %04x\n", addr, val);
432 #endif
433 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
434 #ifdef USE_KQEMU
435 if (env)
436 env->last_io_time = cpu_get_time_fast();
437 #endif
440 void cpu_outl(CPUState *env, int addr, int val)
442 #ifdef DEBUG_IOPORT
443 if (loglevel & CPU_LOG_IOPORT)
444 fprintf(logfile, "outl: %04x %08x\n", addr, val);
445 #endif
446 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
447 #ifdef USE_KQEMU
448 if (env)
449 env->last_io_time = cpu_get_time_fast();
450 #endif
453 int cpu_inb(CPUState *env, int addr)
455 int val;
456 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
457 #ifdef DEBUG_IOPORT
458 if (loglevel & CPU_LOG_IOPORT)
459 fprintf(logfile, "inb : %04x %02x\n", addr, val);
460 #endif
461 #ifdef USE_KQEMU
462 if (env)
463 env->last_io_time = cpu_get_time_fast();
464 #endif
465 return val;
468 int cpu_inw(CPUState *env, int addr)
470 int val;
471 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
472 #ifdef DEBUG_IOPORT
473 if (loglevel & CPU_LOG_IOPORT)
474 fprintf(logfile, "inw : %04x %04x\n", addr, val);
475 #endif
476 #ifdef USE_KQEMU
477 if (env)
478 env->last_io_time = cpu_get_time_fast();
479 #endif
480 return val;
483 int cpu_inl(CPUState *env, int addr)
485 int val;
486 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
487 #ifdef DEBUG_IOPORT
488 if (loglevel & CPU_LOG_IOPORT)
489 fprintf(logfile, "inl : %04x %08x\n", addr, val);
490 #endif
491 #ifdef USE_KQEMU
492 if (env)
493 env->last_io_time = cpu_get_time_fast();
494 #endif
495 return val;
498 /***********************************************************/
499 void hw_error(const char *fmt, ...)
501 va_list ap;
502 CPUState *env;
504 va_start(ap, fmt);
505 fprintf(stderr, "qemu: hardware error: ");
506 vfprintf(stderr, fmt, ap);
507 fprintf(stderr, "\n");
508 for(env = first_cpu; env != NULL; env = env->next_cpu) {
509 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
510 #ifdef TARGET_I386
511 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
512 #else
513 cpu_dump_state(env, stderr, fprintf, 0);
514 #endif
516 va_end(ap);
517 abort();
520 /***********************************************************/
521 /* keyboard/mouse */
523 static QEMUPutKBDEvent *qemu_put_kbd_event;
524 static void *qemu_put_kbd_event_opaque;
525 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
526 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
528 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
530 qemu_put_kbd_event_opaque = opaque;
531 qemu_put_kbd_event = func;
534 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
535 void *opaque, int absolute,
536 const char *name)
538 QEMUPutMouseEntry *s, *cursor;
540 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
541 if (!s)
542 return NULL;
544 s->qemu_put_mouse_event = func;
545 s->qemu_put_mouse_event_opaque = opaque;
546 s->qemu_put_mouse_event_absolute = absolute;
547 s->qemu_put_mouse_event_name = qemu_strdup(name);
548 s->next = NULL;
550 if (!qemu_put_mouse_event_head) {
551 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
552 return s;
555 cursor = qemu_put_mouse_event_head;
556 while (cursor->next != NULL)
557 cursor = cursor->next;
559 cursor->next = s;
560 qemu_put_mouse_event_current = s;
562 return s;
565 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
567 QEMUPutMouseEntry *prev = NULL, *cursor;
569 if (!qemu_put_mouse_event_head || entry == NULL)
570 return;
572 cursor = qemu_put_mouse_event_head;
573 while (cursor != NULL && cursor != entry) {
574 prev = cursor;
575 cursor = cursor->next;
578 if (cursor == NULL) // does not exist or list empty
579 return;
580 else if (prev == NULL) { // entry is head
581 qemu_put_mouse_event_head = cursor->next;
582 if (qemu_put_mouse_event_current == entry)
583 qemu_put_mouse_event_current = cursor->next;
584 qemu_free(entry->qemu_put_mouse_event_name);
585 qemu_free(entry);
586 return;
589 prev->next = entry->next;
591 if (qemu_put_mouse_event_current == entry)
592 qemu_put_mouse_event_current = prev;
594 qemu_free(entry->qemu_put_mouse_event_name);
595 qemu_free(entry);
598 void kbd_put_keycode(int keycode)
600 if (qemu_put_kbd_event) {
601 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
605 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
607 QEMUPutMouseEvent *mouse_event;
608 void *mouse_event_opaque;
609 int width;
611 if (!qemu_put_mouse_event_current) {
612 return;
615 mouse_event =
616 qemu_put_mouse_event_current->qemu_put_mouse_event;
617 mouse_event_opaque =
618 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
620 if (mouse_event) {
621 if (graphic_rotate) {
622 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
623 width = 0x7fff;
624 else
625 width = graphic_width - 1;
626 mouse_event(mouse_event_opaque,
627 width - dy, dx, dz, buttons_state);
628 } else
629 mouse_event(mouse_event_opaque,
630 dx, dy, dz, buttons_state);
634 int kbd_mouse_is_absolute(void)
636 if (!qemu_put_mouse_event_current)
637 return 0;
639 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
642 void do_info_mice(void)
644 QEMUPutMouseEntry *cursor;
645 int index = 0;
647 if (!qemu_put_mouse_event_head) {
648 term_printf("No mouse devices connected\n");
649 return;
652 term_printf("Mouse devices available:\n");
653 cursor = qemu_put_mouse_event_head;
654 while (cursor != NULL) {
655 term_printf("%c Mouse #%d: %s\n",
656 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
657 index, cursor->qemu_put_mouse_event_name);
658 index++;
659 cursor = cursor->next;
663 void do_mouse_set(int index)
665 QEMUPutMouseEntry *cursor;
666 int i = 0;
668 if (!qemu_put_mouse_event_head) {
669 term_printf("No mouse devices connected\n");
670 return;
673 cursor = qemu_put_mouse_event_head;
674 while (cursor != NULL && index != i) {
675 i++;
676 cursor = cursor->next;
679 if (cursor != NULL)
680 qemu_put_mouse_event_current = cursor;
681 else
682 term_printf("Mouse at given index not found\n");
685 /* compute with 96 bit intermediate result: (a*b)/c */
686 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
688 union {
689 uint64_t ll;
690 struct {
691 #ifdef WORDS_BIGENDIAN
692 uint32_t high, low;
693 #else
694 uint32_t low, high;
695 #endif
696 } l;
697 } u, res;
698 uint64_t rl, rh;
700 u.ll = a;
701 rl = (uint64_t)u.l.low * (uint64_t)b;
702 rh = (uint64_t)u.l.high * (uint64_t)b;
703 rh += (rl >> 32);
704 res.l.high = rh / c;
705 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
706 return res.ll;
709 /***********************************************************/
710 /* real time host monotonic timer */
712 #define QEMU_TIMER_BASE 1000000000LL
714 #ifdef WIN32
716 static int64_t clock_freq;
718 static void init_get_clock(void)
720 LARGE_INTEGER freq;
721 int ret;
722 ret = QueryPerformanceFrequency(&freq);
723 if (ret == 0) {
724 fprintf(stderr, "Could not calibrate ticks\n");
725 exit(1);
727 clock_freq = freq.QuadPart;
730 static int64_t get_clock(void)
732 LARGE_INTEGER ti;
733 QueryPerformanceCounter(&ti);
734 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
737 #else
739 static int use_rt_clock;
741 static void init_get_clock(void)
743 use_rt_clock = 0;
744 #if defined(__linux__)
746 struct timespec ts;
747 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
748 use_rt_clock = 1;
751 #endif
754 static int64_t get_clock(void)
756 #if defined(__linux__)
757 if (use_rt_clock) {
758 struct timespec ts;
759 clock_gettime(CLOCK_MONOTONIC, &ts);
760 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
761 } else
762 #endif
764 /* XXX: using gettimeofday leads to problems if the date
765 changes, so it should be avoided. */
766 struct timeval tv;
767 gettimeofday(&tv, NULL);
768 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
772 #endif
774 /***********************************************************/
775 /* guest cycle counter */
777 static int64_t cpu_ticks_prev;
778 static int64_t cpu_ticks_offset;
779 static int64_t cpu_clock_offset;
780 static int cpu_ticks_enabled;
782 /* return the host CPU cycle counter and handle stop/restart */
783 int64_t cpu_get_ticks(void)
785 if (!cpu_ticks_enabled) {
786 return cpu_ticks_offset;
787 } else {
788 int64_t ticks;
789 ticks = cpu_get_real_ticks();
790 if (cpu_ticks_prev > ticks) {
791 /* Note: non increasing ticks may happen if the host uses
792 software suspend */
793 cpu_ticks_offset += cpu_ticks_prev - ticks;
795 cpu_ticks_prev = ticks;
796 return ticks + cpu_ticks_offset;
800 /* return the host CPU monotonic timer and handle stop/restart */
801 static int64_t cpu_get_clock(void)
803 int64_t ti;
804 if (!cpu_ticks_enabled) {
805 return cpu_clock_offset;
806 } else {
807 ti = get_clock();
808 return ti + cpu_clock_offset;
812 /* enable cpu_get_ticks() */
813 void cpu_enable_ticks(void)
815 if (!cpu_ticks_enabled) {
816 cpu_ticks_offset -= cpu_get_real_ticks();
817 cpu_clock_offset -= get_clock();
818 cpu_ticks_enabled = 1;
822 /* disable cpu_get_ticks() : the clock is stopped. You must not call
823 cpu_get_ticks() after that. */
824 void cpu_disable_ticks(void)
826 if (cpu_ticks_enabled) {
827 cpu_ticks_offset = cpu_get_ticks();
828 cpu_clock_offset = cpu_get_clock();
829 cpu_ticks_enabled = 0;
833 /***********************************************************/
834 /* timers */
836 #define QEMU_TIMER_REALTIME 0
837 #define QEMU_TIMER_VIRTUAL 1
839 struct QEMUClock {
840 int type;
841 /* XXX: add frequency */
844 struct QEMUTimer {
845 QEMUClock *clock;
846 int64_t expire_time;
847 QEMUTimerCB *cb;
848 void *opaque;
849 struct QEMUTimer *next;
852 struct qemu_alarm_timer {
853 char const *name;
854 unsigned int flags;
856 int (*start)(struct qemu_alarm_timer *t);
857 void (*stop)(struct qemu_alarm_timer *t);
858 void (*rearm)(struct qemu_alarm_timer *t);
859 void *priv;
862 #define ALARM_FLAG_DYNTICKS 0x1
863 #define ALARM_FLAG_EXPIRED 0x2
865 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
867 return t->flags & ALARM_FLAG_DYNTICKS;
870 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
872 if (!alarm_has_dynticks(t))
873 return;
875 t->rearm(t);
878 /* TODO: MIN_TIMER_REARM_US should be optimized */
879 #define MIN_TIMER_REARM_US 250
881 static struct qemu_alarm_timer *alarm_timer;
883 #ifdef _WIN32
885 struct qemu_alarm_win32 {
886 MMRESULT timerId;
887 HANDLE host_alarm;
888 unsigned int period;
889 } alarm_win32_data = {0, NULL, -1};
891 static int win32_start_timer(struct qemu_alarm_timer *t);
892 static void win32_stop_timer(struct qemu_alarm_timer *t);
893 static void win32_rearm_timer(struct qemu_alarm_timer *t);
895 #else
897 static int unix_start_timer(struct qemu_alarm_timer *t);
898 static void unix_stop_timer(struct qemu_alarm_timer *t);
900 #ifdef __linux__
902 static int dynticks_start_timer(struct qemu_alarm_timer *t);
903 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
904 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
906 static int hpet_start_timer(struct qemu_alarm_timer *t);
907 static void hpet_stop_timer(struct qemu_alarm_timer *t);
909 static int rtc_start_timer(struct qemu_alarm_timer *t);
910 static void rtc_stop_timer(struct qemu_alarm_timer *t);
912 #endif /* __linux__ */
914 #endif /* _WIN32 */
916 static struct qemu_alarm_timer alarm_timers[] = {
917 #ifndef _WIN32
918 #ifdef __linux__
919 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
920 dynticks_stop_timer, dynticks_rearm_timer, NULL},
921 /* HPET - if available - is preferred */
922 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
923 /* ...otherwise try RTC */
924 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
925 #endif
926 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
927 #else
928 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
929 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
930 {"win32", 0, win32_start_timer,
931 win32_stop_timer, NULL, &alarm_win32_data},
932 #endif
933 {NULL, }
936 static void show_available_alarms(void)
938 int i;
940 printf("Available alarm timers, in order of precedence:\n");
941 for (i = 0; alarm_timers[i].name; i++)
942 printf("%s\n", alarm_timers[i].name);
945 static void configure_alarms(char const *opt)
947 int i;
948 int cur = 0;
949 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
950 char *arg;
951 char *name;
953 if (!strcmp(opt, "?")) {
954 show_available_alarms();
955 exit(0);
958 arg = strdup(opt);
960 /* Reorder the array */
961 name = strtok(arg, ",");
962 while (name) {
963 struct qemu_alarm_timer tmp;
965 for (i = 0; i < count && alarm_timers[i].name; i++) {
966 if (!strcmp(alarm_timers[i].name, name))
967 break;
970 if (i == count) {
971 fprintf(stderr, "Unknown clock %s\n", name);
972 goto next;
975 if (i < cur)
976 /* Ignore */
977 goto next;
979 /* Swap */
980 tmp = alarm_timers[i];
981 alarm_timers[i] = alarm_timers[cur];
982 alarm_timers[cur] = tmp;
984 cur++;
985 next:
986 name = strtok(NULL, ",");
989 free(arg);
991 if (cur) {
992 /* Disable remaining timers */
993 for (i = cur; i < count; i++)
994 alarm_timers[i].name = NULL;
995 } else {
996 show_available_alarms();
997 exit(1);
1001 QEMUClock *rt_clock;
1002 QEMUClock *vm_clock;
1004 static QEMUTimer *active_timers[2];
1006 static QEMUClock *qemu_new_clock(int type)
1008 QEMUClock *clock;
1009 clock = qemu_mallocz(sizeof(QEMUClock));
1010 if (!clock)
1011 return NULL;
1012 clock->type = type;
1013 return clock;
1016 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1018 QEMUTimer *ts;
1020 ts = qemu_mallocz(sizeof(QEMUTimer));
1021 ts->clock = clock;
1022 ts->cb = cb;
1023 ts->opaque = opaque;
1024 return ts;
1027 void qemu_free_timer(QEMUTimer *ts)
1029 qemu_free(ts);
1032 /* stop a timer, but do not dealloc it */
1033 void qemu_del_timer(QEMUTimer *ts)
1035 QEMUTimer **pt, *t;
1037 /* NOTE: this code must be signal safe because
1038 qemu_timer_expired() can be called from a signal. */
1039 pt = &active_timers[ts->clock->type];
1040 for(;;) {
1041 t = *pt;
1042 if (!t)
1043 break;
1044 if (t == ts) {
1045 *pt = t->next;
1046 break;
1048 pt = &t->next;
1052 /* modify the current timer so that it will be fired when current_time
1053 >= expire_time. The corresponding callback will be called. */
1054 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1056 QEMUTimer **pt, *t;
1058 qemu_del_timer(ts);
1060 /* add the timer in the sorted list */
1061 /* NOTE: this code must be signal safe because
1062 qemu_timer_expired() can be called from a signal. */
1063 pt = &active_timers[ts->clock->type];
1064 for(;;) {
1065 t = *pt;
1066 if (!t)
1067 break;
1068 if (t->expire_time > expire_time)
1069 break;
1070 pt = &t->next;
1072 ts->expire_time = expire_time;
1073 ts->next = *pt;
1074 *pt = ts;
1076 /* Rearm if necessary */
1077 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1078 pt == &active_timers[ts->clock->type])
1079 qemu_rearm_alarm_timer(alarm_timer);
1082 int qemu_timer_pending(QEMUTimer *ts)
1084 QEMUTimer *t;
1085 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1086 if (t == ts)
1087 return 1;
1089 return 0;
1092 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1094 if (!timer_head)
1095 return 0;
1096 return (timer_head->expire_time <= current_time);
1099 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1101 QEMUTimer *ts;
1103 for(;;) {
1104 ts = *ptimer_head;
1105 if (!ts || ts->expire_time > current_time)
1106 break;
1107 /* remove timer from the list before calling the callback */
1108 *ptimer_head = ts->next;
1109 ts->next = NULL;
1111 /* run the callback (the timer list can be modified) */
1112 ts->cb(ts->opaque);
1116 int64_t qemu_get_clock(QEMUClock *clock)
1118 switch(clock->type) {
1119 case QEMU_TIMER_REALTIME:
1120 return get_clock() / 1000000;
1121 default:
1122 case QEMU_TIMER_VIRTUAL:
1123 return cpu_get_clock();
1127 static void init_timers(void)
1129 init_get_clock();
1130 ticks_per_sec = QEMU_TIMER_BASE;
1131 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1132 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1135 /* save a timer */
1136 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1138 uint64_t expire_time;
1140 if (qemu_timer_pending(ts)) {
1141 expire_time = ts->expire_time;
1142 } else {
1143 expire_time = -1;
1145 qemu_put_be64(f, expire_time);
1148 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1150 uint64_t expire_time;
1152 expire_time = qemu_get_be64(f);
1153 if (expire_time != -1) {
1154 qemu_mod_timer(ts, expire_time);
1155 } else {
1156 qemu_del_timer(ts);
1160 static void timer_save(QEMUFile *f, void *opaque)
1162 if (cpu_ticks_enabled) {
1163 hw_error("cannot save state if virtual timers are running");
1165 qemu_put_be64(f, cpu_ticks_offset);
1166 qemu_put_be64(f, ticks_per_sec);
1167 qemu_put_be64(f, cpu_clock_offset);
1170 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1172 if (version_id != 1 && version_id != 2)
1173 return -EINVAL;
1174 if (cpu_ticks_enabled) {
1175 return -EINVAL;
1177 cpu_ticks_offset=qemu_get_be64(f);
1178 ticks_per_sec=qemu_get_be64(f);
1179 if (version_id == 2) {
1180 cpu_clock_offset=qemu_get_be64(f);
1182 return 0;
1185 #ifdef _WIN32
1186 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1187 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1188 #else
1189 static void host_alarm_handler(int host_signum)
1190 #endif
1192 #if 0
1193 #define DISP_FREQ 1000
1195 static int64_t delta_min = INT64_MAX;
1196 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1197 static int count;
1198 ti = qemu_get_clock(vm_clock);
1199 if (last_clock != 0) {
1200 delta = ti - last_clock;
1201 if (delta < delta_min)
1202 delta_min = delta;
1203 if (delta > delta_max)
1204 delta_max = delta;
1205 delta_cum += delta;
1206 if (++count == DISP_FREQ) {
1207 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1208 muldiv64(delta_min, 1000000, ticks_per_sec),
1209 muldiv64(delta_max, 1000000, ticks_per_sec),
1210 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1211 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1212 count = 0;
1213 delta_min = INT64_MAX;
1214 delta_max = 0;
1215 delta_cum = 0;
1218 last_clock = ti;
1220 #endif
1221 if (1 ||
1222 alarm_has_dynticks(alarm_timer) ||
1223 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1224 qemu_get_clock(vm_clock)) ||
1225 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1226 qemu_get_clock(rt_clock))) {
1227 #ifdef _WIN32
1228 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1229 SetEvent(data->host_alarm);
1230 #endif
1231 CPUState *env = next_cpu;
1233 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1235 if (env) {
1236 /* stop the currently executing cpu because a timer occured */
1237 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1238 #ifdef USE_KQEMU
1239 if (env->kqemu_enabled) {
1240 kqemu_cpu_interrupt(env);
1242 #endif
1244 event_pending = 1;
1248 static uint64_t qemu_next_deadline(void)
1250 int64_t nearest_delta_us = INT64_MAX;
1251 int64_t vmdelta_us;
1253 if (active_timers[QEMU_TIMER_REALTIME])
1254 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1255 qemu_get_clock(rt_clock))*1000;
1257 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1258 /* round up */
1259 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1260 qemu_get_clock(vm_clock)+999)/1000;
1261 if (vmdelta_us < nearest_delta_us)
1262 nearest_delta_us = vmdelta_us;
1265 /* Avoid arming the timer to negative, zero, or too low values */
1266 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1267 nearest_delta_us = MIN_TIMER_REARM_US;
1269 return nearest_delta_us;
1272 #ifndef _WIN32
1274 #if defined(__linux__)
1276 #define RTC_FREQ 1024
1278 static void enable_sigio_timer(int fd)
1280 struct sigaction act;
1282 /* timer signal */
1283 sigfillset(&act.sa_mask);
1284 act.sa_flags = 0;
1285 act.sa_handler = host_alarm_handler;
1287 sigaction(SIGIO, &act, NULL);
1288 fcntl(fd, F_SETFL, O_ASYNC);
1289 fcntl(fd, F_SETOWN, getpid());
1292 static int hpet_start_timer(struct qemu_alarm_timer *t)
1294 struct hpet_info info;
1295 int r, fd;
1297 fd = open("/dev/hpet", O_RDONLY);
1298 if (fd < 0)
1299 return -1;
1301 /* Set frequency */
1302 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1303 if (r < 0) {
1304 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1305 "error, but for better emulation accuracy type:\n"
1306 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1307 goto fail;
1310 /* Check capabilities */
1311 r = ioctl(fd, HPET_INFO, &info);
1312 if (r < 0)
1313 goto fail;
1315 /* Enable periodic mode */
1316 r = ioctl(fd, HPET_EPI, 0);
1317 if (info.hi_flags && (r < 0))
1318 goto fail;
1320 /* Enable interrupt */
1321 r = ioctl(fd, HPET_IE_ON, 0);
1322 if (r < 0)
1323 goto fail;
1325 enable_sigio_timer(fd);
1326 t->priv = (void *)(long)fd;
1328 return 0;
1329 fail:
1330 close(fd);
1331 return -1;
1334 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1336 int fd = (long)t->priv;
1338 close(fd);
1341 static int rtc_start_timer(struct qemu_alarm_timer *t)
1343 int rtc_fd;
1344 unsigned long current_rtc_freq = 0;
1346 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1347 if (rtc_fd < 0)
1348 return -1;
1349 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1350 if (current_rtc_freq != RTC_FREQ &&
1351 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1352 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1353 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1354 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1355 goto fail;
1357 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1358 fail:
1359 close(rtc_fd);
1360 return -1;
1363 enable_sigio_timer(rtc_fd);
1365 t->priv = (void *)(long)rtc_fd;
1367 return 0;
1370 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1372 int rtc_fd = (long)t->priv;
1374 close(rtc_fd);
1377 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1379 struct sigevent ev;
1380 timer_t host_timer;
1381 struct sigaction act;
1383 sigfillset(&act.sa_mask);
1384 act.sa_flags = 0;
1385 act.sa_handler = host_alarm_handler;
1387 sigaction(SIGALRM, &act, NULL);
1389 ev.sigev_value.sival_int = 0;
1390 ev.sigev_notify = SIGEV_SIGNAL;
1391 ev.sigev_signo = SIGALRM;
1393 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1394 perror("timer_create");
1396 /* disable dynticks */
1397 fprintf(stderr, "Dynamic Ticks disabled\n");
1399 return -1;
1402 t->priv = (void *)host_timer;
1404 return 0;
1407 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1409 timer_t host_timer = (timer_t)t->priv;
1411 timer_delete(host_timer);
1414 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1416 timer_t host_timer = (timer_t)t->priv;
1417 struct itimerspec timeout;
1418 int64_t nearest_delta_us = INT64_MAX;
1419 int64_t current_us;
1421 if (!active_timers[QEMU_TIMER_REALTIME] &&
1422 !active_timers[QEMU_TIMER_VIRTUAL])
1423 return;
1425 nearest_delta_us = qemu_next_deadline();
1427 /* check whether a timer is already running */
1428 if (timer_gettime(host_timer, &timeout)) {
1429 perror("gettime");
1430 fprintf(stderr, "Internal timer error: aborting\n");
1431 exit(1);
1433 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1434 if (current_us && current_us <= nearest_delta_us)
1435 return;
1437 timeout.it_interval.tv_sec = 0;
1438 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1439 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1440 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1441 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1442 perror("settime");
1443 fprintf(stderr, "Internal timer error: aborting\n");
1444 exit(1);
1448 #endif /* defined(__linux__) */
1450 static int unix_start_timer(struct qemu_alarm_timer *t)
1452 struct sigaction act;
1453 struct itimerval itv;
1454 int err;
1456 /* timer signal */
1457 sigfillset(&act.sa_mask);
1458 act.sa_flags = 0;
1459 act.sa_handler = host_alarm_handler;
1461 sigaction(SIGALRM, &act, NULL);
1463 itv.it_interval.tv_sec = 0;
1464 /* for i386 kernel 2.6 to get 1 ms */
1465 itv.it_interval.tv_usec = 999;
1466 itv.it_value.tv_sec = 0;
1467 itv.it_value.tv_usec = 10 * 1000;
1469 err = setitimer(ITIMER_REAL, &itv, NULL);
1470 if (err)
1471 return -1;
1473 return 0;
1476 static void unix_stop_timer(struct qemu_alarm_timer *t)
1478 struct itimerval itv;
1480 memset(&itv, 0, sizeof(itv));
1481 setitimer(ITIMER_REAL, &itv, NULL);
1484 #endif /* !defined(_WIN32) */
1486 #ifdef _WIN32
1488 static int win32_start_timer(struct qemu_alarm_timer *t)
1490 TIMECAPS tc;
1491 struct qemu_alarm_win32 *data = t->priv;
1492 UINT flags;
1494 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1495 if (!data->host_alarm) {
1496 perror("Failed CreateEvent");
1497 return -1;
1500 memset(&tc, 0, sizeof(tc));
1501 timeGetDevCaps(&tc, sizeof(tc));
1503 if (data->period < tc.wPeriodMin)
1504 data->period = tc.wPeriodMin;
1506 timeBeginPeriod(data->period);
1508 flags = TIME_CALLBACK_FUNCTION;
1509 if (alarm_has_dynticks(t))
1510 flags |= TIME_ONESHOT;
1511 else
1512 flags |= TIME_PERIODIC;
1514 data->timerId = timeSetEvent(1, // interval (ms)
1515 data->period, // resolution
1516 host_alarm_handler, // function
1517 (DWORD)t, // parameter
1518 flags);
1520 if (!data->timerId) {
1521 perror("Failed to initialize win32 alarm timer");
1523 timeEndPeriod(data->period);
1524 CloseHandle(data->host_alarm);
1525 return -1;
1528 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1530 return 0;
1533 static void win32_stop_timer(struct qemu_alarm_timer *t)
1535 struct qemu_alarm_win32 *data = t->priv;
1537 timeKillEvent(data->timerId);
1538 timeEndPeriod(data->period);
1540 CloseHandle(data->host_alarm);
1543 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1545 struct qemu_alarm_win32 *data = t->priv;
1546 uint64_t nearest_delta_us;
1548 if (!active_timers[QEMU_TIMER_REALTIME] &&
1549 !active_timers[QEMU_TIMER_VIRTUAL])
1550 return;
1552 nearest_delta_us = qemu_next_deadline();
1553 nearest_delta_us /= 1000;
1555 timeKillEvent(data->timerId);
1557 data->timerId = timeSetEvent(1,
1558 data->period,
1559 host_alarm_handler,
1560 (DWORD)t,
1561 TIME_ONESHOT | TIME_PERIODIC);
1563 if (!data->timerId) {
1564 perror("Failed to re-arm win32 alarm timer");
1566 timeEndPeriod(data->period);
1567 CloseHandle(data->host_alarm);
1568 exit(1);
1572 #endif /* _WIN32 */
1574 static void init_timer_alarm(void)
1576 struct qemu_alarm_timer *t;
1577 int i, err = -1;
1579 for (i = 0; alarm_timers[i].name; i++) {
1580 t = &alarm_timers[i];
1582 err = t->start(t);
1583 if (!err)
1584 break;
1587 if (err) {
1588 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1589 fprintf(stderr, "Terminating\n");
1590 exit(1);
1593 alarm_timer = t;
1596 static void quit_timers(void)
1598 alarm_timer->stop(alarm_timer);
1599 alarm_timer = NULL;
1602 /***********************************************************/
1603 /* host time/date access */
1604 void qemu_get_timedate(struct tm *tm, int offset)
1606 time_t ti;
1607 struct tm *ret;
1609 time(&ti);
1610 ti += offset;
1611 if (rtc_date_offset == -1) {
1612 if (rtc_utc)
1613 ret = gmtime(&ti);
1614 else
1615 ret = localtime(&ti);
1616 } else {
1617 ti -= rtc_date_offset;
1618 ret = gmtime(&ti);
1621 memcpy(tm, ret, sizeof(struct tm));
1624 int qemu_timedate_diff(struct tm *tm)
1626 time_t seconds;
1628 if (rtc_date_offset == -1)
1629 if (rtc_utc)
1630 seconds = mktimegm(tm);
1631 else
1632 seconds = mktime(tm);
1633 else
1634 seconds = mktimegm(tm) + rtc_date_offset;
1636 return seconds - time(NULL);
1639 /***********************************************************/
1640 /* character device */
1642 static void qemu_chr_event(CharDriverState *s, int event)
1644 if (!s->chr_event)
1645 return;
1646 s->chr_event(s->handler_opaque, event);
1649 static void qemu_chr_reset_bh(void *opaque)
1651 CharDriverState *s = opaque;
1652 qemu_chr_event(s, CHR_EVENT_RESET);
1653 qemu_bh_delete(s->bh);
1654 s->bh = NULL;
1657 void qemu_chr_reset(CharDriverState *s)
1659 if (s->bh == NULL) {
1660 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1661 qemu_bh_schedule(s->bh);
1665 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1667 return s->chr_write(s, buf, len);
1670 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1672 if (!s->chr_ioctl)
1673 return -ENOTSUP;
1674 return s->chr_ioctl(s, cmd, arg);
1677 int qemu_chr_can_read(CharDriverState *s)
1679 if (!s->chr_can_read)
1680 return 0;
1681 return s->chr_can_read(s->handler_opaque);
1684 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1686 s->chr_read(s->handler_opaque, buf, len);
1689 void qemu_chr_accept_input(CharDriverState *s)
1691 if (s->chr_accept_input)
1692 s->chr_accept_input(s);
1695 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1697 char buf[4096];
1698 va_list ap;
1699 va_start(ap, fmt);
1700 vsnprintf(buf, sizeof(buf), fmt, ap);
1701 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1702 va_end(ap);
1705 void qemu_chr_send_event(CharDriverState *s, int event)
1707 if (s->chr_send_event)
1708 s->chr_send_event(s, event);
1711 void qemu_chr_add_handlers(CharDriverState *s,
1712 IOCanRWHandler *fd_can_read,
1713 IOReadHandler *fd_read,
1714 IOEventHandler *fd_event,
1715 void *opaque)
1717 s->chr_can_read = fd_can_read;
1718 s->chr_read = fd_read;
1719 s->chr_event = fd_event;
1720 s->handler_opaque = opaque;
1721 if (s->chr_update_read_handler)
1722 s->chr_update_read_handler(s);
1725 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1727 return len;
1730 static CharDriverState *qemu_chr_open_null(void)
1732 CharDriverState *chr;
1734 chr = qemu_mallocz(sizeof(CharDriverState));
1735 if (!chr)
1736 return NULL;
1737 chr->chr_write = null_chr_write;
1738 return chr;
1741 /* MUX driver for serial I/O splitting */
1742 static int term_timestamps;
1743 static int64_t term_timestamps_start;
1744 #define MAX_MUX 4
1745 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1746 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1747 typedef struct {
1748 IOCanRWHandler *chr_can_read[MAX_MUX];
1749 IOReadHandler *chr_read[MAX_MUX];
1750 IOEventHandler *chr_event[MAX_MUX];
1751 void *ext_opaque[MAX_MUX];
1752 CharDriverState *drv;
1753 unsigned char buffer[MUX_BUFFER_SIZE];
1754 int prod;
1755 int cons;
1756 int mux_cnt;
1757 int term_got_escape;
1758 int max_size;
1759 } MuxDriver;
1762 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1764 MuxDriver *d = chr->opaque;
1765 int ret;
1766 if (!term_timestamps) {
1767 ret = d->drv->chr_write(d->drv, buf, len);
1768 } else {
1769 int i;
1771 ret = 0;
1772 for(i = 0; i < len; i++) {
1773 ret += d->drv->chr_write(d->drv, buf+i, 1);
1774 if (buf[i] == '\n') {
1775 char buf1[64];
1776 int64_t ti;
1777 int secs;
1779 ti = get_clock();
1780 if (term_timestamps_start == -1)
1781 term_timestamps_start = ti;
1782 ti -= term_timestamps_start;
1783 secs = ti / 1000000000;
1784 snprintf(buf1, sizeof(buf1),
1785 "[%02d:%02d:%02d.%03d] ",
1786 secs / 3600,
1787 (secs / 60) % 60,
1788 secs % 60,
1789 (int)((ti / 1000000) % 1000));
1790 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1794 return ret;
1797 static char *mux_help[] = {
1798 "% h print this help\n\r",
1799 "% x exit emulator\n\r",
1800 "% s save disk data back to file (if -snapshot)\n\r",
1801 "% t toggle console timestamps\n\r"
1802 "% b send break (magic sysrq)\n\r",
1803 "% c switch between console and monitor\n\r",
1804 "% % sends %\n\r",
1805 NULL
1808 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1809 static void mux_print_help(CharDriverState *chr)
1811 int i, j;
1812 char ebuf[15] = "Escape-Char";
1813 char cbuf[50] = "\n\r";
1815 if (term_escape_char > 0 && term_escape_char < 26) {
1816 sprintf(cbuf,"\n\r");
1817 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1818 } else {
1819 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1820 term_escape_char);
1822 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1823 for (i = 0; mux_help[i] != NULL; i++) {
1824 for (j=0; mux_help[i][j] != '\0'; j++) {
1825 if (mux_help[i][j] == '%')
1826 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1827 else
1828 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1833 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1835 if (d->term_got_escape) {
1836 d->term_got_escape = 0;
1837 if (ch == term_escape_char)
1838 goto send_char;
1839 switch(ch) {
1840 case '?':
1841 case 'h':
1842 mux_print_help(chr);
1843 break;
1844 case 'x':
1846 char *term = "QEMU: Terminated\n\r";
1847 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1848 exit(0);
1849 break;
1851 case 's':
1853 int i;
1854 for (i = 0; i < nb_drives; i++) {
1855 bdrv_commit(drives_table[i].bdrv);
1858 break;
1859 case 'b':
1860 qemu_chr_event(chr, CHR_EVENT_BREAK);
1861 break;
1862 case 'c':
1863 /* Switch to the next registered device */
1864 chr->focus++;
1865 if (chr->focus >= d->mux_cnt)
1866 chr->focus = 0;
1867 break;
1868 case 't':
1869 term_timestamps = !term_timestamps;
1870 term_timestamps_start = -1;
1871 break;
1873 } else if (ch == term_escape_char) {
1874 d->term_got_escape = 1;
1875 } else {
1876 send_char:
1877 return 1;
1879 return 0;
1882 static void mux_chr_accept_input(CharDriverState *chr)
1884 int m = chr->focus;
1885 MuxDriver *d = chr->opaque;
1887 while (d->prod != d->cons &&
1888 d->chr_can_read[m] &&
1889 d->chr_can_read[m](d->ext_opaque[m])) {
1890 d->chr_read[m](d->ext_opaque[m],
1891 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1895 static int mux_chr_can_read(void *opaque)
1897 CharDriverState *chr = opaque;
1898 MuxDriver *d = chr->opaque;
1900 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1901 return 1;
1902 if (d->chr_can_read[chr->focus])
1903 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1904 return 0;
1907 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1909 CharDriverState *chr = opaque;
1910 MuxDriver *d = chr->opaque;
1911 int m = chr->focus;
1912 int i;
1914 mux_chr_accept_input (opaque);
1916 for(i = 0; i < size; i++)
1917 if (mux_proc_byte(chr, d, buf[i])) {
1918 if (d->prod == d->cons &&
1919 d->chr_can_read[m] &&
1920 d->chr_can_read[m](d->ext_opaque[m]))
1921 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1922 else
1923 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1927 static void mux_chr_event(void *opaque, int event)
1929 CharDriverState *chr = opaque;
1930 MuxDriver *d = chr->opaque;
1931 int i;
1933 /* Send the event to all registered listeners */
1934 for (i = 0; i < d->mux_cnt; i++)
1935 if (d->chr_event[i])
1936 d->chr_event[i](d->ext_opaque[i], event);
1939 static void mux_chr_update_read_handler(CharDriverState *chr)
1941 MuxDriver *d = chr->opaque;
1943 if (d->mux_cnt >= MAX_MUX) {
1944 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1945 return;
1947 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1948 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1949 d->chr_read[d->mux_cnt] = chr->chr_read;
1950 d->chr_event[d->mux_cnt] = chr->chr_event;
1951 /* Fix up the real driver with mux routines */
1952 if (d->mux_cnt == 0) {
1953 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1954 mux_chr_event, chr);
1956 chr->focus = d->mux_cnt;
1957 d->mux_cnt++;
1960 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1962 CharDriverState *chr;
1963 MuxDriver *d;
1965 chr = qemu_mallocz(sizeof(CharDriverState));
1966 if (!chr)
1967 return NULL;
1968 d = qemu_mallocz(sizeof(MuxDriver));
1969 if (!d) {
1970 free(chr);
1971 return NULL;
1974 chr->opaque = d;
1975 d->drv = drv;
1976 chr->focus = -1;
1977 chr->chr_write = mux_chr_write;
1978 chr->chr_update_read_handler = mux_chr_update_read_handler;
1979 chr->chr_accept_input = mux_chr_accept_input;
1980 return chr;
1984 #ifdef _WIN32
1986 static void socket_cleanup(void)
1988 WSACleanup();
1991 static int socket_init(void)
1993 WSADATA Data;
1994 int ret, err;
1996 ret = WSAStartup(MAKEWORD(2,2), &Data);
1997 if (ret != 0) {
1998 err = WSAGetLastError();
1999 fprintf(stderr, "WSAStartup: %d\n", err);
2000 return -1;
2002 atexit(socket_cleanup);
2003 return 0;
2006 static int send_all(int fd, const uint8_t *buf, int len1)
2008 int ret, len;
2010 len = len1;
2011 while (len > 0) {
2012 ret = send(fd, buf, len, 0);
2013 if (ret < 0) {
2014 int errno;
2015 errno = WSAGetLastError();
2016 if (errno != WSAEWOULDBLOCK) {
2017 return -1;
2019 } else if (ret == 0) {
2020 break;
2021 } else {
2022 buf += ret;
2023 len -= ret;
2026 return len1 - len;
2029 void socket_set_nonblock(int fd)
2031 unsigned long opt = 1;
2032 ioctlsocket(fd, FIONBIO, &opt);
2035 #else
2037 static int unix_write(int fd, const uint8_t *buf, int len1)
2039 int ret, len;
2041 len = len1;
2042 while (len > 0) {
2043 ret = write(fd, buf, len);
2044 if (ret < 0) {
2045 if (errno != EINTR && errno != EAGAIN)
2046 return -1;
2047 } else if (ret == 0) {
2048 break;
2049 } else {
2050 buf += ret;
2051 len -= ret;
2054 return len1 - len;
2057 static inline int send_all(int fd, const uint8_t *buf, int len1)
2059 return unix_write(fd, buf, len1);
2062 void socket_set_nonblock(int fd)
2064 fcntl(fd, F_SETFL, O_NONBLOCK);
2066 #endif /* !_WIN32 */
2068 #ifndef _WIN32
2070 typedef struct {
2071 int fd_in, fd_out;
2072 int max_size;
2073 } FDCharDriver;
2075 #define STDIO_MAX_CLIENTS 1
2076 static int stdio_nb_clients = 0;
2078 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2080 FDCharDriver *s = chr->opaque;
2081 return unix_write(s->fd_out, buf, len);
2084 static int fd_chr_read_poll(void *opaque)
2086 CharDriverState *chr = opaque;
2087 FDCharDriver *s = chr->opaque;
2089 s->max_size = qemu_chr_can_read(chr);
2090 return s->max_size;
2093 static void fd_chr_read(void *opaque)
2095 CharDriverState *chr = opaque;
2096 FDCharDriver *s = chr->opaque;
2097 int size, len;
2098 uint8_t buf[1024];
2100 len = sizeof(buf);
2101 if (len > s->max_size)
2102 len = s->max_size;
2103 if (len == 0)
2104 return;
2105 size = read(s->fd_in, buf, len);
2106 if (size == 0) {
2107 /* FD has been closed. Remove it from the active list. */
2108 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2109 return;
2111 if (size > 0) {
2112 qemu_chr_read(chr, buf, size);
2116 static void fd_chr_update_read_handler(CharDriverState *chr)
2118 FDCharDriver *s = chr->opaque;
2120 if (s->fd_in >= 0) {
2121 if (nographic && s->fd_in == 0) {
2122 } else {
2123 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2124 fd_chr_read, NULL, chr);
2129 static void fd_chr_close(struct CharDriverState *chr)
2131 FDCharDriver *s = chr->opaque;
2133 if (s->fd_in >= 0) {
2134 if (nographic && s->fd_in == 0) {
2135 } else {
2136 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2140 qemu_free(s);
2143 /* open a character device to a unix fd */
2144 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2146 CharDriverState *chr;
2147 FDCharDriver *s;
2149 chr = qemu_mallocz(sizeof(CharDriverState));
2150 if (!chr)
2151 return NULL;
2152 s = qemu_mallocz(sizeof(FDCharDriver));
2153 if (!s) {
2154 free(chr);
2155 return NULL;
2157 s->fd_in = fd_in;
2158 s->fd_out = fd_out;
2159 chr->opaque = s;
2160 chr->chr_write = fd_chr_write;
2161 chr->chr_update_read_handler = fd_chr_update_read_handler;
2162 chr->chr_close = fd_chr_close;
2164 qemu_chr_reset(chr);
2166 return chr;
2169 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2171 int fd_out;
2173 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2174 if (fd_out < 0)
2175 return NULL;
2176 return qemu_chr_open_fd(-1, fd_out);
2179 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2181 int fd_in, fd_out;
2182 char filename_in[256], filename_out[256];
2184 snprintf(filename_in, 256, "%s.in", filename);
2185 snprintf(filename_out, 256, "%s.out", filename);
2186 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2187 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2188 if (fd_in < 0 || fd_out < 0) {
2189 if (fd_in >= 0)
2190 close(fd_in);
2191 if (fd_out >= 0)
2192 close(fd_out);
2193 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2194 if (fd_in < 0)
2195 return NULL;
2197 return qemu_chr_open_fd(fd_in, fd_out);
2201 /* for STDIO, we handle the case where several clients use it
2202 (nographic mode) */
2204 #define TERM_FIFO_MAX_SIZE 1
2206 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2207 static int term_fifo_size;
2209 static int stdio_read_poll(void *opaque)
2211 CharDriverState *chr = opaque;
2213 /* try to flush the queue if needed */
2214 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2215 qemu_chr_read(chr, term_fifo, 1);
2216 term_fifo_size = 0;
2218 /* see if we can absorb more chars */
2219 if (term_fifo_size == 0)
2220 return 1;
2221 else
2222 return 0;
2225 static void stdio_read(void *opaque)
2227 int size;
2228 uint8_t buf[1];
2229 CharDriverState *chr = opaque;
2231 size = read(0, buf, 1);
2232 if (size == 0) {
2233 /* stdin has been closed. Remove it from the active list. */
2234 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2235 return;
2237 if (size > 0) {
2238 if (qemu_chr_can_read(chr) > 0) {
2239 qemu_chr_read(chr, buf, 1);
2240 } else if (term_fifo_size == 0) {
2241 term_fifo[term_fifo_size++] = buf[0];
2246 /* init terminal so that we can grab keys */
2247 static struct termios oldtty;
2248 static int old_fd0_flags;
2249 static int term_atexit_done;
2251 static void term_exit(void)
2253 tcsetattr (0, TCSANOW, &oldtty);
2254 fcntl(0, F_SETFL, old_fd0_flags);
2257 static void term_init(void)
2259 struct termios tty;
2261 tcgetattr (0, &tty);
2262 oldtty = tty;
2263 old_fd0_flags = fcntl(0, F_GETFL);
2265 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2266 |INLCR|IGNCR|ICRNL|IXON);
2267 tty.c_oflag |= OPOST;
2268 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2269 /* if graphical mode, we allow Ctrl-C handling */
2270 if (nographic)
2271 tty.c_lflag &= ~ISIG;
2272 tty.c_cflag &= ~(CSIZE|PARENB);
2273 tty.c_cflag |= CS8;
2274 tty.c_cc[VMIN] = 1;
2275 tty.c_cc[VTIME] = 0;
2277 tcsetattr (0, TCSANOW, &tty);
2279 if (!term_atexit_done++)
2280 atexit(term_exit);
2282 fcntl(0, F_SETFL, O_NONBLOCK);
2285 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2287 term_exit();
2288 stdio_nb_clients--;
2289 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2290 fd_chr_close(chr);
2293 static CharDriverState *qemu_chr_open_stdio(void)
2295 CharDriverState *chr;
2297 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2298 return NULL;
2299 chr = qemu_chr_open_fd(0, 1);
2300 chr->chr_close = qemu_chr_close_stdio;
2301 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2302 stdio_nb_clients++;
2303 term_init();
2305 return chr;
2308 #ifdef __sun__
2309 /* Once Solaris has openpty(), this is going to be removed. */
2310 int openpty(int *amaster, int *aslave, char *name,
2311 struct termios *termp, struct winsize *winp)
2313 const char *slave;
2314 int mfd = -1, sfd = -1;
2316 *amaster = *aslave = -1;
2318 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2319 if (mfd < 0)
2320 goto err;
2322 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2323 goto err;
2325 if ((slave = ptsname(mfd)) == NULL)
2326 goto err;
2328 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2329 goto err;
2331 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2332 (termp != NULL && tcgetattr(sfd, termp) < 0))
2333 goto err;
2335 if (amaster)
2336 *amaster = mfd;
2337 if (aslave)
2338 *aslave = sfd;
2339 if (winp)
2340 ioctl(sfd, TIOCSWINSZ, winp);
2342 return 0;
2344 err:
2345 if (sfd != -1)
2346 close(sfd);
2347 close(mfd);
2348 return -1;
2351 void cfmakeraw (struct termios *termios_p)
2353 termios_p->c_iflag &=
2354 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2355 termios_p->c_oflag &= ~OPOST;
2356 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2357 termios_p->c_cflag &= ~(CSIZE|PARENB);
2358 termios_p->c_cflag |= CS8;
2360 termios_p->c_cc[VMIN] = 0;
2361 termios_p->c_cc[VTIME] = 0;
2363 #endif
2365 #if defined(__linux__) || defined(__sun__)
2366 static CharDriverState *qemu_chr_open_pty(void)
2368 struct termios tty;
2369 int master_fd, slave_fd;
2371 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
2372 return NULL;
2375 /* Set raw attributes on the pty. */
2376 cfmakeraw(&tty);
2377 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2379 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
2380 return qemu_chr_open_fd(master_fd, master_fd);
2383 static void tty_serial_init(int fd, int speed,
2384 int parity, int data_bits, int stop_bits)
2386 struct termios tty;
2387 speed_t spd;
2389 #if 0
2390 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2391 speed, parity, data_bits, stop_bits);
2392 #endif
2393 tcgetattr (fd, &tty);
2395 #define MARGIN 1.1
2396 if (speed <= 50 * MARGIN)
2397 spd = B50;
2398 else if (speed <= 75 * MARGIN)
2399 spd = B75;
2400 else if (speed <= 300 * MARGIN)
2401 spd = B300;
2402 else if (speed <= 600 * MARGIN)
2403 spd = B600;
2404 else if (speed <= 1200 * MARGIN)
2405 spd = B1200;
2406 else if (speed <= 2400 * MARGIN)
2407 spd = B2400;
2408 else if (speed <= 4800 * MARGIN)
2409 spd = B4800;
2410 else if (speed <= 9600 * MARGIN)
2411 spd = B9600;
2412 else if (speed <= 19200 * MARGIN)
2413 spd = B19200;
2414 else if (speed <= 38400 * MARGIN)
2415 spd = B38400;
2416 else if (speed <= 57600 * MARGIN)
2417 spd = B57600;
2418 else if (speed <= 115200 * MARGIN)
2419 spd = B115200;
2420 else
2421 spd = B115200;
2423 cfsetispeed(&tty, spd);
2424 cfsetospeed(&tty, spd);
2426 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2427 |INLCR|IGNCR|ICRNL|IXON);
2428 tty.c_oflag |= OPOST;
2429 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2430 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2431 switch(data_bits) {
2432 default:
2433 case 8:
2434 tty.c_cflag |= CS8;
2435 break;
2436 case 7:
2437 tty.c_cflag |= CS7;
2438 break;
2439 case 6:
2440 tty.c_cflag |= CS6;
2441 break;
2442 case 5:
2443 tty.c_cflag |= CS5;
2444 break;
2446 switch(parity) {
2447 default:
2448 case 'N':
2449 break;
2450 case 'E':
2451 tty.c_cflag |= PARENB;
2452 break;
2453 case 'O':
2454 tty.c_cflag |= PARENB | PARODD;
2455 break;
2457 if (stop_bits == 2)
2458 tty.c_cflag |= CSTOPB;
2460 tcsetattr (fd, TCSANOW, &tty);
2463 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2465 FDCharDriver *s = chr->opaque;
2467 switch(cmd) {
2468 case CHR_IOCTL_SERIAL_SET_PARAMS:
2470 QEMUSerialSetParams *ssp = arg;
2471 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2472 ssp->data_bits, ssp->stop_bits);
2474 break;
2475 case CHR_IOCTL_SERIAL_SET_BREAK:
2477 int enable = *(int *)arg;
2478 if (enable)
2479 tcsendbreak(s->fd_in, 1);
2481 break;
2482 default:
2483 return -ENOTSUP;
2485 return 0;
2488 static CharDriverState *qemu_chr_open_tty(const char *filename)
2490 CharDriverState *chr;
2491 int fd;
2493 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2494 fcntl(fd, F_SETFL, O_NONBLOCK);
2495 tty_serial_init(fd, 115200, 'N', 8, 1);
2496 chr = qemu_chr_open_fd(fd, fd);
2497 if (!chr) {
2498 close(fd);
2499 return NULL;
2501 chr->chr_ioctl = tty_serial_ioctl;
2502 qemu_chr_reset(chr);
2503 return chr;
2505 #else /* ! __linux__ && ! __sun__ */
2506 static CharDriverState *qemu_chr_open_pty(void)
2508 return NULL;
2510 #endif /* __linux__ || __sun__ */
2512 #if defined(__linux__)
2513 typedef struct {
2514 int fd;
2515 int mode;
2516 } ParallelCharDriver;
2518 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2520 if (s->mode != mode) {
2521 int m = mode;
2522 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2523 return 0;
2524 s->mode = mode;
2526 return 1;
2529 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2531 ParallelCharDriver *drv = chr->opaque;
2532 int fd = drv->fd;
2533 uint8_t b;
2535 switch(cmd) {
2536 case CHR_IOCTL_PP_READ_DATA:
2537 if (ioctl(fd, PPRDATA, &b) < 0)
2538 return -ENOTSUP;
2539 *(uint8_t *)arg = b;
2540 break;
2541 case CHR_IOCTL_PP_WRITE_DATA:
2542 b = *(uint8_t *)arg;
2543 if (ioctl(fd, PPWDATA, &b) < 0)
2544 return -ENOTSUP;
2545 break;
2546 case CHR_IOCTL_PP_READ_CONTROL:
2547 if (ioctl(fd, PPRCONTROL, &b) < 0)
2548 return -ENOTSUP;
2549 /* Linux gives only the lowest bits, and no way to know data
2550 direction! For better compatibility set the fixed upper
2551 bits. */
2552 *(uint8_t *)arg = b | 0xc0;
2553 break;
2554 case CHR_IOCTL_PP_WRITE_CONTROL:
2555 b = *(uint8_t *)arg;
2556 if (ioctl(fd, PPWCONTROL, &b) < 0)
2557 return -ENOTSUP;
2558 break;
2559 case CHR_IOCTL_PP_READ_STATUS:
2560 if (ioctl(fd, PPRSTATUS, &b) < 0)
2561 return -ENOTSUP;
2562 *(uint8_t *)arg = b;
2563 break;
2564 case CHR_IOCTL_PP_EPP_READ_ADDR:
2565 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2566 struct ParallelIOArg *parg = arg;
2567 int n = read(fd, parg->buffer, parg->count);
2568 if (n != parg->count) {
2569 return -EIO;
2572 break;
2573 case CHR_IOCTL_PP_EPP_READ:
2574 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2575 struct ParallelIOArg *parg = arg;
2576 int n = read(fd, parg->buffer, parg->count);
2577 if (n != parg->count) {
2578 return -EIO;
2581 break;
2582 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2583 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2584 struct ParallelIOArg *parg = arg;
2585 int n = write(fd, parg->buffer, parg->count);
2586 if (n != parg->count) {
2587 return -EIO;
2590 break;
2591 case CHR_IOCTL_PP_EPP_WRITE:
2592 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2593 struct ParallelIOArg *parg = arg;
2594 int n = write(fd, parg->buffer, parg->count);
2595 if (n != parg->count) {
2596 return -EIO;
2599 break;
2600 default:
2601 return -ENOTSUP;
2603 return 0;
2606 static void pp_close(CharDriverState *chr)
2608 ParallelCharDriver *drv = chr->opaque;
2609 int fd = drv->fd;
2611 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2612 ioctl(fd, PPRELEASE);
2613 close(fd);
2614 qemu_free(drv);
2617 static CharDriverState *qemu_chr_open_pp(const char *filename)
2619 CharDriverState *chr;
2620 ParallelCharDriver *drv;
2621 int fd;
2623 TFR(fd = open(filename, O_RDWR));
2624 if (fd < 0)
2625 return NULL;
2627 if (ioctl(fd, PPCLAIM) < 0) {
2628 close(fd);
2629 return NULL;
2632 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2633 if (!drv) {
2634 close(fd);
2635 return NULL;
2637 drv->fd = fd;
2638 drv->mode = IEEE1284_MODE_COMPAT;
2640 chr = qemu_mallocz(sizeof(CharDriverState));
2641 if (!chr) {
2642 qemu_free(drv);
2643 close(fd);
2644 return NULL;
2646 chr->chr_write = null_chr_write;
2647 chr->chr_ioctl = pp_ioctl;
2648 chr->chr_close = pp_close;
2649 chr->opaque = drv;
2651 qemu_chr_reset(chr);
2653 return chr;
2655 #endif /* __linux__ */
2657 #else /* _WIN32 */
2659 typedef struct {
2660 int max_size;
2661 HANDLE hcom, hrecv, hsend;
2662 OVERLAPPED orecv, osend;
2663 BOOL fpipe;
2664 DWORD len;
2665 } WinCharState;
2667 #define NSENDBUF 2048
2668 #define NRECVBUF 2048
2669 #define MAXCONNECT 1
2670 #define NTIMEOUT 5000
2672 static int win_chr_poll(void *opaque);
2673 static int win_chr_pipe_poll(void *opaque);
2675 static void win_chr_close(CharDriverState *chr)
2677 WinCharState *s = chr->opaque;
2679 if (s->hsend) {
2680 CloseHandle(s->hsend);
2681 s->hsend = NULL;
2683 if (s->hrecv) {
2684 CloseHandle(s->hrecv);
2685 s->hrecv = NULL;
2687 if (s->hcom) {
2688 CloseHandle(s->hcom);
2689 s->hcom = NULL;
2691 if (s->fpipe)
2692 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2693 else
2694 qemu_del_polling_cb(win_chr_poll, chr);
2697 static int win_chr_init(CharDriverState *chr, const char *filename)
2699 WinCharState *s = chr->opaque;
2700 COMMCONFIG comcfg;
2701 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2702 COMSTAT comstat;
2703 DWORD size;
2704 DWORD err;
2706 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2707 if (!s->hsend) {
2708 fprintf(stderr, "Failed CreateEvent\n");
2709 goto fail;
2711 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2712 if (!s->hrecv) {
2713 fprintf(stderr, "Failed CreateEvent\n");
2714 goto fail;
2717 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2718 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2719 if (s->hcom == INVALID_HANDLE_VALUE) {
2720 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2721 s->hcom = NULL;
2722 goto fail;
2725 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2726 fprintf(stderr, "Failed SetupComm\n");
2727 goto fail;
2730 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2731 size = sizeof(COMMCONFIG);
2732 GetDefaultCommConfig(filename, &comcfg, &size);
2733 comcfg.dcb.DCBlength = sizeof(DCB);
2734 CommConfigDialog(filename, NULL, &comcfg);
2736 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2737 fprintf(stderr, "Failed SetCommState\n");
2738 goto fail;
2741 if (!SetCommMask(s->hcom, EV_ERR)) {
2742 fprintf(stderr, "Failed SetCommMask\n");
2743 goto fail;
2746 cto.ReadIntervalTimeout = MAXDWORD;
2747 if (!SetCommTimeouts(s->hcom, &cto)) {
2748 fprintf(stderr, "Failed SetCommTimeouts\n");
2749 goto fail;
2752 if (!ClearCommError(s->hcom, &err, &comstat)) {
2753 fprintf(stderr, "Failed ClearCommError\n");
2754 goto fail;
2756 qemu_add_polling_cb(win_chr_poll, chr);
2757 return 0;
2759 fail:
2760 win_chr_close(chr);
2761 return -1;
2764 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2766 WinCharState *s = chr->opaque;
2767 DWORD len, ret, size, err;
2769 len = len1;
2770 ZeroMemory(&s->osend, sizeof(s->osend));
2771 s->osend.hEvent = s->hsend;
2772 while (len > 0) {
2773 if (s->hsend)
2774 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2775 else
2776 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2777 if (!ret) {
2778 err = GetLastError();
2779 if (err == ERROR_IO_PENDING) {
2780 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2781 if (ret) {
2782 buf += size;
2783 len -= size;
2784 } else {
2785 break;
2787 } else {
2788 break;
2790 } else {
2791 buf += size;
2792 len -= size;
2795 return len1 - len;
2798 static int win_chr_read_poll(CharDriverState *chr)
2800 WinCharState *s = chr->opaque;
2802 s->max_size = qemu_chr_can_read(chr);
2803 return s->max_size;
2806 static void win_chr_readfile(CharDriverState *chr)
2808 WinCharState *s = chr->opaque;
2809 int ret, err;
2810 uint8_t buf[1024];
2811 DWORD size;
2813 ZeroMemory(&s->orecv, sizeof(s->orecv));
2814 s->orecv.hEvent = s->hrecv;
2815 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2816 if (!ret) {
2817 err = GetLastError();
2818 if (err == ERROR_IO_PENDING) {
2819 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2823 if (size > 0) {
2824 qemu_chr_read(chr, buf, size);
2828 static void win_chr_read(CharDriverState *chr)
2830 WinCharState *s = chr->opaque;
2832 if (s->len > s->max_size)
2833 s->len = s->max_size;
2834 if (s->len == 0)
2835 return;
2837 win_chr_readfile(chr);
2840 static int win_chr_poll(void *opaque)
2842 CharDriverState *chr = opaque;
2843 WinCharState *s = chr->opaque;
2844 COMSTAT status;
2845 DWORD comerr;
2847 ClearCommError(s->hcom, &comerr, &status);
2848 if (status.cbInQue > 0) {
2849 s->len = status.cbInQue;
2850 win_chr_read_poll(chr);
2851 win_chr_read(chr);
2852 return 1;
2854 return 0;
2857 static CharDriverState *qemu_chr_open_win(const char *filename)
2859 CharDriverState *chr;
2860 WinCharState *s;
2862 chr = qemu_mallocz(sizeof(CharDriverState));
2863 if (!chr)
2864 return NULL;
2865 s = qemu_mallocz(sizeof(WinCharState));
2866 if (!s) {
2867 free(chr);
2868 return NULL;
2870 chr->opaque = s;
2871 chr->chr_write = win_chr_write;
2872 chr->chr_close = win_chr_close;
2874 if (win_chr_init(chr, filename) < 0) {
2875 free(s);
2876 free(chr);
2877 return NULL;
2879 qemu_chr_reset(chr);
2880 return chr;
2883 static int win_chr_pipe_poll(void *opaque)
2885 CharDriverState *chr = opaque;
2886 WinCharState *s = chr->opaque;
2887 DWORD size;
2889 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2890 if (size > 0) {
2891 s->len = size;
2892 win_chr_read_poll(chr);
2893 win_chr_read(chr);
2894 return 1;
2896 return 0;
2899 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2901 WinCharState *s = chr->opaque;
2902 OVERLAPPED ov;
2903 int ret;
2904 DWORD size;
2905 char openname[256];
2907 s->fpipe = TRUE;
2909 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2910 if (!s->hsend) {
2911 fprintf(stderr, "Failed CreateEvent\n");
2912 goto fail;
2914 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2915 if (!s->hrecv) {
2916 fprintf(stderr, "Failed CreateEvent\n");
2917 goto fail;
2920 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2921 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2922 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2923 PIPE_WAIT,
2924 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2925 if (s->hcom == INVALID_HANDLE_VALUE) {
2926 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2927 s->hcom = NULL;
2928 goto fail;
2931 ZeroMemory(&ov, sizeof(ov));
2932 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2933 ret = ConnectNamedPipe(s->hcom, &ov);
2934 if (ret) {
2935 fprintf(stderr, "Failed ConnectNamedPipe\n");
2936 goto fail;
2939 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2940 if (!ret) {
2941 fprintf(stderr, "Failed GetOverlappedResult\n");
2942 if (ov.hEvent) {
2943 CloseHandle(ov.hEvent);
2944 ov.hEvent = NULL;
2946 goto fail;
2949 if (ov.hEvent) {
2950 CloseHandle(ov.hEvent);
2951 ov.hEvent = NULL;
2953 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2954 return 0;
2956 fail:
2957 win_chr_close(chr);
2958 return -1;
2962 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2964 CharDriverState *chr;
2965 WinCharState *s;
2967 chr = qemu_mallocz(sizeof(CharDriverState));
2968 if (!chr)
2969 return NULL;
2970 s = qemu_mallocz(sizeof(WinCharState));
2971 if (!s) {
2972 free(chr);
2973 return NULL;
2975 chr->opaque = s;
2976 chr->chr_write = win_chr_write;
2977 chr->chr_close = win_chr_close;
2979 if (win_chr_pipe_init(chr, filename) < 0) {
2980 free(s);
2981 free(chr);
2982 return NULL;
2984 qemu_chr_reset(chr);
2985 return chr;
2988 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2990 CharDriverState *chr;
2991 WinCharState *s;
2993 chr = qemu_mallocz(sizeof(CharDriverState));
2994 if (!chr)
2995 return NULL;
2996 s = qemu_mallocz(sizeof(WinCharState));
2997 if (!s) {
2998 free(chr);
2999 return NULL;
3001 s->hcom = fd_out;
3002 chr->opaque = s;
3003 chr->chr_write = win_chr_write;
3004 qemu_chr_reset(chr);
3005 return chr;
3008 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3010 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3013 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3015 HANDLE fd_out;
3017 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3018 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3019 if (fd_out == INVALID_HANDLE_VALUE)
3020 return NULL;
3022 return qemu_chr_open_win_file(fd_out);
3024 #endif /* !_WIN32 */
3026 /***********************************************************/
3027 /* UDP Net console */
3029 typedef struct {
3030 int fd;
3031 struct sockaddr_in daddr;
3032 uint8_t buf[1024];
3033 int bufcnt;
3034 int bufptr;
3035 int max_size;
3036 } NetCharDriver;
3038 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3040 NetCharDriver *s = chr->opaque;
3042 return sendto(s->fd, buf, len, 0,
3043 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3046 static int udp_chr_read_poll(void *opaque)
3048 CharDriverState *chr = opaque;
3049 NetCharDriver *s = chr->opaque;
3051 s->max_size = qemu_chr_can_read(chr);
3053 /* If there were any stray characters in the queue process them
3054 * first
3056 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3057 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3058 s->bufptr++;
3059 s->max_size = qemu_chr_can_read(chr);
3061 return s->max_size;
3064 static void udp_chr_read(void *opaque)
3066 CharDriverState *chr = opaque;
3067 NetCharDriver *s = chr->opaque;
3069 if (s->max_size == 0)
3070 return;
3071 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3072 s->bufptr = s->bufcnt;
3073 if (s->bufcnt <= 0)
3074 return;
3076 s->bufptr = 0;
3077 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3078 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3079 s->bufptr++;
3080 s->max_size = qemu_chr_can_read(chr);
3084 static void udp_chr_update_read_handler(CharDriverState *chr)
3086 NetCharDriver *s = chr->opaque;
3088 if (s->fd >= 0) {
3089 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3090 udp_chr_read, NULL, chr);
3094 #ifndef _WIN32
3095 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3096 #endif
3097 int parse_host_src_port(struct sockaddr_in *haddr,
3098 struct sockaddr_in *saddr,
3099 const char *str);
3101 static CharDriverState *qemu_chr_open_udp(const char *def)
3103 CharDriverState *chr = NULL;
3104 NetCharDriver *s = NULL;
3105 int fd = -1;
3106 struct sockaddr_in saddr;
3108 chr = qemu_mallocz(sizeof(CharDriverState));
3109 if (!chr)
3110 goto return_err;
3111 s = qemu_mallocz(sizeof(NetCharDriver));
3112 if (!s)
3113 goto return_err;
3115 fd = socket(PF_INET, SOCK_DGRAM, 0);
3116 if (fd < 0) {
3117 perror("socket(PF_INET, SOCK_DGRAM)");
3118 goto return_err;
3121 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3122 printf("Could not parse: %s\n", def);
3123 goto return_err;
3126 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3128 perror("bind");
3129 goto return_err;
3132 s->fd = fd;
3133 s->bufcnt = 0;
3134 s->bufptr = 0;
3135 chr->opaque = s;
3136 chr->chr_write = udp_chr_write;
3137 chr->chr_update_read_handler = udp_chr_update_read_handler;
3138 return chr;
3140 return_err:
3141 if (chr)
3142 free(chr);
3143 if (s)
3144 free(s);
3145 if (fd >= 0)
3146 closesocket(fd);
3147 return NULL;
3150 /***********************************************************/
3151 /* TCP Net console */
3153 typedef struct {
3154 int fd, listen_fd;
3155 int connected;
3156 int max_size;
3157 int do_telnetopt;
3158 int do_nodelay;
3159 int is_unix;
3160 } TCPCharDriver;
3162 static void tcp_chr_accept(void *opaque);
3164 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3166 TCPCharDriver *s = chr->opaque;
3167 if (s->connected) {
3168 return send_all(s->fd, buf, len);
3169 } else {
3170 /* XXX: indicate an error ? */
3171 return len;
3175 static int tcp_chr_read_poll(void *opaque)
3177 CharDriverState *chr = opaque;
3178 TCPCharDriver *s = chr->opaque;
3179 if (!s->connected)
3180 return 0;
3181 s->max_size = qemu_chr_can_read(chr);
3182 return s->max_size;
3185 #define IAC 255
3186 #define IAC_BREAK 243
3187 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3188 TCPCharDriver *s,
3189 uint8_t *buf, int *size)
3191 /* Handle any telnet client's basic IAC options to satisfy char by
3192 * char mode with no echo. All IAC options will be removed from
3193 * the buf and the do_telnetopt variable will be used to track the
3194 * state of the width of the IAC information.
3196 * IAC commands come in sets of 3 bytes with the exception of the
3197 * "IAC BREAK" command and the double IAC.
3200 int i;
3201 int j = 0;
3203 for (i = 0; i < *size; i++) {
3204 if (s->do_telnetopt > 1) {
3205 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3206 /* Double IAC means send an IAC */
3207 if (j != i)
3208 buf[j] = buf[i];
3209 j++;
3210 s->do_telnetopt = 1;
3211 } else {
3212 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3213 /* Handle IAC break commands by sending a serial break */
3214 qemu_chr_event(chr, CHR_EVENT_BREAK);
3215 s->do_telnetopt++;
3217 s->do_telnetopt++;
3219 if (s->do_telnetopt >= 4) {
3220 s->do_telnetopt = 1;
3222 } else {
3223 if ((unsigned char)buf[i] == IAC) {
3224 s->do_telnetopt = 2;
3225 } else {
3226 if (j != i)
3227 buf[j] = buf[i];
3228 j++;
3232 *size = j;
3235 static void tcp_chr_read(void *opaque)
3237 CharDriverState *chr = opaque;
3238 TCPCharDriver *s = chr->opaque;
3239 uint8_t buf[1024];
3240 int len, size;
3242 if (!s->connected || s->max_size <= 0)
3243 return;
3244 len = sizeof(buf);
3245 if (len > s->max_size)
3246 len = s->max_size;
3247 size = recv(s->fd, buf, len, 0);
3248 if (size == 0) {
3249 /* connection closed */
3250 s->connected = 0;
3251 if (s->listen_fd >= 0) {
3252 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3254 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3255 closesocket(s->fd);
3256 s->fd = -1;
3257 } else if (size > 0) {
3258 if (s->do_telnetopt)
3259 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3260 if (size > 0)
3261 qemu_chr_read(chr, buf, size);
3265 static void tcp_chr_connect(void *opaque)
3267 CharDriverState *chr = opaque;
3268 TCPCharDriver *s = chr->opaque;
3270 s->connected = 1;
3271 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3272 tcp_chr_read, NULL, chr);
3273 qemu_chr_reset(chr);
3276 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3277 static void tcp_chr_telnet_init(int fd)
3279 char buf[3];
3280 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3281 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3282 send(fd, (char *)buf, 3, 0);
3283 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3284 send(fd, (char *)buf, 3, 0);
3285 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3286 send(fd, (char *)buf, 3, 0);
3287 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3288 send(fd, (char *)buf, 3, 0);
3291 static void socket_set_nodelay(int fd)
3293 int val = 1;
3294 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3297 static void tcp_chr_accept(void *opaque)
3299 CharDriverState *chr = opaque;
3300 TCPCharDriver *s = chr->opaque;
3301 struct sockaddr_in saddr;
3302 #ifndef _WIN32
3303 struct sockaddr_un uaddr;
3304 #endif
3305 struct sockaddr *addr;
3306 socklen_t len;
3307 int fd;
3309 for(;;) {
3310 #ifndef _WIN32
3311 if (s->is_unix) {
3312 len = sizeof(uaddr);
3313 addr = (struct sockaddr *)&uaddr;
3314 } else
3315 #endif
3317 len = sizeof(saddr);
3318 addr = (struct sockaddr *)&saddr;
3320 fd = accept(s->listen_fd, addr, &len);
3321 if (fd < 0 && errno != EINTR) {
3322 return;
3323 } else if (fd >= 0) {
3324 if (s->do_telnetopt)
3325 tcp_chr_telnet_init(fd);
3326 break;
3329 socket_set_nonblock(fd);
3330 if (s->do_nodelay)
3331 socket_set_nodelay(fd);
3332 s->fd = fd;
3333 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3334 tcp_chr_connect(chr);
3337 static void tcp_chr_close(CharDriverState *chr)
3339 TCPCharDriver *s = chr->opaque;
3340 if (s->fd >= 0)
3341 closesocket(s->fd);
3342 if (s->listen_fd >= 0)
3343 closesocket(s->listen_fd);
3344 qemu_free(s);
3347 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3348 int is_telnet,
3349 int is_unix)
3351 CharDriverState *chr = NULL;
3352 TCPCharDriver *s = NULL;
3353 int fd = -1, ret, err, val;
3354 int is_listen = 0;
3355 int is_waitconnect = 1;
3356 int do_nodelay = 0;
3357 const char *ptr;
3358 struct sockaddr_in saddr;
3359 #ifndef _WIN32
3360 struct sockaddr_un uaddr;
3361 #endif
3362 struct sockaddr *addr;
3363 socklen_t addrlen;
3365 #ifndef _WIN32
3366 if (is_unix) {
3367 addr = (struct sockaddr *)&uaddr;
3368 addrlen = sizeof(uaddr);
3369 if (parse_unix_path(&uaddr, host_str) < 0)
3370 goto fail;
3371 } else
3372 #endif
3374 addr = (struct sockaddr *)&saddr;
3375 addrlen = sizeof(saddr);
3376 if (parse_host_port(&saddr, host_str) < 0)
3377 goto fail;
3380 ptr = host_str;
3381 while((ptr = strchr(ptr,','))) {
3382 ptr++;
3383 if (!strncmp(ptr,"server",6)) {
3384 is_listen = 1;
3385 } else if (!strncmp(ptr,"nowait",6)) {
3386 is_waitconnect = 0;
3387 } else if (!strncmp(ptr,"nodelay",6)) {
3388 do_nodelay = 1;
3389 } else {
3390 printf("Unknown option: %s\n", ptr);
3391 goto fail;
3394 if (!is_listen)
3395 is_waitconnect = 0;
3397 chr = qemu_mallocz(sizeof(CharDriverState));
3398 if (!chr)
3399 goto fail;
3400 s = qemu_mallocz(sizeof(TCPCharDriver));
3401 if (!s)
3402 goto fail;
3404 #ifndef _WIN32
3405 if (is_unix)
3406 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3407 else
3408 #endif
3409 fd = socket(PF_INET, SOCK_STREAM, 0);
3411 if (fd < 0)
3412 goto fail;
3414 if (!is_waitconnect)
3415 socket_set_nonblock(fd);
3417 s->connected = 0;
3418 s->fd = -1;
3419 s->listen_fd = -1;
3420 s->is_unix = is_unix;
3421 s->do_nodelay = do_nodelay && !is_unix;
3423 chr->opaque = s;
3424 chr->chr_write = tcp_chr_write;
3425 chr->chr_close = tcp_chr_close;
3427 if (is_listen) {
3428 /* allow fast reuse */
3429 #ifndef _WIN32
3430 if (is_unix) {
3431 char path[109];
3432 strncpy(path, uaddr.sun_path, 108);
3433 path[108] = 0;
3434 unlink(path);
3435 } else
3436 #endif
3438 val = 1;
3439 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3442 ret = bind(fd, addr, addrlen);
3443 if (ret < 0)
3444 goto fail;
3446 ret = listen(fd, 0);
3447 if (ret < 0)
3448 goto fail;
3450 s->listen_fd = fd;
3451 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3452 if (is_telnet)
3453 s->do_telnetopt = 1;
3454 } else {
3455 for(;;) {
3456 ret = connect(fd, addr, addrlen);
3457 if (ret < 0) {
3458 err = socket_error();
3459 if (err == EINTR || err == EWOULDBLOCK) {
3460 } else if (err == EINPROGRESS) {
3461 break;
3462 #ifdef _WIN32
3463 } else if (err == WSAEALREADY) {
3464 break;
3465 #endif
3466 } else {
3467 goto fail;
3469 } else {
3470 s->connected = 1;
3471 break;
3474 s->fd = fd;
3475 socket_set_nodelay(fd);
3476 if (s->connected)
3477 tcp_chr_connect(chr);
3478 else
3479 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3482 if (is_listen && is_waitconnect) {
3483 printf("QEMU waiting for connection on: %s\n", host_str);
3484 tcp_chr_accept(chr);
3485 socket_set_nonblock(s->listen_fd);
3488 return chr;
3489 fail:
3490 if (fd >= 0)
3491 closesocket(fd);
3492 qemu_free(s);
3493 qemu_free(chr);
3494 return NULL;
3497 CharDriverState *qemu_chr_open(const char *filename)
3499 const char *p;
3501 if (!strcmp(filename, "vc")) {
3502 return text_console_init(&display_state, 0);
3503 } else if (strstart(filename, "vc:", &p)) {
3504 return text_console_init(&display_state, p);
3505 } else if (!strcmp(filename, "null")) {
3506 return qemu_chr_open_null();
3507 } else
3508 if (strstart(filename, "tcp:", &p)) {
3509 return qemu_chr_open_tcp(p, 0, 0);
3510 } else
3511 if (strstart(filename, "telnet:", &p)) {
3512 return qemu_chr_open_tcp(p, 1, 0);
3513 } else
3514 if (strstart(filename, "udp:", &p)) {
3515 return qemu_chr_open_udp(p);
3516 } else
3517 if (strstart(filename, "mon:", &p)) {
3518 CharDriverState *drv = qemu_chr_open(p);
3519 if (drv) {
3520 drv = qemu_chr_open_mux(drv);
3521 monitor_init(drv, !nographic);
3522 return drv;
3524 printf("Unable to open driver: %s\n", p);
3525 return 0;
3526 } else
3527 #ifndef _WIN32
3528 if (strstart(filename, "unix:", &p)) {
3529 return qemu_chr_open_tcp(p, 0, 1);
3530 } else if (strstart(filename, "file:", &p)) {
3531 return qemu_chr_open_file_out(p);
3532 } else if (strstart(filename, "pipe:", &p)) {
3533 return qemu_chr_open_pipe(p);
3534 } else if (!strcmp(filename, "pty")) {
3535 return qemu_chr_open_pty();
3536 } else if (!strcmp(filename, "stdio")) {
3537 return qemu_chr_open_stdio();
3538 } else
3539 #if defined(__linux__)
3540 if (strstart(filename, "/dev/parport", NULL)) {
3541 return qemu_chr_open_pp(filename);
3542 } else
3543 #endif
3544 #if defined(__linux__) || defined(__sun__)
3545 if (strstart(filename, "/dev/", NULL)) {
3546 return qemu_chr_open_tty(filename);
3547 } else
3548 #endif
3549 #else /* !_WIN32 */
3550 if (strstart(filename, "COM", NULL)) {
3551 return qemu_chr_open_win(filename);
3552 } else
3553 if (strstart(filename, "pipe:", &p)) {
3554 return qemu_chr_open_win_pipe(p);
3555 } else
3556 if (strstart(filename, "con:", NULL)) {
3557 return qemu_chr_open_win_con(filename);
3558 } else
3559 if (strstart(filename, "file:", &p)) {
3560 return qemu_chr_open_win_file_out(p);
3561 } else
3562 #endif
3563 #ifdef CONFIG_BRLAPI
3564 if (!strcmp(filename, "braille")) {
3565 return chr_baum_init();
3566 } else
3567 #endif
3569 return NULL;
3573 void qemu_chr_close(CharDriverState *chr)
3575 if (chr->chr_close)
3576 chr->chr_close(chr);
3577 qemu_free(chr);
3580 /***********************************************************/
3581 /* network device redirectors */
3583 __attribute__ (( unused ))
3584 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3586 int len, i, j, c;
3588 for(i=0;i<size;i+=16) {
3589 len = size - i;
3590 if (len > 16)
3591 len = 16;
3592 fprintf(f, "%08x ", i);
3593 for(j=0;j<16;j++) {
3594 if (j < len)
3595 fprintf(f, " %02x", buf[i+j]);
3596 else
3597 fprintf(f, " ");
3599 fprintf(f, " ");
3600 for(j=0;j<len;j++) {
3601 c = buf[i+j];
3602 if (c < ' ' || c > '~')
3603 c = '.';
3604 fprintf(f, "%c", c);
3606 fprintf(f, "\n");
3610 static int parse_macaddr(uint8_t *macaddr, const char *p)
3612 int i;
3613 char *last_char;
3614 long int offset;
3616 errno = 0;
3617 offset = strtol(p, &last_char, 0);
3618 if (0 == errno && '\0' == *last_char &&
3619 offset >= 0 && offset <= 0xFFFFFF) {
3620 macaddr[3] = (offset & 0xFF0000) >> 16;
3621 macaddr[4] = (offset & 0xFF00) >> 8;
3622 macaddr[5] = offset & 0xFF;
3623 return 0;
3624 } else {
3625 for(i = 0; i < 6; i++) {
3626 macaddr[i] = strtol(p, (char **)&p, 16);
3627 if (i == 5) {
3628 if (*p != '\0')
3629 return -1;
3630 } else {
3631 if (*p != ':' && *p != '-')
3632 return -1;
3633 p++;
3636 return 0;
3639 return -1;
3642 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3644 const char *p, *p1;
3645 int len;
3646 p = *pp;
3647 p1 = strchr(p, sep);
3648 if (!p1)
3649 return -1;
3650 len = p1 - p;
3651 p1++;
3652 if (buf_size > 0) {
3653 if (len > buf_size - 1)
3654 len = buf_size - 1;
3655 memcpy(buf, p, len);
3656 buf[len] = '\0';
3658 *pp = p1;
3659 return 0;
3662 int parse_host_src_port(struct sockaddr_in *haddr,
3663 struct sockaddr_in *saddr,
3664 const char *input_str)
3666 char *str = strdup(input_str);
3667 char *host_str = str;
3668 char *src_str;
3669 char *ptr;
3672 * Chop off any extra arguments at the end of the string which
3673 * would start with a comma, then fill in the src port information
3674 * if it was provided else use the "any address" and "any port".
3676 if ((ptr = strchr(str,',')))
3677 *ptr = '\0';
3679 if ((src_str = strchr(input_str,'@'))) {
3680 *src_str = '\0';
3681 src_str++;
3684 if (parse_host_port(haddr, host_str) < 0)
3685 goto fail;
3687 if (!src_str || *src_str == '\0')
3688 src_str = ":0";
3690 if (parse_host_port(saddr, src_str) < 0)
3691 goto fail;
3693 free(str);
3694 return(0);
3696 fail:
3697 free(str);
3698 return -1;
3701 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3703 char buf[512];
3704 struct hostent *he;
3705 const char *p, *r;
3706 int port;
3708 p = str;
3709 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3710 return -1;
3711 saddr->sin_family = AF_INET;
3712 if (buf[0] == '\0') {
3713 saddr->sin_addr.s_addr = 0;
3714 } else {
3715 if (isdigit(buf[0])) {
3716 if (!inet_aton(buf, &saddr->sin_addr))
3717 return -1;
3718 } else {
3719 if ((he = gethostbyname(buf)) == NULL)
3720 return - 1;
3721 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3724 port = strtol(p, (char **)&r, 0);
3725 if (r == p)
3726 return -1;
3727 saddr->sin_port = htons(port);
3728 return 0;
3731 #ifndef _WIN32
3732 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3734 const char *p;
3735 int len;
3737 len = MIN(108, strlen(str));
3738 p = strchr(str, ',');
3739 if (p)
3740 len = MIN(len, p - str);
3742 memset(uaddr, 0, sizeof(*uaddr));
3744 uaddr->sun_family = AF_UNIX;
3745 memcpy(uaddr->sun_path, str, len);
3747 return 0;
3749 #endif
3751 /* find or alloc a new VLAN */
3752 VLANState *qemu_find_vlan(int id)
3754 VLANState **pvlan, *vlan;
3755 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3756 if (vlan->id == id)
3757 return vlan;
3759 vlan = qemu_mallocz(sizeof(VLANState));
3760 if (!vlan)
3761 return NULL;
3762 vlan->id = id;
3763 vlan->next = NULL;
3764 pvlan = &first_vlan;
3765 while (*pvlan != NULL)
3766 pvlan = &(*pvlan)->next;
3767 *pvlan = vlan;
3768 return vlan;
3771 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3772 IOReadHandler *fd_read,
3773 IOCanRWHandler *fd_can_read,
3774 void *opaque)
3776 VLANClientState *vc, **pvc;
3777 vc = qemu_mallocz(sizeof(VLANClientState));
3778 if (!vc)
3779 return NULL;
3780 vc->fd_read = fd_read;
3781 vc->fd_can_read = fd_can_read;
3782 vc->opaque = opaque;
3783 vc->vlan = vlan;
3785 vc->next = NULL;
3786 pvc = &vlan->first_client;
3787 while (*pvc != NULL)
3788 pvc = &(*pvc)->next;
3789 *pvc = vc;
3790 return vc;
3793 int qemu_can_send_packet(VLANClientState *vc1)
3795 VLANState *vlan = vc1->vlan;
3796 VLANClientState *vc;
3798 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3799 if (vc != vc1) {
3800 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3801 return 1;
3804 return 0;
3807 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3809 VLANState *vlan = vc1->vlan;
3810 VLANClientState *vc;
3811 int ret = -EAGAIN;
3813 #if 0
3814 printf("vlan %d send:\n", vlan->id);
3815 hex_dump(stdout, buf, size);
3816 #endif
3817 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3818 if (vc != vc1) {
3819 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
3820 vc->fd_read(vc->opaque, buf, size);
3821 ret = 0;
3826 return ret;
3829 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
3830 int iovcnt)
3832 char buffer[4096];
3833 size_t offset = 0;
3834 int i;
3836 for (i = 0; i < iovcnt; i++) {
3837 size_t len;
3839 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
3840 memcpy(buffer + offset, iov[i].iov_base, len);
3841 offset += len;
3844 vc->fd_read(vc->opaque, buffer, offset);
3846 return offset;
3849 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
3850 int iovcnt)
3852 VLANState *vlan = vc1->vlan;
3853 VLANClientState *vc;
3854 ssize_t max_len = 0;
3856 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
3857 ssize_t len = 0;
3859 if (vc == vc1)
3860 continue;
3862 if (vc->fd_readv)
3863 len = vc->fd_readv(vc->opaque, iov, iovcnt);
3864 else if (vc->fd_read)
3865 len = vc_sendv_compat(vc, iov, iovcnt);
3867 max_len = MAX(max_len, len);
3870 return max_len;
3873 #if defined(CONFIG_SLIRP)
3875 /* slirp network adapter */
3877 static int slirp_inited;
3878 static VLANClientState *slirp_vc;
3880 int slirp_can_output(void)
3882 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3885 void slirp_output(const uint8_t *pkt, int pkt_len)
3887 #if 0
3888 printf("slirp output:\n");
3889 hex_dump(stdout, pkt, pkt_len);
3890 #endif
3891 if (!slirp_vc)
3892 return;
3893 qemu_send_packet(slirp_vc, pkt, pkt_len);
3896 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3898 #if 0
3899 printf("slirp input:\n");
3900 hex_dump(stdout, buf, size);
3901 #endif
3902 slirp_input(buf, size);
3905 static int net_slirp_init(VLANState *vlan)
3907 if (!slirp_inited) {
3908 slirp_inited = 1;
3909 slirp_init();
3911 slirp_vc = qemu_new_vlan_client(vlan,
3912 slirp_receive, NULL, NULL);
3913 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3914 return 0;
3917 static void net_slirp_redir(const char *redir_str)
3919 int is_udp;
3920 char buf[256], *r;
3921 const char *p;
3922 struct in_addr guest_addr;
3923 int host_port, guest_port;
3925 if (!slirp_inited) {
3926 slirp_inited = 1;
3927 slirp_init();
3930 p = redir_str;
3931 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3932 goto fail;
3933 if (!strcmp(buf, "tcp")) {
3934 is_udp = 0;
3935 } else if (!strcmp(buf, "udp")) {
3936 is_udp = 1;
3937 } else {
3938 goto fail;
3941 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3942 goto fail;
3943 host_port = strtol(buf, &r, 0);
3944 if (r == buf)
3945 goto fail;
3947 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3948 goto fail;
3949 if (buf[0] == '\0') {
3950 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3952 if (!inet_aton(buf, &guest_addr))
3953 goto fail;
3955 guest_port = strtol(p, &r, 0);
3956 if (r == p)
3957 goto fail;
3959 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3960 fprintf(stderr, "qemu: could not set up redirection\n");
3961 exit(1);
3963 return;
3964 fail:
3965 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3966 exit(1);
3969 #ifndef _WIN32
3971 char smb_dir[1024];
3973 static void erase_dir(char *dir_name)
3975 DIR *d;
3976 struct dirent *de;
3977 char filename[1024];
3979 /* erase all the files in the directory */
3980 if ((d = opendir(dir_name)) != 0) {
3981 for(;;) {
3982 de = readdir(d);
3983 if (!de)
3984 break;
3985 if (strcmp(de->d_name, ".") != 0 &&
3986 strcmp(de->d_name, "..") != 0) {
3987 snprintf(filename, sizeof(filename), "%s/%s",
3988 smb_dir, de->d_name);
3989 if (unlink(filename) != 0) /* is it a directory? */
3990 erase_dir(filename);
3993 closedir(d);
3994 rmdir(dir_name);
3998 /* automatic user mode samba server configuration */
3999 static void smb_exit(void)
4001 erase_dir(smb_dir);
4004 /* automatic user mode samba server configuration */
4005 static void net_slirp_smb(const char *exported_dir)
4007 char smb_conf[1024];
4008 char smb_cmdline[1024];
4009 FILE *f;
4011 if (!slirp_inited) {
4012 slirp_inited = 1;
4013 slirp_init();
4016 /* XXX: better tmp dir construction */
4017 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4018 if (mkdir(smb_dir, 0700) < 0) {
4019 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4020 exit(1);
4022 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4024 f = fopen(smb_conf, "w");
4025 if (!f) {
4026 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4027 exit(1);
4029 fprintf(f,
4030 "[global]\n"
4031 "private dir=%s\n"
4032 "smb ports=0\n"
4033 "socket address=127.0.0.1\n"
4034 "pid directory=%s\n"
4035 "lock directory=%s\n"
4036 "log file=%s/log.smbd\n"
4037 "smb passwd file=%s/smbpasswd\n"
4038 "security = share\n"
4039 "[qemu]\n"
4040 "path=%s\n"
4041 "read only=no\n"
4042 "guest ok=yes\n",
4043 smb_dir,
4044 smb_dir,
4045 smb_dir,
4046 smb_dir,
4047 smb_dir,
4048 exported_dir
4050 fclose(f);
4051 atexit(smb_exit);
4053 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4054 SMBD_COMMAND, smb_conf);
4056 slirp_add_exec(0, smb_cmdline, 4, 139);
4059 #endif /* !defined(_WIN32) */
4060 void do_info_slirp(void)
4062 slirp_stats();
4065 #endif /* CONFIG_SLIRP */
4067 #if !defined(_WIN32)
4069 typedef struct TAPState {
4070 VLANClientState *vc;
4071 int fd;
4072 char down_script[1024];
4073 char buf[4096];
4074 int size;
4075 } TAPState;
4077 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4079 TAPState *s = opaque;
4080 int ret;
4081 for(;;) {
4082 ret = write(s->fd, buf, size);
4083 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4084 } else {
4085 break;
4090 static ssize_t tap_readv(void *opaque, const struct iovec *iov,
4091 int iovcnt)
4093 TAPState *s = opaque;
4094 ssize_t len;
4096 do {
4097 len = writev(s->fd, iov, iovcnt);
4098 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
4100 return len;
4103 static int tap_can_send(void *opaque)
4105 TAPState *s = opaque;
4106 VLANClientState *vc;
4107 int can_receive = 0;
4109 /* Check to see if any of our clients can receive a packet */
4110 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
4111 /* Skip ourselves */
4112 if (vc == s->vc)
4113 continue;
4115 if (!vc->fd_can_read) {
4116 /* no fd_can_read handler, they always can receive */
4117 can_receive = 1;
4118 } else
4119 can_receive = vc->fd_can_read(vc->opaque);
4121 /* Once someone can receive, we try to send a packet */
4122 if (can_receive)
4123 break;
4126 return can_receive;
4129 static void tap_send(void *opaque)
4131 TAPState *s = opaque;
4133 /* First try to send any buffered packet */
4134 if (s->size > 0) {
4135 int err;
4137 /* If noone can receive the packet, buffer it */
4138 err = qemu_send_packet(s->vc, s->buf, s->size);
4139 if (err == -EAGAIN)
4140 return;
4143 /* Read packets until we hit EAGAIN */
4144 do {
4145 #ifdef __sun__
4146 struct strbuf sbuf;
4147 int f = 0;
4148 sbuf.maxlen = sizeof(s->buf);
4149 sbuf.buf = s->buf;
4150 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4151 #else
4152 s->size = read(s->fd, s->buf, sizeof(s->buf));
4153 #endif
4155 if (s->size == -1 && errno == EINTR)
4156 continue;
4158 if (s->size > 0) {
4159 int err;
4161 /* If noone can receive the packet, buffer it */
4162 err = qemu_send_packet(s->vc, s->buf, s->size);
4163 if (err == -EAGAIN)
4164 break;
4166 } while (s->size > 0);
4169 /* fd support */
4171 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4173 TAPState *s;
4175 s = qemu_mallocz(sizeof(TAPState));
4176 if (!s)
4177 return NULL;
4178 s->fd = fd;
4179 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4180 s->vc->fd_readv = tap_readv;
4181 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
4182 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4183 return s;
4186 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4187 static int tap_open(char *ifname, int ifname_size)
4189 int fd;
4190 char *dev;
4191 struct stat s;
4193 TFR(fd = open("/dev/tap", O_RDWR));
4194 if (fd < 0) {
4195 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4196 return -1;
4199 fstat(fd, &s);
4200 dev = devname(s.st_rdev, S_IFCHR);
4201 pstrcpy(ifname, ifname_size, dev);
4203 fcntl(fd, F_SETFL, O_NONBLOCK);
4204 return fd;
4206 #elif defined(__sun__)
4207 #define TUNNEWPPA (('T'<<16) | 0x0001)
4209 * Allocate TAP device, returns opened fd.
4210 * Stores dev name in the first arg(must be large enough).
4212 int tap_alloc(char *dev)
4214 int tap_fd, if_fd, ppa = -1;
4215 static int ip_fd = 0;
4216 char *ptr;
4218 static int arp_fd = 0;
4219 int ip_muxid, arp_muxid;
4220 struct strioctl strioc_if, strioc_ppa;
4221 int link_type = I_PLINK;;
4222 struct lifreq ifr;
4223 char actual_name[32] = "";
4225 memset(&ifr, 0x0, sizeof(ifr));
4227 if( *dev ){
4228 ptr = dev;
4229 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4230 ppa = atoi(ptr);
4233 /* Check if IP device was opened */
4234 if( ip_fd )
4235 close(ip_fd);
4237 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4238 if (ip_fd < 0) {
4239 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4240 return -1;
4243 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4244 if (tap_fd < 0) {
4245 syslog(LOG_ERR, "Can't open /dev/tap");
4246 return -1;
4249 /* Assign a new PPA and get its unit number. */
4250 strioc_ppa.ic_cmd = TUNNEWPPA;
4251 strioc_ppa.ic_timout = 0;
4252 strioc_ppa.ic_len = sizeof(ppa);
4253 strioc_ppa.ic_dp = (char *)&ppa;
4254 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4255 syslog (LOG_ERR, "Can't assign new interface");
4257 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4258 if (if_fd < 0) {
4259 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4260 return -1;
4262 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4263 syslog(LOG_ERR, "Can't push IP module");
4264 return -1;
4267 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4268 syslog(LOG_ERR, "Can't get flags\n");
4270 snprintf (actual_name, 32, "tap%d", ppa);
4271 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4273 ifr.lifr_ppa = ppa;
4274 /* Assign ppa according to the unit number returned by tun device */
4276 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4277 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4278 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4279 syslog (LOG_ERR, "Can't get flags\n");
4280 /* Push arp module to if_fd */
4281 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4282 syslog (LOG_ERR, "Can't push ARP module (2)");
4284 /* Push arp module to ip_fd */
4285 if (ioctl (ip_fd, I_POP, NULL) < 0)
4286 syslog (LOG_ERR, "I_POP failed\n");
4287 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4288 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4289 /* Open arp_fd */
4290 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4291 if (arp_fd < 0)
4292 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4294 /* Set ifname to arp */
4295 strioc_if.ic_cmd = SIOCSLIFNAME;
4296 strioc_if.ic_timout = 0;
4297 strioc_if.ic_len = sizeof(ifr);
4298 strioc_if.ic_dp = (char *)&ifr;
4299 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4300 syslog (LOG_ERR, "Can't set ifname to arp\n");
4303 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4304 syslog(LOG_ERR, "Can't link TAP device to IP");
4305 return -1;
4308 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4309 syslog (LOG_ERR, "Can't link TAP device to ARP");
4311 close (if_fd);
4313 memset(&ifr, 0x0, sizeof(ifr));
4314 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4315 ifr.lifr_ip_muxid = ip_muxid;
4316 ifr.lifr_arp_muxid = arp_muxid;
4318 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4320 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4321 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4322 syslog (LOG_ERR, "Can't set multiplexor id");
4325 sprintf(dev, "tap%d", ppa);
4326 return tap_fd;
4329 static int tap_open(char *ifname, int ifname_size)
4331 char dev[10]="";
4332 int fd;
4333 if( (fd = tap_alloc(dev)) < 0 ){
4334 fprintf(stderr, "Cannot allocate TAP device\n");
4335 return -1;
4337 pstrcpy(ifname, ifname_size, dev);
4338 fcntl(fd, F_SETFL, O_NONBLOCK);
4339 return fd;
4341 #else
4342 static int tap_open(char *ifname, int ifname_size)
4344 struct ifreq ifr;
4345 int fd, ret;
4347 TFR(fd = open("/dev/net/tun", O_RDWR));
4348 if (fd < 0) {
4349 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4350 return -1;
4352 memset(&ifr, 0, sizeof(ifr));
4353 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4354 if (ifname[0] != '\0')
4355 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4356 else
4357 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4358 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4359 if (ret != 0) {
4360 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4361 close(fd);
4362 return -1;
4364 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4365 fcntl(fd, F_SETFL, O_NONBLOCK);
4366 return fd;
4368 #endif
4370 static int launch_script(const char *setup_script, const char *ifname, int fd)
4372 int pid, status;
4373 char *args[3];
4374 char **parg;
4376 /* try to launch network script */
4377 pid = fork();
4378 if (pid >= 0) {
4379 if (pid == 0) {
4380 int open_max = sysconf (_SC_OPEN_MAX), i;
4381 for (i = 0; i < open_max; i++)
4382 if (i != STDIN_FILENO &&
4383 i != STDOUT_FILENO &&
4384 i != STDERR_FILENO &&
4385 i != fd)
4386 close(i);
4388 parg = args;
4389 *parg++ = (char *)setup_script;
4390 *parg++ = (char *)ifname;
4391 *parg++ = NULL;
4392 execv(setup_script, args);
4393 _exit(1);
4395 while (waitpid(pid, &status, 0) != pid);
4396 if (!WIFEXITED(status) ||
4397 WEXITSTATUS(status) != 0) {
4398 fprintf(stderr, "%s: could not launch network script\n",
4399 setup_script);
4400 return -1;
4403 return 0;
4406 static int net_tap_init(VLANState *vlan, const char *ifname1,
4407 const char *setup_script, const char *down_script)
4409 TAPState *s;
4410 int fd;
4411 char ifname[128];
4413 if (ifname1 != NULL)
4414 pstrcpy(ifname, sizeof(ifname), ifname1);
4415 else
4416 ifname[0] = '\0';
4417 TFR(fd = tap_open(ifname, sizeof(ifname)));
4418 if (fd < 0)
4419 return -1;
4421 if (!setup_script || !strcmp(setup_script, "no"))
4422 setup_script = "";
4423 if (setup_script[0] != '\0') {
4424 if (launch_script(setup_script, ifname, fd))
4425 return -1;
4427 s = net_tap_fd_init(vlan, fd);
4428 if (!s)
4429 return -1;
4430 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4431 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4432 if (down_script && strcmp(down_script, "no"))
4433 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4434 return 0;
4437 #endif /* !_WIN32 */
4439 /* network connection */
4440 typedef struct NetSocketState {
4441 VLANClientState *vc;
4442 int fd;
4443 int state; /* 0 = getting length, 1 = getting data */
4444 int index;
4445 int packet_len;
4446 uint8_t buf[4096];
4447 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4448 } NetSocketState;
4450 typedef struct NetSocketListenState {
4451 VLANState *vlan;
4452 int fd;
4453 } NetSocketListenState;
4455 /* XXX: we consider we can send the whole packet without blocking */
4456 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4458 NetSocketState *s = opaque;
4459 uint32_t len;
4460 len = htonl(size);
4462 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4463 send_all(s->fd, buf, size);
4466 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4468 NetSocketState *s = opaque;
4469 sendto(s->fd, buf, size, 0,
4470 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4473 static void net_socket_send(void *opaque)
4475 NetSocketState *s = opaque;
4476 int l, size, err;
4477 uint8_t buf1[4096];
4478 const uint8_t *buf;
4480 size = recv(s->fd, buf1, sizeof(buf1), 0);
4481 if (size < 0) {
4482 err = socket_error();
4483 if (err != EWOULDBLOCK)
4484 goto eoc;
4485 } else if (size == 0) {
4486 /* end of connection */
4487 eoc:
4488 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4489 closesocket(s->fd);
4490 return;
4492 buf = buf1;
4493 while (size > 0) {
4494 /* reassemble a packet from the network */
4495 switch(s->state) {
4496 case 0:
4497 l = 4 - s->index;
4498 if (l > size)
4499 l = size;
4500 memcpy(s->buf + s->index, buf, l);
4501 buf += l;
4502 size -= l;
4503 s->index += l;
4504 if (s->index == 4) {
4505 /* got length */
4506 s->packet_len = ntohl(*(uint32_t *)s->buf);
4507 s->index = 0;
4508 s->state = 1;
4510 break;
4511 case 1:
4512 l = s->packet_len - s->index;
4513 if (l > size)
4514 l = size;
4515 memcpy(s->buf + s->index, buf, l);
4516 s->index += l;
4517 buf += l;
4518 size -= l;
4519 if (s->index >= s->packet_len) {
4520 qemu_send_packet(s->vc, s->buf, s->packet_len);
4521 s->index = 0;
4522 s->state = 0;
4524 break;
4529 static void net_socket_send_dgram(void *opaque)
4531 NetSocketState *s = opaque;
4532 int size;
4534 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4535 if (size < 0)
4536 return;
4537 if (size == 0) {
4538 /* end of connection */
4539 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4540 return;
4542 qemu_send_packet(s->vc, s->buf, size);
4545 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4547 struct ip_mreq imr;
4548 int fd;
4549 int val, ret;
4550 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4551 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4552 inet_ntoa(mcastaddr->sin_addr),
4553 (int)ntohl(mcastaddr->sin_addr.s_addr));
4554 return -1;
4557 fd = socket(PF_INET, SOCK_DGRAM, 0);
4558 if (fd < 0) {
4559 perror("socket(PF_INET, SOCK_DGRAM)");
4560 return -1;
4563 val = 1;
4564 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4565 (const char *)&val, sizeof(val));
4566 if (ret < 0) {
4567 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4568 goto fail;
4571 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4572 if (ret < 0) {
4573 perror("bind");
4574 goto fail;
4577 /* Add host to multicast group */
4578 imr.imr_multiaddr = mcastaddr->sin_addr;
4579 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4581 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4582 (const char *)&imr, sizeof(struct ip_mreq));
4583 if (ret < 0) {
4584 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4585 goto fail;
4588 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4589 val = 1;
4590 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4591 (const char *)&val, sizeof(val));
4592 if (ret < 0) {
4593 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4594 goto fail;
4597 socket_set_nonblock(fd);
4598 return fd;
4599 fail:
4600 if (fd >= 0)
4601 closesocket(fd);
4602 return -1;
4605 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4606 int is_connected)
4608 struct sockaddr_in saddr;
4609 int newfd;
4610 socklen_t saddr_len;
4611 NetSocketState *s;
4613 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4614 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4615 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4618 if (is_connected) {
4619 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4620 /* must be bound */
4621 if (saddr.sin_addr.s_addr==0) {
4622 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4623 fd);
4624 return NULL;
4626 /* clone dgram socket */
4627 newfd = net_socket_mcast_create(&saddr);
4628 if (newfd < 0) {
4629 /* error already reported by net_socket_mcast_create() */
4630 close(fd);
4631 return NULL;
4633 /* clone newfd to fd, close newfd */
4634 dup2(newfd, fd);
4635 close(newfd);
4637 } else {
4638 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4639 fd, strerror(errno));
4640 return NULL;
4644 s = qemu_mallocz(sizeof(NetSocketState));
4645 if (!s)
4646 return NULL;
4647 s->fd = fd;
4649 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4650 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4652 /* mcast: save bound address as dst */
4653 if (is_connected) s->dgram_dst=saddr;
4655 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4656 "socket: fd=%d (%s mcast=%s:%d)",
4657 fd, is_connected? "cloned" : "",
4658 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4659 return s;
4662 static void net_socket_connect(void *opaque)
4664 NetSocketState *s = opaque;
4665 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4668 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4669 int is_connected)
4671 NetSocketState *s;
4672 s = qemu_mallocz(sizeof(NetSocketState));
4673 if (!s)
4674 return NULL;
4675 s->fd = fd;
4676 s->vc = qemu_new_vlan_client(vlan,
4677 net_socket_receive, NULL, s);
4678 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4679 "socket: fd=%d", fd);
4680 if (is_connected) {
4681 net_socket_connect(s);
4682 } else {
4683 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4685 return s;
4688 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4689 int is_connected)
4691 int so_type=-1, optlen=sizeof(so_type);
4693 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4694 (socklen_t *)&optlen)< 0) {
4695 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4696 return NULL;
4698 switch(so_type) {
4699 case SOCK_DGRAM:
4700 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4701 case SOCK_STREAM:
4702 return net_socket_fd_init_stream(vlan, fd, is_connected);
4703 default:
4704 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4705 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4706 return net_socket_fd_init_stream(vlan, fd, is_connected);
4708 return NULL;
4711 static void net_socket_accept(void *opaque)
4713 NetSocketListenState *s = opaque;
4714 NetSocketState *s1;
4715 struct sockaddr_in saddr;
4716 socklen_t len;
4717 int fd;
4719 for(;;) {
4720 len = sizeof(saddr);
4721 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4722 if (fd < 0 && errno != EINTR) {
4723 return;
4724 } else if (fd >= 0) {
4725 break;
4728 s1 = net_socket_fd_init(s->vlan, fd, 1);
4729 if (!s1) {
4730 closesocket(fd);
4731 } else {
4732 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4733 "socket: connection from %s:%d",
4734 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4738 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4740 NetSocketListenState *s;
4741 int fd, val, ret;
4742 struct sockaddr_in saddr;
4744 if (parse_host_port(&saddr, host_str) < 0)
4745 return -1;
4747 s = qemu_mallocz(sizeof(NetSocketListenState));
4748 if (!s)
4749 return -1;
4751 fd = socket(PF_INET, SOCK_STREAM, 0);
4752 if (fd < 0) {
4753 perror("socket");
4754 return -1;
4756 socket_set_nonblock(fd);
4758 /* allow fast reuse */
4759 val = 1;
4760 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4762 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4763 if (ret < 0) {
4764 perror("bind");
4765 return -1;
4767 ret = listen(fd, 0);
4768 if (ret < 0) {
4769 perror("listen");
4770 return -1;
4772 s->vlan = vlan;
4773 s->fd = fd;
4774 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4775 return 0;
4778 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4780 NetSocketState *s;
4781 int fd, connected, ret, err;
4782 struct sockaddr_in saddr;
4784 if (parse_host_port(&saddr, host_str) < 0)
4785 return -1;
4787 fd = socket(PF_INET, SOCK_STREAM, 0);
4788 if (fd < 0) {
4789 perror("socket");
4790 return -1;
4792 socket_set_nonblock(fd);
4794 connected = 0;
4795 for(;;) {
4796 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4797 if (ret < 0) {
4798 err = socket_error();
4799 if (err == EINTR || err == EWOULDBLOCK) {
4800 } else if (err == EINPROGRESS) {
4801 break;
4802 #ifdef _WIN32
4803 } else if (err == WSAEALREADY) {
4804 break;
4805 #endif
4806 } else {
4807 perror("connect");
4808 closesocket(fd);
4809 return -1;
4811 } else {
4812 connected = 1;
4813 break;
4816 s = net_socket_fd_init(vlan, fd, connected);
4817 if (!s)
4818 return -1;
4819 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4820 "socket: connect to %s:%d",
4821 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4822 return 0;
4825 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4827 NetSocketState *s;
4828 int fd;
4829 struct sockaddr_in saddr;
4831 if (parse_host_port(&saddr, host_str) < 0)
4832 return -1;
4835 fd = net_socket_mcast_create(&saddr);
4836 if (fd < 0)
4837 return -1;
4839 s = net_socket_fd_init(vlan, fd, 0);
4840 if (!s)
4841 return -1;
4843 s->dgram_dst = saddr;
4845 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4846 "socket: mcast=%s:%d",
4847 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4848 return 0;
4852 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4854 char *q;
4856 q = buf;
4857 while (*p != '\0' && *p != '=') {
4858 if (q && (q - buf) < buf_size - 1)
4859 *q++ = *p;
4860 p++;
4862 if (q)
4863 *q = '\0';
4865 return p;
4868 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4870 char *q;
4872 q = buf;
4873 while (*p != '\0') {
4874 if (*p == ',') {
4875 if (*(p + 1) != ',')
4876 break;
4877 p++;
4879 if (q && (q - buf) < buf_size - 1)
4880 *q++ = *p;
4881 p++;
4883 if (q)
4884 *q = '\0';
4886 return p;
4889 int get_param_value(char *buf, int buf_size,
4890 const char *tag, const char *str)
4892 const char *p;
4893 char option[128];
4895 p = str;
4896 for(;;) {
4897 p = get_opt_name(option, sizeof(option), p);
4898 if (*p != '=')
4899 break;
4900 p++;
4901 if (!strcmp(tag, option)) {
4902 (void)get_opt_value(buf, buf_size, p);
4903 return strlen(buf);
4904 } else {
4905 p = get_opt_value(NULL, 0, p);
4907 if (*p != ',')
4908 break;
4909 p++;
4911 return 0;
4914 int check_params(char *buf, int buf_size,
4915 char **params, const char *str)
4917 const char *p;
4918 int i;
4920 p = str;
4921 for(;;) {
4922 p = get_opt_name(buf, buf_size, p);
4923 if (*p != '=')
4924 return -1;
4925 p++;
4926 for(i = 0; params[i] != NULL; i++)
4927 if (!strcmp(params[i], buf))
4928 break;
4929 if (params[i] == NULL)
4930 return -1;
4931 p = get_opt_value(NULL, 0, p);
4932 if (*p != ',')
4933 break;
4934 p++;
4936 return 0;
4939 static int nic_get_free_idx(void)
4941 int index;
4943 for (index = 0; index < MAX_NICS; index++)
4944 if (!nd_table[index].used)
4945 return index;
4946 return -1;
4949 int net_client_init(const char *str)
4951 const char *p;
4952 char *q;
4953 char device[64];
4954 char buf[1024];
4955 int vlan_id, ret;
4956 VLANState *vlan;
4958 p = str;
4959 q = device;
4960 while (*p != '\0' && *p != ',') {
4961 if ((q - device) < sizeof(device) - 1)
4962 *q++ = *p;
4963 p++;
4965 *q = '\0';
4966 if (*p == ',')
4967 p++;
4968 vlan_id = 0;
4969 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4970 vlan_id = strtol(buf, NULL, 0);
4972 vlan = qemu_find_vlan(vlan_id);
4973 if (!vlan) {
4974 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4975 return -1;
4977 if (!strcmp(device, "nic")) {
4978 NICInfo *nd;
4979 uint8_t *macaddr;
4980 int idx = nic_get_free_idx();
4982 if (idx == -1 || nb_nics >= MAX_NICS) {
4983 fprintf(stderr, "Too Many NICs\n");
4984 return -1;
4986 nd = &nd_table[idx];
4987 macaddr = nd->macaddr;
4988 macaddr[0] = 0x52;
4989 macaddr[1] = 0x54;
4990 macaddr[2] = 0x00;
4991 macaddr[3] = 0x12;
4992 macaddr[4] = 0x34;
4993 macaddr[5] = 0x56 + idx;
4995 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4996 if (parse_macaddr(macaddr, buf) < 0) {
4997 fprintf(stderr, "invalid syntax for ethernet address\n");
4998 return -1;
5001 if (get_param_value(buf, sizeof(buf), "model", p)) {
5002 nd->model = strdup(buf);
5004 nd->vlan = vlan;
5005 nd->used = 1;
5006 nb_nics++;
5007 vlan->nb_guest_devs++;
5008 ret = idx;
5009 } else
5010 if (!strcmp(device, "none")) {
5011 /* does nothing. It is needed to signal that no network cards
5012 are wanted */
5013 ret = 0;
5014 } else
5015 #ifdef CONFIG_SLIRP
5016 if (!strcmp(device, "user")) {
5017 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5018 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5020 vlan->nb_host_devs++;
5021 ret = net_slirp_init(vlan);
5022 } else
5023 #endif
5024 #ifdef _WIN32
5025 if (!strcmp(device, "tap")) {
5026 char ifname[64];
5027 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5028 fprintf(stderr, "tap: no interface name\n");
5029 return -1;
5031 vlan->nb_host_devs++;
5032 ret = tap_win32_init(vlan, ifname);
5033 } else
5034 #else
5035 if (!strcmp(device, "tap")) {
5036 char ifname[64];
5037 char setup_script[1024], down_script[1024];
5038 int fd;
5039 vlan->nb_host_devs++;
5040 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5041 fd = strtol(buf, NULL, 0);
5042 fcntl(fd, F_SETFL, O_NONBLOCK);
5043 ret = -1;
5044 if (net_tap_fd_init(vlan, fd))
5045 ret = 0;
5046 } else {
5047 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5048 ifname[0] = '\0';
5050 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5051 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5053 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5054 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5056 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5058 } else
5059 #endif
5060 if (!strcmp(device, "socket")) {
5061 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5062 int fd;
5063 fd = strtol(buf, NULL, 0);
5064 ret = -1;
5065 if (net_socket_fd_init(vlan, fd, 1))
5066 ret = 0;
5067 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5068 ret = net_socket_listen_init(vlan, buf);
5069 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5070 ret = net_socket_connect_init(vlan, buf);
5071 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5072 ret = net_socket_mcast_init(vlan, buf);
5073 } else {
5074 fprintf(stderr, "Unknown socket options: %s\n", p);
5075 return -1;
5077 vlan->nb_host_devs++;
5078 } else
5080 fprintf(stderr, "Unknown network device: %s\n", device);
5081 return -1;
5083 if (ret < 0) {
5084 fprintf(stderr, "Could not initialize device '%s'\n", device);
5087 return ret;
5090 void net_client_uninit(NICInfo *nd)
5092 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
5093 nb_nics--;
5094 nd->used = 0;
5095 free((void *)nd->model);
5098 void do_info_network(void)
5100 VLANState *vlan;
5101 VLANClientState *vc;
5103 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5104 term_printf("VLAN %d devices:\n", vlan->id);
5105 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5106 term_printf(" %s\n", vc->info_str);
5110 #define HD_ALIAS "index=%d,media=disk"
5111 #ifdef TARGET_PPC
5112 #define CDROM_ALIAS "index=1,media=cdrom"
5113 #else
5114 #define CDROM_ALIAS "index=2,media=cdrom"
5115 #endif
5116 #define FD_ALIAS "index=%d,if=floppy"
5117 #define PFLASH_ALIAS "if=pflash"
5118 #define MTD_ALIAS "if=mtd"
5119 #define SD_ALIAS "index=0,if=sd"
5121 static int drive_opt_get_free_idx(void)
5123 int index;
5125 for (index = 0; index < MAX_DRIVES; index++)
5126 if (!drives_opt[index].used) {
5127 drives_opt[index].used = 1;
5128 return index;
5131 return -1;
5134 static int drive_get_free_idx(void)
5136 int index;
5138 for (index = 0; index < MAX_DRIVES; index++)
5139 if (!drives_table[index].used) {
5140 drives_table[index].used = 1;
5141 return index;
5144 return -1;
5147 int drive_add(const char *file, const char *fmt, ...)
5149 va_list ap;
5150 int index = drive_opt_get_free_idx();
5152 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5153 fprintf(stderr, "qemu: too many drives\n");
5154 return -1;
5157 drives_opt[index].file = file;
5158 va_start(ap, fmt);
5159 vsnprintf(drives_opt[index].opt,
5160 sizeof(drives_opt[0].opt), fmt, ap);
5161 va_end(ap);
5163 nb_drives_opt++;
5164 return index;
5167 void drive_remove(int index)
5169 drives_opt[index].used = 0;
5170 nb_drives_opt--;
5173 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5175 int index;
5177 /* seek interface, bus and unit */
5179 for (index = 0; index < MAX_DRIVES; index++)
5180 if (drives_table[index].type == type &&
5181 drives_table[index].bus == bus &&
5182 drives_table[index].unit == unit &&
5183 drives_table[index].used)
5184 return index;
5186 return -1;
5189 int drive_get_max_bus(BlockInterfaceType type)
5191 int max_bus;
5192 int index;
5194 max_bus = -1;
5195 for (index = 0; index < nb_drives; index++) {
5196 if(drives_table[index].type == type &&
5197 drives_table[index].bus > max_bus)
5198 max_bus = drives_table[index].bus;
5200 return max_bus;
5203 static void bdrv_format_print(void *opaque, const char *name)
5205 fprintf(stderr, " %s", name);
5208 void drive_uninit(BlockDriverState *bdrv)
5210 int i;
5212 for (i = 0; i < MAX_DRIVES; i++)
5213 if (drives_table[i].bdrv == bdrv) {
5214 drives_table[i].bdrv = NULL;
5215 drives_table[i].used = 0;
5216 drive_remove(drives_table[i].drive_opt_idx);
5217 nb_drives--;
5218 break;
5222 int drive_init(struct drive_opt *arg, int snapshot,
5223 QEMUMachine *machine)
5225 char buf[128];
5226 char file[1024];
5227 char devname[128];
5228 const char *mediastr = "";
5229 BlockInterfaceType type;
5230 enum { MEDIA_DISK, MEDIA_CDROM } media;
5231 int bus_id, unit_id;
5232 int cyls, heads, secs, translation;
5233 BlockDriverState *bdrv;
5234 BlockDriver *drv = NULL;
5235 int max_devs;
5236 int index;
5237 int cache;
5238 int bdrv_flags;
5239 int drives_table_idx;
5240 char *str = arg->opt;
5241 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5242 "secs", "trans", "media", "snapshot", "file",
5243 "cache", "format", "boot", NULL };
5245 if (check_params(buf, sizeof(buf), params, str) < 0) {
5246 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5247 buf, str);
5248 return -1;
5251 file[0] = 0;
5252 cyls = heads = secs = 0;
5253 bus_id = 0;
5254 unit_id = -1;
5255 translation = BIOS_ATA_TRANSLATION_AUTO;
5256 index = -1;
5257 cache = 1;
5259 if (!strcmp(machine->name, "realview") ||
5260 !strcmp(machine->name, "SS-5") ||
5261 !strcmp(machine->name, "SS-10") ||
5262 !strcmp(machine->name, "SS-600MP") ||
5263 !strcmp(machine->name, "versatilepb") ||
5264 !strcmp(machine->name, "versatileab")) {
5265 type = IF_SCSI;
5266 max_devs = MAX_SCSI_DEVS;
5267 strcpy(devname, "scsi");
5268 } else {
5269 type = IF_IDE;
5270 max_devs = MAX_IDE_DEVS;
5271 strcpy(devname, "ide");
5273 media = MEDIA_DISK;
5275 /* extract parameters */
5277 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5278 bus_id = strtol(buf, NULL, 0);
5279 if (bus_id < 0) {
5280 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5281 return -1;
5285 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5286 unit_id = strtol(buf, NULL, 0);
5287 if (unit_id < 0) {
5288 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5289 return -1;
5293 if (get_param_value(buf, sizeof(buf), "if", str)) {
5294 strncpy(devname, buf, sizeof(devname));
5295 if (!strcmp(buf, "ide")) {
5296 type = IF_IDE;
5297 max_devs = MAX_IDE_DEVS;
5298 } else if (!strcmp(buf, "scsi")) {
5299 type = IF_SCSI;
5300 max_devs = MAX_SCSI_DEVS;
5301 } else if (!strcmp(buf, "floppy")) {
5302 type = IF_FLOPPY;
5303 max_devs = 0;
5304 } else if (!strcmp(buf, "pflash")) {
5305 type = IF_PFLASH;
5306 max_devs = 0;
5307 } else if (!strcmp(buf, "mtd")) {
5308 type = IF_MTD;
5309 max_devs = 0;
5310 } else if (!strcmp(buf, "sd")) {
5311 type = IF_SD;
5312 max_devs = 0;
5313 } else if (!strcmp(buf, "virtio")) {
5314 type = IF_VIRTIO;
5315 max_devs = 0;
5316 } else {
5317 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5318 return -1;
5322 if (get_param_value(buf, sizeof(buf), "index", str)) {
5323 index = strtol(buf, NULL, 0);
5324 if (index < 0) {
5325 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5326 return -1;
5330 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5331 cyls = strtol(buf, NULL, 0);
5334 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5335 heads = strtol(buf, NULL, 0);
5338 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5339 secs = strtol(buf, NULL, 0);
5342 if (cyls || heads || secs) {
5343 if (cyls < 1 || cyls > 16383) {
5344 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5345 return -1;
5347 if (heads < 1 || heads > 16) {
5348 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5349 return -1;
5351 if (secs < 1 || secs > 63) {
5352 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5353 return -1;
5357 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5358 if (!cyls) {
5359 fprintf(stderr,
5360 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5361 str);
5362 return -1;
5364 if (!strcmp(buf, "none"))
5365 translation = BIOS_ATA_TRANSLATION_NONE;
5366 else if (!strcmp(buf, "lba"))
5367 translation = BIOS_ATA_TRANSLATION_LBA;
5368 else if (!strcmp(buf, "auto"))
5369 translation = BIOS_ATA_TRANSLATION_AUTO;
5370 else {
5371 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5372 return -1;
5376 if (get_param_value(buf, sizeof(buf), "media", str)) {
5377 if (!strcmp(buf, "disk")) {
5378 media = MEDIA_DISK;
5379 } else if (!strcmp(buf, "cdrom")) {
5380 if (cyls || secs || heads) {
5381 fprintf(stderr,
5382 "qemu: '%s' invalid physical CHS format\n", str);
5383 return -1;
5385 media = MEDIA_CDROM;
5386 } else {
5387 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5388 return -1;
5392 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5393 if (!strcmp(buf, "on"))
5394 snapshot = 1;
5395 else if (!strcmp(buf, "off"))
5396 snapshot = 0;
5397 else {
5398 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5399 return -1;
5403 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5404 if (!strcmp(buf, "off"))
5405 cache = 0;
5406 else if (!strcmp(buf, "on"))
5407 cache = 1;
5408 else {
5409 fprintf(stderr, "qemu: invalid cache option\n");
5410 return -1;
5414 if (get_param_value(buf, sizeof(buf), "format", str)) {
5415 if (strcmp(buf, "?") == 0) {
5416 fprintf(stderr, "qemu: Supported formats:");
5417 bdrv_iterate_format(bdrv_format_print, NULL);
5418 fprintf(stderr, "\n");
5419 return -1;
5421 drv = bdrv_find_format(buf);
5422 if (!drv) {
5423 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5424 return -1;
5428 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5429 if (!strcmp(buf, "on")) {
5430 if (extboot_drive != -1) {
5431 fprintf(stderr, "qemu: two bootable drives specified\n");
5432 return -1;
5434 extboot_drive = nb_drives;
5435 } else if (strcmp(buf, "off")) {
5436 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5437 return -1;
5441 if (arg->file == NULL)
5442 get_param_value(file, sizeof(file), "file", str);
5443 else
5444 pstrcpy(file, sizeof(file), arg->file);
5446 /* compute bus and unit according index */
5448 if (index != -1) {
5449 if (bus_id != 0 || unit_id != -1) {
5450 fprintf(stderr,
5451 "qemu: '%s' index cannot be used with bus and unit\n", str);
5452 return -1;
5454 if (max_devs == 0)
5456 unit_id = index;
5457 bus_id = 0;
5458 } else {
5459 unit_id = index % max_devs;
5460 bus_id = index / max_devs;
5464 /* if user doesn't specify a unit_id,
5465 * try to find the first free
5468 if (unit_id == -1) {
5469 unit_id = 0;
5470 while (drive_get_index(type, bus_id, unit_id) != -1) {
5471 unit_id++;
5472 if (max_devs && unit_id >= max_devs) {
5473 unit_id -= max_devs;
5474 bus_id++;
5479 /* check unit id */
5481 if (max_devs && unit_id >= max_devs) {
5482 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5483 str, unit_id, max_devs - 1);
5484 return -1;
5488 * ignore multiple definitions
5491 if (drive_get_index(type, bus_id, unit_id) != -1)
5492 return -2;
5494 /* init */
5496 if (type == IF_IDE || type == IF_SCSI)
5497 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5498 if (max_devs)
5499 snprintf(buf, sizeof(buf), "%s%i%s%i",
5500 devname, bus_id, mediastr, unit_id);
5501 else
5502 snprintf(buf, sizeof(buf), "%s%s%i",
5503 devname, mediastr, unit_id);
5504 bdrv = bdrv_new(buf);
5505 drives_table_idx = drive_get_free_idx();
5506 drives_table[drives_table_idx].bdrv = bdrv;
5507 drives_table[drives_table_idx].type = type;
5508 drives_table[drives_table_idx].bus = bus_id;
5509 drives_table[drives_table_idx].unit = unit_id;
5510 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
5511 nb_drives++;
5513 switch(type) {
5514 case IF_IDE:
5515 case IF_SCSI:
5516 switch(media) {
5517 case MEDIA_DISK:
5518 if (cyls != 0) {
5519 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5520 bdrv_set_translation_hint(bdrv, translation);
5522 break;
5523 case MEDIA_CDROM:
5524 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5525 break;
5527 break;
5528 case IF_SD:
5529 /* FIXME: This isn't really a floppy, but it's a reasonable
5530 approximation. */
5531 case IF_FLOPPY:
5532 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5533 break;
5534 case IF_PFLASH:
5535 case IF_MTD:
5536 case IF_VIRTIO:
5537 break;
5539 if (!file[0])
5540 return -2;
5541 bdrv_flags = 0;
5542 if (snapshot)
5543 bdrv_flags |= BDRV_O_SNAPSHOT;
5544 if (!cache)
5545 bdrv_flags |= BDRV_O_DIRECT;
5546 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5547 fprintf(stderr, "qemu: could not open disk image %s\n",
5548 file);
5549 return -1;
5551 return drives_table_idx;
5554 /***********************************************************/
5555 /* USB devices */
5557 static USBPort *used_usb_ports;
5558 static USBPort *free_usb_ports;
5560 /* ??? Maybe change this to register a hub to keep track of the topology. */
5561 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5562 usb_attachfn attach)
5564 port->opaque = opaque;
5565 port->index = index;
5566 port->attach = attach;
5567 port->next = free_usb_ports;
5568 free_usb_ports = port;
5571 static int usb_device_add(const char *devname)
5573 const char *p;
5574 USBDevice *dev;
5575 USBPort *port;
5577 if (!free_usb_ports)
5578 return -1;
5580 if (strstart(devname, "host:", &p)) {
5581 dev = usb_host_device_open(p);
5582 } else if (!strcmp(devname, "mouse")) {
5583 dev = usb_mouse_init();
5584 } else if (!strcmp(devname, "tablet")) {
5585 dev = usb_tablet_init();
5586 } else if (!strcmp(devname, "keyboard")) {
5587 dev = usb_keyboard_init();
5588 } else if (strstart(devname, "disk:", &p)) {
5589 dev = usb_msd_init(p);
5590 } else if (!strcmp(devname, "wacom-tablet")) {
5591 dev = usb_wacom_init();
5592 } else if (strstart(devname, "serial:", &p)) {
5593 dev = usb_serial_init(p);
5594 #ifdef CONFIG_BRLAPI
5595 } else if (!strcmp(devname, "braille")) {
5596 dev = usb_baum_init();
5597 #endif
5598 } else {
5599 return -1;
5601 if (!dev)
5602 return -1;
5604 /* Find a USB port to add the device to. */
5605 port = free_usb_ports;
5606 if (!port->next) {
5607 USBDevice *hub;
5609 /* Create a new hub and chain it on. */
5610 free_usb_ports = NULL;
5611 port->next = used_usb_ports;
5612 used_usb_ports = port;
5614 hub = usb_hub_init(VM_USB_HUB_SIZE);
5615 usb_attach(port, hub);
5616 port = free_usb_ports;
5619 free_usb_ports = port->next;
5620 port->next = used_usb_ports;
5621 used_usb_ports = port;
5622 usb_attach(port, dev);
5623 return 0;
5626 static int usb_device_del(const char *devname)
5628 USBPort *port;
5629 USBPort **lastp;
5630 USBDevice *dev;
5631 int bus_num, addr;
5632 const char *p;
5634 if (!used_usb_ports)
5635 return -1;
5637 p = strchr(devname, '.');
5638 if (!p)
5639 return -1;
5640 bus_num = strtoul(devname, NULL, 0);
5641 addr = strtoul(p + 1, NULL, 0);
5642 if (bus_num != 0)
5643 return -1;
5645 lastp = &used_usb_ports;
5646 port = used_usb_ports;
5647 while (port && port->dev->addr != addr) {
5648 lastp = &port->next;
5649 port = port->next;
5652 if (!port)
5653 return -1;
5655 dev = port->dev;
5656 *lastp = port->next;
5657 usb_attach(port, NULL);
5658 dev->handle_destroy(dev);
5659 port->next = free_usb_ports;
5660 free_usb_ports = port;
5661 return 0;
5664 void do_usb_add(const char *devname)
5666 int ret;
5667 ret = usb_device_add(devname);
5668 if (ret < 0)
5669 term_printf("Could not add USB device '%s'\n", devname);
5672 void do_usb_del(const char *devname)
5674 int ret;
5675 ret = usb_device_del(devname);
5676 if (ret < 0)
5677 term_printf("Could not remove USB device '%s'\n", devname);
5680 void usb_info(void)
5682 USBDevice *dev;
5683 USBPort *port;
5684 const char *speed_str;
5686 if (!usb_enabled) {
5687 term_printf("USB support not enabled\n");
5688 return;
5691 for (port = used_usb_ports; port; port = port->next) {
5692 dev = port->dev;
5693 if (!dev)
5694 continue;
5695 switch(dev->speed) {
5696 case USB_SPEED_LOW:
5697 speed_str = "1.5";
5698 break;
5699 case USB_SPEED_FULL:
5700 speed_str = "12";
5701 break;
5702 case USB_SPEED_HIGH:
5703 speed_str = "480";
5704 break;
5705 default:
5706 speed_str = "?";
5707 break;
5709 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5710 0, dev->addr, speed_str, dev->devname);
5714 /***********************************************************/
5715 /* PCMCIA/Cardbus */
5717 static struct pcmcia_socket_entry_s {
5718 struct pcmcia_socket_s *socket;
5719 struct pcmcia_socket_entry_s *next;
5720 } *pcmcia_sockets = 0;
5722 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5724 struct pcmcia_socket_entry_s *entry;
5726 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5727 entry->socket = socket;
5728 entry->next = pcmcia_sockets;
5729 pcmcia_sockets = entry;
5732 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5734 struct pcmcia_socket_entry_s *entry, **ptr;
5736 ptr = &pcmcia_sockets;
5737 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5738 if (entry->socket == socket) {
5739 *ptr = entry->next;
5740 qemu_free(entry);
5744 void pcmcia_info(void)
5746 struct pcmcia_socket_entry_s *iter;
5747 if (!pcmcia_sockets)
5748 term_printf("No PCMCIA sockets\n");
5750 for (iter = pcmcia_sockets; iter; iter = iter->next)
5751 term_printf("%s: %s\n", iter->socket->slot_string,
5752 iter->socket->attached ? iter->socket->card_string :
5753 "Empty");
5756 /***********************************************************/
5757 /* dumb display */
5759 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5763 static void dumb_resize(DisplayState *ds, int w, int h)
5767 static void dumb_refresh(DisplayState *ds)
5769 #if defined(CONFIG_SDL)
5770 vga_hw_update();
5771 #endif
5774 static void dumb_display_init(DisplayState *ds)
5776 ds->data = NULL;
5777 ds->linesize = 0;
5778 ds->depth = 0;
5779 ds->dpy_update = dumb_update;
5780 ds->dpy_resize = dumb_resize;
5781 ds->dpy_refresh = dumb_refresh;
5784 /***********************************************************/
5785 /* I/O handling */
5787 #define MAX_IO_HANDLERS 64
5789 typedef struct IOHandlerRecord {
5790 int fd;
5791 IOCanRWHandler *fd_read_poll;
5792 IOHandler *fd_read;
5793 IOHandler *fd_write;
5794 int deleted;
5795 void *opaque;
5796 /* temporary data */
5797 struct pollfd *ufd;
5798 struct IOHandlerRecord *next;
5799 } IOHandlerRecord;
5801 static IOHandlerRecord *first_io_handler;
5803 /* XXX: fd_read_poll should be suppressed, but an API change is
5804 necessary in the character devices to suppress fd_can_read(). */
5805 int qemu_set_fd_handler2(int fd,
5806 IOCanRWHandler *fd_read_poll,
5807 IOHandler *fd_read,
5808 IOHandler *fd_write,
5809 void *opaque)
5811 IOHandlerRecord **pioh, *ioh;
5813 if (!fd_read && !fd_write) {
5814 pioh = &first_io_handler;
5815 for(;;) {
5816 ioh = *pioh;
5817 if (ioh == NULL)
5818 break;
5819 if (ioh->fd == fd) {
5820 ioh->deleted = 1;
5821 break;
5823 pioh = &ioh->next;
5825 } else {
5826 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5827 if (ioh->fd == fd)
5828 goto found;
5830 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5831 if (!ioh)
5832 return -1;
5833 ioh->next = first_io_handler;
5834 first_io_handler = ioh;
5835 found:
5836 ioh->fd = fd;
5837 ioh->fd_read_poll = fd_read_poll;
5838 ioh->fd_read = fd_read;
5839 ioh->fd_write = fd_write;
5840 ioh->opaque = opaque;
5841 ioh->deleted = 0;
5843 main_loop_break();
5844 return 0;
5847 int qemu_set_fd_handler(int fd,
5848 IOHandler *fd_read,
5849 IOHandler *fd_write,
5850 void *opaque)
5852 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5855 /***********************************************************/
5856 /* Polling handling */
5858 typedef struct PollingEntry {
5859 PollingFunc *func;
5860 void *opaque;
5861 struct PollingEntry *next;
5862 } PollingEntry;
5864 static PollingEntry *first_polling_entry;
5866 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5868 PollingEntry **ppe, *pe;
5869 pe = qemu_mallocz(sizeof(PollingEntry));
5870 if (!pe)
5871 return -1;
5872 pe->func = func;
5873 pe->opaque = opaque;
5874 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5875 *ppe = pe;
5876 return 0;
5879 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5881 PollingEntry **ppe, *pe;
5882 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5883 pe = *ppe;
5884 if (pe->func == func && pe->opaque == opaque) {
5885 *ppe = pe->next;
5886 qemu_free(pe);
5887 break;
5892 #ifdef _WIN32
5893 /***********************************************************/
5894 /* Wait objects support */
5895 typedef struct WaitObjects {
5896 int num;
5897 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5898 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5899 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5900 } WaitObjects;
5902 static WaitObjects wait_objects = {0};
5904 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5906 WaitObjects *w = &wait_objects;
5908 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5909 return -1;
5910 w->events[w->num] = handle;
5911 w->func[w->num] = func;
5912 w->opaque[w->num] = opaque;
5913 w->num++;
5914 return 0;
5917 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5919 int i, found;
5920 WaitObjects *w = &wait_objects;
5922 found = 0;
5923 for (i = 0; i < w->num; i++) {
5924 if (w->events[i] == handle)
5925 found = 1;
5926 if (found) {
5927 w->events[i] = w->events[i + 1];
5928 w->func[i] = w->func[i + 1];
5929 w->opaque[i] = w->opaque[i + 1];
5932 if (found)
5933 w->num--;
5935 #endif
5937 #define SELF_ANNOUNCE_ROUNDS 5
5938 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5939 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5940 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5942 static int announce_self_create(uint8_t *buf,
5943 uint8_t *mac_addr)
5945 uint32_t magic = EXPERIMENTAL_MAGIC;
5946 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5948 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5950 memset(buf, 0xff, 6); /* h_dst */
5951 memcpy(buf + 6, mac_addr, 6); /* h_src */
5952 memcpy(buf + 12, &proto, 2); /* h_proto */
5953 memcpy(buf + 14, &magic, 4); /* magic */
5955 return 18; /* len */
5958 static void qemu_announce_self(void)
5960 int i, j, len;
5961 VLANState *vlan;
5962 VLANClientState *vc;
5963 uint8_t buf[256];
5965 for (i = 0; i < nb_nics; i++) {
5966 len = announce_self_create(buf, nd_table[i].macaddr);
5967 vlan = nd_table[i].vlan;
5968 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5969 if (vc->fd_read == tap_receive) /* send only if tap */
5970 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5971 vc->fd_read(vc->opaque, buf, len);
5976 /***********************************************************/
5977 /* savevm/loadvm support */
5979 #define IO_BUF_SIZE 32768
5981 struct QEMUFile {
5982 QEMUFilePutBufferFunc *put_buffer;
5983 QEMUFileGetBufferFunc *get_buffer;
5984 QEMUFileCloseFunc *close;
5985 void *opaque;
5987 int64_t buf_offset; /* start of buffer when writing, end of buffer
5988 when reading */
5989 int buf_index;
5990 int buf_size; /* 0 when writing */
5991 uint8_t buf[IO_BUF_SIZE];
5994 typedef struct QEMUFileFD
5996 int fd;
5997 } QEMUFileFD;
5999 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6001 QEMUFileFD *s = opaque;
6002 int offset = 0;
6003 ssize_t len;
6005 again:
6006 len = read(s->fd, buf + offset, size - offset);
6007 if (len == -1) {
6008 if (errno == EINTR || errno == EAGAIN)
6009 goto again;
6012 return len;
6015 QEMUFile *qemu_fopen_fd(int fd)
6017 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
6018 s->fd = fd;
6019 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
6022 typedef struct QEMUFileUnix
6024 FILE *outfile;
6025 } QEMUFileUnix;
6027 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6029 QEMUFileUnix *s = opaque;
6030 fseek(s->outfile, pos, SEEK_SET);
6031 fwrite(buf, 1, size, s->outfile);
6034 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6036 QEMUFileUnix *s = opaque;
6037 fseek(s->outfile, pos, SEEK_SET);
6038 return fread(buf, 1, size, s->outfile);
6041 static void file_close(void *opaque)
6043 QEMUFileUnix *s = opaque;
6044 fclose(s->outfile);
6045 qemu_free(s);
6048 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
6050 QEMUFileUnix *s;
6052 s = qemu_mallocz(sizeof(QEMUFileUnix));
6053 if (!s)
6054 return NULL;
6056 s->outfile = fopen(filename, mode);
6057 if (!s->outfile)
6058 goto fail;
6060 if (!strcmp(mode, "wb"))
6061 return qemu_fopen(s, file_put_buffer, NULL, file_close);
6062 else if (!strcmp(mode, "rb"))
6063 return qemu_fopen(s, NULL, file_get_buffer, file_close);
6065 fail:
6066 if (s->outfile)
6067 fclose(s->outfile);
6068 qemu_free(s);
6069 return NULL;
6072 typedef struct QEMUFileBdrv
6074 BlockDriverState *bs;
6075 int64_t base_offset;
6076 } QEMUFileBdrv;
6078 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
6080 QEMUFileBdrv *s = opaque;
6081 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
6084 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6086 QEMUFileBdrv *s = opaque;
6087 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6090 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6092 QEMUFileBdrv *s;
6094 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6095 if (!s)
6096 return NULL;
6098 s->bs = bs;
6099 s->base_offset = offset;
6101 if (is_writable)
6102 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
6104 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
6107 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6108 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
6110 QEMUFile *f;
6112 f = qemu_mallocz(sizeof(QEMUFile));
6113 if (!f)
6114 return NULL;
6116 f->opaque = opaque;
6117 f->put_buffer = put_buffer;
6118 f->get_buffer = get_buffer;
6119 f->close = close;
6121 return f;
6124 void qemu_fflush(QEMUFile *f)
6126 if (!f->put_buffer)
6127 return;
6129 if (f->buf_index > 0) {
6130 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
6131 f->buf_offset += f->buf_index;
6132 f->buf_index = 0;
6136 static void qemu_fill_buffer(QEMUFile *f)
6138 int len;
6140 if (!f->get_buffer)
6141 return;
6143 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6144 if (len < 0)
6145 len = 0;
6147 f->buf_index = 0;
6148 f->buf_size = len;
6149 f->buf_offset += len;
6152 void qemu_fclose(QEMUFile *f)
6154 qemu_fflush(f);
6155 if (f->close)
6156 f->close(f->opaque);
6157 qemu_free(f);
6160 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6162 int l;
6163 while (size > 0) {
6164 l = IO_BUF_SIZE - f->buf_index;
6165 if (l > size)
6166 l = size;
6167 memcpy(f->buf + f->buf_index, buf, l);
6168 f->buf_index += l;
6169 buf += l;
6170 size -= l;
6171 if (f->buf_index >= IO_BUF_SIZE)
6172 qemu_fflush(f);
6176 void qemu_put_byte(QEMUFile *f, int v)
6178 f->buf[f->buf_index++] = v;
6179 if (f->buf_index >= IO_BUF_SIZE)
6180 qemu_fflush(f);
6183 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6185 int size, l;
6187 size = size1;
6188 while (size > 0) {
6189 l = f->buf_size - f->buf_index;
6190 if (l == 0) {
6191 qemu_fill_buffer(f);
6192 l = f->buf_size - f->buf_index;
6193 if (l == 0)
6194 break;
6196 if (l > size)
6197 l = size;
6198 memcpy(buf, f->buf + f->buf_index, l);
6199 f->buf_index += l;
6200 buf += l;
6201 size -= l;
6203 return size1 - size;
6206 int qemu_get_byte(QEMUFile *f)
6208 if (f->buf_index >= f->buf_size) {
6209 qemu_fill_buffer(f);
6210 if (f->buf_index >= f->buf_size)
6211 return 0;
6213 return f->buf[f->buf_index++];
6216 int64_t qemu_ftell(QEMUFile *f)
6218 return f->buf_offset - f->buf_size + f->buf_index;
6221 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6223 if (whence == SEEK_SET) {
6224 /* nothing to do */
6225 } else if (whence == SEEK_CUR) {
6226 pos += qemu_ftell(f);
6227 } else {
6228 /* SEEK_END not supported */
6229 return -1;
6231 if (f->put_buffer) {
6232 qemu_fflush(f);
6233 f->buf_offset = pos;
6234 } else {
6235 f->buf_offset = pos;
6236 f->buf_index = 0;
6237 f->buf_size = 0;
6239 return pos;
6242 void qemu_put_be16(QEMUFile *f, unsigned int v)
6244 qemu_put_byte(f, v >> 8);
6245 qemu_put_byte(f, v);
6248 void qemu_put_be32(QEMUFile *f, unsigned int v)
6250 qemu_put_byte(f, v >> 24);
6251 qemu_put_byte(f, v >> 16);
6252 qemu_put_byte(f, v >> 8);
6253 qemu_put_byte(f, v);
6256 void qemu_put_be64(QEMUFile *f, uint64_t v)
6258 qemu_put_be32(f, v >> 32);
6259 qemu_put_be32(f, v);
6262 unsigned int qemu_get_be16(QEMUFile *f)
6264 unsigned int v;
6265 v = qemu_get_byte(f) << 8;
6266 v |= qemu_get_byte(f);
6267 return v;
6270 unsigned int qemu_get_be32(QEMUFile *f)
6272 unsigned int v;
6273 v = qemu_get_byte(f) << 24;
6274 v |= qemu_get_byte(f) << 16;
6275 v |= qemu_get_byte(f) << 8;
6276 v |= qemu_get_byte(f);
6277 return v;
6280 uint64_t qemu_get_be64(QEMUFile *f)
6282 uint64_t v;
6283 v = (uint64_t)qemu_get_be32(f) << 32;
6284 v |= qemu_get_be32(f);
6285 return v;
6288 typedef struct SaveStateEntry {
6289 char idstr[256];
6290 int instance_id;
6291 int version_id;
6292 SaveStateHandler *save_state;
6293 LoadStateHandler *load_state;
6294 void *opaque;
6295 struct SaveStateEntry *next;
6296 } SaveStateEntry;
6298 static SaveStateEntry *first_se;
6300 int register_savevm(const char *idstr,
6301 int instance_id,
6302 int version_id,
6303 SaveStateHandler *save_state,
6304 LoadStateHandler *load_state,
6305 void *opaque)
6307 SaveStateEntry *se, **pse;
6309 se = qemu_malloc(sizeof(SaveStateEntry));
6310 if (!se)
6311 return -1;
6312 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6313 se->instance_id = instance_id;
6314 se->version_id = version_id;
6315 se->save_state = save_state;
6316 se->load_state = load_state;
6317 se->opaque = opaque;
6318 se->next = NULL;
6320 /* add at the end of list */
6321 pse = &first_se;
6322 while (*pse != NULL)
6323 pse = &(*pse)->next;
6324 *pse = se;
6325 return 0;
6328 #define QEMU_VM_FILE_MAGIC 0x5145564d
6329 #define QEMU_VM_FILE_VERSION 0x00000002
6331 static int qemu_savevm_state(QEMUFile *f)
6333 SaveStateEntry *se;
6334 int len, ret;
6335 int64_t cur_pos, len_pos, total_len_pos;
6337 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6338 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6339 total_len_pos = qemu_ftell(f);
6340 qemu_put_be64(f, 0); /* total size */
6342 for(se = first_se; se != NULL; se = se->next) {
6343 /* ID string */
6344 len = strlen(se->idstr);
6345 qemu_put_byte(f, len);
6346 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6348 qemu_put_be32(f, se->instance_id);
6349 qemu_put_be32(f, se->version_id);
6351 /* record size: filled later */
6352 len_pos = qemu_ftell(f);
6353 qemu_put_be32(f, 0);
6354 se->save_state(f, se->opaque);
6356 /* fill record size */
6357 cur_pos = qemu_ftell(f);
6358 len = cur_pos - len_pos - 4;
6359 qemu_fseek(f, len_pos, SEEK_SET);
6360 qemu_put_be32(f, len);
6361 qemu_fseek(f, cur_pos, SEEK_SET);
6363 cur_pos = qemu_ftell(f);
6364 qemu_fseek(f, total_len_pos, SEEK_SET);
6365 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6366 qemu_fseek(f, cur_pos, SEEK_SET);
6368 ret = 0;
6369 return ret;
6372 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6374 SaveStateEntry *se;
6376 for(se = first_se; se != NULL; se = se->next) {
6377 if (!strcmp(se->idstr, idstr) &&
6378 instance_id == se->instance_id)
6379 return se;
6381 return NULL;
6384 static int qemu_loadvm_state(QEMUFile *f)
6386 SaveStateEntry *se;
6387 int len, ret, instance_id, record_len, version_id;
6388 int64_t total_len, end_pos, cur_pos;
6389 unsigned int v;
6390 char idstr[256];
6392 v = qemu_get_be32(f);
6393 if (v != QEMU_VM_FILE_MAGIC)
6394 goto fail;
6395 v = qemu_get_be32(f);
6396 if (v != QEMU_VM_FILE_VERSION) {
6397 fail:
6398 ret = -1;
6399 goto the_end;
6401 total_len = qemu_get_be64(f);
6402 end_pos = total_len + qemu_ftell(f);
6403 for(;;) {
6404 if (qemu_ftell(f) >= end_pos)
6405 break;
6406 len = qemu_get_byte(f);
6407 qemu_get_buffer(f, (uint8_t *)idstr, len);
6408 idstr[len] = '\0';
6409 instance_id = qemu_get_be32(f);
6410 version_id = qemu_get_be32(f);
6411 record_len = qemu_get_be32(f);
6412 #if 0
6413 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6414 idstr, instance_id, version_id, record_len);
6415 #endif
6416 cur_pos = qemu_ftell(f);
6417 se = find_se(idstr, instance_id);
6418 if (!se) {
6419 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6420 instance_id, idstr);
6421 } else {
6422 ret = se->load_state(f, se->opaque, version_id);
6423 if (ret < 0) {
6424 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6425 instance_id, idstr);
6426 goto the_end;
6429 /* always seek to exact end of record */
6430 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6432 ret = 0;
6433 the_end:
6434 return ret;
6437 int qemu_live_savevm_state(QEMUFile *f)
6439 SaveStateEntry *se;
6440 int len, ret;
6442 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6443 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6445 for(se = first_se; se != NULL; se = se->next) {
6446 len = strlen(se->idstr);
6448 qemu_put_byte(f, len);
6449 qemu_put_buffer(f, se->idstr, len);
6450 qemu_put_be32(f, se->instance_id);
6451 qemu_put_be32(f, se->version_id);
6453 se->save_state(f, se->opaque);
6456 qemu_put_byte(f, 0);
6458 ret = 0;
6459 return ret;
6462 int qemu_live_loadvm_state(QEMUFile *f)
6464 SaveStateEntry *se;
6465 int len, ret, instance_id, version_id;
6466 unsigned int v;
6467 char idstr[256];
6469 v = qemu_get_be32(f);
6470 if (v != QEMU_VM_FILE_MAGIC)
6471 goto fail;
6472 v = qemu_get_be32(f);
6473 if (v != QEMU_VM_FILE_VERSION) {
6474 fail:
6475 ret = -1;
6476 goto the_end;
6479 for(;;) {
6480 len = qemu_get_byte(f);
6481 if (len == 0)
6482 break;
6483 qemu_get_buffer(f, idstr, len);
6484 idstr[len] = '\0';
6485 instance_id = qemu_get_be32(f);
6486 version_id = qemu_get_be32(f);
6487 se = find_se(idstr, instance_id);
6488 if (!se) {
6489 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6490 instance_id, idstr);
6491 } else {
6492 if (version_id > se->version_id) { /* src version > dst version */
6493 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6494 idstr, version_id, se->version_id);
6495 ret = -1;
6496 goto the_end;
6498 ret = se->load_state(f, se->opaque, version_id);
6499 if (ret < 0) {
6500 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6501 instance_id, idstr);
6502 goto the_end;
6506 ret = 0;
6508 qemu_announce_self();
6510 the_end:
6511 return ret;
6514 /* device can contain snapshots */
6515 static int bdrv_can_snapshot(BlockDriverState *bs)
6517 return (bs &&
6518 !bdrv_is_removable(bs) &&
6519 !bdrv_is_read_only(bs));
6522 /* device must be snapshots in order to have a reliable snapshot */
6523 static int bdrv_has_snapshot(BlockDriverState *bs)
6525 return (bs &&
6526 !bdrv_is_removable(bs) &&
6527 !bdrv_is_read_only(bs));
6530 static BlockDriverState *get_bs_snapshots(void)
6532 BlockDriverState *bs;
6533 int i;
6535 if (bs_snapshots)
6536 return bs_snapshots;
6537 for(i = 0; i <= nb_drives; i++) {
6538 bs = drives_table[i].bdrv;
6539 if (bdrv_can_snapshot(bs))
6540 goto ok;
6542 return NULL;
6544 bs_snapshots = bs;
6545 return bs;
6548 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6549 const char *name)
6551 QEMUSnapshotInfo *sn_tab, *sn;
6552 int nb_sns, i, ret;
6554 ret = -ENOENT;
6555 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6556 if (nb_sns < 0)
6557 return ret;
6558 for(i = 0; i < nb_sns; i++) {
6559 sn = &sn_tab[i];
6560 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6561 *sn_info = *sn;
6562 ret = 0;
6563 break;
6566 qemu_free(sn_tab);
6567 return ret;
6570 void do_savevm(const char *name)
6572 BlockDriverState *bs, *bs1;
6573 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6574 int must_delete, ret, i;
6575 BlockDriverInfo bdi1, *bdi = &bdi1;
6576 QEMUFile *f;
6577 int saved_vm_running;
6578 #ifdef _WIN32
6579 struct _timeb tb;
6580 #else
6581 struct timeval tv;
6582 #endif
6584 bs = get_bs_snapshots();
6585 if (!bs) {
6586 term_printf("No block device can accept snapshots\n");
6587 return;
6590 /* ??? Should this occur after vm_stop? */
6591 qemu_aio_flush();
6593 saved_vm_running = vm_running;
6594 vm_stop(0);
6596 must_delete = 0;
6597 if (name) {
6598 ret = bdrv_snapshot_find(bs, old_sn, name);
6599 if (ret >= 0) {
6600 must_delete = 1;
6603 memset(sn, 0, sizeof(*sn));
6604 if (must_delete) {
6605 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6606 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6607 } else {
6608 if (name)
6609 pstrcpy(sn->name, sizeof(sn->name), name);
6612 /* fill auxiliary fields */
6613 #ifdef _WIN32
6614 _ftime(&tb);
6615 sn->date_sec = tb.time;
6616 sn->date_nsec = tb.millitm * 1000000;
6617 #else
6618 gettimeofday(&tv, NULL);
6619 sn->date_sec = tv.tv_sec;
6620 sn->date_nsec = tv.tv_usec * 1000;
6621 #endif
6622 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6624 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6625 term_printf("Device %s does not support VM state snapshots\n",
6626 bdrv_get_device_name(bs));
6627 goto the_end;
6630 /* save the VM state */
6631 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6632 if (!f) {
6633 term_printf("Could not open VM state file\n");
6634 goto the_end;
6636 ret = qemu_savevm_state(f);
6637 sn->vm_state_size = qemu_ftell(f);
6638 qemu_fclose(f);
6639 if (ret < 0) {
6640 term_printf("Error %d while writing VM\n", ret);
6641 goto the_end;
6644 /* create the snapshots */
6646 for(i = 0; i < nb_drives; i++) {
6647 bs1 = drives_table[i].bdrv;
6648 if (bdrv_has_snapshot(bs1)) {
6649 if (must_delete) {
6650 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6651 if (ret < 0) {
6652 term_printf("Error while deleting snapshot on '%s'\n",
6653 bdrv_get_device_name(bs1));
6656 ret = bdrv_snapshot_create(bs1, sn);
6657 if (ret < 0) {
6658 term_printf("Error while creating snapshot on '%s'\n",
6659 bdrv_get_device_name(bs1));
6664 the_end:
6665 if (saved_vm_running)
6666 vm_start();
6669 void do_loadvm(const char *name)
6671 BlockDriverState *bs, *bs1;
6672 BlockDriverInfo bdi1, *bdi = &bdi1;
6673 QEMUFile *f;
6674 int i, ret;
6675 int saved_vm_running;
6677 bs = get_bs_snapshots();
6678 if (!bs) {
6679 term_printf("No block device supports snapshots\n");
6680 return;
6683 /* Flush all IO requests so they don't interfere with the new state. */
6684 qemu_aio_flush();
6686 saved_vm_running = vm_running;
6687 vm_stop(0);
6689 for(i = 0; i <= nb_drives; i++) {
6690 bs1 = drives_table[i].bdrv;
6691 if (bdrv_has_snapshot(bs1)) {
6692 ret = bdrv_snapshot_goto(bs1, name);
6693 if (ret < 0) {
6694 if (bs != bs1)
6695 term_printf("Warning: ");
6696 switch(ret) {
6697 case -ENOTSUP:
6698 term_printf("Snapshots not supported on device '%s'\n",
6699 bdrv_get_device_name(bs1));
6700 break;
6701 case -ENOENT:
6702 term_printf("Could not find snapshot '%s' on device '%s'\n",
6703 name, bdrv_get_device_name(bs1));
6704 break;
6705 default:
6706 term_printf("Error %d while activating snapshot on '%s'\n",
6707 ret, bdrv_get_device_name(bs1));
6708 break;
6710 /* fatal on snapshot block device */
6711 if (bs == bs1)
6712 goto the_end;
6717 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6718 term_printf("Device %s does not support VM state snapshots\n",
6719 bdrv_get_device_name(bs));
6720 return;
6723 /* restore the VM state */
6724 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6725 if (!f) {
6726 term_printf("Could not open VM state file\n");
6727 goto the_end;
6729 ret = qemu_loadvm_state(f);
6730 qemu_fclose(f);
6731 if (ret < 0) {
6732 term_printf("Error %d while loading VM state\n", ret);
6734 the_end:
6735 if (saved_vm_running)
6736 vm_start();
6739 void do_delvm(const char *name)
6741 BlockDriverState *bs, *bs1;
6742 int i, ret;
6744 bs = get_bs_snapshots();
6745 if (!bs) {
6746 term_printf("No block device supports snapshots\n");
6747 return;
6750 for(i = 0; i <= nb_drives; i++) {
6751 bs1 = drives_table[i].bdrv;
6752 if (bdrv_has_snapshot(bs1)) {
6753 ret = bdrv_snapshot_delete(bs1, name);
6754 if (ret < 0) {
6755 if (ret == -ENOTSUP)
6756 term_printf("Snapshots not supported on device '%s'\n",
6757 bdrv_get_device_name(bs1));
6758 else
6759 term_printf("Error %d while deleting snapshot on '%s'\n",
6760 ret, bdrv_get_device_name(bs1));
6766 void do_info_snapshots(void)
6768 BlockDriverState *bs, *bs1;
6769 QEMUSnapshotInfo *sn_tab, *sn;
6770 int nb_sns, i;
6771 char buf[256];
6773 bs = get_bs_snapshots();
6774 if (!bs) {
6775 term_printf("No available block device supports snapshots\n");
6776 return;
6778 term_printf("Snapshot devices:");
6779 for(i = 0; i <= nb_drives; i++) {
6780 bs1 = drives_table[i].bdrv;
6781 if (bdrv_has_snapshot(bs1)) {
6782 if (bs == bs1)
6783 term_printf(" %s", bdrv_get_device_name(bs1));
6786 term_printf("\n");
6788 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6789 if (nb_sns < 0) {
6790 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6791 return;
6793 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6794 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6795 for(i = 0; i < nb_sns; i++) {
6796 sn = &sn_tab[i];
6797 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6799 qemu_free(sn_tab);
6802 /***********************************************************/
6803 /* ram save/restore */
6805 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6807 int v;
6809 v = qemu_get_byte(f);
6810 switch(v) {
6811 case 0:
6812 if (qemu_get_buffer(f, buf, len) != len)
6813 return -EIO;
6814 break;
6815 case 1:
6816 v = qemu_get_byte(f);
6817 memset(buf, v, len);
6818 break;
6819 default:
6820 return -EINVAL;
6822 return 0;
6825 static int ram_load_v1(QEMUFile *f, void *opaque)
6827 int ret;
6828 ram_addr_t i;
6830 if (qemu_get_be32(f) != phys_ram_size)
6831 return -EINVAL;
6832 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6833 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
6834 continue;
6835 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6836 if (ret)
6837 return ret;
6839 return 0;
6842 #define BDRV_HASH_BLOCK_SIZE 1024
6843 #define IOBUF_SIZE 4096
6844 #define RAM_CBLOCK_MAGIC 0xfabe
6846 typedef struct RamCompressState {
6847 z_stream zstream;
6848 QEMUFile *f;
6849 uint8_t buf[IOBUF_SIZE];
6850 } RamCompressState;
6852 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6854 int ret;
6855 memset(s, 0, sizeof(*s));
6856 s->f = f;
6857 ret = deflateInit2(&s->zstream, 1,
6858 Z_DEFLATED, 15,
6859 9, Z_DEFAULT_STRATEGY);
6860 if (ret != Z_OK)
6861 return -1;
6862 s->zstream.avail_out = IOBUF_SIZE;
6863 s->zstream.next_out = s->buf;
6864 return 0;
6867 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6869 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6870 qemu_put_be16(s->f, len);
6871 qemu_put_buffer(s->f, buf, len);
6874 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6876 int ret;
6878 s->zstream.avail_in = len;
6879 s->zstream.next_in = (uint8_t *)buf;
6880 while (s->zstream.avail_in > 0) {
6881 ret = deflate(&s->zstream, Z_NO_FLUSH);
6882 if (ret != Z_OK)
6883 return -1;
6884 if (s->zstream.avail_out == 0) {
6885 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6886 s->zstream.avail_out = IOBUF_SIZE;
6887 s->zstream.next_out = s->buf;
6890 return 0;
6893 static void ram_compress_close(RamCompressState *s)
6895 int len, ret;
6897 /* compress last bytes */
6898 for(;;) {
6899 ret = deflate(&s->zstream, Z_FINISH);
6900 if (ret == Z_OK || ret == Z_STREAM_END) {
6901 len = IOBUF_SIZE - s->zstream.avail_out;
6902 if (len > 0) {
6903 ram_put_cblock(s, s->buf, len);
6905 s->zstream.avail_out = IOBUF_SIZE;
6906 s->zstream.next_out = s->buf;
6907 if (ret == Z_STREAM_END)
6908 break;
6909 } else {
6910 goto fail;
6913 fail:
6914 deflateEnd(&s->zstream);
6917 typedef struct RamDecompressState {
6918 z_stream zstream;
6919 QEMUFile *f;
6920 uint8_t buf[IOBUF_SIZE];
6921 } RamDecompressState;
6923 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6925 int ret;
6926 memset(s, 0, sizeof(*s));
6927 s->f = f;
6928 ret = inflateInit(&s->zstream);
6929 if (ret != Z_OK)
6930 return -1;
6931 return 0;
6934 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6936 int ret, clen;
6938 s->zstream.avail_out = len;
6939 s->zstream.next_out = buf;
6940 while (s->zstream.avail_out > 0) {
6941 if (s->zstream.avail_in == 0) {
6942 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6943 return -1;
6944 clen = qemu_get_be16(s->f);
6945 if (clen > IOBUF_SIZE)
6946 return -1;
6947 qemu_get_buffer(s->f, s->buf, clen);
6948 s->zstream.avail_in = clen;
6949 s->zstream.next_in = s->buf;
6951 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6952 if (ret != Z_OK && ret != Z_STREAM_END) {
6953 return -1;
6956 return 0;
6959 static void ram_decompress_close(RamDecompressState *s)
6961 inflateEnd(&s->zstream);
6964 static void ram_save_live(QEMUFile *f, void *opaque)
6966 target_ulong addr;
6968 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
6969 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
6970 continue;
6971 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
6972 qemu_put_be32(f, addr);
6973 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
6976 qemu_put_be32(f, 1);
6979 static void ram_save_static(QEMUFile *f, void *opaque)
6981 ram_addr_t i;
6982 RamCompressState s1, *s = &s1;
6983 uint8_t buf[10];
6985 qemu_put_be32(f, phys_ram_size);
6986 if (ram_compress_open(s, f) < 0)
6987 return;
6988 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6989 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
6990 continue;
6991 #if 0
6992 if (tight_savevm_enabled) {
6993 int64_t sector_num;
6994 int j;
6996 /* find if the memory block is available on a virtual
6997 block device */
6998 sector_num = -1;
6999 for(j = 0; j < nb_drives; j++) {
7000 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7001 phys_ram_base + i,
7002 BDRV_HASH_BLOCK_SIZE);
7003 if (sector_num >= 0)
7004 break;
7006 if (j == nb_drives)
7007 goto normal_compress;
7008 buf[0] = 1;
7009 buf[1] = j;
7010 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7011 ram_compress_buf(s, buf, 10);
7012 } else
7013 #endif
7015 // normal_compress:
7016 buf[0] = 0;
7017 ram_compress_buf(s, buf, 1);
7018 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7021 ram_compress_close(s);
7024 static void ram_save(QEMUFile *f, void *opaque)
7026 int in_migration = cpu_physical_memory_get_dirty_tracking();
7028 qemu_put_byte(f, in_migration);
7030 if (in_migration)
7031 ram_save_live(f, opaque);
7032 else
7033 ram_save_static(f, opaque);
7036 static int ram_load_live(QEMUFile *f, void *opaque)
7038 target_ulong addr;
7040 do {
7041 addr = qemu_get_be32(f);
7042 if (addr == 1)
7043 break;
7045 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7046 } while (1);
7048 return 0;
7051 static int ram_load_static(QEMUFile *f, void *opaque)
7053 RamDecompressState s1, *s = &s1;
7054 uint8_t buf[10];
7055 ram_addr_t i;
7057 if (qemu_get_be32(f) != phys_ram_size)
7058 return -EINVAL;
7059 if (ram_decompress_open(s, f) < 0)
7060 return -EINVAL;
7061 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7062 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
7063 continue;
7064 if (ram_decompress_buf(s, buf, 1) < 0) {
7065 fprintf(stderr, "Error while reading ram block header\n");
7066 goto error;
7068 if (buf[0] == 0) {
7069 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7070 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7071 goto error;
7073 } else
7074 #if 0
7075 if (buf[0] == 1) {
7076 int bs_index;
7077 int64_t sector_num;
7079 ram_decompress_buf(s, buf + 1, 9);
7080 bs_index = buf[1];
7081 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7082 if (bs_index >= nb_drives) {
7083 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7084 goto error;
7086 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7087 phys_ram_base + i,
7088 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7089 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7090 bs_index, sector_num);
7091 goto error;
7093 } else
7094 #endif
7096 error:
7097 printf("Error block header\n");
7098 return -EINVAL;
7101 ram_decompress_close(s);
7102 return 0;
7105 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7107 int ret;
7109 switch (version_id) {
7110 case 1:
7111 ret = ram_load_v1(f, opaque);
7112 break;
7113 case 3:
7114 if (qemu_get_byte(f)) {
7115 ret = ram_load_live(f, opaque);
7116 break;
7118 case 2:
7119 ret = ram_load_static(f, opaque);
7120 break;
7121 default:
7122 ret = -EINVAL;
7123 break;
7126 return ret;
7129 /***********************************************************/
7130 /* bottom halves (can be seen as timers which expire ASAP) */
7132 struct QEMUBH {
7133 QEMUBHFunc *cb;
7134 void *opaque;
7135 int scheduled;
7136 QEMUBH *next;
7139 static QEMUBH *first_bh = NULL;
7141 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7143 QEMUBH *bh;
7144 bh = qemu_mallocz(sizeof(QEMUBH));
7145 if (!bh)
7146 return NULL;
7147 bh->cb = cb;
7148 bh->opaque = opaque;
7149 return bh;
7152 int qemu_bh_poll(void)
7154 QEMUBH *bh, **pbh;
7155 int ret;
7157 ret = 0;
7158 for(;;) {
7159 pbh = &first_bh;
7160 bh = *pbh;
7161 if (!bh)
7162 break;
7163 ret = 1;
7164 *pbh = bh->next;
7165 bh->scheduled = 0;
7166 bh->cb(bh->opaque);
7168 return ret;
7171 void qemu_bh_schedule(QEMUBH *bh)
7173 CPUState *env = cpu_single_env;
7174 if (bh->scheduled)
7175 return;
7176 bh->scheduled = 1;
7177 bh->next = first_bh;
7178 first_bh = bh;
7180 /* stop the currently executing CPU to execute the BH ASAP */
7181 if (env) {
7182 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7184 main_loop_break();
7187 void qemu_bh_cancel(QEMUBH *bh)
7189 QEMUBH **pbh;
7190 if (bh->scheduled) {
7191 pbh = &first_bh;
7192 while (*pbh != bh)
7193 pbh = &(*pbh)->next;
7194 *pbh = bh->next;
7195 bh->scheduled = 0;
7199 void qemu_bh_delete(QEMUBH *bh)
7201 qemu_bh_cancel(bh);
7202 qemu_free(bh);
7205 /***********************************************************/
7206 /* machine registration */
7208 QEMUMachine *first_machine = NULL;
7209 QEMUMachine *current_machine = NULL;
7211 int qemu_register_machine(QEMUMachine *m)
7213 QEMUMachine **pm;
7214 pm = &first_machine;
7215 while (*pm != NULL)
7216 pm = &(*pm)->next;
7217 m->next = NULL;
7218 *pm = m;
7219 return 0;
7222 static QEMUMachine *find_machine(const char *name)
7224 QEMUMachine *m;
7226 for(m = first_machine; m != NULL; m = m->next) {
7227 if (!strcmp(m->name, name))
7228 return m;
7230 return NULL;
7233 /***********************************************************/
7234 /* main execution loop */
7236 static void gui_update(void *opaque)
7238 DisplayState *ds = opaque;
7239 ds->dpy_refresh(ds);
7240 qemu_mod_timer(ds->gui_timer,
7241 (ds->gui_timer_interval ?
7242 ds->gui_timer_interval :
7243 GUI_REFRESH_INTERVAL)
7244 + qemu_get_clock(rt_clock));
7247 struct vm_change_state_entry {
7248 VMChangeStateHandler *cb;
7249 void *opaque;
7250 LIST_ENTRY (vm_change_state_entry) entries;
7253 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7255 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7256 void *opaque)
7258 VMChangeStateEntry *e;
7260 e = qemu_mallocz(sizeof (*e));
7261 if (!e)
7262 return NULL;
7264 e->cb = cb;
7265 e->opaque = opaque;
7266 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7267 return e;
7270 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7272 LIST_REMOVE (e, entries);
7273 qemu_free (e);
7276 static void vm_state_notify(int running)
7278 VMChangeStateEntry *e;
7280 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7281 e->cb(e->opaque, running);
7285 /* XXX: support several handlers */
7286 static VMStopHandler *vm_stop_cb;
7287 static void *vm_stop_opaque;
7289 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7291 vm_stop_cb = cb;
7292 vm_stop_opaque = opaque;
7293 return 0;
7296 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7298 vm_stop_cb = NULL;
7301 void vm_start(void)
7303 if (!vm_running) {
7304 cpu_enable_ticks();
7305 vm_running = 1;
7306 vm_state_notify(1);
7307 qemu_rearm_alarm_timer(alarm_timer);
7311 void vm_stop(int reason)
7313 if (vm_running) {
7314 cpu_disable_ticks();
7315 vm_running = 0;
7316 if (reason != 0) {
7317 if (vm_stop_cb) {
7318 vm_stop_cb(vm_stop_opaque, reason);
7321 vm_state_notify(0);
7325 /* reset/shutdown handler */
7327 typedef struct QEMUResetEntry {
7328 QEMUResetHandler *func;
7329 void *opaque;
7330 struct QEMUResetEntry *next;
7331 } QEMUResetEntry;
7333 static QEMUResetEntry *first_reset_entry;
7334 static int reset_requested;
7335 static int shutdown_requested;
7336 static int powerdown_requested;
7338 int qemu_shutdown_requested(void)
7340 int r = shutdown_requested;
7341 shutdown_requested = 0;
7342 return r;
7345 int qemu_reset_requested(void)
7347 int r = reset_requested;
7348 reset_requested = 0;
7349 return r;
7352 int qemu_powerdown_requested(void)
7354 int r = powerdown_requested;
7355 powerdown_requested = 0;
7356 return r;
7359 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7361 QEMUResetEntry **pre, *re;
7363 pre = &first_reset_entry;
7364 while (*pre != NULL)
7365 pre = &(*pre)->next;
7366 re = qemu_mallocz(sizeof(QEMUResetEntry));
7367 re->func = func;
7368 re->opaque = opaque;
7369 re->next = NULL;
7370 *pre = re;
7373 void qemu_system_reset(void)
7375 QEMUResetEntry *re;
7377 /* reset all devices */
7378 for(re = first_reset_entry; re != NULL; re = re->next) {
7379 re->func(re->opaque);
7383 void qemu_system_reset_request(void)
7385 if (no_reboot) {
7386 shutdown_requested = 1;
7387 } else {
7388 reset_requested = 1;
7390 if (cpu_single_env)
7391 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7392 main_loop_break();
7395 void qemu_system_shutdown_request(void)
7397 shutdown_requested = 1;
7398 if (cpu_single_env)
7399 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7402 void qemu_system_powerdown_request(void)
7404 powerdown_requested = 1;
7405 if (cpu_single_env)
7406 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7409 /* boot_set handler */
7410 QEMUBootSetHandler *qemu_boot_set_handler = NULL;
7412 void qemu_register_boot_set(QEMUBootSetHandler *func)
7414 qemu_boot_set_handler = func;
7417 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
7418 struct timeval *tv)
7420 int ret;
7422 /* KVM holds a mutex while QEMU code is running, we need hooks to
7423 release the mutex whenever QEMU code sleeps. */
7425 kvm_sleep_begin();
7427 ret = select(max_fd, rfds, wfds, xfds, tv);
7429 kvm_sleep_end();
7431 return ret;
7434 void main_loop_wait(int timeout)
7436 IOHandlerRecord *ioh;
7437 fd_set rfds, wfds, xfds;
7438 int ret, nfds;
7439 #ifdef _WIN32
7440 int ret2, i;
7441 #endif
7442 struct timeval tv;
7443 PollingEntry *pe;
7446 /* XXX: need to suppress polling by better using win32 events */
7447 ret = 0;
7448 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7449 ret |= pe->func(pe->opaque);
7451 #ifdef _WIN32
7452 if (ret == 0) {
7453 int err;
7454 WaitObjects *w = &wait_objects;
7456 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7457 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7458 if (w->func[ret - WAIT_OBJECT_0])
7459 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7461 /* Check for additional signaled events */
7462 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7464 /* Check if event is signaled */
7465 ret2 = WaitForSingleObject(w->events[i], 0);
7466 if(ret2 == WAIT_OBJECT_0) {
7467 if (w->func[i])
7468 w->func[i](w->opaque[i]);
7469 } else if (ret2 == WAIT_TIMEOUT) {
7470 } else {
7471 err = GetLastError();
7472 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7475 } else if (ret == WAIT_TIMEOUT) {
7476 } else {
7477 err = GetLastError();
7478 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7481 #endif
7482 /* poll any events */
7483 /* XXX: separate device handlers from system ones */
7484 nfds = -1;
7485 FD_ZERO(&rfds);
7486 FD_ZERO(&wfds);
7487 FD_ZERO(&xfds);
7488 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7489 if (ioh->deleted)
7490 continue;
7491 if (ioh->fd_read &&
7492 (!ioh->fd_read_poll ||
7493 ioh->fd_read_poll(ioh->opaque) != 0)) {
7494 FD_SET(ioh->fd, &rfds);
7495 if (ioh->fd > nfds)
7496 nfds = ioh->fd;
7498 if (ioh->fd_write) {
7499 FD_SET(ioh->fd, &wfds);
7500 if (ioh->fd > nfds)
7501 nfds = ioh->fd;
7505 #ifdef _WIN32
7506 tv.tv_sec = 0;
7507 tv.tv_usec = 0;
7508 #else
7509 tv.tv_sec = timeout / 1000;
7510 tv.tv_usec = (timeout % 1000) * 1000;
7511 #endif
7512 #if defined(CONFIG_SLIRP)
7513 if (slirp_inited) {
7514 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7516 #endif
7517 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7518 if (ret > 0) {
7519 IOHandlerRecord **pioh;
7521 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7522 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7523 ioh->fd_read(ioh->opaque);
7524 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
7525 FD_CLR(ioh->fd, &rfds);
7527 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7528 ioh->fd_write(ioh->opaque);
7532 /* remove deleted IO handlers */
7533 pioh = &first_io_handler;
7534 while (*pioh) {
7535 ioh = *pioh;
7536 if (ioh->deleted) {
7537 *pioh = ioh->next;
7538 qemu_free(ioh);
7539 } else
7540 pioh = &ioh->next;
7543 #if defined(CONFIG_SLIRP)
7544 if (slirp_inited) {
7545 if (ret < 0) {
7546 FD_ZERO(&rfds);
7547 FD_ZERO(&wfds);
7548 FD_ZERO(&xfds);
7550 slirp_select_poll(&rfds, &wfds, &xfds);
7552 #endif
7553 qemu_aio_poll();
7554 if (vm_running) {
7555 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7556 qemu_get_clock(vm_clock));
7557 /* run dma transfers, if any */
7558 DMA_run();
7561 /* real time timers */
7562 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7563 qemu_get_clock(rt_clock));
7565 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7566 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7567 qemu_rearm_alarm_timer(alarm_timer);
7570 /* Check bottom-halves last in case any of the earlier events triggered
7571 them. */
7572 qemu_bh_poll();
7576 static int main_loop(void)
7578 int ret, timeout;
7579 #ifdef CONFIG_PROFILER
7580 int64_t ti;
7581 #endif
7582 CPUState *env;
7585 if (kvm_enabled()) {
7586 kvm_main_loop();
7587 cpu_disable_ticks();
7588 return 0;
7591 cur_cpu = first_cpu;
7592 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7593 for(;;) {
7594 if (vm_running) {
7596 for(;;) {
7597 /* get next cpu */
7598 env = next_cpu;
7599 #ifdef CONFIG_PROFILER
7600 ti = profile_getclock();
7601 #endif
7602 ret = cpu_exec(env);
7603 #ifdef CONFIG_PROFILER
7604 qemu_time += profile_getclock() - ti;
7605 #endif
7606 next_cpu = env->next_cpu ?: first_cpu;
7607 if (event_pending && likely(ret != EXCP_DEBUG)) {
7608 ret = EXCP_INTERRUPT;
7609 event_pending = 0;
7610 break;
7612 if (ret == EXCP_HLT) {
7613 /* Give the next CPU a chance to run. */
7614 cur_cpu = env;
7615 continue;
7617 if (ret != EXCP_HALTED)
7618 break;
7619 /* all CPUs are halted ? */
7620 if (env == cur_cpu)
7621 break;
7623 cur_cpu = env;
7625 if (shutdown_requested) {
7626 ret = EXCP_INTERRUPT;
7627 if (no_shutdown) {
7628 vm_stop(0);
7629 no_shutdown = 0;
7631 else
7632 break;
7634 if (reset_requested) {
7635 reset_requested = 0;
7636 qemu_system_reset();
7637 if (kvm_enabled())
7638 kvm_load_registers(env);
7639 ret = EXCP_INTERRUPT;
7641 if (powerdown_requested) {
7642 powerdown_requested = 0;
7643 qemu_system_powerdown();
7644 ret = EXCP_INTERRUPT;
7646 if (unlikely(ret == EXCP_DEBUG)) {
7647 vm_stop(EXCP_DEBUG);
7649 /* If all cpus are halted then wait until the next IRQ */
7650 /* XXX: use timeout computed from timers */
7651 if (ret == EXCP_HALTED)
7652 timeout = 10;
7653 else
7654 timeout = 0;
7655 } else {
7656 timeout = 10;
7658 #ifdef CONFIG_PROFILER
7659 ti = profile_getclock();
7660 #endif
7661 main_loop_wait(timeout);
7662 #ifdef CONFIG_PROFILER
7663 dev_time += profile_getclock() - ti;
7664 #endif
7666 cpu_disable_ticks();
7667 return ret;
7670 static void help(int exitcode)
7672 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
7673 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7674 "usage: %s [options] [disk_image]\n"
7675 "\n"
7676 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7677 "\n"
7678 "Standard options:\n"
7679 "-M machine select emulated machine (-M ? for list)\n"
7680 "-cpu cpu select CPU (-cpu ? for list)\n"
7681 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7682 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7683 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7684 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7685 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7686 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7687 " [,cache=on|off][,format=f][,boot=on|off]\n"
7688 " use 'file' as a drive image\n"
7689 "-mtdblock file use 'file' as on-board Flash memory image\n"
7690 "-sd file use 'file' as SecureDigital card image\n"
7691 "-pflash file use 'file' as a parallel flash image\n"
7692 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7693 "-snapshot write to temporary files instead of disk image files\n"
7694 #ifdef CONFIG_SDL
7695 "-no-frame open SDL window without a frame and window decorations\n"
7696 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7697 "-no-quit disable SDL window close capability\n"
7698 #endif
7699 #ifdef TARGET_I386
7700 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7701 #endif
7702 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7703 "-smp n set the number of CPUs to 'n' [default=1]\n"
7704 "-nographic disable graphical output and redirect serial I/Os to console\n"
7705 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7706 #ifndef _WIN32
7707 "-k language use keyboard layout (for example \"fr\" for French)\n"
7708 #endif
7709 #ifdef HAS_AUDIO
7710 "-audio-help print list of audio drivers and their options\n"
7711 "-soundhw c1,... enable audio support\n"
7712 " and only specified sound cards (comma separated list)\n"
7713 " use -soundhw ? to get the list of supported cards\n"
7714 " use -soundhw all to enable all of them\n"
7715 #endif
7716 "-localtime set the real time clock to local time [default=utc]\n"
7717 "-full-screen start in full screen\n"
7718 #ifdef TARGET_I386
7719 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7720 #endif
7721 "-usb enable the USB driver (will be the default soon)\n"
7722 "-usbdevice name add the host or guest USB device 'name'\n"
7723 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7724 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7725 #endif
7726 "-name string set the name of the guest\n"
7727 "\n"
7728 "Network options:\n"
7729 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7730 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7731 #ifdef CONFIG_SLIRP
7732 "-net user[,vlan=n][,hostname=host]\n"
7733 " connect the user mode network stack to VLAN 'n' and send\n"
7734 " hostname 'host' to DHCP clients\n"
7735 #endif
7736 #ifdef _WIN32
7737 "-net tap[,vlan=n],ifname=name\n"
7738 " connect the host TAP network interface to VLAN 'n'\n"
7739 #else
7740 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7741 " connect the host TAP network interface to VLAN 'n' and use the\n"
7742 " network scripts 'file' (default=%s)\n"
7743 " and 'dfile' (default=%s);\n"
7744 " use '[down]script=no' to disable script execution;\n"
7745 " use 'fd=h' to connect to an already opened TAP interface\n"
7746 #endif
7747 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7748 " connect the vlan 'n' to another VLAN using a socket connection\n"
7749 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7750 " connect the vlan 'n' to multicast maddr and port\n"
7751 "-net none use it alone to have zero network devices; if no -net option\n"
7752 " is provided, the default is '-net nic -net user'\n"
7753 "\n"
7754 #ifdef CONFIG_SLIRP
7755 "-tftp dir allow tftp access to files in dir [-net user]\n"
7756 "-bootp file advertise file in BOOTP replies\n"
7757 #ifndef _WIN32
7758 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7759 #endif
7760 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7761 " redirect TCP or UDP connections from host to guest [-net user]\n"
7762 #endif
7763 "\n"
7764 "Linux boot specific:\n"
7765 "-kernel bzImage use 'bzImage' as kernel image\n"
7766 "-append cmdline use 'cmdline' as kernel command line\n"
7767 "-initrd file use 'file' as initial ram disk\n"
7768 "\n"
7769 "Debug/Expert options:\n"
7770 "-monitor dev redirect the monitor to char device 'dev'\n"
7771 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
7772 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
7773 "-serial dev redirect the serial port to char device 'dev'\n"
7774 "-parallel dev redirect the parallel port to char device 'dev'\n"
7775 "-pidfile file Write PID to 'file'\n"
7776 "-S freeze CPU at startup (use 'c' to start execution)\n"
7777 "-s wait gdb connection to port\n"
7778 "-p port set gdb connection port [default=%s]\n"
7779 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7780 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7781 " translation (t=none or lba) (usually qemu can guess them)\n"
7782 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7783 #ifdef USE_KQEMU
7784 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7785 "-no-kqemu disable KQEMU kernel module usage\n"
7786 #endif
7787 #ifdef USE_KVM
7788 #ifndef NO_CPU_EMULATION
7789 "-no-kvm disable KVM hardware virtualization\n"
7790 #endif
7791 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
7792 "-no-kvm-pit disable KVM kernel mode PIT\n"
7793 #endif
7794 #ifdef TARGET_I386
7795 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7796 " (default is CL-GD5446 PCI VGA)\n"
7797 "-no-acpi disable ACPI\n"
7798 #endif
7799 #ifdef CONFIG_CURSES
7800 "-curses use a curses/ncurses interface instead of SDL\n"
7801 #endif
7802 "-no-reboot exit instead of rebooting\n"
7803 "-no-shutdown stop before shutdown\n"
7804 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7805 "-vnc display start a VNC server on display\n"
7806 #ifndef _WIN32
7807 "-daemonize daemonize QEMU after initializing\n"
7808 #endif
7809 "-tdf inject timer interrupts that got lost\n"
7810 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
7811 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
7812 "-option-rom rom load a file, rom, into the option ROM space\n"
7813 #ifdef TARGET_SPARC
7814 "-prom-env variable=value set OpenBIOS nvram variables\n"
7815 #endif
7816 "-clock force the use of the given methods for timer alarm.\n"
7817 " To see what timers are available use -clock ?\n"
7818 "-startdate select initial date of the clock\n"
7819 "\n"
7820 "During emulation, the following keys are useful:\n"
7821 "ctrl-alt-f toggle full screen\n"
7822 "ctrl-alt-n switch to virtual console 'n'\n"
7823 "ctrl-alt toggle mouse and keyboard grab\n"
7824 "\n"
7825 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7827 "qemu",
7828 DEFAULT_RAM_SIZE,
7829 #ifndef _WIN32
7830 DEFAULT_NETWORK_SCRIPT,
7831 DEFAULT_NETWORK_DOWN_SCRIPT,
7832 #endif
7833 DEFAULT_GDBSTUB_PORT,
7834 "/tmp/qemu.log");
7835 exit(exitcode);
7838 #define HAS_ARG 0x0001
7840 enum {
7841 QEMU_OPTION_h,
7843 QEMU_OPTION_M,
7844 QEMU_OPTION_cpu,
7845 QEMU_OPTION_fda,
7846 QEMU_OPTION_fdb,
7847 QEMU_OPTION_hda,
7848 QEMU_OPTION_hdb,
7849 QEMU_OPTION_hdc,
7850 QEMU_OPTION_hdd,
7851 QEMU_OPTION_drive,
7852 QEMU_OPTION_cdrom,
7853 QEMU_OPTION_mtdblock,
7854 QEMU_OPTION_sd,
7855 QEMU_OPTION_pflash,
7856 QEMU_OPTION_boot,
7857 QEMU_OPTION_snapshot,
7858 #ifdef TARGET_I386
7859 QEMU_OPTION_no_fd_bootchk,
7860 #endif
7861 QEMU_OPTION_m,
7862 QEMU_OPTION_nographic,
7863 QEMU_OPTION_portrait,
7864 #ifdef HAS_AUDIO
7865 QEMU_OPTION_audio_help,
7866 QEMU_OPTION_soundhw,
7867 #endif
7869 QEMU_OPTION_net,
7870 QEMU_OPTION_tftp,
7871 QEMU_OPTION_bootp,
7872 QEMU_OPTION_smb,
7873 QEMU_OPTION_redir,
7875 QEMU_OPTION_kernel,
7876 QEMU_OPTION_append,
7877 QEMU_OPTION_initrd,
7879 QEMU_OPTION_S,
7880 QEMU_OPTION_s,
7881 QEMU_OPTION_p,
7882 QEMU_OPTION_d,
7883 QEMU_OPTION_hdachs,
7884 QEMU_OPTION_L,
7885 QEMU_OPTION_bios,
7886 QEMU_OPTION_no_code_copy,
7887 QEMU_OPTION_k,
7888 QEMU_OPTION_localtime,
7889 QEMU_OPTION_cirrusvga,
7890 QEMU_OPTION_vmsvga,
7891 QEMU_OPTION_g,
7892 QEMU_OPTION_std_vga,
7893 QEMU_OPTION_echr,
7894 QEMU_OPTION_monitor,
7895 QEMU_OPTION_balloon,
7896 QEMU_OPTION_vmchannel,
7897 QEMU_OPTION_serial,
7898 QEMU_OPTION_parallel,
7899 QEMU_OPTION_loadvm,
7900 QEMU_OPTION_full_screen,
7901 QEMU_OPTION_no_frame,
7902 QEMU_OPTION_alt_grab,
7903 QEMU_OPTION_no_quit,
7904 QEMU_OPTION_pidfile,
7905 QEMU_OPTION_no_kqemu,
7906 QEMU_OPTION_kernel_kqemu,
7907 QEMU_OPTION_win2k_hack,
7908 QEMU_OPTION_usb,
7909 QEMU_OPTION_usbdevice,
7910 QEMU_OPTION_smp,
7911 QEMU_OPTION_vnc,
7912 QEMU_OPTION_no_acpi,
7913 QEMU_OPTION_curses,
7914 QEMU_OPTION_no_kvm,
7915 QEMU_OPTION_no_kvm_irqchip,
7916 QEMU_OPTION_no_kvm_pit,
7917 QEMU_OPTION_no_reboot,
7918 QEMU_OPTION_no_shutdown,
7919 QEMU_OPTION_show_cursor,
7920 QEMU_OPTION_daemonize,
7921 QEMU_OPTION_option_rom,
7922 QEMU_OPTION_semihosting,
7923 QEMU_OPTION_cpu_vendor,
7924 QEMU_OPTION_name,
7925 QEMU_OPTION_prom_env,
7926 QEMU_OPTION_old_param,
7927 QEMU_OPTION_clock,
7928 QEMU_OPTION_startdate,
7929 QEMU_OPTION_translation,
7930 QEMU_OPTION_incoming,
7931 QEMU_OPTION_tdf,
7932 QEMU_OPTION_kvm_shadow_memory,
7933 QEMU_OPTION_mempath,
7936 typedef struct QEMUOption {
7937 const char *name;
7938 int flags;
7939 int index;
7940 } QEMUOption;
7942 const QEMUOption qemu_options[] = {
7943 { "h", 0, QEMU_OPTION_h },
7944 { "help", 0, QEMU_OPTION_h },
7946 { "M", HAS_ARG, QEMU_OPTION_M },
7947 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7948 { "fda", HAS_ARG, QEMU_OPTION_fda },
7949 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7950 { "hda", HAS_ARG, QEMU_OPTION_hda },
7951 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7952 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7953 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7954 { "drive", HAS_ARG, QEMU_OPTION_drive },
7955 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7956 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7957 { "sd", HAS_ARG, QEMU_OPTION_sd },
7958 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7959 { "boot", HAS_ARG, QEMU_OPTION_boot },
7960 { "snapshot", 0, QEMU_OPTION_snapshot },
7961 #ifdef TARGET_I386
7962 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7963 #endif
7964 { "m", HAS_ARG, QEMU_OPTION_m },
7965 { "nographic", 0, QEMU_OPTION_nographic },
7966 { "portrait", 0, QEMU_OPTION_portrait },
7967 { "k", HAS_ARG, QEMU_OPTION_k },
7968 #ifdef HAS_AUDIO
7969 { "audio-help", 0, QEMU_OPTION_audio_help },
7970 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7971 #endif
7973 { "net", HAS_ARG, QEMU_OPTION_net},
7974 #ifdef CONFIG_SLIRP
7975 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7976 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7977 #ifndef _WIN32
7978 { "smb", HAS_ARG, QEMU_OPTION_smb },
7979 #endif
7980 { "redir", HAS_ARG, QEMU_OPTION_redir },
7981 #endif
7983 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7984 { "append", HAS_ARG, QEMU_OPTION_append },
7985 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7987 { "S", 0, QEMU_OPTION_S },
7988 { "s", 0, QEMU_OPTION_s },
7989 { "p", HAS_ARG, QEMU_OPTION_p },
7990 { "d", HAS_ARG, QEMU_OPTION_d },
7991 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7992 { "L", HAS_ARG, QEMU_OPTION_L },
7993 { "bios", HAS_ARG, QEMU_OPTION_bios },
7994 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7995 #ifdef USE_KQEMU
7996 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7997 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7998 #endif
7999 #ifdef USE_KVM
8000 #ifndef NO_CPU_EMULATION
8001 { "no-kvm", 0, QEMU_OPTION_no_kvm },
8002 #endif
8003 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
8004 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
8005 #endif
8006 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8007 { "g", 1, QEMU_OPTION_g },
8008 #endif
8009 { "localtime", 0, QEMU_OPTION_localtime },
8010 { "std-vga", 0, QEMU_OPTION_std_vga },
8011 { "monitor", 1, QEMU_OPTION_monitor },
8012 { "balloon", 1, QEMU_OPTION_balloon },
8013 { "vmchannel", 1, QEMU_OPTION_vmchannel },
8014 { "echr", HAS_ARG, QEMU_OPTION_echr },
8015 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8016 { "serial", HAS_ARG, QEMU_OPTION_serial },
8017 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8018 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8019 { "incoming", 1, QEMU_OPTION_incoming },
8020 { "full-screen", 0, QEMU_OPTION_full_screen },
8021 #ifdef CONFIG_SDL
8022 { "no-frame", 0, QEMU_OPTION_no_frame },
8023 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8024 { "no-quit", 0, QEMU_OPTION_no_quit },
8025 #endif
8026 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8027 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8028 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8029 { "smp", HAS_ARG, QEMU_OPTION_smp },
8030 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8031 #ifdef CONFIG_CURSES
8032 { "curses", 0, QEMU_OPTION_curses },
8033 #endif
8035 /* temporary options */
8036 { "usb", 0, QEMU_OPTION_usb },
8037 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8038 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8039 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8040 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8041 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8042 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8043 { "daemonize", 0, QEMU_OPTION_daemonize },
8044 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8045 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8046 { "semihosting", 0, QEMU_OPTION_semihosting },
8047 #endif
8048 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
8049 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
8050 { "name", HAS_ARG, QEMU_OPTION_name },
8051 #if defined(TARGET_SPARC)
8052 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8053 #endif
8054 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
8055 #if defined(TARGET_ARM)
8056 { "old-param", 0, QEMU_OPTION_old_param },
8057 #endif
8058 { "clock", HAS_ARG, QEMU_OPTION_clock },
8059 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8060 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
8061 { NULL },
8064 /* password input */
8066 int qemu_key_check(BlockDriverState *bs, const char *name)
8068 char password[256];
8069 int i;
8071 if (!bdrv_is_encrypted(bs))
8072 return 0;
8074 term_printf("%s is encrypted.\n", name);
8075 for(i = 0; i < 3; i++) {
8076 monitor_readline("Password: ", 1, password, sizeof(password));
8077 if (bdrv_set_key(bs, password) == 0)
8078 return 0;
8079 term_printf("invalid password\n");
8081 return -EPERM;
8084 static BlockDriverState *get_bdrv(int index)
8086 if (index > nb_drives)
8087 return NULL;
8088 return drives_table[index].bdrv;
8091 static void read_passwords(void)
8093 BlockDriverState *bs;
8094 int i;
8096 for(i = 0; i < 6; i++) {
8097 bs = get_bdrv(i);
8098 if (bs)
8099 qemu_key_check(bs, bdrv_get_device_name(bs));
8103 #ifdef HAS_AUDIO
8104 struct soundhw soundhw[] = {
8105 #ifdef HAS_AUDIO_CHOICE
8106 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8108 "pcspk",
8109 "PC speaker",
8112 { .init_isa = pcspk_audio_init }
8114 #endif
8116 "sb16",
8117 "Creative Sound Blaster 16",
8120 { .init_isa = SB16_init }
8123 #ifdef CONFIG_ADLIB
8125 "adlib",
8126 #ifdef HAS_YMF262
8127 "Yamaha YMF262 (OPL3)",
8128 #else
8129 "Yamaha YM3812 (OPL2)",
8130 #endif
8133 { .init_isa = Adlib_init }
8135 #endif
8137 #ifdef CONFIG_GUS
8139 "gus",
8140 "Gravis Ultrasound GF1",
8143 { .init_isa = GUS_init }
8145 #endif
8147 #ifdef CONFIG_AC97
8149 "ac97",
8150 "Intel 82801AA AC97 Audio",
8153 { .init_pci = ac97_init }
8155 #endif
8158 "es1370",
8159 "ENSONIQ AudioPCI ES1370",
8162 { .init_pci = es1370_init }
8164 #endif
8166 { NULL, NULL, 0, 0, { NULL } }
8169 static void select_soundhw (const char *optarg)
8171 struct soundhw *c;
8173 if (*optarg == '?') {
8174 show_valid_cards:
8176 printf ("Valid sound card names (comma separated):\n");
8177 for (c = soundhw; c->name; ++c) {
8178 printf ("%-11s %s\n", c->name, c->descr);
8180 printf ("\n-soundhw all will enable all of the above\n");
8181 exit (*optarg != '?');
8183 else {
8184 size_t l;
8185 const char *p;
8186 char *e;
8187 int bad_card = 0;
8189 if (!strcmp (optarg, "all")) {
8190 for (c = soundhw; c->name; ++c) {
8191 c->enabled = 1;
8193 return;
8196 p = optarg;
8197 while (*p) {
8198 e = strchr (p, ',');
8199 l = !e ? strlen (p) : (size_t) (e - p);
8201 for (c = soundhw; c->name; ++c) {
8202 if (!strncmp (c->name, p, l)) {
8203 c->enabled = 1;
8204 break;
8208 if (!c->name) {
8209 if (l > 80) {
8210 fprintf (stderr,
8211 "Unknown sound card name (too big to show)\n");
8213 else {
8214 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8215 (int) l, p);
8217 bad_card = 1;
8219 p += l + (e != NULL);
8222 if (bad_card)
8223 goto show_valid_cards;
8226 #endif
8228 #ifdef _WIN32
8229 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8231 exit(STATUS_CONTROL_C_EXIT);
8232 return TRUE;
8234 #endif
8236 #define MAX_NET_CLIENTS 32
8238 static int saved_argc;
8239 static char **saved_argv;
8241 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8243 *argc = saved_argc;
8244 *argv = saved_argv;
8245 *opt_daemonize = daemonize;
8246 *opt_incoming = incoming;
8250 static int gethugepagesize(void)
8252 int ret, fd;
8253 char buf[4096];
8254 char *needle = "Hugepagesize:";
8255 char *size;
8256 unsigned long hugepagesize;
8258 fd = open("/proc/meminfo", O_RDONLY);
8259 if (fd < 0) {
8260 perror("open");
8261 exit(0);
8264 ret = read(fd, buf, sizeof(buf));
8265 if (ret < 0) {
8266 perror("read");
8267 exit(0);
8270 size = strstr(buf, needle);
8271 if (!size)
8272 return 0;
8273 size += strlen(needle);
8274 hugepagesize = strtol(size, NULL, 0);
8275 return hugepagesize;
8278 void *alloc_mem_area(unsigned long memory, const char *path)
8280 char *filename;
8281 void *area;
8282 int fd;
8284 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8285 return NULL;
8287 hpagesize = gethugepagesize() * 1024;
8288 if (!hpagesize)
8289 return NULL;
8291 fd = mkstemp(filename);
8292 if (fd < 0) {
8293 perror("mkstemp");
8294 free(filename);
8295 return NULL;
8297 unlink(filename);
8298 free(filename);
8300 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8303 * ftruncate is not supported by hugetlbfs in older
8304 * hosts, so don't bother checking for errors.
8305 * If anything goes wrong with it under other filesystems,
8306 * mmap will fail.
8308 ftruncate(fd, memory);
8310 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8311 if (area == MAP_FAILED) {
8312 perror("mmap");
8313 close(fd);
8314 return NULL;
8317 return area;
8320 void *qemu_alloc_physram(unsigned long memory)
8322 void *area = NULL;
8324 if (mem_path)
8325 area = alloc_mem_area(memory, mem_path);
8326 if (!area)
8327 area = qemu_vmalloc(memory);
8329 return area;
8332 int main(int argc, char **argv)
8334 #ifdef CONFIG_GDBSTUB
8335 int use_gdbstub;
8336 const char *gdbstub_port;
8337 #endif
8338 uint32_t boot_devices_bitmap = 0;
8339 int i;
8340 int snapshot, linux_boot, net_boot;
8341 const char *initrd_filename;
8342 const char *kernel_filename, *kernel_cmdline;
8343 const char *boot_devices = "";
8344 DisplayState *ds = &display_state;
8345 int cyls, heads, secs, translation;
8346 const char *net_clients[MAX_NET_CLIENTS];
8347 int nb_net_clients;
8348 int hda_index;
8349 int optind;
8350 const char *r, *optarg;
8351 CharDriverState *monitor_hd;
8352 const char *monitor_device;
8353 const char *serial_devices[MAX_SERIAL_PORTS];
8354 int serial_device_index;
8355 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8356 int vmchannel_device_index;
8357 const char *parallel_devices[MAX_PARALLEL_PORTS];
8358 int parallel_device_index;
8359 const char *loadvm = NULL;
8360 QEMUMachine *machine;
8361 const char *cpu_model;
8362 const char *usb_devices[MAX_USB_CMDLINE];
8363 int usb_devices_index;
8364 int fds[2];
8365 const char *pid_file = NULL;
8366 VLANState *vlan;
8368 saved_argc = argc;
8369 saved_argv = argv;
8371 LIST_INIT (&vm_change_state_head);
8372 #ifndef _WIN32
8374 struct sigaction act;
8375 sigfillset(&act.sa_mask);
8376 act.sa_flags = 0;
8377 act.sa_handler = SIG_IGN;
8378 sigaction(SIGPIPE, &act, NULL);
8380 #else
8381 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8382 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8383 QEMU to run on a single CPU */
8385 HANDLE h;
8386 DWORD mask, smask;
8387 int i;
8388 h = GetCurrentProcess();
8389 if (GetProcessAffinityMask(h, &mask, &smask)) {
8390 for(i = 0; i < 32; i++) {
8391 if (mask & (1 << i))
8392 break;
8394 if (i != 32) {
8395 mask = 1 << i;
8396 SetProcessAffinityMask(h, mask);
8400 #endif
8402 register_machines();
8403 machine = first_machine;
8404 cpu_model = NULL;
8405 initrd_filename = NULL;
8406 ram_size = 0;
8407 vga_ram_size = VGA_RAM_SIZE;
8408 #ifdef CONFIG_GDBSTUB
8409 use_gdbstub = 0;
8410 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8411 #endif
8412 snapshot = 0;
8413 nographic = 0;
8414 curses = 0;
8415 kernel_filename = NULL;
8416 kernel_cmdline = "";
8417 cyls = heads = secs = 0;
8418 translation = BIOS_ATA_TRANSLATION_AUTO;
8419 monitor_device = "vc:800x600";
8421 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8422 vmchannel_devices[i][0] = '\0';
8423 vmchannel_device_index = 0;
8425 serial_devices[0] = "vc:80Cx24C";
8426 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8427 serial_devices[i] = NULL;
8428 serial_device_index = 0;
8430 parallel_devices[0] = "vc:640x480";
8431 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8432 parallel_devices[i] = NULL;
8433 parallel_device_index = 0;
8435 usb_devices_index = 0;
8437 nb_net_clients = 0;
8438 nb_drives = 0;
8439 nb_drives_opt = 0;
8440 hda_index = -1;
8442 nb_nics = 0;
8443 /* default mac address of the first network interface */
8445 optind = 1;
8446 for(;;) {
8447 if (optind >= argc)
8448 break;
8449 r = argv[optind];
8450 if (r[0] != '-') {
8451 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8452 } else {
8453 const QEMUOption *popt;
8455 optind++;
8456 /* Treat --foo the same as -foo. */
8457 if (r[1] == '-')
8458 r++;
8459 popt = qemu_options;
8460 for(;;) {
8461 if (!popt->name) {
8462 fprintf(stderr, "%s: invalid option -- '%s'\n",
8463 argv[0], r);
8464 exit(1);
8466 if (!strcmp(popt->name, r + 1))
8467 break;
8468 popt++;
8470 if (popt->flags & HAS_ARG) {
8471 if (optind >= argc) {
8472 fprintf(stderr, "%s: option '%s' requires an argument\n",
8473 argv[0], r);
8474 exit(1);
8476 optarg = argv[optind++];
8477 } else {
8478 optarg = NULL;
8481 switch(popt->index) {
8482 case QEMU_OPTION_M:
8483 machine = find_machine(optarg);
8484 if (!machine) {
8485 QEMUMachine *m;
8486 printf("Supported machines are:\n");
8487 for(m = first_machine; m != NULL; m = m->next) {
8488 printf("%-10s %s%s\n",
8489 m->name, m->desc,
8490 m == first_machine ? " (default)" : "");
8492 exit(*optarg != '?');
8494 break;
8495 case QEMU_OPTION_cpu:
8496 /* hw initialization will check this */
8497 if (*optarg == '?') {
8498 /* XXX: implement xxx_cpu_list for targets that still miss it */
8499 #if defined(cpu_list)
8500 cpu_list(stdout, &fprintf);
8501 #endif
8502 exit(0);
8503 } else {
8504 cpu_model = optarg;
8506 break;
8507 case QEMU_OPTION_initrd:
8508 initrd_filename = optarg;
8509 break;
8510 case QEMU_OPTION_hda:
8511 if (cyls == 0)
8512 hda_index = drive_add(optarg, HD_ALIAS, 0);
8513 else
8514 hda_index = drive_add(optarg, HD_ALIAS
8515 ",cyls=%d,heads=%d,secs=%d%s",
8516 0, cyls, heads, secs,
8517 translation == BIOS_ATA_TRANSLATION_LBA ?
8518 ",trans=lba" :
8519 translation == BIOS_ATA_TRANSLATION_NONE ?
8520 ",trans=none" : "");
8521 break;
8522 case QEMU_OPTION_hdb:
8523 case QEMU_OPTION_hdc:
8524 case QEMU_OPTION_hdd:
8525 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8526 break;
8527 case QEMU_OPTION_drive:
8528 drive_add(NULL, "%s", optarg);
8529 break;
8530 case QEMU_OPTION_mtdblock:
8531 drive_add(optarg, MTD_ALIAS);
8532 break;
8533 case QEMU_OPTION_sd:
8534 drive_add(optarg, SD_ALIAS);
8535 break;
8536 case QEMU_OPTION_pflash:
8537 drive_add(optarg, PFLASH_ALIAS);
8538 break;
8539 case QEMU_OPTION_snapshot:
8540 snapshot = 1;
8541 break;
8542 case QEMU_OPTION_hdachs:
8544 const char *p;
8545 p = optarg;
8546 cyls = strtol(p, (char **)&p, 0);
8547 if (cyls < 1 || cyls > 16383)
8548 goto chs_fail;
8549 if (*p != ',')
8550 goto chs_fail;
8551 p++;
8552 heads = strtol(p, (char **)&p, 0);
8553 if (heads < 1 || heads > 16)
8554 goto chs_fail;
8555 if (*p != ',')
8556 goto chs_fail;
8557 p++;
8558 secs = strtol(p, (char **)&p, 0);
8559 if (secs < 1 || secs > 63)
8560 goto chs_fail;
8561 if (*p == ',') {
8562 p++;
8563 if (!strcmp(p, "none"))
8564 translation = BIOS_ATA_TRANSLATION_NONE;
8565 else if (!strcmp(p, "lba"))
8566 translation = BIOS_ATA_TRANSLATION_LBA;
8567 else if (!strcmp(p, "auto"))
8568 translation = BIOS_ATA_TRANSLATION_AUTO;
8569 else
8570 goto chs_fail;
8571 } else if (*p != '\0') {
8572 chs_fail:
8573 fprintf(stderr, "qemu: invalid physical CHS format\n");
8574 exit(1);
8576 if (hda_index != -1)
8577 snprintf(drives_opt[hda_index].opt,
8578 sizeof(drives_opt[hda_index].opt),
8579 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8580 0, cyls, heads, secs,
8581 translation == BIOS_ATA_TRANSLATION_LBA ?
8582 ",trans=lba" :
8583 translation == BIOS_ATA_TRANSLATION_NONE ?
8584 ",trans=none" : "");
8586 break;
8587 case QEMU_OPTION_nographic:
8588 serial_devices[0] = "stdio";
8589 parallel_devices[0] = "null";
8590 monitor_device = "stdio";
8591 nographic = 1;
8592 break;
8593 #ifdef CONFIG_CURSES
8594 case QEMU_OPTION_curses:
8595 curses = 1;
8596 break;
8597 #endif
8598 case QEMU_OPTION_portrait:
8599 graphic_rotate = 1;
8600 break;
8601 case QEMU_OPTION_kernel:
8602 kernel_filename = optarg;
8603 break;
8604 case QEMU_OPTION_append:
8605 kernel_cmdline = optarg;
8606 break;
8607 case QEMU_OPTION_cdrom:
8608 drive_add(optarg, CDROM_ALIAS);
8609 break;
8610 case QEMU_OPTION_boot:
8611 boot_devices = optarg;
8612 /* We just do some generic consistency checks */
8614 /* Could easily be extended to 64 devices if needed */
8615 const char *p;
8617 boot_devices_bitmap = 0;
8618 for (p = boot_devices; *p != '\0'; p++) {
8619 /* Allowed boot devices are:
8620 * a b : floppy disk drives
8621 * c ... f : IDE disk drives
8622 * g ... m : machine implementation dependant drives
8623 * n ... p : network devices
8624 * It's up to each machine implementation to check
8625 * if the given boot devices match the actual hardware
8626 * implementation and firmware features.
8628 if (*p < 'a' || *p > 'q') {
8629 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8630 exit(1);
8632 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8633 fprintf(stderr,
8634 "Boot device '%c' was given twice\n",*p);
8635 exit(1);
8637 boot_devices_bitmap |= 1 << (*p - 'a');
8640 break;
8641 case QEMU_OPTION_fda:
8642 case QEMU_OPTION_fdb:
8643 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8644 break;
8645 #ifdef TARGET_I386
8646 case QEMU_OPTION_no_fd_bootchk:
8647 fd_bootchk = 0;
8648 break;
8649 #endif
8650 case QEMU_OPTION_no_code_copy:
8651 code_copy_enabled = 0;
8652 break;
8653 case QEMU_OPTION_net:
8654 if (nb_net_clients >= MAX_NET_CLIENTS) {
8655 fprintf(stderr, "qemu: too many network clients\n");
8656 exit(1);
8658 net_clients[nb_net_clients] = optarg;
8659 nb_net_clients++;
8660 break;
8661 #ifdef CONFIG_SLIRP
8662 case QEMU_OPTION_tftp:
8663 tftp_prefix = optarg;
8664 break;
8665 case QEMU_OPTION_bootp:
8666 bootp_filename = optarg;
8667 break;
8668 #ifndef _WIN32
8669 case QEMU_OPTION_smb:
8670 net_slirp_smb(optarg);
8671 break;
8672 #endif
8673 case QEMU_OPTION_redir:
8674 net_slirp_redir(optarg);
8675 break;
8676 #endif
8677 #ifdef HAS_AUDIO
8678 case QEMU_OPTION_audio_help:
8679 AUD_help ();
8680 exit (0);
8681 break;
8682 case QEMU_OPTION_soundhw:
8683 select_soundhw (optarg);
8684 break;
8685 #endif
8686 case QEMU_OPTION_h:
8687 help(0);
8688 break;
8689 case QEMU_OPTION_m: {
8690 uint64_t value;
8691 char *ptr;
8693 value = strtoul(optarg, &ptr, 10);
8694 switch (*ptr) {
8695 case 0: case 'M': case 'm':
8696 value <<= 20;
8697 break;
8698 case 'G': case 'g':
8699 value <<= 30;
8700 break;
8701 default:
8702 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8703 exit(1);
8706 /* On 32-bit hosts, QEMU is limited by virtual address space */
8707 if (value > (2047 << 20)
8708 #ifndef USE_KQEMU
8709 && HOST_LONG_BITS == 32
8710 #endif
8712 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8713 exit(1);
8715 if (value != (uint64_t)(ram_addr_t)value) {
8716 fprintf(stderr, "qemu: ram size too large\n");
8717 exit(1);
8719 ram_size = value;
8720 break;
8722 case QEMU_OPTION_d:
8724 int mask;
8725 CPULogItem *item;
8727 mask = cpu_str_to_log_mask(optarg);
8728 if (!mask) {
8729 printf("Log items (comma separated):\n");
8730 for(item = cpu_log_items; item->mask != 0; item++) {
8731 printf("%-10s %s\n", item->name, item->help);
8733 exit(1);
8735 cpu_set_log(mask);
8737 break;
8738 #ifdef CONFIG_GDBSTUB
8739 case QEMU_OPTION_s:
8740 use_gdbstub = 1;
8741 break;
8742 case QEMU_OPTION_p:
8743 gdbstub_port = optarg;
8744 break;
8745 #endif
8746 case QEMU_OPTION_L:
8747 bios_dir = optarg;
8748 break;
8749 case QEMU_OPTION_bios:
8750 bios_name = optarg;
8751 break;
8752 case QEMU_OPTION_S:
8753 autostart = 0;
8754 break;
8755 case QEMU_OPTION_k:
8756 keyboard_layout = optarg;
8757 break;
8758 case QEMU_OPTION_localtime:
8759 rtc_utc = 0;
8760 break;
8761 case QEMU_OPTION_cirrusvga:
8762 cirrus_vga_enabled = 1;
8763 vmsvga_enabled = 0;
8764 break;
8765 case QEMU_OPTION_vmsvga:
8766 cirrus_vga_enabled = 0;
8767 vmsvga_enabled = 1;
8768 break;
8769 case QEMU_OPTION_std_vga:
8770 cirrus_vga_enabled = 0;
8771 vmsvga_enabled = 0;
8772 break;
8773 case QEMU_OPTION_g:
8775 const char *p;
8776 int w, h, depth;
8777 p = optarg;
8778 w = strtol(p, (char **)&p, 10);
8779 if (w <= 0) {
8780 graphic_error:
8781 fprintf(stderr, "qemu: invalid resolution or depth\n");
8782 exit(1);
8784 if (*p != 'x')
8785 goto graphic_error;
8786 p++;
8787 h = strtol(p, (char **)&p, 10);
8788 if (h <= 0)
8789 goto graphic_error;
8790 if (*p == 'x') {
8791 p++;
8792 depth = strtol(p, (char **)&p, 10);
8793 if (depth != 8 && depth != 15 && depth != 16 &&
8794 depth != 24 && depth != 32)
8795 goto graphic_error;
8796 } else if (*p == '\0') {
8797 depth = graphic_depth;
8798 } else {
8799 goto graphic_error;
8802 graphic_width = w;
8803 graphic_height = h;
8804 graphic_depth = depth;
8806 break;
8807 case QEMU_OPTION_echr:
8809 char *r;
8810 term_escape_char = strtol(optarg, &r, 0);
8811 if (r == optarg)
8812 printf("Bad argument to echr\n");
8813 break;
8815 case QEMU_OPTION_monitor:
8816 monitor_device = optarg;
8817 break;
8818 case QEMU_OPTION_balloon:
8819 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8820 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8821 exit(1);
8823 if (balloon_used) {
8824 fprintf(stderr, "qemu: only one balloon device can be used\n");
8825 exit(1);
8827 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
8828 vmchannel_device_index++;
8829 balloon_used = 1;
8830 break;
8831 case QEMU_OPTION_vmchannel:
8832 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8833 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8834 exit(1);
8836 pstrcpy(vmchannel_devices[vmchannel_device_index],
8837 sizeof(vmchannel_devices[0]), optarg);
8838 vmchannel_device_index++;
8839 break;
8840 case QEMU_OPTION_serial:
8841 if (serial_device_index >= MAX_SERIAL_PORTS) {
8842 fprintf(stderr, "qemu: too many serial ports\n");
8843 exit(1);
8845 serial_devices[serial_device_index] = optarg;
8846 serial_device_index++;
8847 break;
8848 case QEMU_OPTION_parallel:
8849 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8850 fprintf(stderr, "qemu: too many parallel ports\n");
8851 exit(1);
8853 parallel_devices[parallel_device_index] = optarg;
8854 parallel_device_index++;
8855 break;
8856 case QEMU_OPTION_loadvm:
8857 loadvm = optarg;
8858 break;
8859 case QEMU_OPTION_incoming:
8860 incoming = optarg;
8861 break;
8862 case QEMU_OPTION_full_screen:
8863 full_screen = 1;
8864 break;
8865 #ifdef CONFIG_SDL
8866 case QEMU_OPTION_no_frame:
8867 no_frame = 1;
8868 break;
8869 case QEMU_OPTION_alt_grab:
8870 alt_grab = 1;
8871 break;
8872 case QEMU_OPTION_no_quit:
8873 no_quit = 1;
8874 break;
8875 #endif
8876 case QEMU_OPTION_pidfile:
8877 pid_file = optarg;
8878 break;
8879 #ifdef TARGET_I386
8880 case QEMU_OPTION_win2k_hack:
8881 win2k_install_hack = 1;
8882 break;
8883 #endif
8884 #ifdef USE_KQEMU
8885 case QEMU_OPTION_no_kqemu:
8886 kqemu_allowed = 0;
8887 break;
8888 case QEMU_OPTION_kernel_kqemu:
8889 kqemu_allowed = 2;
8890 break;
8891 #endif
8892 #ifdef USE_KVM
8893 case QEMU_OPTION_no_kvm:
8894 kvm_allowed = 0;
8895 break;
8896 case QEMU_OPTION_no_kvm_irqchip: {
8897 extern int kvm_irqchip, kvm_pit;
8898 kvm_irqchip = 0;
8899 kvm_pit = 0;
8900 break;
8902 case QEMU_OPTION_no_kvm_pit: {
8903 extern int kvm_pit;
8904 kvm_pit = 0;
8905 break;
8907 #endif
8908 case QEMU_OPTION_usb:
8909 usb_enabled = 1;
8910 break;
8911 case QEMU_OPTION_usbdevice:
8912 usb_enabled = 1;
8913 if (usb_devices_index >= MAX_USB_CMDLINE) {
8914 fprintf(stderr, "Too many USB devices\n");
8915 exit(1);
8917 usb_devices[usb_devices_index] = optarg;
8918 usb_devices_index++;
8919 break;
8920 case QEMU_OPTION_smp:
8921 smp_cpus = atoi(optarg);
8922 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8923 fprintf(stderr, "Invalid number of CPUs\n");
8924 exit(1);
8926 break;
8927 case QEMU_OPTION_vnc:
8928 vnc_display = optarg;
8929 break;
8930 case QEMU_OPTION_no_acpi:
8931 acpi_enabled = 0;
8932 break;
8933 case QEMU_OPTION_no_reboot:
8934 no_reboot = 1;
8935 break;
8936 case QEMU_OPTION_no_shutdown:
8937 no_shutdown = 1;
8938 break;
8939 case QEMU_OPTION_show_cursor:
8940 cursor_hide = 0;
8941 break;
8942 case QEMU_OPTION_daemonize:
8943 daemonize = 1;
8944 break;
8945 case QEMU_OPTION_option_rom:
8946 if (nb_option_roms >= MAX_OPTION_ROMS) {
8947 fprintf(stderr, "Too many option ROMs\n");
8948 exit(1);
8950 option_rom[nb_option_roms] = optarg;
8951 nb_option_roms++;
8952 break;
8953 case QEMU_OPTION_semihosting:
8954 semihosting_enabled = 1;
8955 break;
8956 case QEMU_OPTION_tdf:
8957 time_drift_fix = 1;
8958 break;
8959 case QEMU_OPTION_kvm_shadow_memory:
8960 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
8961 break;
8962 case QEMU_OPTION_mempath:
8963 mem_path = optarg;
8964 break;
8965 case QEMU_OPTION_name:
8966 qemu_name = optarg;
8967 break;
8968 #ifdef TARGET_SPARC
8969 case QEMU_OPTION_prom_env:
8970 if (nb_prom_envs >= MAX_PROM_ENVS) {
8971 fprintf(stderr, "Too many prom variables\n");
8972 exit(1);
8974 prom_envs[nb_prom_envs] = optarg;
8975 nb_prom_envs++;
8976 break;
8977 #endif
8978 case QEMU_OPTION_cpu_vendor:
8979 cpu_vendor_string = optarg;
8980 break;
8981 #ifdef TARGET_ARM
8982 case QEMU_OPTION_old_param:
8983 old_param = 1;
8984 break;
8985 #endif
8986 case QEMU_OPTION_clock:
8987 configure_alarms(optarg);
8988 break;
8989 case QEMU_OPTION_startdate:
8991 struct tm tm;
8992 time_t rtc_start_date;
8993 if (!strcmp(optarg, "now")) {
8994 rtc_date_offset = -1;
8995 } else {
8996 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8997 &tm.tm_year,
8998 &tm.tm_mon,
8999 &tm.tm_mday,
9000 &tm.tm_hour,
9001 &tm.tm_min,
9002 &tm.tm_sec) == 6) {
9003 /* OK */
9004 } else if (sscanf(optarg, "%d-%d-%d",
9005 &tm.tm_year,
9006 &tm.tm_mon,
9007 &tm.tm_mday) == 3) {
9008 tm.tm_hour = 0;
9009 tm.tm_min = 0;
9010 tm.tm_sec = 0;
9011 } else {
9012 goto date_fail;
9014 tm.tm_year -= 1900;
9015 tm.tm_mon--;
9016 rtc_start_date = mktimegm(&tm);
9017 if (rtc_start_date == -1) {
9018 date_fail:
9019 fprintf(stderr, "Invalid date format. Valid format are:\n"
9020 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9021 exit(1);
9023 rtc_date_offset = time(NULL) - rtc_start_date;
9026 break;
9031 #ifndef _WIN32
9032 if (daemonize) {
9033 pid_t pid;
9035 if (pipe(fds) == -1)
9036 exit(1);
9038 pid = fork();
9039 if (pid > 0) {
9040 uint8_t status;
9041 ssize_t len;
9043 close(fds[1]);
9045 again:
9046 len = read(fds[0], &status, 1);
9047 if (len == -1 && (errno == EINTR))
9048 goto again;
9050 if (len != 1)
9051 exit(1);
9052 else if (status == 1) {
9053 fprintf(stderr, "Could not acquire pidfile\n");
9054 exit(1);
9055 } else
9056 exit(0);
9057 } else if (pid < 0)
9058 exit(1);
9060 setsid();
9062 pid = fork();
9063 if (pid > 0)
9064 exit(0);
9065 else if (pid < 0)
9066 exit(1);
9068 umask(027);
9070 signal(SIGTSTP, SIG_IGN);
9071 signal(SIGTTOU, SIG_IGN);
9072 signal(SIGTTIN, SIG_IGN);
9074 #endif
9076 #if USE_KVM
9077 if (kvm_enabled()) {
9078 if (kvm_qemu_init() < 0) {
9079 extern int kvm_allowed;
9080 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9081 #ifdef NO_CPU_EMULATION
9082 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9083 exit(1);
9084 #endif
9085 kvm_allowed = 0;
9088 #endif
9090 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9091 if (daemonize) {
9092 uint8_t status = 1;
9093 write(fds[1], &status, 1);
9094 } else
9095 fprintf(stderr, "Could not acquire pid file\n");
9096 exit(1);
9099 #ifdef USE_KQEMU
9100 if (smp_cpus > 1)
9101 kqemu_allowed = 0;
9102 #endif
9103 linux_boot = (kernel_filename != NULL);
9104 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9106 /* XXX: this should not be: some embedded targets just have flash */
9107 if (!linux_boot && net_boot == 0 &&
9108 nb_drives_opt == 0)
9109 help(1);
9111 /* boot to floppy or the default cd if no hard disk defined yet */
9112 if (!boot_devices[0]) {
9113 boot_devices = "cad";
9115 setvbuf(stdout, NULL, _IOLBF, 0);
9117 init_timers();
9118 init_timer_alarm();
9119 qemu_aio_init();
9121 #ifdef _WIN32
9122 socket_init();
9123 #endif
9125 /* init network clients */
9126 if (nb_net_clients == 0) {
9127 /* if no clients, we use a default config */
9128 net_clients[0] = "nic";
9129 net_clients[1] = "user";
9130 nb_net_clients = 2;
9133 for(i = 0;i < nb_net_clients; i++) {
9134 if (net_client_init(net_clients[i]) < 0)
9135 exit(1);
9137 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9138 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9139 continue;
9140 if (vlan->nb_guest_devs == 0) {
9141 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9142 exit(1);
9144 if (vlan->nb_host_devs == 0)
9145 fprintf(stderr,
9146 "Warning: vlan %d is not connected to host network\n",
9147 vlan->id);
9150 #ifdef TARGET_I386
9151 /* XXX: this should be moved in the PC machine instantiation code */
9152 if (net_boot != 0) {
9153 int netroms = 0;
9154 for (i = 0; i < nb_nics && i < 4; i++) {
9155 const char *model = nd_table[i].model;
9156 char buf[1024];
9157 if (net_boot & (1 << i)) {
9158 if (model == NULL)
9159 model = "rtl8139";
9160 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9161 if (get_image_size(buf) > 0) {
9162 if (nb_option_roms >= MAX_OPTION_ROMS) {
9163 fprintf(stderr, "Too many option ROMs\n");
9164 exit(1);
9166 option_rom[nb_option_roms] = strdup(buf);
9167 nb_option_roms++;
9168 netroms++;
9172 if (netroms == 0) {
9173 fprintf(stderr, "No valid PXE rom found for network device\n");
9174 exit(1);
9177 #endif
9179 /* init the memory */
9180 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9182 if (machine->ram_require & RAMSIZE_FIXED) {
9183 if (ram_size > 0) {
9184 if (ram_size < phys_ram_size) {
9185 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9186 machine->name, (unsigned long long) phys_ram_size);
9187 exit(-1);
9190 phys_ram_size = ram_size;
9191 } else
9192 ram_size = phys_ram_size;
9193 } else {
9194 if (ram_size == 0)
9195 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9197 phys_ram_size += ram_size;
9200 /* Initialize kvm */
9201 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9202 #define KVM_EXTRA_PAGES 3
9203 #else
9204 #define KVM_EXTRA_PAGES 0
9205 #endif
9206 if (kvm_enabled()) {
9207 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9208 if (kvm_qemu_create_context() < 0) {
9209 fprintf(stderr, "Could not create KVM context\n");
9210 exit(1);
9212 #ifdef KVM_CAP_USER_MEMORY
9214 int ret;
9216 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9217 if (ret) {
9218 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9219 if (!phys_ram_base) {
9220 fprintf(stderr, "Could not allocate physical memory\n");
9221 exit(1);
9225 #endif
9226 } else {
9227 phys_ram_base = qemu_vmalloc(phys_ram_size);
9228 if (!phys_ram_base) {
9229 fprintf(stderr, "Could not allocate physical memory\n");
9230 exit(1);
9234 bdrv_init();
9236 /* we always create the cdrom drive, even if no disk is there */
9238 if (nb_drives_opt < MAX_DRIVES)
9239 drive_add(NULL, CDROM_ALIAS);
9241 /* we always create at least one floppy */
9243 if (nb_drives_opt < MAX_DRIVES)
9244 drive_add(NULL, FD_ALIAS, 0);
9246 /* we always create one sd slot, even if no card is in it */
9248 if (nb_drives_opt < MAX_DRIVES)
9249 drive_add(NULL, SD_ALIAS);
9251 /* open the virtual block devices
9252 * note that migration with device
9253 * hot add/remove is broken.
9255 for(i = 0; i < nb_drives_opt; i++)
9256 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9257 exit(1);
9259 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9260 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9262 init_ioports();
9264 /* terminal init */
9265 memset(&display_state, 0, sizeof(display_state));
9266 if (nographic) {
9267 if (curses) {
9268 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9269 exit(1);
9271 /* nearly nothing to do */
9272 dumb_display_init(ds);
9273 } else if (vnc_display != NULL) {
9274 vnc_display_init(ds);
9275 if (vnc_display_open(ds, vnc_display) < 0)
9276 exit(1);
9277 } else
9278 #if defined(CONFIG_CURSES)
9279 if (curses) {
9280 curses_display_init(ds, full_screen);
9281 } else
9282 #endif
9284 #if defined(CONFIG_SDL)
9285 sdl_display_init(ds, full_screen, no_frame);
9286 #elif defined(CONFIG_COCOA)
9287 cocoa_display_init(ds, full_screen);
9288 #else
9289 dumb_display_init(ds);
9290 #endif
9293 /* Maintain compatibility with multiple stdio monitors */
9294 if (!strcmp(monitor_device,"stdio")) {
9295 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9296 const char *devname = serial_devices[i];
9297 if (devname && !strcmp(devname,"mon:stdio")) {
9298 monitor_device = NULL;
9299 break;
9300 } else if (devname && !strcmp(devname,"stdio")) {
9301 monitor_device = NULL;
9302 serial_devices[i] = "mon:stdio";
9303 break;
9307 if (monitor_device) {
9308 monitor_hd = qemu_chr_open(monitor_device);
9309 if (!monitor_hd) {
9310 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9311 exit(1);
9313 monitor_init(monitor_hd, !nographic);
9316 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9317 const char *devname = vmchannel_devices[i];
9318 if (devname[0] != '\0' && strcmp(devname, "none")) {
9319 int devid;
9320 char *termn;
9322 if (strstart(devname, "di:", &devname)) {
9323 devid = strtol(devname, &termn, 16);
9324 devname = termn + 1;
9326 else {
9327 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9328 devname);
9329 exit(1);
9331 vmchannel_hds[i] = qemu_chr_open(devname);
9332 if (!vmchannel_hds[i]) {
9333 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9334 devname);
9335 exit(1);
9337 vmchannel_init(vmchannel_hds[i], devid, i);
9341 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9342 const char *devname = serial_devices[i];
9343 if (devname && strcmp(devname, "none")) {
9344 serial_hds[i] = qemu_chr_open(devname);
9345 if (!serial_hds[i]) {
9346 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9347 devname);
9348 exit(1);
9350 if (strstart(devname, "vc", 0))
9351 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9355 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9356 const char *devname = parallel_devices[i];
9357 if (devname && strcmp(devname, "none")) {
9358 parallel_hds[i] = qemu_chr_open(devname);
9359 if (!parallel_hds[i]) {
9360 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9361 devname);
9362 exit(1);
9364 if (strstart(devname, "vc", 0))
9365 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9369 if (kvm_enabled())
9370 kvm_init_ap();
9372 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9373 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9375 current_machine = machine;
9377 /* init USB devices */
9378 if (usb_enabled) {
9379 for(i = 0; i < usb_devices_index; i++) {
9380 if (usb_device_add(usb_devices[i]) < 0) {
9381 fprintf(stderr, "Warning: could not add USB device %s\n",
9382 usb_devices[i]);
9387 if (display_state.dpy_refresh) {
9388 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9389 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9392 #ifdef CONFIG_GDBSTUB
9393 if (use_gdbstub) {
9394 /* XXX: use standard host:port notation and modify options
9395 accordingly. */
9396 if (gdbserver_start(gdbstub_port) < 0) {
9397 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9398 gdbstub_port);
9399 exit(1);
9402 #endif
9403 if (loadvm)
9404 do_loadvm(loadvm);
9406 if (incoming) {
9407 int rc;
9409 rc = migrate_incoming(incoming);
9410 if (rc != 0) {
9411 fprintf(stderr, "Migration failed rc=%d\n", rc);
9412 exit(rc);
9417 /* XXX: simplify init */
9418 read_passwords();
9419 if (autostart) {
9420 vm_start();
9424 if (daemonize) {
9425 uint8_t status = 0;
9426 ssize_t len;
9427 int fd;
9429 again1:
9430 len = write(fds[1], &status, 1);
9431 if (len == -1 && (errno == EINTR))
9432 goto again1;
9434 if (len != 1)
9435 exit(1);
9437 chdir("/");
9438 TFR(fd = open("/dev/null", O_RDWR));
9439 if (fd == -1)
9440 exit(1);
9442 dup2(fd, 0);
9443 dup2(fd, 1);
9444 dup2(fd, 2);
9446 close(fd);
9449 main_loop();
9450 quit_timers();
9452 #if !defined(_WIN32)
9453 /* close network clients */
9454 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9455 VLANClientState *vc;
9457 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9458 if (vc->fd_read == tap_receive) {
9459 char ifname[64];
9460 TAPState *s = vc->opaque;
9462 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9463 s->down_script[0])
9464 launch_script(s->down_script, ifname, s->fd);
9468 #endif
9469 return 0;