Virtio-blk save/restore support
[qemu-kvm/fedora.git] / vl.c
blob45c97aff0cd3d05433f7bf935a6b45fb16445ddf
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 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3809 VLANState *vlan = vc1->vlan;
3810 VLANClientState *vc;
3812 #if 0
3813 printf("vlan %d send:\n", vlan->id);
3814 hex_dump(stdout, buf, size);
3815 #endif
3816 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3817 if (vc != vc1) {
3818 vc->fd_read(vc->opaque, buf, size);
3823 #if defined(CONFIG_SLIRP)
3825 /* slirp network adapter */
3827 static int slirp_inited;
3828 static VLANClientState *slirp_vc;
3830 int slirp_can_output(void)
3832 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3835 void slirp_output(const uint8_t *pkt, int pkt_len)
3837 #if 0
3838 printf("slirp output:\n");
3839 hex_dump(stdout, pkt, pkt_len);
3840 #endif
3841 if (!slirp_vc)
3842 return;
3843 qemu_send_packet(slirp_vc, pkt, pkt_len);
3846 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3848 #if 0
3849 printf("slirp input:\n");
3850 hex_dump(stdout, buf, size);
3851 #endif
3852 slirp_input(buf, size);
3855 static int net_slirp_init(VLANState *vlan)
3857 if (!slirp_inited) {
3858 slirp_inited = 1;
3859 slirp_init();
3861 slirp_vc = qemu_new_vlan_client(vlan,
3862 slirp_receive, NULL, NULL);
3863 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3864 return 0;
3867 static void net_slirp_redir(const char *redir_str)
3869 int is_udp;
3870 char buf[256], *r;
3871 const char *p;
3872 struct in_addr guest_addr;
3873 int host_port, guest_port;
3875 if (!slirp_inited) {
3876 slirp_inited = 1;
3877 slirp_init();
3880 p = redir_str;
3881 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3882 goto fail;
3883 if (!strcmp(buf, "tcp")) {
3884 is_udp = 0;
3885 } else if (!strcmp(buf, "udp")) {
3886 is_udp = 1;
3887 } else {
3888 goto fail;
3891 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3892 goto fail;
3893 host_port = strtol(buf, &r, 0);
3894 if (r == buf)
3895 goto fail;
3897 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3898 goto fail;
3899 if (buf[0] == '\0') {
3900 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3902 if (!inet_aton(buf, &guest_addr))
3903 goto fail;
3905 guest_port = strtol(p, &r, 0);
3906 if (r == p)
3907 goto fail;
3909 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3910 fprintf(stderr, "qemu: could not set up redirection\n");
3911 exit(1);
3913 return;
3914 fail:
3915 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3916 exit(1);
3919 #ifndef _WIN32
3921 char smb_dir[1024];
3923 static void erase_dir(char *dir_name)
3925 DIR *d;
3926 struct dirent *de;
3927 char filename[1024];
3929 /* erase all the files in the directory */
3930 if ((d = opendir(dir_name)) != 0) {
3931 for(;;) {
3932 de = readdir(d);
3933 if (!de)
3934 break;
3935 if (strcmp(de->d_name, ".") != 0 &&
3936 strcmp(de->d_name, "..") != 0) {
3937 snprintf(filename, sizeof(filename), "%s/%s",
3938 smb_dir, de->d_name);
3939 if (unlink(filename) != 0) /* is it a directory? */
3940 erase_dir(filename);
3943 closedir(d);
3944 rmdir(dir_name);
3948 /* automatic user mode samba server configuration */
3949 static void smb_exit(void)
3951 erase_dir(smb_dir);
3954 /* automatic user mode samba server configuration */
3955 static void net_slirp_smb(const char *exported_dir)
3957 char smb_conf[1024];
3958 char smb_cmdline[1024];
3959 FILE *f;
3961 if (!slirp_inited) {
3962 slirp_inited = 1;
3963 slirp_init();
3966 /* XXX: better tmp dir construction */
3967 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3968 if (mkdir(smb_dir, 0700) < 0) {
3969 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3970 exit(1);
3972 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3974 f = fopen(smb_conf, "w");
3975 if (!f) {
3976 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3977 exit(1);
3979 fprintf(f,
3980 "[global]\n"
3981 "private dir=%s\n"
3982 "smb ports=0\n"
3983 "socket address=127.0.0.1\n"
3984 "pid directory=%s\n"
3985 "lock directory=%s\n"
3986 "log file=%s/log.smbd\n"
3987 "smb passwd file=%s/smbpasswd\n"
3988 "security = share\n"
3989 "[qemu]\n"
3990 "path=%s\n"
3991 "read only=no\n"
3992 "guest ok=yes\n",
3993 smb_dir,
3994 smb_dir,
3995 smb_dir,
3996 smb_dir,
3997 smb_dir,
3998 exported_dir
4000 fclose(f);
4001 atexit(smb_exit);
4003 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4004 SMBD_COMMAND, smb_conf);
4006 slirp_add_exec(0, smb_cmdline, 4, 139);
4009 #endif /* !defined(_WIN32) */
4010 void do_info_slirp(void)
4012 slirp_stats();
4015 #endif /* CONFIG_SLIRP */
4017 #if !defined(_WIN32)
4019 typedef struct TAPState {
4020 VLANClientState *vc;
4021 int fd;
4022 char down_script[1024];
4023 int no_poll;
4024 } TAPState;
4026 static int tap_read_poll(void *opaque)
4028 TAPState *s = opaque;
4029 return (!s->no_poll);
4032 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4034 TAPState *s = opaque;
4035 int ret;
4036 for(;;) {
4037 ret = write(s->fd, buf, size);
4038 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4039 } else {
4040 break;
4045 static void tap_send(void *opaque)
4047 TAPState *s = opaque;
4048 uint8_t buf[4096];
4049 int size;
4051 #ifdef __sun__
4052 struct strbuf sbuf;
4053 int f = 0;
4054 sbuf.maxlen = sizeof(buf);
4055 sbuf.buf = buf;
4056 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4057 #else
4058 size = read(s->fd, buf, sizeof(buf));
4059 #endif
4060 if (size > 0) {
4061 qemu_send_packet(s->vc, buf, size);
4065 int hack_around_tap(void *opaque)
4067 VLANClientState *vc = opaque;
4068 TAPState *ts = vc->opaque;
4070 if (vc->fd_read != tap_receive)
4071 return -1;
4073 if (ts) {
4074 ts->no_poll = 1;
4075 return ts->fd;
4078 return -1;
4081 /* fd support */
4083 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4085 TAPState *s;
4087 s = qemu_mallocz(sizeof(TAPState));
4088 if (!s)
4089 return NULL;
4090 s->fd = fd;
4091 s->no_poll = 0;
4092 enable_sigio_timer(fd);
4093 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4094 qemu_set_fd_handler2(s->fd, tap_read_poll, tap_send, NULL, s);
4095 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4096 return s;
4099 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4100 static int tap_open(char *ifname, int ifname_size)
4102 int fd;
4103 char *dev;
4104 struct stat s;
4106 TFR(fd = open("/dev/tap", O_RDWR));
4107 if (fd < 0) {
4108 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4109 return -1;
4112 fstat(fd, &s);
4113 dev = devname(s.st_rdev, S_IFCHR);
4114 pstrcpy(ifname, ifname_size, dev);
4116 fcntl(fd, F_SETFL, O_NONBLOCK);
4117 return fd;
4119 #elif defined(__sun__)
4120 #define TUNNEWPPA (('T'<<16) | 0x0001)
4122 * Allocate TAP device, returns opened fd.
4123 * Stores dev name in the first arg(must be large enough).
4125 int tap_alloc(char *dev)
4127 int tap_fd, if_fd, ppa = -1;
4128 static int ip_fd = 0;
4129 char *ptr;
4131 static int arp_fd = 0;
4132 int ip_muxid, arp_muxid;
4133 struct strioctl strioc_if, strioc_ppa;
4134 int link_type = I_PLINK;;
4135 struct lifreq ifr;
4136 char actual_name[32] = "";
4138 memset(&ifr, 0x0, sizeof(ifr));
4140 if( *dev ){
4141 ptr = dev;
4142 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4143 ppa = atoi(ptr);
4146 /* Check if IP device was opened */
4147 if( ip_fd )
4148 close(ip_fd);
4150 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4151 if (ip_fd < 0) {
4152 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4153 return -1;
4156 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4157 if (tap_fd < 0) {
4158 syslog(LOG_ERR, "Can't open /dev/tap");
4159 return -1;
4162 /* Assign a new PPA and get its unit number. */
4163 strioc_ppa.ic_cmd = TUNNEWPPA;
4164 strioc_ppa.ic_timout = 0;
4165 strioc_ppa.ic_len = sizeof(ppa);
4166 strioc_ppa.ic_dp = (char *)&ppa;
4167 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4168 syslog (LOG_ERR, "Can't assign new interface");
4170 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4171 if (if_fd < 0) {
4172 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4173 return -1;
4175 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4176 syslog(LOG_ERR, "Can't push IP module");
4177 return -1;
4180 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4181 syslog(LOG_ERR, "Can't get flags\n");
4183 snprintf (actual_name, 32, "tap%d", ppa);
4184 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4186 ifr.lifr_ppa = ppa;
4187 /* Assign ppa according to the unit number returned by tun device */
4189 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4190 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4191 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4192 syslog (LOG_ERR, "Can't get flags\n");
4193 /* Push arp module to if_fd */
4194 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4195 syslog (LOG_ERR, "Can't push ARP module (2)");
4197 /* Push arp module to ip_fd */
4198 if (ioctl (ip_fd, I_POP, NULL) < 0)
4199 syslog (LOG_ERR, "I_POP failed\n");
4200 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4201 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4202 /* Open arp_fd */
4203 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4204 if (arp_fd < 0)
4205 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4207 /* Set ifname to arp */
4208 strioc_if.ic_cmd = SIOCSLIFNAME;
4209 strioc_if.ic_timout = 0;
4210 strioc_if.ic_len = sizeof(ifr);
4211 strioc_if.ic_dp = (char *)&ifr;
4212 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4213 syslog (LOG_ERR, "Can't set ifname to arp\n");
4216 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4217 syslog(LOG_ERR, "Can't link TAP device to IP");
4218 return -1;
4221 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4222 syslog (LOG_ERR, "Can't link TAP device to ARP");
4224 close (if_fd);
4226 memset(&ifr, 0x0, sizeof(ifr));
4227 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4228 ifr.lifr_ip_muxid = ip_muxid;
4229 ifr.lifr_arp_muxid = arp_muxid;
4231 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4233 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4234 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4235 syslog (LOG_ERR, "Can't set multiplexor id");
4238 sprintf(dev, "tap%d", ppa);
4239 return tap_fd;
4242 static int tap_open(char *ifname, int ifname_size)
4244 char dev[10]="";
4245 int fd;
4246 if( (fd = tap_alloc(dev)) < 0 ){
4247 fprintf(stderr, "Cannot allocate TAP device\n");
4248 return -1;
4250 pstrcpy(ifname, ifname_size, dev);
4251 fcntl(fd, F_SETFL, O_NONBLOCK);
4252 return fd;
4254 #else
4255 static int tap_open(char *ifname, int ifname_size)
4257 struct ifreq ifr;
4258 int fd, ret;
4260 TFR(fd = open("/dev/net/tun", O_RDWR));
4261 if (fd < 0) {
4262 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4263 return -1;
4265 memset(&ifr, 0, sizeof(ifr));
4266 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4267 if (ifname[0] != '\0')
4268 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4269 else
4270 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4271 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4272 if (ret != 0) {
4273 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4274 close(fd);
4275 return -1;
4277 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4278 fcntl(fd, F_SETFL, O_NONBLOCK);
4279 return fd;
4281 #endif
4283 static int launch_script(const char *setup_script, const char *ifname, int fd)
4285 int pid, status;
4286 char *args[3];
4287 char **parg;
4289 /* try to launch network script */
4290 pid = fork();
4291 if (pid >= 0) {
4292 if (pid == 0) {
4293 int open_max = sysconf (_SC_OPEN_MAX), i;
4294 for (i = 0; i < open_max; i++)
4295 if (i != STDIN_FILENO &&
4296 i != STDOUT_FILENO &&
4297 i != STDERR_FILENO &&
4298 i != fd)
4299 close(i);
4301 parg = args;
4302 *parg++ = (char *)setup_script;
4303 *parg++ = (char *)ifname;
4304 *parg++ = NULL;
4305 execv(setup_script, args);
4306 _exit(1);
4308 while (waitpid(pid, &status, 0) != pid);
4309 if (!WIFEXITED(status) ||
4310 WEXITSTATUS(status) != 0) {
4311 fprintf(stderr, "%s: could not launch network script\n",
4312 setup_script);
4313 return -1;
4316 return 0;
4319 static int net_tap_init(VLANState *vlan, const char *ifname1,
4320 const char *setup_script, const char *down_script)
4322 TAPState *s;
4323 int fd;
4324 char ifname[128];
4326 if (ifname1 != NULL)
4327 pstrcpy(ifname, sizeof(ifname), ifname1);
4328 else
4329 ifname[0] = '\0';
4330 TFR(fd = tap_open(ifname, sizeof(ifname)));
4331 if (fd < 0)
4332 return -1;
4334 if (!setup_script || !strcmp(setup_script, "no"))
4335 setup_script = "";
4336 if (setup_script[0] != '\0') {
4337 if (launch_script(setup_script, ifname, fd))
4338 return -1;
4340 s = net_tap_fd_init(vlan, fd);
4341 if (!s)
4342 return -1;
4343 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4344 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4345 if (down_script && strcmp(down_script, "no"))
4346 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4347 return 0;
4350 #endif /* !_WIN32 */
4352 /* network connection */
4353 typedef struct NetSocketState {
4354 VLANClientState *vc;
4355 int fd;
4356 int state; /* 0 = getting length, 1 = getting data */
4357 int index;
4358 int packet_len;
4359 uint8_t buf[4096];
4360 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4361 } NetSocketState;
4363 typedef struct NetSocketListenState {
4364 VLANState *vlan;
4365 int fd;
4366 } NetSocketListenState;
4368 /* XXX: we consider we can send the whole packet without blocking */
4369 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4371 NetSocketState *s = opaque;
4372 uint32_t len;
4373 len = htonl(size);
4375 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4376 send_all(s->fd, buf, size);
4379 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4381 NetSocketState *s = opaque;
4382 sendto(s->fd, buf, size, 0,
4383 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4386 static void net_socket_send(void *opaque)
4388 NetSocketState *s = opaque;
4389 int l, size, err;
4390 uint8_t buf1[4096];
4391 const uint8_t *buf;
4393 size = recv(s->fd, buf1, sizeof(buf1), 0);
4394 if (size < 0) {
4395 err = socket_error();
4396 if (err != EWOULDBLOCK)
4397 goto eoc;
4398 } else if (size == 0) {
4399 /* end of connection */
4400 eoc:
4401 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4402 closesocket(s->fd);
4403 return;
4405 buf = buf1;
4406 while (size > 0) {
4407 /* reassemble a packet from the network */
4408 switch(s->state) {
4409 case 0:
4410 l = 4 - s->index;
4411 if (l > size)
4412 l = size;
4413 memcpy(s->buf + s->index, buf, l);
4414 buf += l;
4415 size -= l;
4416 s->index += l;
4417 if (s->index == 4) {
4418 /* got length */
4419 s->packet_len = ntohl(*(uint32_t *)s->buf);
4420 s->index = 0;
4421 s->state = 1;
4423 break;
4424 case 1:
4425 l = s->packet_len - s->index;
4426 if (l > size)
4427 l = size;
4428 memcpy(s->buf + s->index, buf, l);
4429 s->index += l;
4430 buf += l;
4431 size -= l;
4432 if (s->index >= s->packet_len) {
4433 qemu_send_packet(s->vc, s->buf, s->packet_len);
4434 s->index = 0;
4435 s->state = 0;
4437 break;
4442 static void net_socket_send_dgram(void *opaque)
4444 NetSocketState *s = opaque;
4445 int size;
4447 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4448 if (size < 0)
4449 return;
4450 if (size == 0) {
4451 /* end of connection */
4452 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4453 return;
4455 qemu_send_packet(s->vc, s->buf, size);
4458 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4460 struct ip_mreq imr;
4461 int fd;
4462 int val, ret;
4463 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4464 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4465 inet_ntoa(mcastaddr->sin_addr),
4466 (int)ntohl(mcastaddr->sin_addr.s_addr));
4467 return -1;
4470 fd = socket(PF_INET, SOCK_DGRAM, 0);
4471 if (fd < 0) {
4472 perror("socket(PF_INET, SOCK_DGRAM)");
4473 return -1;
4476 val = 1;
4477 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4478 (const char *)&val, sizeof(val));
4479 if (ret < 0) {
4480 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4481 goto fail;
4484 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4485 if (ret < 0) {
4486 perror("bind");
4487 goto fail;
4490 /* Add host to multicast group */
4491 imr.imr_multiaddr = mcastaddr->sin_addr;
4492 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4494 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4495 (const char *)&imr, sizeof(struct ip_mreq));
4496 if (ret < 0) {
4497 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4498 goto fail;
4501 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4502 val = 1;
4503 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4504 (const char *)&val, sizeof(val));
4505 if (ret < 0) {
4506 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4507 goto fail;
4510 socket_set_nonblock(fd);
4511 return fd;
4512 fail:
4513 if (fd >= 0)
4514 closesocket(fd);
4515 return -1;
4518 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4519 int is_connected)
4521 struct sockaddr_in saddr;
4522 int newfd;
4523 socklen_t saddr_len;
4524 NetSocketState *s;
4526 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4527 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4528 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4531 if (is_connected) {
4532 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4533 /* must be bound */
4534 if (saddr.sin_addr.s_addr==0) {
4535 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4536 fd);
4537 return NULL;
4539 /* clone dgram socket */
4540 newfd = net_socket_mcast_create(&saddr);
4541 if (newfd < 0) {
4542 /* error already reported by net_socket_mcast_create() */
4543 close(fd);
4544 return NULL;
4546 /* clone newfd to fd, close newfd */
4547 dup2(newfd, fd);
4548 close(newfd);
4550 } else {
4551 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4552 fd, strerror(errno));
4553 return NULL;
4557 s = qemu_mallocz(sizeof(NetSocketState));
4558 if (!s)
4559 return NULL;
4560 s->fd = fd;
4562 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4563 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4565 /* mcast: save bound address as dst */
4566 if (is_connected) s->dgram_dst=saddr;
4568 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4569 "socket: fd=%d (%s mcast=%s:%d)",
4570 fd, is_connected? "cloned" : "",
4571 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4572 return s;
4575 static void net_socket_connect(void *opaque)
4577 NetSocketState *s = opaque;
4578 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4581 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4582 int is_connected)
4584 NetSocketState *s;
4585 s = qemu_mallocz(sizeof(NetSocketState));
4586 if (!s)
4587 return NULL;
4588 s->fd = fd;
4589 s->vc = qemu_new_vlan_client(vlan,
4590 net_socket_receive, NULL, s);
4591 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4592 "socket: fd=%d", fd);
4593 if (is_connected) {
4594 net_socket_connect(s);
4595 } else {
4596 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4598 return s;
4601 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4602 int is_connected)
4604 int so_type=-1, optlen=sizeof(so_type);
4606 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4607 (socklen_t *)&optlen)< 0) {
4608 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4609 return NULL;
4611 switch(so_type) {
4612 case SOCK_DGRAM:
4613 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4614 case SOCK_STREAM:
4615 return net_socket_fd_init_stream(vlan, fd, is_connected);
4616 default:
4617 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4618 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4619 return net_socket_fd_init_stream(vlan, fd, is_connected);
4621 return NULL;
4624 static void net_socket_accept(void *opaque)
4626 NetSocketListenState *s = opaque;
4627 NetSocketState *s1;
4628 struct sockaddr_in saddr;
4629 socklen_t len;
4630 int fd;
4632 for(;;) {
4633 len = sizeof(saddr);
4634 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4635 if (fd < 0 && errno != EINTR) {
4636 return;
4637 } else if (fd >= 0) {
4638 break;
4641 s1 = net_socket_fd_init(s->vlan, fd, 1);
4642 if (!s1) {
4643 closesocket(fd);
4644 } else {
4645 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4646 "socket: connection from %s:%d",
4647 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4651 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4653 NetSocketListenState *s;
4654 int fd, val, ret;
4655 struct sockaddr_in saddr;
4657 if (parse_host_port(&saddr, host_str) < 0)
4658 return -1;
4660 s = qemu_mallocz(sizeof(NetSocketListenState));
4661 if (!s)
4662 return -1;
4664 fd = socket(PF_INET, SOCK_STREAM, 0);
4665 if (fd < 0) {
4666 perror("socket");
4667 return -1;
4669 socket_set_nonblock(fd);
4671 /* allow fast reuse */
4672 val = 1;
4673 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4675 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4676 if (ret < 0) {
4677 perror("bind");
4678 return -1;
4680 ret = listen(fd, 0);
4681 if (ret < 0) {
4682 perror("listen");
4683 return -1;
4685 s->vlan = vlan;
4686 s->fd = fd;
4687 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4688 return 0;
4691 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4693 NetSocketState *s;
4694 int fd, connected, ret, err;
4695 struct sockaddr_in saddr;
4697 if (parse_host_port(&saddr, host_str) < 0)
4698 return -1;
4700 fd = socket(PF_INET, SOCK_STREAM, 0);
4701 if (fd < 0) {
4702 perror("socket");
4703 return -1;
4705 socket_set_nonblock(fd);
4707 connected = 0;
4708 for(;;) {
4709 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4710 if (ret < 0) {
4711 err = socket_error();
4712 if (err == EINTR || err == EWOULDBLOCK) {
4713 } else if (err == EINPROGRESS) {
4714 break;
4715 #ifdef _WIN32
4716 } else if (err == WSAEALREADY) {
4717 break;
4718 #endif
4719 } else {
4720 perror("connect");
4721 closesocket(fd);
4722 return -1;
4724 } else {
4725 connected = 1;
4726 break;
4729 s = net_socket_fd_init(vlan, fd, connected);
4730 if (!s)
4731 return -1;
4732 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4733 "socket: connect to %s:%d",
4734 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4735 return 0;
4738 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4740 NetSocketState *s;
4741 int fd;
4742 struct sockaddr_in saddr;
4744 if (parse_host_port(&saddr, host_str) < 0)
4745 return -1;
4748 fd = net_socket_mcast_create(&saddr);
4749 if (fd < 0)
4750 return -1;
4752 s = net_socket_fd_init(vlan, fd, 0);
4753 if (!s)
4754 return -1;
4756 s->dgram_dst = saddr;
4758 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4759 "socket: mcast=%s:%d",
4760 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4761 return 0;
4765 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4767 char *q;
4769 q = buf;
4770 while (*p != '\0' && *p != '=') {
4771 if (q && (q - buf) < buf_size - 1)
4772 *q++ = *p;
4773 p++;
4775 if (q)
4776 *q = '\0';
4778 return p;
4781 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4783 char *q;
4785 q = buf;
4786 while (*p != '\0') {
4787 if (*p == ',') {
4788 if (*(p + 1) != ',')
4789 break;
4790 p++;
4792 if (q && (q - buf) < buf_size - 1)
4793 *q++ = *p;
4794 p++;
4796 if (q)
4797 *q = '\0';
4799 return p;
4802 int get_param_value(char *buf, int buf_size,
4803 const char *tag, const char *str)
4805 const char *p;
4806 char option[128];
4808 p = str;
4809 for(;;) {
4810 p = get_opt_name(option, sizeof(option), p);
4811 if (*p != '=')
4812 break;
4813 p++;
4814 if (!strcmp(tag, option)) {
4815 (void)get_opt_value(buf, buf_size, p);
4816 return strlen(buf);
4817 } else {
4818 p = get_opt_value(NULL, 0, p);
4820 if (*p != ',')
4821 break;
4822 p++;
4824 return 0;
4827 int check_params(char *buf, int buf_size,
4828 char **params, const char *str)
4830 const char *p;
4831 int i;
4833 p = str;
4834 for(;;) {
4835 p = get_opt_name(buf, buf_size, p);
4836 if (*p != '=')
4837 return -1;
4838 p++;
4839 for(i = 0; params[i] != NULL; i++)
4840 if (!strcmp(params[i], buf))
4841 break;
4842 if (params[i] == NULL)
4843 return -1;
4844 p = get_opt_value(NULL, 0, p);
4845 if (*p != ',')
4846 break;
4847 p++;
4849 return 0;
4852 static int nic_get_free_idx(void)
4854 int index;
4856 for (index = 0; index < MAX_NICS; index++)
4857 if (!nd_table[index].used)
4858 return index;
4859 return -1;
4862 int net_client_init(const char *str)
4864 const char *p;
4865 char *q;
4866 char device[64];
4867 char buf[1024];
4868 int vlan_id, ret;
4869 VLANState *vlan;
4871 p = str;
4872 q = device;
4873 while (*p != '\0' && *p != ',') {
4874 if ((q - device) < sizeof(device) - 1)
4875 *q++ = *p;
4876 p++;
4878 *q = '\0';
4879 if (*p == ',')
4880 p++;
4881 vlan_id = 0;
4882 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4883 vlan_id = strtol(buf, NULL, 0);
4885 vlan = qemu_find_vlan(vlan_id);
4886 if (!vlan) {
4887 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4888 return -1;
4890 if (!strcmp(device, "nic")) {
4891 NICInfo *nd;
4892 uint8_t *macaddr;
4893 int idx = nic_get_free_idx();
4895 if (idx == -1 || nb_nics >= MAX_NICS) {
4896 fprintf(stderr, "Too Many NICs\n");
4897 return -1;
4899 nd = &nd_table[idx];
4900 macaddr = nd->macaddr;
4901 macaddr[0] = 0x52;
4902 macaddr[1] = 0x54;
4903 macaddr[2] = 0x00;
4904 macaddr[3] = 0x12;
4905 macaddr[4] = 0x34;
4906 macaddr[5] = 0x56 + idx;
4908 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4909 if (parse_macaddr(macaddr, buf) < 0) {
4910 fprintf(stderr, "invalid syntax for ethernet address\n");
4911 return -1;
4914 if (get_param_value(buf, sizeof(buf), "model", p)) {
4915 nd->model = strdup(buf);
4917 nd->vlan = vlan;
4918 nd->used = 1;
4919 nb_nics++;
4920 vlan->nb_guest_devs++;
4921 ret = idx;
4922 } else
4923 if (!strcmp(device, "none")) {
4924 /* does nothing. It is needed to signal that no network cards
4925 are wanted */
4926 ret = 0;
4927 } else
4928 #ifdef CONFIG_SLIRP
4929 if (!strcmp(device, "user")) {
4930 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4931 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4933 vlan->nb_host_devs++;
4934 ret = net_slirp_init(vlan);
4935 } else
4936 #endif
4937 #ifdef _WIN32
4938 if (!strcmp(device, "tap")) {
4939 char ifname[64];
4940 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4941 fprintf(stderr, "tap: no interface name\n");
4942 return -1;
4944 vlan->nb_host_devs++;
4945 ret = tap_win32_init(vlan, ifname);
4946 } else
4947 #else
4948 if (!strcmp(device, "tap")) {
4949 char ifname[64];
4950 char setup_script[1024], down_script[1024];
4951 int fd;
4952 vlan->nb_host_devs++;
4953 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4954 fd = strtol(buf, NULL, 0);
4955 fcntl(fd, F_SETFL, O_NONBLOCK);
4956 ret = -1;
4957 if (net_tap_fd_init(vlan, fd))
4958 ret = 0;
4959 } else {
4960 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4961 ifname[0] = '\0';
4963 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4964 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4966 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4967 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4969 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4971 } else
4972 #endif
4973 if (!strcmp(device, "socket")) {
4974 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4975 int fd;
4976 fd = strtol(buf, NULL, 0);
4977 ret = -1;
4978 if (net_socket_fd_init(vlan, fd, 1))
4979 ret = 0;
4980 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4981 ret = net_socket_listen_init(vlan, buf);
4982 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4983 ret = net_socket_connect_init(vlan, buf);
4984 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4985 ret = net_socket_mcast_init(vlan, buf);
4986 } else {
4987 fprintf(stderr, "Unknown socket options: %s\n", p);
4988 return -1;
4990 vlan->nb_host_devs++;
4991 } else
4993 fprintf(stderr, "Unknown network device: %s\n", device);
4994 return -1;
4996 if (ret < 0) {
4997 fprintf(stderr, "Could not initialize device '%s'\n", device);
5000 return ret;
5003 void net_client_uninit(NICInfo *nd)
5005 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
5006 nb_nics--;
5007 nd->used = 0;
5008 free((void *)nd->model);
5011 void do_info_network(void)
5013 VLANState *vlan;
5014 VLANClientState *vc;
5016 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5017 term_printf("VLAN %d devices:\n", vlan->id);
5018 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5019 term_printf(" %s\n", vc->info_str);
5023 #define HD_ALIAS "index=%d,media=disk"
5024 #ifdef TARGET_PPC
5025 #define CDROM_ALIAS "index=1,media=cdrom"
5026 #else
5027 #define CDROM_ALIAS "index=2,media=cdrom"
5028 #endif
5029 #define FD_ALIAS "index=%d,if=floppy"
5030 #define PFLASH_ALIAS "if=pflash"
5031 #define MTD_ALIAS "if=mtd"
5032 #define SD_ALIAS "index=0,if=sd"
5034 static int drive_opt_get_free_idx(void)
5036 int index;
5038 for (index = 0; index < MAX_DRIVES; index++)
5039 if (!drives_opt[index].used) {
5040 drives_opt[index].used = 1;
5041 return index;
5044 return -1;
5047 static int drive_get_free_idx(void)
5049 int index;
5051 for (index = 0; index < MAX_DRIVES; index++)
5052 if (!drives_table[index].used) {
5053 drives_table[index].used = 1;
5054 return index;
5057 return -1;
5060 int drive_add(const char *file, const char *fmt, ...)
5062 va_list ap;
5063 int index = drive_opt_get_free_idx();
5065 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
5066 fprintf(stderr, "qemu: too many drives\n");
5067 return -1;
5070 drives_opt[index].file = file;
5071 va_start(ap, fmt);
5072 vsnprintf(drives_opt[index].opt,
5073 sizeof(drives_opt[0].opt), fmt, ap);
5074 va_end(ap);
5076 nb_drives_opt++;
5077 return index;
5080 void drive_remove(int index)
5082 drives_opt[index].used = 0;
5083 nb_drives_opt--;
5086 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5088 int index;
5090 /* seek interface, bus and unit */
5092 for (index = 0; index < MAX_DRIVES; index++)
5093 if (drives_table[index].type == type &&
5094 drives_table[index].bus == bus &&
5095 drives_table[index].unit == unit &&
5096 drives_table[index].used)
5097 return index;
5099 return -1;
5102 int drive_get_max_bus(BlockInterfaceType type)
5104 int max_bus;
5105 int index;
5107 max_bus = -1;
5108 for (index = 0; index < nb_drives; index++) {
5109 if(drives_table[index].type == type &&
5110 drives_table[index].bus > max_bus)
5111 max_bus = drives_table[index].bus;
5113 return max_bus;
5116 static void bdrv_format_print(void *opaque, const char *name)
5118 fprintf(stderr, " %s", name);
5121 void drive_uninit(BlockDriverState *bdrv)
5123 int i;
5125 for (i = 0; i < MAX_DRIVES; i++)
5126 if (drives_table[i].bdrv == bdrv) {
5127 drives_table[i].bdrv = NULL;
5128 drives_table[i].used = 0;
5129 drive_remove(drives_table[i].drive_opt_idx);
5130 nb_drives--;
5131 break;
5135 int drive_init(struct drive_opt *arg, int snapshot,
5136 QEMUMachine *machine)
5138 char buf[128];
5139 char file[1024];
5140 char devname[128];
5141 const char *mediastr = "";
5142 BlockInterfaceType type;
5143 enum { MEDIA_DISK, MEDIA_CDROM } media;
5144 int bus_id, unit_id;
5145 int cyls, heads, secs, translation;
5146 BlockDriverState *bdrv;
5147 BlockDriver *drv = NULL;
5148 int max_devs;
5149 int index;
5150 int cache;
5151 int bdrv_flags;
5152 int drives_table_idx;
5153 char *str = arg->opt;
5154 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5155 "secs", "trans", "media", "snapshot", "file",
5156 "cache", "format", "boot", NULL };
5158 if (check_params(buf, sizeof(buf), params, str) < 0) {
5159 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5160 buf, str);
5161 return -1;
5164 file[0] = 0;
5165 cyls = heads = secs = 0;
5166 bus_id = 0;
5167 unit_id = -1;
5168 translation = BIOS_ATA_TRANSLATION_AUTO;
5169 index = -1;
5170 cache = 1;
5172 if (!strcmp(machine->name, "realview") ||
5173 !strcmp(machine->name, "SS-5") ||
5174 !strcmp(machine->name, "SS-10") ||
5175 !strcmp(machine->name, "SS-600MP") ||
5176 !strcmp(machine->name, "versatilepb") ||
5177 !strcmp(machine->name, "versatileab")) {
5178 type = IF_SCSI;
5179 max_devs = MAX_SCSI_DEVS;
5180 strcpy(devname, "scsi");
5181 } else {
5182 type = IF_IDE;
5183 max_devs = MAX_IDE_DEVS;
5184 strcpy(devname, "ide");
5186 media = MEDIA_DISK;
5188 /* extract parameters */
5190 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5191 bus_id = strtol(buf, NULL, 0);
5192 if (bus_id < 0) {
5193 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5194 return -1;
5198 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5199 unit_id = strtol(buf, NULL, 0);
5200 if (unit_id < 0) {
5201 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5202 return -1;
5206 if (get_param_value(buf, sizeof(buf), "if", str)) {
5207 strncpy(devname, buf, sizeof(devname));
5208 if (!strcmp(buf, "ide")) {
5209 type = IF_IDE;
5210 max_devs = MAX_IDE_DEVS;
5211 } else if (!strcmp(buf, "scsi")) {
5212 type = IF_SCSI;
5213 max_devs = MAX_SCSI_DEVS;
5214 } else if (!strcmp(buf, "floppy")) {
5215 type = IF_FLOPPY;
5216 max_devs = 0;
5217 } else if (!strcmp(buf, "pflash")) {
5218 type = IF_PFLASH;
5219 max_devs = 0;
5220 } else if (!strcmp(buf, "mtd")) {
5221 type = IF_MTD;
5222 max_devs = 0;
5223 } else if (!strcmp(buf, "sd")) {
5224 type = IF_SD;
5225 max_devs = 0;
5226 } else if (!strcmp(buf, "virtio")) {
5227 type = IF_VIRTIO;
5228 max_devs = 0;
5229 } else {
5230 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5231 return -1;
5235 if (get_param_value(buf, sizeof(buf), "index", str)) {
5236 index = strtol(buf, NULL, 0);
5237 if (index < 0) {
5238 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5239 return -1;
5243 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5244 cyls = strtol(buf, NULL, 0);
5247 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5248 heads = strtol(buf, NULL, 0);
5251 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5252 secs = strtol(buf, NULL, 0);
5255 if (cyls || heads || secs) {
5256 if (cyls < 1 || cyls > 16383) {
5257 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5258 return -1;
5260 if (heads < 1 || heads > 16) {
5261 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5262 return -1;
5264 if (secs < 1 || secs > 63) {
5265 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5266 return -1;
5270 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5271 if (!cyls) {
5272 fprintf(stderr,
5273 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5274 str);
5275 return -1;
5277 if (!strcmp(buf, "none"))
5278 translation = BIOS_ATA_TRANSLATION_NONE;
5279 else if (!strcmp(buf, "lba"))
5280 translation = BIOS_ATA_TRANSLATION_LBA;
5281 else if (!strcmp(buf, "auto"))
5282 translation = BIOS_ATA_TRANSLATION_AUTO;
5283 else {
5284 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5285 return -1;
5289 if (get_param_value(buf, sizeof(buf), "media", str)) {
5290 if (!strcmp(buf, "disk")) {
5291 media = MEDIA_DISK;
5292 } else if (!strcmp(buf, "cdrom")) {
5293 if (cyls || secs || heads) {
5294 fprintf(stderr,
5295 "qemu: '%s' invalid physical CHS format\n", str);
5296 return -1;
5298 media = MEDIA_CDROM;
5299 } else {
5300 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5301 return -1;
5305 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5306 if (!strcmp(buf, "on"))
5307 snapshot = 1;
5308 else if (!strcmp(buf, "off"))
5309 snapshot = 0;
5310 else {
5311 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5312 return -1;
5316 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5317 if (!strcmp(buf, "off"))
5318 cache = 0;
5319 else if (!strcmp(buf, "on"))
5320 cache = 1;
5321 else {
5322 fprintf(stderr, "qemu: invalid cache option\n");
5323 return -1;
5327 if (get_param_value(buf, sizeof(buf), "format", str)) {
5328 if (strcmp(buf, "?") == 0) {
5329 fprintf(stderr, "qemu: Supported formats:");
5330 bdrv_iterate_format(bdrv_format_print, NULL);
5331 fprintf(stderr, "\n");
5332 return -1;
5334 drv = bdrv_find_format(buf);
5335 if (!drv) {
5336 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5337 return -1;
5341 if (get_param_value(buf, sizeof(buf), "boot", str)) {
5342 if (!strcmp(buf, "on")) {
5343 if (extboot_drive != -1) {
5344 fprintf(stderr, "qemu: two bootable drives specified\n");
5345 return -1;
5347 extboot_drive = nb_drives;
5348 } else if (strcmp(buf, "off")) {
5349 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
5350 return -1;
5354 if (arg->file == NULL)
5355 get_param_value(file, sizeof(file), "file", str);
5356 else
5357 pstrcpy(file, sizeof(file), arg->file);
5359 /* compute bus and unit according index */
5361 if (index != -1) {
5362 if (bus_id != 0 || unit_id != -1) {
5363 fprintf(stderr,
5364 "qemu: '%s' index cannot be used with bus and unit\n", str);
5365 return -1;
5367 if (max_devs == 0)
5369 unit_id = index;
5370 bus_id = 0;
5371 } else {
5372 unit_id = index % max_devs;
5373 bus_id = index / max_devs;
5377 /* if user doesn't specify a unit_id,
5378 * try to find the first free
5381 if (unit_id == -1) {
5382 unit_id = 0;
5383 while (drive_get_index(type, bus_id, unit_id) != -1) {
5384 unit_id++;
5385 if (max_devs && unit_id >= max_devs) {
5386 unit_id -= max_devs;
5387 bus_id++;
5392 /* check unit id */
5394 if (max_devs && unit_id >= max_devs) {
5395 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5396 str, unit_id, max_devs - 1);
5397 return -1;
5401 * ignore multiple definitions
5404 if (drive_get_index(type, bus_id, unit_id) != -1)
5405 return -2;
5407 /* init */
5409 if (type == IF_IDE || type == IF_SCSI)
5410 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5411 if (max_devs)
5412 snprintf(buf, sizeof(buf), "%s%i%s%i",
5413 devname, bus_id, mediastr, unit_id);
5414 else
5415 snprintf(buf, sizeof(buf), "%s%s%i",
5416 devname, mediastr, unit_id);
5417 bdrv = bdrv_new(buf);
5418 drives_table_idx = drive_get_free_idx();
5419 drives_table[drives_table_idx].bdrv = bdrv;
5420 drives_table[drives_table_idx].type = type;
5421 drives_table[drives_table_idx].bus = bus_id;
5422 drives_table[drives_table_idx].unit = unit_id;
5423 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
5424 nb_drives++;
5426 switch(type) {
5427 case IF_IDE:
5428 case IF_SCSI:
5429 switch(media) {
5430 case MEDIA_DISK:
5431 if (cyls != 0) {
5432 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5433 bdrv_set_translation_hint(bdrv, translation);
5435 break;
5436 case MEDIA_CDROM:
5437 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5438 break;
5440 break;
5441 case IF_SD:
5442 /* FIXME: This isn't really a floppy, but it's a reasonable
5443 approximation. */
5444 case IF_FLOPPY:
5445 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5446 break;
5447 case IF_PFLASH:
5448 case IF_MTD:
5449 case IF_VIRTIO:
5450 break;
5452 if (!file[0])
5453 return -2;
5454 bdrv_flags = 0;
5455 if (snapshot)
5456 bdrv_flags |= BDRV_O_SNAPSHOT;
5457 if (!cache)
5458 bdrv_flags |= BDRV_O_DIRECT;
5459 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5460 fprintf(stderr, "qemu: could not open disk image %s\n",
5461 file);
5462 return -1;
5464 return drives_table_idx;
5467 /***********************************************************/
5468 /* USB devices */
5470 static USBPort *used_usb_ports;
5471 static USBPort *free_usb_ports;
5473 /* ??? Maybe change this to register a hub to keep track of the topology. */
5474 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5475 usb_attachfn attach)
5477 port->opaque = opaque;
5478 port->index = index;
5479 port->attach = attach;
5480 port->next = free_usb_ports;
5481 free_usb_ports = port;
5484 static int usb_device_add(const char *devname)
5486 const char *p;
5487 USBDevice *dev;
5488 USBPort *port;
5490 if (!free_usb_ports)
5491 return -1;
5493 if (strstart(devname, "host:", &p)) {
5494 dev = usb_host_device_open(p);
5495 } else if (!strcmp(devname, "mouse")) {
5496 dev = usb_mouse_init();
5497 } else if (!strcmp(devname, "tablet")) {
5498 dev = usb_tablet_init();
5499 } else if (!strcmp(devname, "keyboard")) {
5500 dev = usb_keyboard_init();
5501 } else if (strstart(devname, "disk:", &p)) {
5502 dev = usb_msd_init(p);
5503 } else if (!strcmp(devname, "wacom-tablet")) {
5504 dev = usb_wacom_init();
5505 } else if (strstart(devname, "serial:", &p)) {
5506 dev = usb_serial_init(p);
5507 #ifdef CONFIG_BRLAPI
5508 } else if (!strcmp(devname, "braille")) {
5509 dev = usb_baum_init();
5510 #endif
5511 } else {
5512 return -1;
5514 if (!dev)
5515 return -1;
5517 /* Find a USB port to add the device to. */
5518 port = free_usb_ports;
5519 if (!port->next) {
5520 USBDevice *hub;
5522 /* Create a new hub and chain it on. */
5523 free_usb_ports = NULL;
5524 port->next = used_usb_ports;
5525 used_usb_ports = port;
5527 hub = usb_hub_init(VM_USB_HUB_SIZE);
5528 usb_attach(port, hub);
5529 port = free_usb_ports;
5532 free_usb_ports = port->next;
5533 port->next = used_usb_ports;
5534 used_usb_ports = port;
5535 usb_attach(port, dev);
5536 return 0;
5539 static int usb_device_del(const char *devname)
5541 USBPort *port;
5542 USBPort **lastp;
5543 USBDevice *dev;
5544 int bus_num, addr;
5545 const char *p;
5547 if (!used_usb_ports)
5548 return -1;
5550 p = strchr(devname, '.');
5551 if (!p)
5552 return -1;
5553 bus_num = strtoul(devname, NULL, 0);
5554 addr = strtoul(p + 1, NULL, 0);
5555 if (bus_num != 0)
5556 return -1;
5558 lastp = &used_usb_ports;
5559 port = used_usb_ports;
5560 while (port && port->dev->addr != addr) {
5561 lastp = &port->next;
5562 port = port->next;
5565 if (!port)
5566 return -1;
5568 dev = port->dev;
5569 *lastp = port->next;
5570 usb_attach(port, NULL);
5571 dev->handle_destroy(dev);
5572 port->next = free_usb_ports;
5573 free_usb_ports = port;
5574 return 0;
5577 void do_usb_add(const char *devname)
5579 int ret;
5580 ret = usb_device_add(devname);
5581 if (ret < 0)
5582 term_printf("Could not add USB device '%s'\n", devname);
5585 void do_usb_del(const char *devname)
5587 int ret;
5588 ret = usb_device_del(devname);
5589 if (ret < 0)
5590 term_printf("Could not remove USB device '%s'\n", devname);
5593 void usb_info(void)
5595 USBDevice *dev;
5596 USBPort *port;
5597 const char *speed_str;
5599 if (!usb_enabled) {
5600 term_printf("USB support not enabled\n");
5601 return;
5604 for (port = used_usb_ports; port; port = port->next) {
5605 dev = port->dev;
5606 if (!dev)
5607 continue;
5608 switch(dev->speed) {
5609 case USB_SPEED_LOW:
5610 speed_str = "1.5";
5611 break;
5612 case USB_SPEED_FULL:
5613 speed_str = "12";
5614 break;
5615 case USB_SPEED_HIGH:
5616 speed_str = "480";
5617 break;
5618 default:
5619 speed_str = "?";
5620 break;
5622 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5623 0, dev->addr, speed_str, dev->devname);
5627 /***********************************************************/
5628 /* PCMCIA/Cardbus */
5630 static struct pcmcia_socket_entry_s {
5631 struct pcmcia_socket_s *socket;
5632 struct pcmcia_socket_entry_s *next;
5633 } *pcmcia_sockets = 0;
5635 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5637 struct pcmcia_socket_entry_s *entry;
5639 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5640 entry->socket = socket;
5641 entry->next = pcmcia_sockets;
5642 pcmcia_sockets = entry;
5645 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5647 struct pcmcia_socket_entry_s *entry, **ptr;
5649 ptr = &pcmcia_sockets;
5650 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5651 if (entry->socket == socket) {
5652 *ptr = entry->next;
5653 qemu_free(entry);
5657 void pcmcia_info(void)
5659 struct pcmcia_socket_entry_s *iter;
5660 if (!pcmcia_sockets)
5661 term_printf("No PCMCIA sockets\n");
5663 for (iter = pcmcia_sockets; iter; iter = iter->next)
5664 term_printf("%s: %s\n", iter->socket->slot_string,
5665 iter->socket->attached ? iter->socket->card_string :
5666 "Empty");
5669 /***********************************************************/
5670 /* dumb display */
5672 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5676 static void dumb_resize(DisplayState *ds, int w, int h)
5680 static void dumb_refresh(DisplayState *ds)
5682 #if defined(CONFIG_SDL)
5683 vga_hw_update();
5684 #endif
5687 static void dumb_display_init(DisplayState *ds)
5689 ds->data = NULL;
5690 ds->linesize = 0;
5691 ds->depth = 0;
5692 ds->dpy_update = dumb_update;
5693 ds->dpy_resize = dumb_resize;
5694 ds->dpy_refresh = dumb_refresh;
5697 /***********************************************************/
5698 /* I/O handling */
5700 #define MAX_IO_HANDLERS 64
5702 typedef struct IOHandlerRecord {
5703 int fd;
5704 IOCanRWHandler *fd_read_poll;
5705 IOHandler *fd_read;
5706 IOHandler *fd_write;
5707 int deleted;
5708 void *opaque;
5709 /* temporary data */
5710 struct pollfd *ufd;
5711 struct IOHandlerRecord *next;
5712 } IOHandlerRecord;
5714 static IOHandlerRecord *first_io_handler;
5716 /* XXX: fd_read_poll should be suppressed, but an API change is
5717 necessary in the character devices to suppress fd_can_read(). */
5718 int qemu_set_fd_handler2(int fd,
5719 IOCanRWHandler *fd_read_poll,
5720 IOHandler *fd_read,
5721 IOHandler *fd_write,
5722 void *opaque)
5724 IOHandlerRecord **pioh, *ioh;
5726 if (!fd_read && !fd_write) {
5727 pioh = &first_io_handler;
5728 for(;;) {
5729 ioh = *pioh;
5730 if (ioh == NULL)
5731 break;
5732 if (ioh->fd == fd) {
5733 ioh->deleted = 1;
5734 break;
5736 pioh = &ioh->next;
5738 } else {
5739 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5740 if (ioh->fd == fd)
5741 goto found;
5743 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5744 if (!ioh)
5745 return -1;
5746 ioh->next = first_io_handler;
5747 first_io_handler = ioh;
5748 found:
5749 ioh->fd = fd;
5750 ioh->fd_read_poll = fd_read_poll;
5751 ioh->fd_read = fd_read;
5752 ioh->fd_write = fd_write;
5753 ioh->opaque = opaque;
5754 ioh->deleted = 0;
5756 main_loop_break();
5757 return 0;
5760 int qemu_set_fd_handler(int fd,
5761 IOHandler *fd_read,
5762 IOHandler *fd_write,
5763 void *opaque)
5765 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5768 /***********************************************************/
5769 /* Polling handling */
5771 typedef struct PollingEntry {
5772 PollingFunc *func;
5773 void *opaque;
5774 struct PollingEntry *next;
5775 } PollingEntry;
5777 static PollingEntry *first_polling_entry;
5779 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5781 PollingEntry **ppe, *pe;
5782 pe = qemu_mallocz(sizeof(PollingEntry));
5783 if (!pe)
5784 return -1;
5785 pe->func = func;
5786 pe->opaque = opaque;
5787 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5788 *ppe = pe;
5789 return 0;
5792 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5794 PollingEntry **ppe, *pe;
5795 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5796 pe = *ppe;
5797 if (pe->func == func && pe->opaque == opaque) {
5798 *ppe = pe->next;
5799 qemu_free(pe);
5800 break;
5805 #ifdef _WIN32
5806 /***********************************************************/
5807 /* Wait objects support */
5808 typedef struct WaitObjects {
5809 int num;
5810 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5811 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5812 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5813 } WaitObjects;
5815 static WaitObjects wait_objects = {0};
5817 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5819 WaitObjects *w = &wait_objects;
5821 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5822 return -1;
5823 w->events[w->num] = handle;
5824 w->func[w->num] = func;
5825 w->opaque[w->num] = opaque;
5826 w->num++;
5827 return 0;
5830 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5832 int i, found;
5833 WaitObjects *w = &wait_objects;
5835 found = 0;
5836 for (i = 0; i < w->num; i++) {
5837 if (w->events[i] == handle)
5838 found = 1;
5839 if (found) {
5840 w->events[i] = w->events[i + 1];
5841 w->func[i] = w->func[i + 1];
5842 w->opaque[i] = w->opaque[i + 1];
5845 if (found)
5846 w->num--;
5848 #endif
5850 #define SELF_ANNOUNCE_ROUNDS 5
5851 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5852 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5853 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5855 static int announce_self_create(uint8_t *buf,
5856 uint8_t *mac_addr)
5858 uint32_t magic = EXPERIMENTAL_MAGIC;
5859 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
5861 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5863 memset(buf, 0xff, 6); /* h_dst */
5864 memcpy(buf + 6, mac_addr, 6); /* h_src */
5865 memcpy(buf + 12, &proto, 2); /* h_proto */
5866 memcpy(buf + 14, &magic, 4); /* magic */
5868 return 18; /* len */
5871 static void qemu_announce_self(void)
5873 int i, j, len;
5874 VLANState *vlan;
5875 VLANClientState *vc;
5876 uint8_t buf[256];
5878 for (i = 0; i < nb_nics; i++) {
5879 len = announce_self_create(buf, nd_table[i].macaddr);
5880 vlan = nd_table[i].vlan;
5881 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
5882 if (vc->fd_read == tap_receive) /* send only if tap */
5883 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
5884 vc->fd_read(vc->opaque, buf, len);
5889 /***********************************************************/
5890 /* savevm/loadvm support */
5892 #define IO_BUF_SIZE 32768
5894 struct QEMUFile {
5895 QEMUFilePutBufferFunc *put_buffer;
5896 QEMUFileGetBufferFunc *get_buffer;
5897 QEMUFileCloseFunc *close;
5898 void *opaque;
5900 int64_t buf_offset; /* start of buffer when writing, end of buffer
5901 when reading */
5902 int buf_index;
5903 int buf_size; /* 0 when writing */
5904 uint8_t buf[IO_BUF_SIZE];
5907 typedef struct QEMUFileFD
5909 int fd;
5910 } QEMUFileFD;
5912 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5914 QEMUFileFD *s = opaque;
5915 int offset = 0;
5916 ssize_t len;
5918 again:
5919 len = read(s->fd, buf + offset, size - offset);
5920 if (len == -1) {
5921 if (errno == EINTR || errno == EAGAIN)
5922 goto again;
5925 return len;
5928 QEMUFile *qemu_fopen_fd(int fd)
5930 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
5931 s->fd = fd;
5932 return qemu_fopen(s, NULL, fd_get_buffer, qemu_free);
5935 typedef struct QEMUFileUnix
5937 FILE *outfile;
5938 } QEMUFileUnix;
5940 static void file_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5942 QEMUFileUnix *s = opaque;
5943 fseek(s->outfile, pos, SEEK_SET);
5944 fwrite(buf, 1, size, s->outfile);
5947 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5949 QEMUFileUnix *s = opaque;
5950 fseek(s->outfile, pos, SEEK_SET);
5951 return fread(buf, 1, size, s->outfile);
5954 static void file_close(void *opaque)
5956 QEMUFileUnix *s = opaque;
5957 fclose(s->outfile);
5958 qemu_free(s);
5961 QEMUFile *qemu_fopen_file(const char *filename, const char *mode)
5963 QEMUFileUnix *s;
5965 s = qemu_mallocz(sizeof(QEMUFileUnix));
5966 if (!s)
5967 return NULL;
5969 s->outfile = fopen(filename, mode);
5970 if (!s->outfile)
5971 goto fail;
5973 if (!strcmp(mode, "wb"))
5974 return qemu_fopen(s, file_put_buffer, NULL, file_close);
5975 else if (!strcmp(mode, "rb"))
5976 return qemu_fopen(s, NULL, file_get_buffer, file_close);
5978 fail:
5979 if (s->outfile)
5980 fclose(s->outfile);
5981 qemu_free(s);
5982 return NULL;
5985 typedef struct QEMUFileBdrv
5987 BlockDriverState *bs;
5988 int64_t base_offset;
5989 } QEMUFileBdrv;
5991 static void bdrv_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
5993 QEMUFileBdrv *s = opaque;
5994 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
5997 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
5999 QEMUFileBdrv *s = opaque;
6000 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6003 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6005 QEMUFileBdrv *s;
6007 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6008 if (!s)
6009 return NULL;
6011 s->bs = bs;
6012 s->base_offset = offset;
6014 if (is_writable)
6015 return qemu_fopen(s, bdrv_put_buffer, NULL, qemu_free);
6017 return qemu_fopen(s, NULL, bdrv_get_buffer, qemu_free);
6020 QEMUFile *qemu_fopen(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6021 QEMUFileGetBufferFunc *get_buffer, QEMUFileCloseFunc *close)
6023 QEMUFile *f;
6025 f = qemu_mallocz(sizeof(QEMUFile));
6026 if (!f)
6027 return NULL;
6029 f->opaque = opaque;
6030 f->put_buffer = put_buffer;
6031 f->get_buffer = get_buffer;
6032 f->close = close;
6034 return f;
6037 void qemu_fflush(QEMUFile *f)
6039 if (!f->put_buffer)
6040 return;
6042 if (f->buf_index > 0) {
6043 f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
6044 f->buf_offset += f->buf_index;
6045 f->buf_index = 0;
6049 static void qemu_fill_buffer(QEMUFile *f)
6051 int len;
6053 if (!f->get_buffer)
6054 return;
6056 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6057 if (len < 0)
6058 len = 0;
6060 f->buf_index = 0;
6061 f->buf_size = len;
6062 f->buf_offset += len;
6065 void qemu_fclose(QEMUFile *f)
6067 qemu_fflush(f);
6068 if (f->close)
6069 f->close(f->opaque);
6070 qemu_free(f);
6073 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6075 int l;
6076 while (size > 0) {
6077 l = IO_BUF_SIZE - f->buf_index;
6078 if (l > size)
6079 l = size;
6080 memcpy(f->buf + f->buf_index, buf, l);
6081 f->buf_index += l;
6082 buf += l;
6083 size -= l;
6084 if (f->buf_index >= IO_BUF_SIZE)
6085 qemu_fflush(f);
6089 void qemu_put_byte(QEMUFile *f, int v)
6091 f->buf[f->buf_index++] = v;
6092 if (f->buf_index >= IO_BUF_SIZE)
6093 qemu_fflush(f);
6096 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6098 int size, l;
6100 size = size1;
6101 while (size > 0) {
6102 l = f->buf_size - f->buf_index;
6103 if (l == 0) {
6104 qemu_fill_buffer(f);
6105 l = f->buf_size - f->buf_index;
6106 if (l == 0)
6107 break;
6109 if (l > size)
6110 l = size;
6111 memcpy(buf, f->buf + f->buf_index, l);
6112 f->buf_index += l;
6113 buf += l;
6114 size -= l;
6116 return size1 - size;
6119 int qemu_get_byte(QEMUFile *f)
6121 if (f->buf_index >= f->buf_size) {
6122 qemu_fill_buffer(f);
6123 if (f->buf_index >= f->buf_size)
6124 return 0;
6126 return f->buf[f->buf_index++];
6129 int64_t qemu_ftell(QEMUFile *f)
6131 return f->buf_offset - f->buf_size + f->buf_index;
6134 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6136 if (whence == SEEK_SET) {
6137 /* nothing to do */
6138 } else if (whence == SEEK_CUR) {
6139 pos += qemu_ftell(f);
6140 } else {
6141 /* SEEK_END not supported */
6142 return -1;
6144 if (f->put_buffer) {
6145 qemu_fflush(f);
6146 f->buf_offset = pos;
6147 } else {
6148 f->buf_offset = pos;
6149 f->buf_index = 0;
6150 f->buf_size = 0;
6152 return pos;
6155 void qemu_put_be16(QEMUFile *f, unsigned int v)
6157 qemu_put_byte(f, v >> 8);
6158 qemu_put_byte(f, v);
6161 void qemu_put_be32(QEMUFile *f, unsigned int v)
6163 qemu_put_byte(f, v >> 24);
6164 qemu_put_byte(f, v >> 16);
6165 qemu_put_byte(f, v >> 8);
6166 qemu_put_byte(f, v);
6169 void qemu_put_be64(QEMUFile *f, uint64_t v)
6171 qemu_put_be32(f, v >> 32);
6172 qemu_put_be32(f, v);
6175 unsigned int qemu_get_be16(QEMUFile *f)
6177 unsigned int v;
6178 v = qemu_get_byte(f) << 8;
6179 v |= qemu_get_byte(f);
6180 return v;
6183 unsigned int qemu_get_be32(QEMUFile *f)
6185 unsigned int v;
6186 v = qemu_get_byte(f) << 24;
6187 v |= qemu_get_byte(f) << 16;
6188 v |= qemu_get_byte(f) << 8;
6189 v |= qemu_get_byte(f);
6190 return v;
6193 uint64_t qemu_get_be64(QEMUFile *f)
6195 uint64_t v;
6196 v = (uint64_t)qemu_get_be32(f) << 32;
6197 v |= qemu_get_be32(f);
6198 return v;
6201 typedef struct SaveStateEntry {
6202 char idstr[256];
6203 int instance_id;
6204 int version_id;
6205 SaveStateHandler *save_state;
6206 LoadStateHandler *load_state;
6207 void *opaque;
6208 struct SaveStateEntry *next;
6209 } SaveStateEntry;
6211 static SaveStateEntry *first_se;
6213 int register_savevm(const char *idstr,
6214 int instance_id,
6215 int version_id,
6216 SaveStateHandler *save_state,
6217 LoadStateHandler *load_state,
6218 void *opaque)
6220 SaveStateEntry *se, **pse;
6222 se = qemu_malloc(sizeof(SaveStateEntry));
6223 if (!se)
6224 return -1;
6225 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6226 se->instance_id = instance_id;
6227 se->version_id = version_id;
6228 se->save_state = save_state;
6229 se->load_state = load_state;
6230 se->opaque = opaque;
6231 se->next = NULL;
6233 /* add at the end of list */
6234 pse = &first_se;
6235 while (*pse != NULL)
6236 pse = &(*pse)->next;
6237 *pse = se;
6238 return 0;
6241 #define QEMU_VM_FILE_MAGIC 0x5145564d
6242 #define QEMU_VM_FILE_VERSION 0x00000002
6244 static int qemu_savevm_state(QEMUFile *f)
6246 SaveStateEntry *se;
6247 int len, ret;
6248 int64_t cur_pos, len_pos, total_len_pos;
6250 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6251 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6252 total_len_pos = qemu_ftell(f);
6253 qemu_put_be64(f, 0); /* total size */
6255 for(se = first_se; se != NULL; se = se->next) {
6256 /* ID string */
6257 len = strlen(se->idstr);
6258 qemu_put_byte(f, len);
6259 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6261 qemu_put_be32(f, se->instance_id);
6262 qemu_put_be32(f, se->version_id);
6264 /* record size: filled later */
6265 len_pos = qemu_ftell(f);
6266 qemu_put_be32(f, 0);
6267 se->save_state(f, se->opaque);
6269 /* fill record size */
6270 cur_pos = qemu_ftell(f);
6271 len = cur_pos - len_pos - 4;
6272 qemu_fseek(f, len_pos, SEEK_SET);
6273 qemu_put_be32(f, len);
6274 qemu_fseek(f, cur_pos, SEEK_SET);
6276 cur_pos = qemu_ftell(f);
6277 qemu_fseek(f, total_len_pos, SEEK_SET);
6278 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6279 qemu_fseek(f, cur_pos, SEEK_SET);
6281 ret = 0;
6282 return ret;
6285 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6287 SaveStateEntry *se;
6289 for(se = first_se; se != NULL; se = se->next) {
6290 if (!strcmp(se->idstr, idstr) &&
6291 instance_id == se->instance_id)
6292 return se;
6294 return NULL;
6297 static int qemu_loadvm_state(QEMUFile *f)
6299 SaveStateEntry *se;
6300 int len, ret, instance_id, record_len, version_id;
6301 int64_t total_len, end_pos, cur_pos;
6302 unsigned int v;
6303 char idstr[256];
6305 v = qemu_get_be32(f);
6306 if (v != QEMU_VM_FILE_MAGIC)
6307 goto fail;
6308 v = qemu_get_be32(f);
6309 if (v != QEMU_VM_FILE_VERSION) {
6310 fail:
6311 ret = -1;
6312 goto the_end;
6314 total_len = qemu_get_be64(f);
6315 end_pos = total_len + qemu_ftell(f);
6316 for(;;) {
6317 if (qemu_ftell(f) >= end_pos)
6318 break;
6319 len = qemu_get_byte(f);
6320 qemu_get_buffer(f, (uint8_t *)idstr, len);
6321 idstr[len] = '\0';
6322 instance_id = qemu_get_be32(f);
6323 version_id = qemu_get_be32(f);
6324 record_len = qemu_get_be32(f);
6325 #if 0
6326 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6327 idstr, instance_id, version_id, record_len);
6328 #endif
6329 cur_pos = qemu_ftell(f);
6330 se = find_se(idstr, instance_id);
6331 if (!se) {
6332 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6333 instance_id, idstr);
6334 } else {
6335 ret = se->load_state(f, se->opaque, version_id);
6336 if (ret < 0) {
6337 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6338 instance_id, idstr);
6339 goto the_end;
6342 /* always seek to exact end of record */
6343 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6345 ret = 0;
6346 the_end:
6347 return ret;
6350 int qemu_live_savevm_state(QEMUFile *f)
6352 SaveStateEntry *se;
6353 int len, ret;
6355 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6356 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6358 for(se = first_se; se != NULL; se = se->next) {
6359 len = strlen(se->idstr);
6361 qemu_put_byte(f, len);
6362 qemu_put_buffer(f, se->idstr, len);
6363 qemu_put_be32(f, se->instance_id);
6364 qemu_put_be32(f, se->version_id);
6366 se->save_state(f, se->opaque);
6369 qemu_put_byte(f, 0);
6371 ret = 0;
6372 return ret;
6375 int qemu_live_loadvm_state(QEMUFile *f)
6377 SaveStateEntry *se;
6378 int len, ret, instance_id, version_id;
6379 unsigned int v;
6380 char idstr[256];
6382 v = qemu_get_be32(f);
6383 if (v != QEMU_VM_FILE_MAGIC)
6384 goto fail;
6385 v = qemu_get_be32(f);
6386 if (v != QEMU_VM_FILE_VERSION) {
6387 fail:
6388 ret = -1;
6389 goto the_end;
6392 for(;;) {
6393 len = qemu_get_byte(f);
6394 if (len == 0)
6395 break;
6396 qemu_get_buffer(f, idstr, len);
6397 idstr[len] = '\0';
6398 instance_id = qemu_get_be32(f);
6399 version_id = qemu_get_be32(f);
6400 se = find_se(idstr, instance_id);
6401 if (!se) {
6402 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6403 instance_id, idstr);
6404 } else {
6405 if (version_id > se->version_id) { /* src version > dst version */
6406 fprintf(stderr, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6407 idstr, version_id, se->version_id);
6408 ret = -1;
6409 goto the_end;
6411 ret = se->load_state(f, se->opaque, version_id);
6412 if (ret < 0) {
6413 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6414 instance_id, idstr);
6415 goto the_end;
6419 ret = 0;
6421 qemu_announce_self();
6423 the_end:
6424 return ret;
6427 /* device can contain snapshots */
6428 static int bdrv_can_snapshot(BlockDriverState *bs)
6430 return (bs &&
6431 !bdrv_is_removable(bs) &&
6432 !bdrv_is_read_only(bs));
6435 /* device must be snapshots in order to have a reliable snapshot */
6436 static int bdrv_has_snapshot(BlockDriverState *bs)
6438 return (bs &&
6439 !bdrv_is_removable(bs) &&
6440 !bdrv_is_read_only(bs));
6443 static BlockDriverState *get_bs_snapshots(void)
6445 BlockDriverState *bs;
6446 int i;
6448 if (bs_snapshots)
6449 return bs_snapshots;
6450 for(i = 0; i <= nb_drives; i++) {
6451 bs = drives_table[i].bdrv;
6452 if (bdrv_can_snapshot(bs))
6453 goto ok;
6455 return NULL;
6457 bs_snapshots = bs;
6458 return bs;
6461 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6462 const char *name)
6464 QEMUSnapshotInfo *sn_tab, *sn;
6465 int nb_sns, i, ret;
6467 ret = -ENOENT;
6468 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6469 if (nb_sns < 0)
6470 return ret;
6471 for(i = 0; i < nb_sns; i++) {
6472 sn = &sn_tab[i];
6473 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6474 *sn_info = *sn;
6475 ret = 0;
6476 break;
6479 qemu_free(sn_tab);
6480 return ret;
6483 void do_savevm(const char *name)
6485 BlockDriverState *bs, *bs1;
6486 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6487 int must_delete, ret, i;
6488 BlockDriverInfo bdi1, *bdi = &bdi1;
6489 QEMUFile *f;
6490 int saved_vm_running;
6491 #ifdef _WIN32
6492 struct _timeb tb;
6493 #else
6494 struct timeval tv;
6495 #endif
6497 bs = get_bs_snapshots();
6498 if (!bs) {
6499 term_printf("No block device can accept snapshots\n");
6500 return;
6503 /* ??? Should this occur after vm_stop? */
6504 qemu_aio_flush();
6506 saved_vm_running = vm_running;
6507 vm_stop(0);
6509 must_delete = 0;
6510 if (name) {
6511 ret = bdrv_snapshot_find(bs, old_sn, name);
6512 if (ret >= 0) {
6513 must_delete = 1;
6516 memset(sn, 0, sizeof(*sn));
6517 if (must_delete) {
6518 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6519 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6520 } else {
6521 if (name)
6522 pstrcpy(sn->name, sizeof(sn->name), name);
6525 /* fill auxiliary fields */
6526 #ifdef _WIN32
6527 _ftime(&tb);
6528 sn->date_sec = tb.time;
6529 sn->date_nsec = tb.millitm * 1000000;
6530 #else
6531 gettimeofday(&tv, NULL);
6532 sn->date_sec = tv.tv_sec;
6533 sn->date_nsec = tv.tv_usec * 1000;
6534 #endif
6535 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6537 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6538 term_printf("Device %s does not support VM state snapshots\n",
6539 bdrv_get_device_name(bs));
6540 goto the_end;
6543 /* save the VM state */
6544 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6545 if (!f) {
6546 term_printf("Could not open VM state file\n");
6547 goto the_end;
6549 ret = qemu_savevm_state(f);
6550 sn->vm_state_size = qemu_ftell(f);
6551 qemu_fclose(f);
6552 if (ret < 0) {
6553 term_printf("Error %d while writing VM\n", ret);
6554 goto the_end;
6557 /* create the snapshots */
6559 for(i = 0; i < nb_drives; i++) {
6560 bs1 = drives_table[i].bdrv;
6561 if (bdrv_has_snapshot(bs1)) {
6562 if (must_delete) {
6563 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6564 if (ret < 0) {
6565 term_printf("Error while deleting snapshot on '%s'\n",
6566 bdrv_get_device_name(bs1));
6569 ret = bdrv_snapshot_create(bs1, sn);
6570 if (ret < 0) {
6571 term_printf("Error while creating snapshot on '%s'\n",
6572 bdrv_get_device_name(bs1));
6577 the_end:
6578 if (saved_vm_running)
6579 vm_start();
6582 void do_loadvm(const char *name)
6584 BlockDriverState *bs, *bs1;
6585 BlockDriverInfo bdi1, *bdi = &bdi1;
6586 QEMUFile *f;
6587 int i, ret;
6588 int saved_vm_running;
6590 bs = get_bs_snapshots();
6591 if (!bs) {
6592 term_printf("No block device supports snapshots\n");
6593 return;
6596 /* Flush all IO requests so they don't interfere with the new state. */
6597 qemu_aio_flush();
6599 saved_vm_running = vm_running;
6600 vm_stop(0);
6602 for(i = 0; i <= nb_drives; i++) {
6603 bs1 = drives_table[i].bdrv;
6604 if (bdrv_has_snapshot(bs1)) {
6605 ret = bdrv_snapshot_goto(bs1, name);
6606 if (ret < 0) {
6607 if (bs != bs1)
6608 term_printf("Warning: ");
6609 switch(ret) {
6610 case -ENOTSUP:
6611 term_printf("Snapshots not supported on device '%s'\n",
6612 bdrv_get_device_name(bs1));
6613 break;
6614 case -ENOENT:
6615 term_printf("Could not find snapshot '%s' on device '%s'\n",
6616 name, bdrv_get_device_name(bs1));
6617 break;
6618 default:
6619 term_printf("Error %d while activating snapshot on '%s'\n",
6620 ret, bdrv_get_device_name(bs1));
6621 break;
6623 /* fatal on snapshot block device */
6624 if (bs == bs1)
6625 goto the_end;
6630 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6631 term_printf("Device %s does not support VM state snapshots\n",
6632 bdrv_get_device_name(bs));
6633 return;
6636 /* restore the VM state */
6637 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6638 if (!f) {
6639 term_printf("Could not open VM state file\n");
6640 goto the_end;
6642 ret = qemu_loadvm_state(f);
6643 qemu_fclose(f);
6644 if (ret < 0) {
6645 term_printf("Error %d while loading VM state\n", ret);
6647 the_end:
6648 if (saved_vm_running)
6649 vm_start();
6652 void do_delvm(const char *name)
6654 BlockDriverState *bs, *bs1;
6655 int i, ret;
6657 bs = get_bs_snapshots();
6658 if (!bs) {
6659 term_printf("No block device supports snapshots\n");
6660 return;
6663 for(i = 0; i <= nb_drives; i++) {
6664 bs1 = drives_table[i].bdrv;
6665 if (bdrv_has_snapshot(bs1)) {
6666 ret = bdrv_snapshot_delete(bs1, name);
6667 if (ret < 0) {
6668 if (ret == -ENOTSUP)
6669 term_printf("Snapshots not supported on device '%s'\n",
6670 bdrv_get_device_name(bs1));
6671 else
6672 term_printf("Error %d while deleting snapshot on '%s'\n",
6673 ret, bdrv_get_device_name(bs1));
6679 void do_info_snapshots(void)
6681 BlockDriverState *bs, *bs1;
6682 QEMUSnapshotInfo *sn_tab, *sn;
6683 int nb_sns, i;
6684 char buf[256];
6686 bs = get_bs_snapshots();
6687 if (!bs) {
6688 term_printf("No available block device supports snapshots\n");
6689 return;
6691 term_printf("Snapshot devices:");
6692 for(i = 0; i <= nb_drives; i++) {
6693 bs1 = drives_table[i].bdrv;
6694 if (bdrv_has_snapshot(bs1)) {
6695 if (bs == bs1)
6696 term_printf(" %s", bdrv_get_device_name(bs1));
6699 term_printf("\n");
6701 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6702 if (nb_sns < 0) {
6703 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6704 return;
6706 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6707 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6708 for(i = 0; i < nb_sns; i++) {
6709 sn = &sn_tab[i];
6710 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6712 qemu_free(sn_tab);
6715 /***********************************************************/
6716 /* ram save/restore */
6718 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6720 int v;
6722 v = qemu_get_byte(f);
6723 switch(v) {
6724 case 0:
6725 if (qemu_get_buffer(f, buf, len) != len)
6726 return -EIO;
6727 break;
6728 case 1:
6729 v = qemu_get_byte(f);
6730 memset(buf, v, len);
6731 break;
6732 default:
6733 return -EINVAL;
6735 return 0;
6738 static int ram_load_v1(QEMUFile *f, void *opaque)
6740 int ret;
6741 ram_addr_t i;
6743 if (qemu_get_be32(f) != phys_ram_size)
6744 return -EINVAL;
6745 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6746 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
6747 continue;
6748 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6749 if (ret)
6750 return ret;
6752 return 0;
6755 #define BDRV_HASH_BLOCK_SIZE 1024
6756 #define IOBUF_SIZE 4096
6757 #define RAM_CBLOCK_MAGIC 0xfabe
6759 typedef struct RamCompressState {
6760 z_stream zstream;
6761 QEMUFile *f;
6762 uint8_t buf[IOBUF_SIZE];
6763 } RamCompressState;
6765 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6767 int ret;
6768 memset(s, 0, sizeof(*s));
6769 s->f = f;
6770 ret = deflateInit2(&s->zstream, 1,
6771 Z_DEFLATED, 15,
6772 9, Z_DEFAULT_STRATEGY);
6773 if (ret != Z_OK)
6774 return -1;
6775 s->zstream.avail_out = IOBUF_SIZE;
6776 s->zstream.next_out = s->buf;
6777 return 0;
6780 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6782 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6783 qemu_put_be16(s->f, len);
6784 qemu_put_buffer(s->f, buf, len);
6787 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6789 int ret;
6791 s->zstream.avail_in = len;
6792 s->zstream.next_in = (uint8_t *)buf;
6793 while (s->zstream.avail_in > 0) {
6794 ret = deflate(&s->zstream, Z_NO_FLUSH);
6795 if (ret != Z_OK)
6796 return -1;
6797 if (s->zstream.avail_out == 0) {
6798 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6799 s->zstream.avail_out = IOBUF_SIZE;
6800 s->zstream.next_out = s->buf;
6803 return 0;
6806 static void ram_compress_close(RamCompressState *s)
6808 int len, ret;
6810 /* compress last bytes */
6811 for(;;) {
6812 ret = deflate(&s->zstream, Z_FINISH);
6813 if (ret == Z_OK || ret == Z_STREAM_END) {
6814 len = IOBUF_SIZE - s->zstream.avail_out;
6815 if (len > 0) {
6816 ram_put_cblock(s, s->buf, len);
6818 s->zstream.avail_out = IOBUF_SIZE;
6819 s->zstream.next_out = s->buf;
6820 if (ret == Z_STREAM_END)
6821 break;
6822 } else {
6823 goto fail;
6826 fail:
6827 deflateEnd(&s->zstream);
6830 typedef struct RamDecompressState {
6831 z_stream zstream;
6832 QEMUFile *f;
6833 uint8_t buf[IOBUF_SIZE];
6834 } RamDecompressState;
6836 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6838 int ret;
6839 memset(s, 0, sizeof(*s));
6840 s->f = f;
6841 ret = inflateInit(&s->zstream);
6842 if (ret != Z_OK)
6843 return -1;
6844 return 0;
6847 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6849 int ret, clen;
6851 s->zstream.avail_out = len;
6852 s->zstream.next_out = buf;
6853 while (s->zstream.avail_out > 0) {
6854 if (s->zstream.avail_in == 0) {
6855 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6856 return -1;
6857 clen = qemu_get_be16(s->f);
6858 if (clen > IOBUF_SIZE)
6859 return -1;
6860 qemu_get_buffer(s->f, s->buf, clen);
6861 s->zstream.avail_in = clen;
6862 s->zstream.next_in = s->buf;
6864 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6865 if (ret != Z_OK && ret != Z_STREAM_END) {
6866 return -1;
6869 return 0;
6872 static void ram_decompress_close(RamDecompressState *s)
6874 inflateEnd(&s->zstream);
6877 static void ram_save_live(QEMUFile *f, void *opaque)
6879 target_ulong addr;
6881 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
6882 if (kvm_enabled() && (addr>=0xa0000) && (addr<0xc0000)) /* do not access video-addresses */
6883 continue;
6884 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG)) {
6885 qemu_put_be32(f, addr);
6886 qemu_put_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
6889 qemu_put_be32(f, 1);
6892 static void ram_save_static(QEMUFile *f, void *opaque)
6894 ram_addr_t i;
6895 RamCompressState s1, *s = &s1;
6896 uint8_t buf[10];
6898 qemu_put_be32(f, phys_ram_size);
6899 if (ram_compress_open(s, f) < 0)
6900 return;
6901 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6902 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
6903 continue;
6904 #if 0
6905 if (tight_savevm_enabled) {
6906 int64_t sector_num;
6907 int j;
6909 /* find if the memory block is available on a virtual
6910 block device */
6911 sector_num = -1;
6912 for(j = 0; j < nb_drives; j++) {
6913 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6914 phys_ram_base + i,
6915 BDRV_HASH_BLOCK_SIZE);
6916 if (sector_num >= 0)
6917 break;
6919 if (j == nb_drives)
6920 goto normal_compress;
6921 buf[0] = 1;
6922 buf[1] = j;
6923 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6924 ram_compress_buf(s, buf, 10);
6925 } else
6926 #endif
6928 // normal_compress:
6929 buf[0] = 0;
6930 ram_compress_buf(s, buf, 1);
6931 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6934 ram_compress_close(s);
6937 static void ram_save(QEMUFile *f, void *opaque)
6939 int in_migration = cpu_physical_memory_get_dirty_tracking();
6941 qemu_put_byte(f, in_migration);
6943 if (in_migration)
6944 ram_save_live(f, opaque);
6945 else
6946 ram_save_static(f, opaque);
6949 static int ram_load_live(QEMUFile *f, void *opaque)
6951 target_ulong addr;
6953 do {
6954 addr = qemu_get_be32(f);
6955 if (addr == 1)
6956 break;
6958 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
6959 } while (1);
6961 return 0;
6964 static int ram_load_static(QEMUFile *f, void *opaque)
6966 RamDecompressState s1, *s = &s1;
6967 uint8_t buf[10];
6968 ram_addr_t i;
6970 if (qemu_get_be32(f) != phys_ram_size)
6971 return -EINVAL;
6972 if (ram_decompress_open(s, f) < 0)
6973 return -EINVAL;
6974 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6975 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
6976 continue;
6977 if (ram_decompress_buf(s, buf, 1) < 0) {
6978 fprintf(stderr, "Error while reading ram block header\n");
6979 goto error;
6981 if (buf[0] == 0) {
6982 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6983 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
6984 goto error;
6986 } else
6987 #if 0
6988 if (buf[0] == 1) {
6989 int bs_index;
6990 int64_t sector_num;
6992 ram_decompress_buf(s, buf + 1, 9);
6993 bs_index = buf[1];
6994 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6995 if (bs_index >= nb_drives) {
6996 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6997 goto error;
6999 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7000 phys_ram_base + i,
7001 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7002 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7003 bs_index, sector_num);
7004 goto error;
7006 } else
7007 #endif
7009 error:
7010 printf("Error block header\n");
7011 return -EINVAL;
7014 ram_decompress_close(s);
7015 return 0;
7018 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7020 int ret;
7022 switch (version_id) {
7023 case 1:
7024 ret = ram_load_v1(f, opaque);
7025 break;
7026 case 3:
7027 if (qemu_get_byte(f)) {
7028 ret = ram_load_live(f, opaque);
7029 break;
7031 case 2:
7032 ret = ram_load_static(f, opaque);
7033 break;
7034 default:
7035 ret = -EINVAL;
7036 break;
7039 return ret;
7042 /***********************************************************/
7043 /* bottom halves (can be seen as timers which expire ASAP) */
7045 struct QEMUBH {
7046 QEMUBHFunc *cb;
7047 void *opaque;
7048 int scheduled;
7049 QEMUBH *next;
7052 static QEMUBH *first_bh = NULL;
7054 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7056 QEMUBH *bh;
7057 bh = qemu_mallocz(sizeof(QEMUBH));
7058 if (!bh)
7059 return NULL;
7060 bh->cb = cb;
7061 bh->opaque = opaque;
7062 return bh;
7065 int qemu_bh_poll(void)
7067 QEMUBH *bh, **pbh;
7068 int ret;
7070 ret = 0;
7071 for(;;) {
7072 pbh = &first_bh;
7073 bh = *pbh;
7074 if (!bh)
7075 break;
7076 ret = 1;
7077 *pbh = bh->next;
7078 bh->scheduled = 0;
7079 bh->cb(bh->opaque);
7081 return ret;
7084 void qemu_bh_schedule(QEMUBH *bh)
7086 CPUState *env = cpu_single_env;
7087 if (bh->scheduled)
7088 return;
7089 bh->scheduled = 1;
7090 bh->next = first_bh;
7091 first_bh = bh;
7093 /* stop the currently executing CPU to execute the BH ASAP */
7094 if (env) {
7095 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7097 main_loop_break();
7100 void qemu_bh_cancel(QEMUBH *bh)
7102 QEMUBH **pbh;
7103 if (bh->scheduled) {
7104 pbh = &first_bh;
7105 while (*pbh != bh)
7106 pbh = &(*pbh)->next;
7107 *pbh = bh->next;
7108 bh->scheduled = 0;
7112 void qemu_bh_delete(QEMUBH *bh)
7114 qemu_bh_cancel(bh);
7115 qemu_free(bh);
7118 /***********************************************************/
7119 /* machine registration */
7121 QEMUMachine *first_machine = NULL;
7122 QEMUMachine *current_machine = NULL;
7124 int qemu_register_machine(QEMUMachine *m)
7126 QEMUMachine **pm;
7127 pm = &first_machine;
7128 while (*pm != NULL)
7129 pm = &(*pm)->next;
7130 m->next = NULL;
7131 *pm = m;
7132 return 0;
7135 static QEMUMachine *find_machine(const char *name)
7137 QEMUMachine *m;
7139 for(m = first_machine; m != NULL; m = m->next) {
7140 if (!strcmp(m->name, name))
7141 return m;
7143 return NULL;
7146 /***********************************************************/
7147 /* main execution loop */
7149 static void gui_update(void *opaque)
7151 DisplayState *ds = opaque;
7152 ds->dpy_refresh(ds);
7153 qemu_mod_timer(ds->gui_timer,
7154 (ds->gui_timer_interval ?
7155 ds->gui_timer_interval :
7156 GUI_REFRESH_INTERVAL)
7157 + qemu_get_clock(rt_clock));
7160 struct vm_change_state_entry {
7161 VMChangeStateHandler *cb;
7162 void *opaque;
7163 LIST_ENTRY (vm_change_state_entry) entries;
7166 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7168 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7169 void *opaque)
7171 VMChangeStateEntry *e;
7173 e = qemu_mallocz(sizeof (*e));
7174 if (!e)
7175 return NULL;
7177 e->cb = cb;
7178 e->opaque = opaque;
7179 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7180 return e;
7183 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7185 LIST_REMOVE (e, entries);
7186 qemu_free (e);
7189 static void vm_state_notify(int running)
7191 VMChangeStateEntry *e;
7193 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7194 e->cb(e->opaque, running);
7198 /* XXX: support several handlers */
7199 static VMStopHandler *vm_stop_cb;
7200 static void *vm_stop_opaque;
7202 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7204 vm_stop_cb = cb;
7205 vm_stop_opaque = opaque;
7206 return 0;
7209 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7211 vm_stop_cb = NULL;
7214 void vm_start(void)
7216 if (!vm_running) {
7217 cpu_enable_ticks();
7218 vm_running = 1;
7219 vm_state_notify(1);
7220 qemu_rearm_alarm_timer(alarm_timer);
7224 void vm_stop(int reason)
7226 if (vm_running) {
7227 cpu_disable_ticks();
7228 vm_running = 0;
7229 if (reason != 0) {
7230 if (vm_stop_cb) {
7231 vm_stop_cb(vm_stop_opaque, reason);
7234 vm_state_notify(0);
7238 /* reset/shutdown handler */
7240 typedef struct QEMUResetEntry {
7241 QEMUResetHandler *func;
7242 void *opaque;
7243 struct QEMUResetEntry *next;
7244 } QEMUResetEntry;
7246 static QEMUResetEntry *first_reset_entry;
7247 static int reset_requested;
7248 static int shutdown_requested;
7249 static int powerdown_requested;
7251 int qemu_shutdown_requested(void)
7253 int r = shutdown_requested;
7254 shutdown_requested = 0;
7255 return r;
7258 int qemu_reset_requested(void)
7260 int r = reset_requested;
7261 reset_requested = 0;
7262 return r;
7265 int qemu_powerdown_requested(void)
7267 int r = powerdown_requested;
7268 powerdown_requested = 0;
7269 return r;
7272 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7274 QEMUResetEntry **pre, *re;
7276 pre = &first_reset_entry;
7277 while (*pre != NULL)
7278 pre = &(*pre)->next;
7279 re = qemu_mallocz(sizeof(QEMUResetEntry));
7280 re->func = func;
7281 re->opaque = opaque;
7282 re->next = NULL;
7283 *pre = re;
7286 void qemu_system_reset(void)
7288 QEMUResetEntry *re;
7290 /* reset all devices */
7291 for(re = first_reset_entry; re != NULL; re = re->next) {
7292 re->func(re->opaque);
7296 void qemu_system_reset_request(void)
7298 if (no_reboot) {
7299 shutdown_requested = 1;
7300 } else {
7301 reset_requested = 1;
7303 if (cpu_single_env)
7304 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7305 #ifdef USE_KVM
7306 if (kvm_allowed)
7307 if (!no_reboot)
7308 qemu_kvm_system_reset_request();
7309 #endif
7312 void qemu_system_shutdown_request(void)
7314 shutdown_requested = 1;
7315 if (cpu_single_env)
7316 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7319 void qemu_system_powerdown_request(void)
7321 powerdown_requested = 1;
7322 if (cpu_single_env)
7323 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7326 /* boot_set handler */
7327 QEMUBootSetHandler *qemu_boot_set_handler = NULL;
7329 void qemu_register_boot_set(QEMUBootSetHandler *func)
7331 qemu_boot_set_handler = func;
7334 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
7335 struct timeval *tv)
7337 int ret;
7339 /* KVM holds a mutex while QEMU code is running, we need hooks to
7340 release the mutex whenever QEMU code sleeps. */
7342 kvm_sleep_begin();
7344 ret = select(max_fd, rfds, wfds, xfds, tv);
7346 kvm_sleep_end();
7348 return ret;
7351 void main_loop_wait(int timeout)
7353 IOHandlerRecord *ioh;
7354 fd_set rfds, wfds, xfds;
7355 int ret, nfds;
7356 #ifdef _WIN32
7357 int ret2, i;
7358 #endif
7359 struct timeval tv;
7360 PollingEntry *pe;
7363 /* XXX: need to suppress polling by better using win32 events */
7364 ret = 0;
7365 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7366 ret |= pe->func(pe->opaque);
7368 #ifdef _WIN32
7369 if (ret == 0) {
7370 int err;
7371 WaitObjects *w = &wait_objects;
7373 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7374 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7375 if (w->func[ret - WAIT_OBJECT_0])
7376 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7378 /* Check for additional signaled events */
7379 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7381 /* Check if event is signaled */
7382 ret2 = WaitForSingleObject(w->events[i], 0);
7383 if(ret2 == WAIT_OBJECT_0) {
7384 if (w->func[i])
7385 w->func[i](w->opaque[i]);
7386 } else if (ret2 == WAIT_TIMEOUT) {
7387 } else {
7388 err = GetLastError();
7389 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7392 } else if (ret == WAIT_TIMEOUT) {
7393 } else {
7394 err = GetLastError();
7395 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7398 #endif
7399 /* poll any events */
7400 /* XXX: separate device handlers from system ones */
7401 nfds = -1;
7402 FD_ZERO(&rfds);
7403 FD_ZERO(&wfds);
7404 FD_ZERO(&xfds);
7405 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7406 if (ioh->deleted)
7407 continue;
7408 if (ioh->fd_read &&
7409 (!ioh->fd_read_poll ||
7410 ioh->fd_read_poll(ioh->opaque) != 0)) {
7411 FD_SET(ioh->fd, &rfds);
7412 if (ioh->fd > nfds)
7413 nfds = ioh->fd;
7415 if (ioh->fd_write) {
7416 FD_SET(ioh->fd, &wfds);
7417 if (ioh->fd > nfds)
7418 nfds = ioh->fd;
7422 #ifdef _WIN32
7423 tv.tv_sec = 0;
7424 tv.tv_usec = 0;
7425 #else
7426 tv.tv_sec = timeout / 1000;
7427 tv.tv_usec = (timeout % 1000) * 1000;
7428 #endif
7429 #if defined(CONFIG_SLIRP)
7430 if (slirp_inited) {
7431 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7433 #endif
7434 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7435 if (ret > 0) {
7436 IOHandlerRecord **pioh;
7438 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7439 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7440 ioh->fd_read(ioh->opaque);
7441 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
7442 FD_CLR(ioh->fd, &rfds);
7444 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7445 ioh->fd_write(ioh->opaque);
7449 /* remove deleted IO handlers */
7450 pioh = &first_io_handler;
7451 while (*pioh) {
7452 ioh = *pioh;
7453 if (ioh->deleted) {
7454 *pioh = ioh->next;
7455 qemu_free(ioh);
7456 } else
7457 pioh = &ioh->next;
7460 #if defined(CONFIG_SLIRP)
7461 if (slirp_inited) {
7462 if (ret < 0) {
7463 FD_ZERO(&rfds);
7464 FD_ZERO(&wfds);
7465 FD_ZERO(&xfds);
7467 slirp_select_poll(&rfds, &wfds, &xfds);
7469 #endif
7470 virtio_net_poll();
7472 qemu_aio_poll();
7474 if (vm_running) {
7475 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7476 qemu_get_clock(vm_clock));
7477 /* run dma transfers, if any */
7478 DMA_run();
7481 /* real time timers */
7482 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7483 qemu_get_clock(rt_clock));
7485 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7486 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7487 qemu_rearm_alarm_timer(alarm_timer);
7490 /* Check bottom-halves last in case any of the earlier events triggered
7491 them. */
7492 qemu_bh_poll();
7496 static int main_loop(void)
7498 int ret, timeout;
7499 #ifdef CONFIG_PROFILER
7500 int64_t ti;
7501 #endif
7502 CPUState *env;
7505 if (kvm_enabled()) {
7506 kvm_main_loop();
7507 cpu_disable_ticks();
7508 return 0;
7511 cur_cpu = first_cpu;
7512 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7513 for(;;) {
7514 if (vm_running) {
7516 for(;;) {
7517 /* get next cpu */
7518 env = next_cpu;
7519 #ifdef CONFIG_PROFILER
7520 ti = profile_getclock();
7521 #endif
7522 ret = cpu_exec(env);
7523 #ifdef CONFIG_PROFILER
7524 qemu_time += profile_getclock() - ti;
7525 #endif
7526 next_cpu = env->next_cpu ?: first_cpu;
7527 if (event_pending && likely(ret != EXCP_DEBUG)) {
7528 ret = EXCP_INTERRUPT;
7529 event_pending = 0;
7530 break;
7532 if (ret == EXCP_HLT) {
7533 /* Give the next CPU a chance to run. */
7534 cur_cpu = env;
7535 continue;
7537 if (ret != EXCP_HALTED)
7538 break;
7539 /* all CPUs are halted ? */
7540 if (env == cur_cpu)
7541 break;
7543 cur_cpu = env;
7545 if (shutdown_requested) {
7546 ret = EXCP_INTERRUPT;
7547 if (no_shutdown) {
7548 vm_stop(0);
7549 no_shutdown = 0;
7551 else
7552 break;
7554 if (reset_requested) {
7555 reset_requested = 0;
7556 qemu_system_reset();
7557 if (kvm_enabled())
7558 kvm_load_registers(env);
7559 ret = EXCP_INTERRUPT;
7561 if (powerdown_requested) {
7562 powerdown_requested = 0;
7563 qemu_system_powerdown();
7564 ret = EXCP_INTERRUPT;
7566 if (unlikely(ret == EXCP_DEBUG)) {
7567 vm_stop(EXCP_DEBUG);
7569 /* If all cpus are halted then wait until the next IRQ */
7570 /* XXX: use timeout computed from timers */
7571 if (ret == EXCP_HALTED)
7572 timeout = 10;
7573 else
7574 timeout = 0;
7575 } else {
7576 timeout = 10;
7578 #ifdef CONFIG_PROFILER
7579 ti = profile_getclock();
7580 #endif
7581 main_loop_wait(timeout);
7582 #ifdef CONFIG_PROFILER
7583 dev_time += profile_getclock() - ti;
7584 #endif
7586 cpu_disable_ticks();
7587 return ret;
7590 static void help(int exitcode)
7592 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
7593 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7594 "usage: %s [options] [disk_image]\n"
7595 "\n"
7596 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7597 "\n"
7598 "Standard options:\n"
7599 "-M machine select emulated machine (-M ? for list)\n"
7600 "-cpu cpu select CPU (-cpu ? for list)\n"
7601 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7602 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7603 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7604 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7605 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7606 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7607 " [,cache=on|off][,format=f][,boot=on|off]\n"
7608 " use 'file' as a drive image\n"
7609 "-mtdblock file use 'file' as on-board Flash memory image\n"
7610 "-sd file use 'file' as SecureDigital card image\n"
7611 "-pflash file use 'file' as a parallel flash image\n"
7612 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7613 "-snapshot write to temporary files instead of disk image files\n"
7614 #ifdef CONFIG_SDL
7615 "-no-frame open SDL window without a frame and window decorations\n"
7616 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7617 "-no-quit disable SDL window close capability\n"
7618 #endif
7619 #ifdef TARGET_I386
7620 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7621 #endif
7622 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7623 "-smp n set the number of CPUs to 'n' [default=1]\n"
7624 "-nographic disable graphical output and redirect serial I/Os to console\n"
7625 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7626 #ifndef _WIN32
7627 "-k language use keyboard layout (for example \"fr\" for French)\n"
7628 #endif
7629 #ifdef HAS_AUDIO
7630 "-audio-help print list of audio drivers and their options\n"
7631 "-soundhw c1,... enable audio support\n"
7632 " and only specified sound cards (comma separated list)\n"
7633 " use -soundhw ? to get the list of supported cards\n"
7634 " use -soundhw all to enable all of them\n"
7635 #endif
7636 "-localtime set the real time clock to local time [default=utc]\n"
7637 "-full-screen start in full screen\n"
7638 #ifdef TARGET_I386
7639 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7640 #endif
7641 "-usb enable the USB driver (will be the default soon)\n"
7642 "-usbdevice name add the host or guest USB device 'name'\n"
7643 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7644 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7645 #endif
7646 "-name string set the name of the guest\n"
7647 "\n"
7648 "Network options:\n"
7649 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7650 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7651 #ifdef CONFIG_SLIRP
7652 "-net user[,vlan=n][,hostname=host]\n"
7653 " connect the user mode network stack to VLAN 'n' and send\n"
7654 " hostname 'host' to DHCP clients\n"
7655 #endif
7656 #ifdef _WIN32
7657 "-net tap[,vlan=n],ifname=name\n"
7658 " connect the host TAP network interface to VLAN 'n'\n"
7659 #else
7660 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7661 " connect the host TAP network interface to VLAN 'n' and use the\n"
7662 " network scripts 'file' (default=%s)\n"
7663 " and 'dfile' (default=%s);\n"
7664 " use '[down]script=no' to disable script execution;\n"
7665 " use 'fd=h' to connect to an already opened TAP interface\n"
7666 #endif
7667 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7668 " connect the vlan 'n' to another VLAN using a socket connection\n"
7669 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7670 " connect the vlan 'n' to multicast maddr and port\n"
7671 "-net none use it alone to have zero network devices; if no -net option\n"
7672 " is provided, the default is '-net nic -net user'\n"
7673 "\n"
7674 #ifdef CONFIG_SLIRP
7675 "-tftp dir allow tftp access to files in dir [-net user]\n"
7676 "-bootp file advertise file in BOOTP replies\n"
7677 #ifndef _WIN32
7678 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7679 #endif
7680 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7681 " redirect TCP or UDP connections from host to guest [-net user]\n"
7682 #endif
7683 "\n"
7684 "Linux boot specific:\n"
7685 "-kernel bzImage use 'bzImage' as kernel image\n"
7686 "-append cmdline use 'cmdline' as kernel command line\n"
7687 "-initrd file use 'file' as initial ram disk\n"
7688 "\n"
7689 "Debug/Expert options:\n"
7690 "-monitor dev redirect the monitor to char device 'dev'\n"
7691 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
7692 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
7693 "-serial dev redirect the serial port to char device 'dev'\n"
7694 "-parallel dev redirect the parallel port to char device 'dev'\n"
7695 "-pidfile file Write PID to 'file'\n"
7696 "-S freeze CPU at startup (use 'c' to start execution)\n"
7697 "-s wait gdb connection to port\n"
7698 "-p port set gdb connection port [default=%s]\n"
7699 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7700 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7701 " translation (t=none or lba) (usually qemu can guess them)\n"
7702 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7703 #ifdef USE_KQEMU
7704 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7705 "-no-kqemu disable KQEMU kernel module usage\n"
7706 #endif
7707 #ifdef USE_KVM
7708 #ifndef NO_CPU_EMULATION
7709 "-no-kvm disable KVM hardware virtualization\n"
7710 #endif
7711 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
7712 "-no-kvm-pit disable KVM kernel mode PIT\n"
7713 #endif
7714 #ifdef TARGET_I386
7715 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7716 " (default is CL-GD5446 PCI VGA)\n"
7717 "-no-acpi disable ACPI\n"
7718 #endif
7719 #ifdef CONFIG_CURSES
7720 "-curses use a curses/ncurses interface instead of SDL\n"
7721 #endif
7722 "-no-reboot exit instead of rebooting\n"
7723 "-no-shutdown stop before shutdown\n"
7724 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7725 "-vnc display start a VNC server on display\n"
7726 #ifndef _WIN32
7727 "-daemonize daemonize QEMU after initializing\n"
7728 #endif
7729 "-tdf inject timer interrupts that got lost\n"
7730 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
7731 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
7732 "-option-rom rom load a file, rom, into the option ROM space\n"
7733 #ifdef TARGET_SPARC
7734 "-prom-env variable=value set OpenBIOS nvram variables\n"
7735 #endif
7736 "-clock force the use of the given methods for timer alarm.\n"
7737 " To see what timers are available use -clock ?\n"
7738 "-startdate select initial date of the clock\n"
7739 "\n"
7740 "During emulation, the following keys are useful:\n"
7741 "ctrl-alt-f toggle full screen\n"
7742 "ctrl-alt-n switch to virtual console 'n'\n"
7743 "ctrl-alt toggle mouse and keyboard grab\n"
7744 "\n"
7745 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7747 "qemu",
7748 DEFAULT_RAM_SIZE,
7749 #ifndef _WIN32
7750 DEFAULT_NETWORK_SCRIPT,
7751 DEFAULT_NETWORK_DOWN_SCRIPT,
7752 #endif
7753 DEFAULT_GDBSTUB_PORT,
7754 "/tmp/qemu.log");
7755 exit(exitcode);
7758 #define HAS_ARG 0x0001
7760 enum {
7761 QEMU_OPTION_h,
7763 QEMU_OPTION_M,
7764 QEMU_OPTION_cpu,
7765 QEMU_OPTION_fda,
7766 QEMU_OPTION_fdb,
7767 QEMU_OPTION_hda,
7768 QEMU_OPTION_hdb,
7769 QEMU_OPTION_hdc,
7770 QEMU_OPTION_hdd,
7771 QEMU_OPTION_drive,
7772 QEMU_OPTION_cdrom,
7773 QEMU_OPTION_mtdblock,
7774 QEMU_OPTION_sd,
7775 QEMU_OPTION_pflash,
7776 QEMU_OPTION_boot,
7777 QEMU_OPTION_snapshot,
7778 #ifdef TARGET_I386
7779 QEMU_OPTION_no_fd_bootchk,
7780 #endif
7781 QEMU_OPTION_m,
7782 QEMU_OPTION_nographic,
7783 QEMU_OPTION_portrait,
7784 #ifdef HAS_AUDIO
7785 QEMU_OPTION_audio_help,
7786 QEMU_OPTION_soundhw,
7787 #endif
7789 QEMU_OPTION_net,
7790 QEMU_OPTION_tftp,
7791 QEMU_OPTION_bootp,
7792 QEMU_OPTION_smb,
7793 QEMU_OPTION_redir,
7795 QEMU_OPTION_kernel,
7796 QEMU_OPTION_append,
7797 QEMU_OPTION_initrd,
7799 QEMU_OPTION_S,
7800 QEMU_OPTION_s,
7801 QEMU_OPTION_p,
7802 QEMU_OPTION_d,
7803 QEMU_OPTION_hdachs,
7804 QEMU_OPTION_L,
7805 QEMU_OPTION_bios,
7806 QEMU_OPTION_no_code_copy,
7807 QEMU_OPTION_k,
7808 QEMU_OPTION_localtime,
7809 QEMU_OPTION_cirrusvga,
7810 QEMU_OPTION_vmsvga,
7811 QEMU_OPTION_g,
7812 QEMU_OPTION_std_vga,
7813 QEMU_OPTION_echr,
7814 QEMU_OPTION_monitor,
7815 QEMU_OPTION_balloon,
7816 QEMU_OPTION_vmchannel,
7817 QEMU_OPTION_serial,
7818 QEMU_OPTION_parallel,
7819 QEMU_OPTION_loadvm,
7820 QEMU_OPTION_full_screen,
7821 QEMU_OPTION_no_frame,
7822 QEMU_OPTION_alt_grab,
7823 QEMU_OPTION_no_quit,
7824 QEMU_OPTION_pidfile,
7825 QEMU_OPTION_no_kqemu,
7826 QEMU_OPTION_kernel_kqemu,
7827 QEMU_OPTION_win2k_hack,
7828 QEMU_OPTION_usb,
7829 QEMU_OPTION_usbdevice,
7830 QEMU_OPTION_smp,
7831 QEMU_OPTION_vnc,
7832 QEMU_OPTION_no_acpi,
7833 QEMU_OPTION_curses,
7834 QEMU_OPTION_no_kvm,
7835 QEMU_OPTION_no_kvm_irqchip,
7836 QEMU_OPTION_no_kvm_pit,
7837 QEMU_OPTION_no_reboot,
7838 QEMU_OPTION_no_shutdown,
7839 QEMU_OPTION_show_cursor,
7840 QEMU_OPTION_daemonize,
7841 QEMU_OPTION_option_rom,
7842 QEMU_OPTION_semihosting,
7843 QEMU_OPTION_cpu_vendor,
7844 QEMU_OPTION_name,
7845 QEMU_OPTION_prom_env,
7846 QEMU_OPTION_old_param,
7847 QEMU_OPTION_clock,
7848 QEMU_OPTION_startdate,
7849 QEMU_OPTION_translation,
7850 QEMU_OPTION_incoming,
7851 QEMU_OPTION_tdf,
7852 QEMU_OPTION_kvm_shadow_memory,
7853 QEMU_OPTION_mempath,
7856 typedef struct QEMUOption {
7857 const char *name;
7858 int flags;
7859 int index;
7860 } QEMUOption;
7862 const QEMUOption qemu_options[] = {
7863 { "h", 0, QEMU_OPTION_h },
7864 { "help", 0, QEMU_OPTION_h },
7866 { "M", HAS_ARG, QEMU_OPTION_M },
7867 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7868 { "fda", HAS_ARG, QEMU_OPTION_fda },
7869 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7870 { "hda", HAS_ARG, QEMU_OPTION_hda },
7871 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7872 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7873 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7874 { "drive", HAS_ARG, QEMU_OPTION_drive },
7875 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7876 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7877 { "sd", HAS_ARG, QEMU_OPTION_sd },
7878 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7879 { "boot", HAS_ARG, QEMU_OPTION_boot },
7880 { "snapshot", 0, QEMU_OPTION_snapshot },
7881 #ifdef TARGET_I386
7882 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7883 #endif
7884 { "m", HAS_ARG, QEMU_OPTION_m },
7885 { "nographic", 0, QEMU_OPTION_nographic },
7886 { "portrait", 0, QEMU_OPTION_portrait },
7887 { "k", HAS_ARG, QEMU_OPTION_k },
7888 #ifdef HAS_AUDIO
7889 { "audio-help", 0, QEMU_OPTION_audio_help },
7890 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7891 #endif
7893 { "net", HAS_ARG, QEMU_OPTION_net},
7894 #ifdef CONFIG_SLIRP
7895 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7896 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7897 #ifndef _WIN32
7898 { "smb", HAS_ARG, QEMU_OPTION_smb },
7899 #endif
7900 { "redir", HAS_ARG, QEMU_OPTION_redir },
7901 #endif
7903 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7904 { "append", HAS_ARG, QEMU_OPTION_append },
7905 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7907 { "S", 0, QEMU_OPTION_S },
7908 { "s", 0, QEMU_OPTION_s },
7909 { "p", HAS_ARG, QEMU_OPTION_p },
7910 { "d", HAS_ARG, QEMU_OPTION_d },
7911 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7912 { "L", HAS_ARG, QEMU_OPTION_L },
7913 { "bios", HAS_ARG, QEMU_OPTION_bios },
7914 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7915 #ifdef USE_KQEMU
7916 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7917 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7918 #endif
7919 #ifdef USE_KVM
7920 #ifndef NO_CPU_EMULATION
7921 { "no-kvm", 0, QEMU_OPTION_no_kvm },
7922 #endif
7923 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
7924 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
7925 #endif
7926 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7927 { "g", 1, QEMU_OPTION_g },
7928 #endif
7929 { "localtime", 0, QEMU_OPTION_localtime },
7930 { "std-vga", 0, QEMU_OPTION_std_vga },
7931 { "monitor", 1, QEMU_OPTION_monitor },
7932 { "balloon", 1, QEMU_OPTION_balloon },
7933 { "vmchannel", 1, QEMU_OPTION_vmchannel },
7934 { "echr", HAS_ARG, QEMU_OPTION_echr },
7935 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7936 { "serial", HAS_ARG, QEMU_OPTION_serial },
7937 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7938 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7939 { "incoming", 1, QEMU_OPTION_incoming },
7940 { "full-screen", 0, QEMU_OPTION_full_screen },
7941 #ifdef CONFIG_SDL
7942 { "no-frame", 0, QEMU_OPTION_no_frame },
7943 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7944 { "no-quit", 0, QEMU_OPTION_no_quit },
7945 #endif
7946 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7947 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7948 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7949 { "smp", HAS_ARG, QEMU_OPTION_smp },
7950 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7951 #ifdef CONFIG_CURSES
7952 { "curses", 0, QEMU_OPTION_curses },
7953 #endif
7955 /* temporary options */
7956 { "usb", 0, QEMU_OPTION_usb },
7957 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7958 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7959 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7960 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7961 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7962 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7963 { "daemonize", 0, QEMU_OPTION_daemonize },
7964 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7965 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7966 { "semihosting", 0, QEMU_OPTION_semihosting },
7967 #endif
7968 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
7969 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
7970 { "name", HAS_ARG, QEMU_OPTION_name },
7971 #if defined(TARGET_SPARC)
7972 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7973 #endif
7974 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
7975 #if defined(TARGET_ARM)
7976 { "old-param", 0, QEMU_OPTION_old_param },
7977 #endif
7978 { "clock", HAS_ARG, QEMU_OPTION_clock },
7979 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7980 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
7981 { NULL },
7984 /* password input */
7986 int qemu_key_check(BlockDriverState *bs, const char *name)
7988 char password[256];
7989 int i;
7991 if (!bdrv_is_encrypted(bs))
7992 return 0;
7994 term_printf("%s is encrypted.\n", name);
7995 for(i = 0; i < 3; i++) {
7996 monitor_readline("Password: ", 1, password, sizeof(password));
7997 if (bdrv_set_key(bs, password) == 0)
7998 return 0;
7999 term_printf("invalid password\n");
8001 return -EPERM;
8004 static BlockDriverState *get_bdrv(int index)
8006 if (index > nb_drives)
8007 return NULL;
8008 return drives_table[index].bdrv;
8011 static void read_passwords(void)
8013 BlockDriverState *bs;
8014 int i;
8016 for(i = 0; i < 6; i++) {
8017 bs = get_bdrv(i);
8018 if (bs)
8019 qemu_key_check(bs, bdrv_get_device_name(bs));
8023 #ifdef HAS_AUDIO
8024 struct soundhw soundhw[] = {
8025 #ifdef HAS_AUDIO_CHOICE
8026 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8028 "pcspk",
8029 "PC speaker",
8032 { .init_isa = pcspk_audio_init }
8034 #endif
8036 "sb16",
8037 "Creative Sound Blaster 16",
8040 { .init_isa = SB16_init }
8043 #ifdef CONFIG_ADLIB
8045 "adlib",
8046 #ifdef HAS_YMF262
8047 "Yamaha YMF262 (OPL3)",
8048 #else
8049 "Yamaha YM3812 (OPL2)",
8050 #endif
8053 { .init_isa = Adlib_init }
8055 #endif
8057 #ifdef CONFIG_GUS
8059 "gus",
8060 "Gravis Ultrasound GF1",
8063 { .init_isa = GUS_init }
8065 #endif
8067 #ifdef CONFIG_AC97
8069 "ac97",
8070 "Intel 82801AA AC97 Audio",
8073 { .init_pci = ac97_init }
8075 #endif
8078 "es1370",
8079 "ENSONIQ AudioPCI ES1370",
8082 { .init_pci = es1370_init }
8084 #endif
8086 { NULL, NULL, 0, 0, { NULL } }
8089 static void select_soundhw (const char *optarg)
8091 struct soundhw *c;
8093 if (*optarg == '?') {
8094 show_valid_cards:
8096 printf ("Valid sound card names (comma separated):\n");
8097 for (c = soundhw; c->name; ++c) {
8098 printf ("%-11s %s\n", c->name, c->descr);
8100 printf ("\n-soundhw all will enable all of the above\n");
8101 exit (*optarg != '?');
8103 else {
8104 size_t l;
8105 const char *p;
8106 char *e;
8107 int bad_card = 0;
8109 if (!strcmp (optarg, "all")) {
8110 for (c = soundhw; c->name; ++c) {
8111 c->enabled = 1;
8113 return;
8116 p = optarg;
8117 while (*p) {
8118 e = strchr (p, ',');
8119 l = !e ? strlen (p) : (size_t) (e - p);
8121 for (c = soundhw; c->name; ++c) {
8122 if (!strncmp (c->name, p, l)) {
8123 c->enabled = 1;
8124 break;
8128 if (!c->name) {
8129 if (l > 80) {
8130 fprintf (stderr,
8131 "Unknown sound card name (too big to show)\n");
8133 else {
8134 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8135 (int) l, p);
8137 bad_card = 1;
8139 p += l + (e != NULL);
8142 if (bad_card)
8143 goto show_valid_cards;
8146 #endif
8148 #ifdef _WIN32
8149 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8151 exit(STATUS_CONTROL_C_EXIT);
8152 return TRUE;
8154 #endif
8156 #define MAX_NET_CLIENTS 32
8158 static int saved_argc;
8159 static char **saved_argv;
8161 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
8163 *argc = saved_argc;
8164 *argv = saved_argv;
8165 *opt_daemonize = daemonize;
8166 *opt_incoming = incoming;
8170 static int gethugepagesize(void)
8172 int ret, fd;
8173 char buf[4096];
8174 char *needle = "Hugepagesize:";
8175 char *size;
8176 unsigned long hugepagesize;
8178 fd = open("/proc/meminfo", O_RDONLY);
8179 if (fd < 0) {
8180 perror("open");
8181 exit(0);
8184 ret = read(fd, buf, sizeof(buf));
8185 if (ret < 0) {
8186 perror("read");
8187 exit(0);
8190 size = strstr(buf, needle);
8191 if (!size)
8192 return 0;
8193 size += strlen(needle);
8194 hugepagesize = strtol(size, NULL, 0);
8195 return hugepagesize;
8198 void *alloc_mem_area(unsigned long memory, const char *path)
8200 char *filename;
8201 void *area;
8202 int fd;
8204 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
8205 return NULL;
8207 hpagesize = gethugepagesize() * 1024;
8208 if (!hpagesize)
8209 return NULL;
8211 fd = mkstemp(filename);
8212 if (fd < 0) {
8213 perror("mkstemp");
8214 free(filename);
8215 return NULL;
8217 unlink(filename);
8218 free(filename);
8220 memory = (memory+hpagesize-1) & ~(hpagesize-1);
8223 * ftruncate is not supported by hugetlbfs in older
8224 * hosts, so don't bother checking for errors.
8225 * If anything goes wrong with it under other filesystems,
8226 * mmap will fail.
8228 ftruncate(fd, memory);
8230 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
8231 if (area == MAP_FAILED) {
8232 perror("mmap");
8233 close(fd);
8234 return NULL;
8237 return area;
8240 void *qemu_alloc_physram(unsigned long memory)
8242 void *area = NULL;
8244 if (mem_path)
8245 area = alloc_mem_area(memory, mem_path);
8246 if (!area)
8247 area = qemu_vmalloc(memory);
8249 return area;
8252 int main(int argc, char **argv)
8254 #ifdef CONFIG_GDBSTUB
8255 int use_gdbstub;
8256 const char *gdbstub_port;
8257 #endif
8258 uint32_t boot_devices_bitmap = 0;
8259 int i;
8260 int snapshot, linux_boot, net_boot;
8261 const char *initrd_filename;
8262 const char *kernel_filename, *kernel_cmdline;
8263 const char *boot_devices = "";
8264 DisplayState *ds = &display_state;
8265 int cyls, heads, secs, translation;
8266 const char *net_clients[MAX_NET_CLIENTS];
8267 int nb_net_clients;
8268 int hda_index;
8269 int optind;
8270 const char *r, *optarg;
8271 CharDriverState *monitor_hd;
8272 const char *monitor_device;
8273 const char *serial_devices[MAX_SERIAL_PORTS];
8274 int serial_device_index;
8275 char vmchannel_devices[MAX_VMCHANNEL_DEVICES][128];
8276 int vmchannel_device_index;
8277 const char *parallel_devices[MAX_PARALLEL_PORTS];
8278 int parallel_device_index;
8279 const char *loadvm = NULL;
8280 QEMUMachine *machine;
8281 const char *cpu_model;
8282 const char *usb_devices[MAX_USB_CMDLINE];
8283 int usb_devices_index;
8284 int fds[2];
8285 const char *pid_file = NULL;
8286 VLANState *vlan;
8288 saved_argc = argc;
8289 saved_argv = argv;
8291 LIST_INIT (&vm_change_state_head);
8292 #ifndef _WIN32
8294 struct sigaction act;
8295 sigfillset(&act.sa_mask);
8296 act.sa_flags = 0;
8297 act.sa_handler = SIG_IGN;
8298 sigaction(SIGPIPE, &act, NULL);
8300 #else
8301 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8302 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8303 QEMU to run on a single CPU */
8305 HANDLE h;
8306 DWORD mask, smask;
8307 int i;
8308 h = GetCurrentProcess();
8309 if (GetProcessAffinityMask(h, &mask, &smask)) {
8310 for(i = 0; i < 32; i++) {
8311 if (mask & (1 << i))
8312 break;
8314 if (i != 32) {
8315 mask = 1 << i;
8316 SetProcessAffinityMask(h, mask);
8320 #endif
8322 register_machines();
8323 machine = first_machine;
8324 cpu_model = NULL;
8325 initrd_filename = NULL;
8326 ram_size = 0;
8327 vga_ram_size = VGA_RAM_SIZE;
8328 #ifdef CONFIG_GDBSTUB
8329 use_gdbstub = 0;
8330 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8331 #endif
8332 snapshot = 0;
8333 nographic = 0;
8334 curses = 0;
8335 kernel_filename = NULL;
8336 kernel_cmdline = "";
8337 cyls = heads = secs = 0;
8338 translation = BIOS_ATA_TRANSLATION_AUTO;
8339 monitor_device = "vc:800x600";
8341 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++)
8342 vmchannel_devices[i][0] = '\0';
8343 vmchannel_device_index = 0;
8345 serial_devices[0] = "vc:80Cx24C";
8346 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8347 serial_devices[i] = NULL;
8348 serial_device_index = 0;
8350 parallel_devices[0] = "vc:640x480";
8351 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8352 parallel_devices[i] = NULL;
8353 parallel_device_index = 0;
8355 usb_devices_index = 0;
8357 nb_net_clients = 0;
8358 nb_drives = 0;
8359 nb_drives_opt = 0;
8360 hda_index = -1;
8362 nb_nics = 0;
8363 /* default mac address of the first network interface */
8365 optind = 1;
8366 for(;;) {
8367 if (optind >= argc)
8368 break;
8369 r = argv[optind];
8370 if (r[0] != '-') {
8371 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8372 } else {
8373 const QEMUOption *popt;
8375 optind++;
8376 /* Treat --foo the same as -foo. */
8377 if (r[1] == '-')
8378 r++;
8379 popt = qemu_options;
8380 for(;;) {
8381 if (!popt->name) {
8382 fprintf(stderr, "%s: invalid option -- '%s'\n",
8383 argv[0], r);
8384 exit(1);
8386 if (!strcmp(popt->name, r + 1))
8387 break;
8388 popt++;
8390 if (popt->flags & HAS_ARG) {
8391 if (optind >= argc) {
8392 fprintf(stderr, "%s: option '%s' requires an argument\n",
8393 argv[0], r);
8394 exit(1);
8396 optarg = argv[optind++];
8397 } else {
8398 optarg = NULL;
8401 switch(popt->index) {
8402 case QEMU_OPTION_M:
8403 machine = find_machine(optarg);
8404 if (!machine) {
8405 QEMUMachine *m;
8406 printf("Supported machines are:\n");
8407 for(m = first_machine; m != NULL; m = m->next) {
8408 printf("%-10s %s%s\n",
8409 m->name, m->desc,
8410 m == first_machine ? " (default)" : "");
8412 exit(*optarg != '?');
8414 break;
8415 case QEMU_OPTION_cpu:
8416 /* hw initialization will check this */
8417 if (*optarg == '?') {
8418 /* XXX: implement xxx_cpu_list for targets that still miss it */
8419 #if defined(cpu_list)
8420 cpu_list(stdout, &fprintf);
8421 #endif
8422 exit(0);
8423 } else {
8424 cpu_model = optarg;
8426 break;
8427 case QEMU_OPTION_initrd:
8428 initrd_filename = optarg;
8429 break;
8430 case QEMU_OPTION_hda:
8431 if (cyls == 0)
8432 hda_index = drive_add(optarg, HD_ALIAS, 0);
8433 else
8434 hda_index = drive_add(optarg, HD_ALIAS
8435 ",cyls=%d,heads=%d,secs=%d%s",
8436 0, cyls, heads, secs,
8437 translation == BIOS_ATA_TRANSLATION_LBA ?
8438 ",trans=lba" :
8439 translation == BIOS_ATA_TRANSLATION_NONE ?
8440 ",trans=none" : "");
8441 break;
8442 case QEMU_OPTION_hdb:
8443 case QEMU_OPTION_hdc:
8444 case QEMU_OPTION_hdd:
8445 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8446 break;
8447 case QEMU_OPTION_drive:
8448 drive_add(NULL, "%s", optarg);
8449 break;
8450 case QEMU_OPTION_mtdblock:
8451 drive_add(optarg, MTD_ALIAS);
8452 break;
8453 case QEMU_OPTION_sd:
8454 drive_add(optarg, SD_ALIAS);
8455 break;
8456 case QEMU_OPTION_pflash:
8457 drive_add(optarg, PFLASH_ALIAS);
8458 break;
8459 case QEMU_OPTION_snapshot:
8460 snapshot = 1;
8461 break;
8462 case QEMU_OPTION_hdachs:
8464 const char *p;
8465 p = optarg;
8466 cyls = strtol(p, (char **)&p, 0);
8467 if (cyls < 1 || cyls > 16383)
8468 goto chs_fail;
8469 if (*p != ',')
8470 goto chs_fail;
8471 p++;
8472 heads = strtol(p, (char **)&p, 0);
8473 if (heads < 1 || heads > 16)
8474 goto chs_fail;
8475 if (*p != ',')
8476 goto chs_fail;
8477 p++;
8478 secs = strtol(p, (char **)&p, 0);
8479 if (secs < 1 || secs > 63)
8480 goto chs_fail;
8481 if (*p == ',') {
8482 p++;
8483 if (!strcmp(p, "none"))
8484 translation = BIOS_ATA_TRANSLATION_NONE;
8485 else if (!strcmp(p, "lba"))
8486 translation = BIOS_ATA_TRANSLATION_LBA;
8487 else if (!strcmp(p, "auto"))
8488 translation = BIOS_ATA_TRANSLATION_AUTO;
8489 else
8490 goto chs_fail;
8491 } else if (*p != '\0') {
8492 chs_fail:
8493 fprintf(stderr, "qemu: invalid physical CHS format\n");
8494 exit(1);
8496 if (hda_index != -1)
8497 snprintf(drives_opt[hda_index].opt,
8498 sizeof(drives_opt[hda_index].opt),
8499 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8500 0, cyls, heads, secs,
8501 translation == BIOS_ATA_TRANSLATION_LBA ?
8502 ",trans=lba" :
8503 translation == BIOS_ATA_TRANSLATION_NONE ?
8504 ",trans=none" : "");
8506 break;
8507 case QEMU_OPTION_nographic:
8508 serial_devices[0] = "stdio";
8509 parallel_devices[0] = "null";
8510 monitor_device = "stdio";
8511 nographic = 1;
8512 break;
8513 #ifdef CONFIG_CURSES
8514 case QEMU_OPTION_curses:
8515 curses = 1;
8516 break;
8517 #endif
8518 case QEMU_OPTION_portrait:
8519 graphic_rotate = 1;
8520 break;
8521 case QEMU_OPTION_kernel:
8522 kernel_filename = optarg;
8523 break;
8524 case QEMU_OPTION_append:
8525 kernel_cmdline = optarg;
8526 break;
8527 case QEMU_OPTION_cdrom:
8528 drive_add(optarg, CDROM_ALIAS);
8529 break;
8530 case QEMU_OPTION_boot:
8531 boot_devices = optarg;
8532 /* We just do some generic consistency checks */
8534 /* Could easily be extended to 64 devices if needed */
8535 const char *p;
8537 boot_devices_bitmap = 0;
8538 for (p = boot_devices; *p != '\0'; p++) {
8539 /* Allowed boot devices are:
8540 * a b : floppy disk drives
8541 * c ... f : IDE disk drives
8542 * g ... m : machine implementation dependant drives
8543 * n ... p : network devices
8544 * It's up to each machine implementation to check
8545 * if the given boot devices match the actual hardware
8546 * implementation and firmware features.
8548 if (*p < 'a' || *p > 'q') {
8549 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8550 exit(1);
8552 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8553 fprintf(stderr,
8554 "Boot device '%c' was given twice\n",*p);
8555 exit(1);
8557 boot_devices_bitmap |= 1 << (*p - 'a');
8560 break;
8561 case QEMU_OPTION_fda:
8562 case QEMU_OPTION_fdb:
8563 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8564 break;
8565 #ifdef TARGET_I386
8566 case QEMU_OPTION_no_fd_bootchk:
8567 fd_bootchk = 0;
8568 break;
8569 #endif
8570 case QEMU_OPTION_no_code_copy:
8571 code_copy_enabled = 0;
8572 break;
8573 case QEMU_OPTION_net:
8574 if (nb_net_clients >= MAX_NET_CLIENTS) {
8575 fprintf(stderr, "qemu: too many network clients\n");
8576 exit(1);
8578 net_clients[nb_net_clients] = optarg;
8579 nb_net_clients++;
8580 break;
8581 #ifdef CONFIG_SLIRP
8582 case QEMU_OPTION_tftp:
8583 tftp_prefix = optarg;
8584 break;
8585 case QEMU_OPTION_bootp:
8586 bootp_filename = optarg;
8587 break;
8588 #ifndef _WIN32
8589 case QEMU_OPTION_smb:
8590 net_slirp_smb(optarg);
8591 break;
8592 #endif
8593 case QEMU_OPTION_redir:
8594 net_slirp_redir(optarg);
8595 break;
8596 #endif
8597 #ifdef HAS_AUDIO
8598 case QEMU_OPTION_audio_help:
8599 AUD_help ();
8600 exit (0);
8601 break;
8602 case QEMU_OPTION_soundhw:
8603 select_soundhw (optarg);
8604 break;
8605 #endif
8606 case QEMU_OPTION_h:
8607 help(0);
8608 break;
8609 case QEMU_OPTION_m: {
8610 uint64_t value;
8611 char *ptr;
8613 value = strtoul(optarg, &ptr, 10);
8614 switch (*ptr) {
8615 case 0: case 'M': case 'm':
8616 value <<= 20;
8617 break;
8618 case 'G': case 'g':
8619 value <<= 30;
8620 break;
8621 default:
8622 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8623 exit(1);
8626 /* On 32-bit hosts, QEMU is limited by virtual address space */
8627 if (value > (2047 << 20)
8628 #ifndef USE_KQEMU
8629 && HOST_LONG_BITS == 32
8630 #endif
8632 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8633 exit(1);
8635 if (value != (uint64_t)(ram_addr_t)value) {
8636 fprintf(stderr, "qemu: ram size too large\n");
8637 exit(1);
8639 ram_size = value;
8640 break;
8642 case QEMU_OPTION_d:
8644 int mask;
8645 CPULogItem *item;
8647 mask = cpu_str_to_log_mask(optarg);
8648 if (!mask) {
8649 printf("Log items (comma separated):\n");
8650 for(item = cpu_log_items; item->mask != 0; item++) {
8651 printf("%-10s %s\n", item->name, item->help);
8653 exit(1);
8655 cpu_set_log(mask);
8657 break;
8658 #ifdef CONFIG_GDBSTUB
8659 case QEMU_OPTION_s:
8660 use_gdbstub = 1;
8661 break;
8662 case QEMU_OPTION_p:
8663 gdbstub_port = optarg;
8664 break;
8665 #endif
8666 case QEMU_OPTION_L:
8667 bios_dir = optarg;
8668 break;
8669 case QEMU_OPTION_bios:
8670 bios_name = optarg;
8671 break;
8672 case QEMU_OPTION_S:
8673 autostart = 0;
8674 break;
8675 case QEMU_OPTION_k:
8676 keyboard_layout = optarg;
8677 break;
8678 case QEMU_OPTION_localtime:
8679 rtc_utc = 0;
8680 break;
8681 case QEMU_OPTION_cirrusvga:
8682 cirrus_vga_enabled = 1;
8683 vmsvga_enabled = 0;
8684 break;
8685 case QEMU_OPTION_vmsvga:
8686 cirrus_vga_enabled = 0;
8687 vmsvga_enabled = 1;
8688 break;
8689 case QEMU_OPTION_std_vga:
8690 cirrus_vga_enabled = 0;
8691 vmsvga_enabled = 0;
8692 break;
8693 case QEMU_OPTION_g:
8695 const char *p;
8696 int w, h, depth;
8697 p = optarg;
8698 w = strtol(p, (char **)&p, 10);
8699 if (w <= 0) {
8700 graphic_error:
8701 fprintf(stderr, "qemu: invalid resolution or depth\n");
8702 exit(1);
8704 if (*p != 'x')
8705 goto graphic_error;
8706 p++;
8707 h = strtol(p, (char **)&p, 10);
8708 if (h <= 0)
8709 goto graphic_error;
8710 if (*p == 'x') {
8711 p++;
8712 depth = strtol(p, (char **)&p, 10);
8713 if (depth != 8 && depth != 15 && depth != 16 &&
8714 depth != 24 && depth != 32)
8715 goto graphic_error;
8716 } else if (*p == '\0') {
8717 depth = graphic_depth;
8718 } else {
8719 goto graphic_error;
8722 graphic_width = w;
8723 graphic_height = h;
8724 graphic_depth = depth;
8726 break;
8727 case QEMU_OPTION_echr:
8729 char *r;
8730 term_escape_char = strtol(optarg, &r, 0);
8731 if (r == optarg)
8732 printf("Bad argument to echr\n");
8733 break;
8735 case QEMU_OPTION_monitor:
8736 monitor_device = optarg;
8737 break;
8738 case QEMU_OPTION_balloon:
8739 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8740 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8741 exit(1);
8743 if (balloon_used) {
8744 fprintf(stderr, "qemu: only one balloon device can be used\n");
8745 exit(1);
8747 sprintf(vmchannel_devices[vmchannel_device_index],"di:cdcd,%s", optarg);
8748 vmchannel_device_index++;
8749 balloon_used = 1;
8750 break;
8751 case QEMU_OPTION_vmchannel:
8752 if (vmchannel_device_index >= MAX_VMCHANNEL_DEVICES) {
8753 fprintf(stderr, "qemu: too many balloon/vmchannel devices\n");
8754 exit(1);
8756 pstrcpy(vmchannel_devices[vmchannel_device_index],
8757 sizeof(vmchannel_devices[0]), optarg);
8758 vmchannel_device_index++;
8759 break;
8760 case QEMU_OPTION_serial:
8761 if (serial_device_index >= MAX_SERIAL_PORTS) {
8762 fprintf(stderr, "qemu: too many serial ports\n");
8763 exit(1);
8765 serial_devices[serial_device_index] = optarg;
8766 serial_device_index++;
8767 break;
8768 case QEMU_OPTION_parallel:
8769 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8770 fprintf(stderr, "qemu: too many parallel ports\n");
8771 exit(1);
8773 parallel_devices[parallel_device_index] = optarg;
8774 parallel_device_index++;
8775 break;
8776 case QEMU_OPTION_loadvm:
8777 loadvm = optarg;
8778 break;
8779 case QEMU_OPTION_incoming:
8780 incoming = optarg;
8781 break;
8782 case QEMU_OPTION_full_screen:
8783 full_screen = 1;
8784 break;
8785 #ifdef CONFIG_SDL
8786 case QEMU_OPTION_no_frame:
8787 no_frame = 1;
8788 break;
8789 case QEMU_OPTION_alt_grab:
8790 alt_grab = 1;
8791 break;
8792 case QEMU_OPTION_no_quit:
8793 no_quit = 1;
8794 break;
8795 #endif
8796 case QEMU_OPTION_pidfile:
8797 pid_file = optarg;
8798 break;
8799 #ifdef TARGET_I386
8800 case QEMU_OPTION_win2k_hack:
8801 win2k_install_hack = 1;
8802 break;
8803 #endif
8804 #ifdef USE_KQEMU
8805 case QEMU_OPTION_no_kqemu:
8806 kqemu_allowed = 0;
8807 break;
8808 case QEMU_OPTION_kernel_kqemu:
8809 kqemu_allowed = 2;
8810 break;
8811 #endif
8812 #ifdef USE_KVM
8813 case QEMU_OPTION_no_kvm:
8814 kvm_allowed = 0;
8815 break;
8816 case QEMU_OPTION_no_kvm_irqchip: {
8817 extern int kvm_irqchip, kvm_pit;
8818 kvm_irqchip = 0;
8819 kvm_pit = 0;
8820 break;
8822 case QEMU_OPTION_no_kvm_pit: {
8823 extern int kvm_pit;
8824 kvm_pit = 0;
8825 break;
8827 #endif
8828 case QEMU_OPTION_usb:
8829 usb_enabled = 1;
8830 break;
8831 case QEMU_OPTION_usbdevice:
8832 usb_enabled = 1;
8833 if (usb_devices_index >= MAX_USB_CMDLINE) {
8834 fprintf(stderr, "Too many USB devices\n");
8835 exit(1);
8837 usb_devices[usb_devices_index] = optarg;
8838 usb_devices_index++;
8839 break;
8840 case QEMU_OPTION_smp:
8841 smp_cpus = atoi(optarg);
8842 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8843 fprintf(stderr, "Invalid number of CPUs\n");
8844 exit(1);
8846 break;
8847 case QEMU_OPTION_vnc:
8848 vnc_display = optarg;
8849 break;
8850 case QEMU_OPTION_no_acpi:
8851 acpi_enabled = 0;
8852 break;
8853 case QEMU_OPTION_no_reboot:
8854 no_reboot = 1;
8855 break;
8856 case QEMU_OPTION_no_shutdown:
8857 no_shutdown = 1;
8858 break;
8859 case QEMU_OPTION_show_cursor:
8860 cursor_hide = 0;
8861 break;
8862 case QEMU_OPTION_daemonize:
8863 daemonize = 1;
8864 break;
8865 case QEMU_OPTION_option_rom:
8866 if (nb_option_roms >= MAX_OPTION_ROMS) {
8867 fprintf(stderr, "Too many option ROMs\n");
8868 exit(1);
8870 option_rom[nb_option_roms] = optarg;
8871 nb_option_roms++;
8872 break;
8873 case QEMU_OPTION_semihosting:
8874 semihosting_enabled = 1;
8875 break;
8876 case QEMU_OPTION_tdf:
8877 time_drift_fix = 1;
8878 break;
8879 case QEMU_OPTION_kvm_shadow_memory:
8880 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
8881 break;
8882 case QEMU_OPTION_mempath:
8883 mem_path = optarg;
8884 break;
8885 case QEMU_OPTION_name:
8886 qemu_name = optarg;
8887 break;
8888 #ifdef TARGET_SPARC
8889 case QEMU_OPTION_prom_env:
8890 if (nb_prom_envs >= MAX_PROM_ENVS) {
8891 fprintf(stderr, "Too many prom variables\n");
8892 exit(1);
8894 prom_envs[nb_prom_envs] = optarg;
8895 nb_prom_envs++;
8896 break;
8897 #endif
8898 case QEMU_OPTION_cpu_vendor:
8899 cpu_vendor_string = optarg;
8900 break;
8901 #ifdef TARGET_ARM
8902 case QEMU_OPTION_old_param:
8903 old_param = 1;
8904 break;
8905 #endif
8906 case QEMU_OPTION_clock:
8907 configure_alarms(optarg);
8908 break;
8909 case QEMU_OPTION_startdate:
8911 struct tm tm;
8912 time_t rtc_start_date;
8913 if (!strcmp(optarg, "now")) {
8914 rtc_date_offset = -1;
8915 } else {
8916 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8917 &tm.tm_year,
8918 &tm.tm_mon,
8919 &tm.tm_mday,
8920 &tm.tm_hour,
8921 &tm.tm_min,
8922 &tm.tm_sec) == 6) {
8923 /* OK */
8924 } else if (sscanf(optarg, "%d-%d-%d",
8925 &tm.tm_year,
8926 &tm.tm_mon,
8927 &tm.tm_mday) == 3) {
8928 tm.tm_hour = 0;
8929 tm.tm_min = 0;
8930 tm.tm_sec = 0;
8931 } else {
8932 goto date_fail;
8934 tm.tm_year -= 1900;
8935 tm.tm_mon--;
8936 rtc_start_date = mktimegm(&tm);
8937 if (rtc_start_date == -1) {
8938 date_fail:
8939 fprintf(stderr, "Invalid date format. Valid format are:\n"
8940 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8941 exit(1);
8943 rtc_date_offset = time(NULL) - rtc_start_date;
8946 break;
8951 #ifndef _WIN32
8952 if (daemonize) {
8953 pid_t pid;
8955 if (pipe(fds) == -1)
8956 exit(1);
8958 pid = fork();
8959 if (pid > 0) {
8960 uint8_t status;
8961 ssize_t len;
8963 close(fds[1]);
8965 again:
8966 len = read(fds[0], &status, 1);
8967 if (len == -1 && (errno == EINTR))
8968 goto again;
8970 if (len != 1)
8971 exit(1);
8972 else if (status == 1) {
8973 fprintf(stderr, "Could not acquire pidfile\n");
8974 exit(1);
8975 } else
8976 exit(0);
8977 } else if (pid < 0)
8978 exit(1);
8980 setsid();
8982 pid = fork();
8983 if (pid > 0)
8984 exit(0);
8985 else if (pid < 0)
8986 exit(1);
8988 umask(027);
8990 signal(SIGTSTP, SIG_IGN);
8991 signal(SIGTTOU, SIG_IGN);
8992 signal(SIGTTIN, SIG_IGN);
8994 #endif
8996 #if USE_KVM
8997 if (kvm_enabled()) {
8998 if (kvm_qemu_init() < 0) {
8999 extern int kvm_allowed;
9000 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
9001 #ifdef NO_CPU_EMULATION
9002 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
9003 exit(1);
9004 #endif
9005 kvm_allowed = 0;
9008 #endif
9010 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9011 if (daemonize) {
9012 uint8_t status = 1;
9013 write(fds[1], &status, 1);
9014 } else
9015 fprintf(stderr, "Could not acquire pid file\n");
9016 exit(1);
9019 #ifdef USE_KQEMU
9020 if (smp_cpus > 1)
9021 kqemu_allowed = 0;
9022 #endif
9023 linux_boot = (kernel_filename != NULL);
9024 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9026 /* XXX: this should not be: some embedded targets just have flash */
9027 if (!linux_boot && net_boot == 0 &&
9028 nb_drives_opt == 0)
9029 help(1);
9031 /* boot to floppy or the default cd if no hard disk defined yet */
9032 if (!boot_devices[0]) {
9033 boot_devices = "cad";
9035 setvbuf(stdout, NULL, _IOLBF, 0);
9037 init_timers();
9038 init_timer_alarm();
9039 qemu_aio_init();
9041 #ifdef _WIN32
9042 socket_init();
9043 #endif
9045 /* init network clients */
9046 if (nb_net_clients == 0) {
9047 /* if no clients, we use a default config */
9048 net_clients[0] = "nic";
9049 net_clients[1] = "user";
9050 nb_net_clients = 2;
9053 for(i = 0;i < nb_net_clients; i++) {
9054 if (net_client_init(net_clients[i]) < 0)
9055 exit(1);
9057 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9058 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9059 continue;
9060 if (vlan->nb_guest_devs == 0) {
9061 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
9062 exit(1);
9064 if (vlan->nb_host_devs == 0)
9065 fprintf(stderr,
9066 "Warning: vlan %d is not connected to host network\n",
9067 vlan->id);
9070 #ifdef TARGET_I386
9071 /* XXX: this should be moved in the PC machine instantiation code */
9072 if (net_boot != 0) {
9073 int netroms = 0;
9074 for (i = 0; i < nb_nics && i < 4; i++) {
9075 const char *model = nd_table[i].model;
9076 char buf[1024];
9077 if (net_boot & (1 << i)) {
9078 if (model == NULL)
9079 model = "rtl8139";
9080 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9081 if (get_image_size(buf) > 0) {
9082 if (nb_option_roms >= MAX_OPTION_ROMS) {
9083 fprintf(stderr, "Too many option ROMs\n");
9084 exit(1);
9086 option_rom[nb_option_roms] = strdup(buf);
9087 nb_option_roms++;
9088 netroms++;
9092 if (netroms == 0) {
9093 fprintf(stderr, "No valid PXE rom found for network device\n");
9094 exit(1);
9097 #endif
9099 /* init the memory */
9100 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9102 if (machine->ram_require & RAMSIZE_FIXED) {
9103 if (ram_size > 0) {
9104 if (ram_size < phys_ram_size) {
9105 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9106 machine->name, (unsigned long long) phys_ram_size);
9107 exit(-1);
9110 phys_ram_size = ram_size;
9111 } else
9112 ram_size = phys_ram_size;
9113 } else {
9114 if (ram_size == 0)
9115 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9117 phys_ram_size += ram_size;
9120 /* Initialize kvm */
9121 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9122 #define KVM_EXTRA_PAGES 3
9123 #else
9124 #define KVM_EXTRA_PAGES 0
9125 #endif
9126 if (kvm_enabled()) {
9127 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
9128 if (kvm_qemu_create_context() < 0) {
9129 fprintf(stderr, "Could not create KVM context\n");
9130 exit(1);
9132 #ifdef KVM_CAP_USER_MEMORY
9134 int ret;
9136 ret = kvm_qemu_check_extension(KVM_CAP_USER_MEMORY);
9137 if (ret) {
9138 phys_ram_base = qemu_alloc_physram(phys_ram_size);
9139 if (!phys_ram_base) {
9140 fprintf(stderr, "Could not allocate physical memory\n");
9141 exit(1);
9145 #endif
9146 } else {
9147 phys_ram_base = qemu_vmalloc(phys_ram_size);
9148 if (!phys_ram_base) {
9149 fprintf(stderr, "Could not allocate physical memory\n");
9150 exit(1);
9154 bdrv_init();
9156 /* we always create the cdrom drive, even if no disk is there */
9158 if (nb_drives_opt < MAX_DRIVES)
9159 drive_add(NULL, CDROM_ALIAS);
9161 /* we always create at least one floppy */
9163 if (nb_drives_opt < MAX_DRIVES)
9164 drive_add(NULL, FD_ALIAS, 0);
9166 /* we always create one sd slot, even if no card is in it */
9168 if (nb_drives_opt < MAX_DRIVES)
9169 drive_add(NULL, SD_ALIAS);
9171 /* open the virtual block devices
9172 * note that migration with device
9173 * hot add/remove is broken.
9175 for(i = 0; i < nb_drives_opt; i++)
9176 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9177 exit(1);
9179 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9180 register_savevm("ram", 0, 3, ram_save, ram_load, NULL);
9182 init_ioports();
9184 /* terminal init */
9185 memset(&display_state, 0, sizeof(display_state));
9186 if (nographic) {
9187 if (curses) {
9188 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9189 exit(1);
9191 /* nearly nothing to do */
9192 dumb_display_init(ds);
9193 } else if (vnc_display != NULL) {
9194 vnc_display_init(ds);
9195 if (vnc_display_open(ds, vnc_display) < 0)
9196 exit(1);
9197 } else
9198 #if defined(CONFIG_CURSES)
9199 if (curses) {
9200 curses_display_init(ds, full_screen);
9201 } else
9202 #endif
9204 #if defined(CONFIG_SDL)
9205 sdl_display_init(ds, full_screen, no_frame);
9206 #elif defined(CONFIG_COCOA)
9207 cocoa_display_init(ds, full_screen);
9208 #else
9209 dumb_display_init(ds);
9210 #endif
9213 /* Maintain compatibility with multiple stdio monitors */
9214 if (!strcmp(monitor_device,"stdio")) {
9215 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9216 const char *devname = serial_devices[i];
9217 if (devname && !strcmp(devname,"mon:stdio")) {
9218 monitor_device = NULL;
9219 break;
9220 } else if (devname && !strcmp(devname,"stdio")) {
9221 monitor_device = NULL;
9222 serial_devices[i] = "mon:stdio";
9223 break;
9227 if (monitor_device) {
9228 monitor_hd = qemu_chr_open(monitor_device);
9229 if (!monitor_hd) {
9230 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9231 exit(1);
9233 monitor_init(monitor_hd, !nographic);
9236 for(i = 0; i < MAX_VMCHANNEL_DEVICES; i++) {
9237 const char *devname = vmchannel_devices[i];
9238 if (devname[0] != '\0' && strcmp(devname, "none")) {
9239 int devid;
9240 char *termn;
9242 if (strstart(devname, "di:", &devname)) {
9243 devid = strtol(devname, &termn, 16);
9244 devname = termn + 1;
9246 else {
9247 fprintf(stderr, "qemu: could not find vmchannel device id '%s'\n",
9248 devname);
9249 exit(1);
9251 vmchannel_hds[i] = qemu_chr_open(devname);
9252 if (!vmchannel_hds[i]) {
9253 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n",
9254 devname);
9255 exit(1);
9257 vmchannel_init(vmchannel_hds[i], devid, i);
9261 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9262 const char *devname = serial_devices[i];
9263 if (devname && strcmp(devname, "none")) {
9264 serial_hds[i] = qemu_chr_open(devname);
9265 if (!serial_hds[i]) {
9266 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9267 devname);
9268 exit(1);
9270 if (strstart(devname, "vc", 0))
9271 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9275 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9276 const char *devname = parallel_devices[i];
9277 if (devname && strcmp(devname, "none")) {
9278 parallel_hds[i] = qemu_chr_open(devname);
9279 if (!parallel_hds[i]) {
9280 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9281 devname);
9282 exit(1);
9284 if (strstart(devname, "vc", 0))
9285 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9289 if (kvm_enabled())
9290 kvm_init_ap();
9292 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9293 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9295 current_machine = machine;
9297 /* init USB devices */
9298 if (usb_enabled) {
9299 for(i = 0; i < usb_devices_index; i++) {
9300 if (usb_device_add(usb_devices[i]) < 0) {
9301 fprintf(stderr, "Warning: could not add USB device %s\n",
9302 usb_devices[i]);
9307 if (display_state.dpy_refresh) {
9308 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9309 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9312 #ifdef CONFIG_GDBSTUB
9313 if (use_gdbstub) {
9314 /* XXX: use standard host:port notation and modify options
9315 accordingly. */
9316 if (gdbserver_start(gdbstub_port) < 0) {
9317 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9318 gdbstub_port);
9319 exit(1);
9322 #endif
9323 if (loadvm)
9324 do_loadvm(loadvm);
9326 if (incoming) {
9327 int rc;
9329 rc = migrate_incoming(incoming);
9330 if (rc != 0) {
9331 fprintf(stderr, "Migration failed rc=%d\n", rc);
9332 exit(rc);
9337 /* XXX: simplify init */
9338 read_passwords();
9339 if (autostart) {
9340 vm_start();
9344 if (daemonize) {
9345 uint8_t status = 0;
9346 ssize_t len;
9347 int fd;
9349 again1:
9350 len = write(fds[1], &status, 1);
9351 if (len == -1 && (errno == EINTR))
9352 goto again1;
9354 if (len != 1)
9355 exit(1);
9357 chdir("/");
9358 TFR(fd = open("/dev/null", O_RDWR));
9359 if (fd == -1)
9360 exit(1);
9362 dup2(fd, 0);
9363 dup2(fd, 1);
9364 dup2(fd, 2);
9366 close(fd);
9369 main_loop();
9370 quit_timers();
9372 #if !defined(_WIN32)
9373 /* close network clients */
9374 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9375 VLANClientState *vc;
9377 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9378 if (vc->fd_read == tap_receive) {
9379 char ifname[64];
9380 TAPState *s = vc->opaque;
9382 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9383 s->down_script[0])
9384 launch_script(s->down_script, ifname, s->fd);
9388 #endif
9389 return 0;