Enable ld flag --warn-common
[qemu/mini2440.git] / vl.c
blob0d964010ff029d7b7a5eb8bd217fd7734312585c
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"
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <time.h>
45 #include <errno.h>
46 #include <sys/time.h>
47 #include <zlib.h>
49 #ifndef _WIN32
50 #include <sys/times.h>
51 #include <sys/wait.h>
52 #include <termios.h>
53 #include <sys/poll.h>
54 #include <sys/mman.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <dirent.h>
59 #include <netdb.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
62 #ifdef _BSD
63 #include <sys/stat.h>
64 #if !defined(__APPLE__) && !defined(__OpenBSD__)
65 #include <libutil.h>
66 #endif
67 #ifdef __OpenBSD__
68 #include <net/if.h>
69 #endif
70 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
71 #include <freebsd/stdlib.h>
72 #else
73 #ifndef __sun__
74 #include <linux/if.h>
75 #include <linux/if_tun.h>
76 #include <pty.h>
77 #include <malloc.h>
78 #include <linux/rtc.h>
80 /* For the benefit of older linux systems which don't supply it,
81 we use a local copy of hpet.h. */
82 /* #include <linux/hpet.h> */
83 #include "hpet.h"
85 #include <linux/ppdev.h>
86 #include <linux/parport.h>
87 #else
88 #include <sys/stat.h>
89 #include <sys/ethernet.h>
90 #include <sys/sockio.h>
91 #include <netinet/arp.h>
92 #include <netinet/in.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/ip.h>
95 #include <netinet/ip_icmp.h> // must come after ip.h
96 #include <netinet/udp.h>
97 #include <netinet/tcp.h>
98 #include <net/if.h>
99 #include <syslog.h>
100 #include <stropts.h>
101 #endif
102 #endif
103 #endif
105 #include "qemu_socket.h"
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
109 #endif
111 #if defined(__OpenBSD__)
112 #include <util.h>
113 #endif
115 #if defined(CONFIG_VDE)
116 #include <libvdeplug.h>
117 #endif
119 #ifdef _WIN32
120 #include <malloc.h>
121 #include <sys/timeb.h>
122 #include <mmsystem.h>
123 #define getopt_long_only getopt_long
124 #define memalign(align, size) malloc(size)
125 #endif
127 #ifdef CONFIG_SDL
128 #ifdef __APPLE__
129 #include <SDL/SDL.h>
130 #endif
131 #endif /* CONFIG_SDL */
133 #ifdef CONFIG_COCOA
134 #undef main
135 #define main qemu_main
136 #endif /* CONFIG_COCOA */
138 #include "disas.h"
140 #include "exec-all.h"
142 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
143 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
144 #ifdef __sun__
145 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
146 #else
147 #define SMBD_COMMAND "/usr/sbin/smbd"
148 #endif
150 //#define DEBUG_UNUSED_IOPORT
151 //#define DEBUG_IOPORT
153 #ifdef TARGET_PPC
154 #define DEFAULT_RAM_SIZE 144
155 #else
156 #define DEFAULT_RAM_SIZE 128
157 #endif
159 /* Max number of USB devices that can be specified on the commandline. */
160 #define MAX_USB_CMDLINE 8
162 /* XXX: use a two level table to limit memory usage */
163 #define MAX_IOPORTS 65536
165 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
166 const char *bios_name = NULL;
167 void *ioport_opaque[MAX_IOPORTS];
168 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
169 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
170 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
171 to store the VM snapshots */
172 DriveInfo drives_table[MAX_DRIVES+1];
173 int nb_drives;
174 /* point to the block driver where the snapshots are managed */
175 BlockDriverState *bs_snapshots;
176 int vga_ram_size;
177 static DisplayState display_state;
178 int nographic;
179 int curses;
180 const char* keyboard_layout = NULL;
181 int64_t ticks_per_sec;
182 ram_addr_t ram_size;
183 int pit_min_timer_count = 0;
184 int nb_nics;
185 NICInfo nd_table[MAX_NICS];
186 int vm_running;
187 static int rtc_utc = 1;
188 static int rtc_date_offset = -1; /* -1 means no change */
189 int cirrus_vga_enabled = 1;
190 int vmsvga_enabled = 0;
191 #ifdef TARGET_SPARC
192 int graphic_width = 1024;
193 int graphic_height = 768;
194 int graphic_depth = 8;
195 #else
196 int graphic_width = 800;
197 int graphic_height = 600;
198 int graphic_depth = 15;
199 #endif
200 int full_screen = 0;
201 int no_frame = 0;
202 int no_quit = 0;
203 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
204 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
205 #ifdef TARGET_I386
206 int win2k_install_hack = 0;
207 #endif
208 int usb_enabled = 0;
209 static VLANState *first_vlan;
210 int smp_cpus = 1;
211 const char *vnc_display;
212 #if defined(TARGET_SPARC)
213 #define MAX_CPUS 16
214 #elif defined(TARGET_I386)
215 #define MAX_CPUS 255
216 #else
217 #define MAX_CPUS 1
218 #endif
219 int acpi_enabled = 1;
220 int fd_bootchk = 1;
221 int no_reboot = 0;
222 int no_shutdown = 0;
223 int cursor_hide = 1;
224 int graphic_rotate = 0;
225 int daemonize = 0;
226 const char *option_rom[MAX_OPTION_ROMS];
227 int nb_option_roms;
228 int semihosting_enabled = 0;
229 int autostart = 1;
230 #ifdef TARGET_ARM
231 int old_param = 0;
232 #endif
233 const char *qemu_name;
234 int alt_grab = 0;
235 #ifdef TARGET_SPARC
236 unsigned int nb_prom_envs = 0;
237 const char *prom_envs[MAX_PROM_ENVS];
238 #endif
239 int nb_drives_opt;
240 struct drive_opt {
241 const char *file;
242 char opt[1024];
243 } drives_opt[MAX_DRIVES];
245 static CPUState *cur_cpu;
246 static CPUState *next_cpu;
247 static int event_pending = 1;
248 /* Conversion factor from emulated instructions to virtual clock ticks. */
249 static int icount_time_shift;
250 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
251 #define MAX_ICOUNT_SHIFT 10
252 /* Compensate for varying guest execution speed. */
253 static int64_t qemu_icount_bias;
254 QEMUTimer *icount_rt_timer;
255 QEMUTimer *icount_vm_timer;
257 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
259 /***********************************************************/
260 /* x86 ISA bus support */
262 target_phys_addr_t isa_mem_base = 0;
263 PicState2 *isa_pic;
265 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
266 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
268 static uint32_t ioport_read(int index, uint32_t address)
270 static IOPortReadFunc *default_func[3] = {
271 default_ioport_readb,
272 default_ioport_readw,
273 default_ioport_readl
275 IOPortReadFunc *func = ioport_read_table[index][address];
276 if (!func)
277 func = default_func[index];
278 return func(ioport_opaque[address], address);
281 static void ioport_write(int index, uint32_t address, uint32_t data)
283 static IOPortWriteFunc *default_func[3] = {
284 default_ioport_writeb,
285 default_ioport_writew,
286 default_ioport_writel
288 IOPortWriteFunc *func = ioport_write_table[index][address];
289 if (!func)
290 func = default_func[index];
291 func(ioport_opaque[address], address, data);
294 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
296 #ifdef DEBUG_UNUSED_IOPORT
297 fprintf(stderr, "unused inb: port=0x%04x\n", address);
298 #endif
299 return 0xff;
302 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
304 #ifdef DEBUG_UNUSED_IOPORT
305 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
306 #endif
309 /* default is to make two byte accesses */
310 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
312 uint32_t data;
313 data = ioport_read(0, address);
314 address = (address + 1) & (MAX_IOPORTS - 1);
315 data |= ioport_read(0, address) << 8;
316 return data;
319 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
321 ioport_write(0, address, data & 0xff);
322 address = (address + 1) & (MAX_IOPORTS - 1);
323 ioport_write(0, address, (data >> 8) & 0xff);
326 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
328 #ifdef DEBUG_UNUSED_IOPORT
329 fprintf(stderr, "unused inl: port=0x%04x\n", address);
330 #endif
331 return 0xffffffff;
334 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
336 #ifdef DEBUG_UNUSED_IOPORT
337 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
338 #endif
341 /* size is the word size in byte */
342 int register_ioport_read(int start, int length, int size,
343 IOPortReadFunc *func, void *opaque)
345 int i, bsize;
347 if (size == 1) {
348 bsize = 0;
349 } else if (size == 2) {
350 bsize = 1;
351 } else if (size == 4) {
352 bsize = 2;
353 } else {
354 hw_error("register_ioport_read: invalid size");
355 return -1;
357 for(i = start; i < start + length; i += size) {
358 ioport_read_table[bsize][i] = func;
359 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
360 hw_error("register_ioport_read: invalid opaque");
361 ioport_opaque[i] = opaque;
363 return 0;
366 /* size is the word size in byte */
367 int register_ioport_write(int start, int length, int size,
368 IOPortWriteFunc *func, void *opaque)
370 int i, bsize;
372 if (size == 1) {
373 bsize = 0;
374 } else if (size == 2) {
375 bsize = 1;
376 } else if (size == 4) {
377 bsize = 2;
378 } else {
379 hw_error("register_ioport_write: invalid size");
380 return -1;
382 for(i = start; i < start + length; i += size) {
383 ioport_write_table[bsize][i] = func;
384 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
385 hw_error("register_ioport_write: invalid opaque");
386 ioport_opaque[i] = opaque;
388 return 0;
391 void isa_unassign_ioport(int start, int length)
393 int i;
395 for(i = start; i < start + length; i++) {
396 ioport_read_table[0][i] = default_ioport_readb;
397 ioport_read_table[1][i] = default_ioport_readw;
398 ioport_read_table[2][i] = default_ioport_readl;
400 ioport_write_table[0][i] = default_ioport_writeb;
401 ioport_write_table[1][i] = default_ioport_writew;
402 ioport_write_table[2][i] = default_ioport_writel;
406 /***********************************************************/
408 void cpu_outb(CPUState *env, int addr, int val)
410 #ifdef DEBUG_IOPORT
411 if (loglevel & CPU_LOG_IOPORT)
412 fprintf(logfile, "outb: %04x %02x\n", addr, val);
413 #endif
414 ioport_write(0, addr, val);
415 #ifdef USE_KQEMU
416 if (env)
417 env->last_io_time = cpu_get_time_fast();
418 #endif
421 void cpu_outw(CPUState *env, int addr, int val)
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "outw: %04x %04x\n", addr, val);
426 #endif
427 ioport_write(1, addr, val);
428 #ifdef USE_KQEMU
429 if (env)
430 env->last_io_time = cpu_get_time_fast();
431 #endif
434 void cpu_outl(CPUState *env, int addr, int val)
436 #ifdef DEBUG_IOPORT
437 if (loglevel & CPU_LOG_IOPORT)
438 fprintf(logfile, "outl: %04x %08x\n", addr, val);
439 #endif
440 ioport_write(2, addr, val);
441 #ifdef USE_KQEMU
442 if (env)
443 env->last_io_time = cpu_get_time_fast();
444 #endif
447 int cpu_inb(CPUState *env, int addr)
449 int val;
450 val = ioport_read(0, addr);
451 #ifdef DEBUG_IOPORT
452 if (loglevel & CPU_LOG_IOPORT)
453 fprintf(logfile, "inb : %04x %02x\n", addr, val);
454 #endif
455 #ifdef USE_KQEMU
456 if (env)
457 env->last_io_time = cpu_get_time_fast();
458 #endif
459 return val;
462 int cpu_inw(CPUState *env, int addr)
464 int val;
465 val = ioport_read(1, addr);
466 #ifdef DEBUG_IOPORT
467 if (loglevel & CPU_LOG_IOPORT)
468 fprintf(logfile, "inw : %04x %04x\n", addr, val);
469 #endif
470 #ifdef USE_KQEMU
471 if (env)
472 env->last_io_time = cpu_get_time_fast();
473 #endif
474 return val;
477 int cpu_inl(CPUState *env, int addr)
479 int val;
480 val = ioport_read(2, addr);
481 #ifdef DEBUG_IOPORT
482 if (loglevel & CPU_LOG_IOPORT)
483 fprintf(logfile, "inl : %04x %08x\n", addr, val);
484 #endif
485 #ifdef USE_KQEMU
486 if (env)
487 env->last_io_time = cpu_get_time_fast();
488 #endif
489 return val;
492 /***********************************************************/
493 void hw_error(const char *fmt, ...)
495 va_list ap;
496 CPUState *env;
498 va_start(ap, fmt);
499 fprintf(stderr, "qemu: hardware error: ");
500 vfprintf(stderr, fmt, ap);
501 fprintf(stderr, "\n");
502 for(env = first_cpu; env != NULL; env = env->next_cpu) {
503 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
504 #ifdef TARGET_I386
505 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
506 #else
507 cpu_dump_state(env, stderr, fprintf, 0);
508 #endif
510 va_end(ap);
511 abort();
514 /***********************************************************/
515 /* keyboard/mouse */
517 static QEMUPutKBDEvent *qemu_put_kbd_event;
518 static void *qemu_put_kbd_event_opaque;
519 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
520 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
522 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
524 qemu_put_kbd_event_opaque = opaque;
525 qemu_put_kbd_event = func;
528 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
529 void *opaque, int absolute,
530 const char *name)
532 QEMUPutMouseEntry *s, *cursor;
534 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
535 if (!s)
536 return NULL;
538 s->qemu_put_mouse_event = func;
539 s->qemu_put_mouse_event_opaque = opaque;
540 s->qemu_put_mouse_event_absolute = absolute;
541 s->qemu_put_mouse_event_name = qemu_strdup(name);
542 s->next = NULL;
544 if (!qemu_put_mouse_event_head) {
545 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
546 return s;
549 cursor = qemu_put_mouse_event_head;
550 while (cursor->next != NULL)
551 cursor = cursor->next;
553 cursor->next = s;
554 qemu_put_mouse_event_current = s;
556 return s;
559 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
561 QEMUPutMouseEntry *prev = NULL, *cursor;
563 if (!qemu_put_mouse_event_head || entry == NULL)
564 return;
566 cursor = qemu_put_mouse_event_head;
567 while (cursor != NULL && cursor != entry) {
568 prev = cursor;
569 cursor = cursor->next;
572 if (cursor == NULL) // does not exist or list empty
573 return;
574 else if (prev == NULL) { // entry is head
575 qemu_put_mouse_event_head = cursor->next;
576 if (qemu_put_mouse_event_current == entry)
577 qemu_put_mouse_event_current = cursor->next;
578 qemu_free(entry->qemu_put_mouse_event_name);
579 qemu_free(entry);
580 return;
583 prev->next = entry->next;
585 if (qemu_put_mouse_event_current == entry)
586 qemu_put_mouse_event_current = prev;
588 qemu_free(entry->qemu_put_mouse_event_name);
589 qemu_free(entry);
592 void kbd_put_keycode(int keycode)
594 if (qemu_put_kbd_event) {
595 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
599 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
601 QEMUPutMouseEvent *mouse_event;
602 void *mouse_event_opaque;
603 int width;
605 if (!qemu_put_mouse_event_current) {
606 return;
609 mouse_event =
610 qemu_put_mouse_event_current->qemu_put_mouse_event;
611 mouse_event_opaque =
612 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
614 if (mouse_event) {
615 if (graphic_rotate) {
616 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
617 width = 0x7fff;
618 else
619 width = graphic_width - 1;
620 mouse_event(mouse_event_opaque,
621 width - dy, dx, dz, buttons_state);
622 } else
623 mouse_event(mouse_event_opaque,
624 dx, dy, dz, buttons_state);
628 int kbd_mouse_is_absolute(void)
630 if (!qemu_put_mouse_event_current)
631 return 0;
633 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
636 void do_info_mice(void)
638 QEMUPutMouseEntry *cursor;
639 int index = 0;
641 if (!qemu_put_mouse_event_head) {
642 term_printf("No mouse devices connected\n");
643 return;
646 term_printf("Mouse devices available:\n");
647 cursor = qemu_put_mouse_event_head;
648 while (cursor != NULL) {
649 term_printf("%c Mouse #%d: %s\n",
650 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
651 index, cursor->qemu_put_mouse_event_name);
652 index++;
653 cursor = cursor->next;
657 void do_mouse_set(int index)
659 QEMUPutMouseEntry *cursor;
660 int i = 0;
662 if (!qemu_put_mouse_event_head) {
663 term_printf("No mouse devices connected\n");
664 return;
667 cursor = qemu_put_mouse_event_head;
668 while (cursor != NULL && index != i) {
669 i++;
670 cursor = cursor->next;
673 if (cursor != NULL)
674 qemu_put_mouse_event_current = cursor;
675 else
676 term_printf("Mouse at given index not found\n");
679 /* compute with 96 bit intermediate result: (a*b)/c */
680 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
682 union {
683 uint64_t ll;
684 struct {
685 #ifdef WORDS_BIGENDIAN
686 uint32_t high, low;
687 #else
688 uint32_t low, high;
689 #endif
690 } l;
691 } u, res;
692 uint64_t rl, rh;
694 u.ll = a;
695 rl = (uint64_t)u.l.low * (uint64_t)b;
696 rh = (uint64_t)u.l.high * (uint64_t)b;
697 rh += (rl >> 32);
698 res.l.high = rh / c;
699 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
700 return res.ll;
703 /***********************************************************/
704 /* real time host monotonic timer */
706 #define QEMU_TIMER_BASE 1000000000LL
708 #ifdef WIN32
710 static int64_t clock_freq;
712 static void init_get_clock(void)
714 LARGE_INTEGER freq;
715 int ret;
716 ret = QueryPerformanceFrequency(&freq);
717 if (ret == 0) {
718 fprintf(stderr, "Could not calibrate ticks\n");
719 exit(1);
721 clock_freq = freq.QuadPart;
724 static int64_t get_clock(void)
726 LARGE_INTEGER ti;
727 QueryPerformanceCounter(&ti);
728 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
731 #else
733 static int use_rt_clock;
735 static void init_get_clock(void)
737 use_rt_clock = 0;
738 #if defined(__linux__)
740 struct timespec ts;
741 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
742 use_rt_clock = 1;
745 #endif
748 static int64_t get_clock(void)
750 #if defined(__linux__)
751 if (use_rt_clock) {
752 struct timespec ts;
753 clock_gettime(CLOCK_MONOTONIC, &ts);
754 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
755 } else
756 #endif
758 /* XXX: using gettimeofday leads to problems if the date
759 changes, so it should be avoided. */
760 struct timeval tv;
761 gettimeofday(&tv, NULL);
762 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
765 #endif
767 /* Return the virtual CPU time, based on the instruction counter. */
768 static int64_t cpu_get_icount(void)
770 int64_t icount;
771 CPUState *env = cpu_single_env;;
772 icount = qemu_icount;
773 if (env) {
774 if (!can_do_io(env))
775 fprintf(stderr, "Bad clock read\n");
776 icount -= (env->icount_decr.u16.low + env->icount_extra);
778 return qemu_icount_bias + (icount << icount_time_shift);
781 /***********************************************************/
782 /* guest cycle counter */
784 static int64_t cpu_ticks_prev;
785 static int64_t cpu_ticks_offset;
786 static int64_t cpu_clock_offset;
787 static int cpu_ticks_enabled;
789 /* return the host CPU cycle counter and handle stop/restart */
790 int64_t cpu_get_ticks(void)
792 if (use_icount) {
793 return cpu_get_icount();
795 if (!cpu_ticks_enabled) {
796 return cpu_ticks_offset;
797 } else {
798 int64_t ticks;
799 ticks = cpu_get_real_ticks();
800 if (cpu_ticks_prev > ticks) {
801 /* Note: non increasing ticks may happen if the host uses
802 software suspend */
803 cpu_ticks_offset += cpu_ticks_prev - ticks;
805 cpu_ticks_prev = ticks;
806 return ticks + cpu_ticks_offset;
810 /* return the host CPU monotonic timer and handle stop/restart */
811 static int64_t cpu_get_clock(void)
813 int64_t ti;
814 if (!cpu_ticks_enabled) {
815 return cpu_clock_offset;
816 } else {
817 ti = get_clock();
818 return ti + cpu_clock_offset;
822 /* enable cpu_get_ticks() */
823 void cpu_enable_ticks(void)
825 if (!cpu_ticks_enabled) {
826 cpu_ticks_offset -= cpu_get_real_ticks();
827 cpu_clock_offset -= get_clock();
828 cpu_ticks_enabled = 1;
832 /* disable cpu_get_ticks() : the clock is stopped. You must not call
833 cpu_get_ticks() after that. */
834 void cpu_disable_ticks(void)
836 if (cpu_ticks_enabled) {
837 cpu_ticks_offset = cpu_get_ticks();
838 cpu_clock_offset = cpu_get_clock();
839 cpu_ticks_enabled = 0;
843 /***********************************************************/
844 /* timers */
846 #define QEMU_TIMER_REALTIME 0
847 #define QEMU_TIMER_VIRTUAL 1
849 struct QEMUClock {
850 int type;
851 /* XXX: add frequency */
854 struct QEMUTimer {
855 QEMUClock *clock;
856 int64_t expire_time;
857 QEMUTimerCB *cb;
858 void *opaque;
859 struct QEMUTimer *next;
862 struct qemu_alarm_timer {
863 char const *name;
864 unsigned int flags;
866 int (*start)(struct qemu_alarm_timer *t);
867 void (*stop)(struct qemu_alarm_timer *t);
868 void (*rearm)(struct qemu_alarm_timer *t);
869 void *priv;
872 #define ALARM_FLAG_DYNTICKS 0x1
873 #define ALARM_FLAG_EXPIRED 0x2
875 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
877 return t->flags & ALARM_FLAG_DYNTICKS;
880 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
882 if (!alarm_has_dynticks(t))
883 return;
885 t->rearm(t);
888 /* TODO: MIN_TIMER_REARM_US should be optimized */
889 #define MIN_TIMER_REARM_US 250
891 static struct qemu_alarm_timer *alarm_timer;
893 #ifdef _WIN32
895 struct qemu_alarm_win32 {
896 MMRESULT timerId;
897 HANDLE host_alarm;
898 unsigned int period;
899 } alarm_win32_data = {0, NULL, -1};
901 static int win32_start_timer(struct qemu_alarm_timer *t);
902 static void win32_stop_timer(struct qemu_alarm_timer *t);
903 static void win32_rearm_timer(struct qemu_alarm_timer *t);
905 #else
907 static int unix_start_timer(struct qemu_alarm_timer *t);
908 static void unix_stop_timer(struct qemu_alarm_timer *t);
910 #ifdef __linux__
912 static int dynticks_start_timer(struct qemu_alarm_timer *t);
913 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
914 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
916 static int hpet_start_timer(struct qemu_alarm_timer *t);
917 static void hpet_stop_timer(struct qemu_alarm_timer *t);
919 static int rtc_start_timer(struct qemu_alarm_timer *t);
920 static void rtc_stop_timer(struct qemu_alarm_timer *t);
922 #endif /* __linux__ */
924 #endif /* _WIN32 */
926 /* Correlation between real and virtual time is always going to be
927 fairly approximate, so ignore small variation.
928 When the guest is idle real and virtual time will be aligned in
929 the IO wait loop. */
930 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
932 static void icount_adjust(void)
934 int64_t cur_time;
935 int64_t cur_icount;
936 int64_t delta;
937 static int64_t last_delta;
938 /* If the VM is not running, then do nothing. */
939 if (!vm_running)
940 return;
942 cur_time = cpu_get_clock();
943 cur_icount = qemu_get_clock(vm_clock);
944 delta = cur_icount - cur_time;
945 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
946 if (delta > 0
947 && last_delta + ICOUNT_WOBBLE < delta * 2
948 && icount_time_shift > 0) {
949 /* The guest is getting too far ahead. Slow time down. */
950 icount_time_shift--;
952 if (delta < 0
953 && last_delta - ICOUNT_WOBBLE > delta * 2
954 && icount_time_shift < MAX_ICOUNT_SHIFT) {
955 /* The guest is getting too far behind. Speed time up. */
956 icount_time_shift++;
958 last_delta = delta;
959 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
962 static void icount_adjust_rt(void * opaque)
964 qemu_mod_timer(icount_rt_timer,
965 qemu_get_clock(rt_clock) + 1000);
966 icount_adjust();
969 static void icount_adjust_vm(void * opaque)
971 qemu_mod_timer(icount_vm_timer,
972 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
973 icount_adjust();
976 static void init_icount_adjust(void)
978 /* Have both realtime and virtual time triggers for speed adjustment.
979 The realtime trigger catches emulated time passing too slowly,
980 the virtual time trigger catches emulated time passing too fast.
981 Realtime triggers occur even when idle, so use them less frequently
982 than VM triggers. */
983 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
984 qemu_mod_timer(icount_rt_timer,
985 qemu_get_clock(rt_clock) + 1000);
986 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
987 qemu_mod_timer(icount_vm_timer,
988 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
991 static struct qemu_alarm_timer alarm_timers[] = {
992 #ifndef _WIN32
993 #ifdef __linux__
994 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
995 dynticks_stop_timer, dynticks_rearm_timer, NULL},
996 /* HPET - if available - is preferred */
997 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
998 /* ...otherwise try RTC */
999 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1000 #endif
1001 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1002 #else
1003 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1004 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1005 {"win32", 0, win32_start_timer,
1006 win32_stop_timer, NULL, &alarm_win32_data},
1007 #endif
1008 {NULL, }
1011 static void show_available_alarms(void)
1013 int i;
1015 printf("Available alarm timers, in order of precedence:\n");
1016 for (i = 0; alarm_timers[i].name; i++)
1017 printf("%s\n", alarm_timers[i].name);
1020 static void configure_alarms(char const *opt)
1022 int i;
1023 int cur = 0;
1024 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1025 char *arg;
1026 char *name;
1027 struct qemu_alarm_timer tmp;
1029 if (!strcmp(opt, "?")) {
1030 show_available_alarms();
1031 exit(0);
1034 arg = strdup(opt);
1036 /* Reorder the array */
1037 name = strtok(arg, ",");
1038 while (name) {
1039 for (i = 0; i < count && alarm_timers[i].name; i++) {
1040 if (!strcmp(alarm_timers[i].name, name))
1041 break;
1044 if (i == count) {
1045 fprintf(stderr, "Unknown clock %s\n", name);
1046 goto next;
1049 if (i < cur)
1050 /* Ignore */
1051 goto next;
1053 /* Swap */
1054 tmp = alarm_timers[i];
1055 alarm_timers[i] = alarm_timers[cur];
1056 alarm_timers[cur] = tmp;
1058 cur++;
1059 next:
1060 name = strtok(NULL, ",");
1063 free(arg);
1065 if (cur) {
1066 /* Disable remaining timers */
1067 for (i = cur; i < count; i++)
1068 alarm_timers[i].name = NULL;
1069 } else {
1070 show_available_alarms();
1071 exit(1);
1075 QEMUClock *rt_clock;
1076 QEMUClock *vm_clock;
1078 static QEMUTimer *active_timers[2];
1080 static QEMUClock *qemu_new_clock(int type)
1082 QEMUClock *clock;
1083 clock = qemu_mallocz(sizeof(QEMUClock));
1084 if (!clock)
1085 return NULL;
1086 clock->type = type;
1087 return clock;
1090 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1092 QEMUTimer *ts;
1094 ts = qemu_mallocz(sizeof(QEMUTimer));
1095 ts->clock = clock;
1096 ts->cb = cb;
1097 ts->opaque = opaque;
1098 return ts;
1101 void qemu_free_timer(QEMUTimer *ts)
1103 qemu_free(ts);
1106 /* stop a timer, but do not dealloc it */
1107 void qemu_del_timer(QEMUTimer *ts)
1109 QEMUTimer **pt, *t;
1111 /* NOTE: this code must be signal safe because
1112 qemu_timer_expired() can be called from a signal. */
1113 pt = &active_timers[ts->clock->type];
1114 for(;;) {
1115 t = *pt;
1116 if (!t)
1117 break;
1118 if (t == ts) {
1119 *pt = t->next;
1120 break;
1122 pt = &t->next;
1126 /* modify the current timer so that it will be fired when current_time
1127 >= expire_time. The corresponding callback will be called. */
1128 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1130 QEMUTimer **pt, *t;
1132 qemu_del_timer(ts);
1134 /* add the timer in the sorted list */
1135 /* NOTE: this code must be signal safe because
1136 qemu_timer_expired() can be called from a signal. */
1137 pt = &active_timers[ts->clock->type];
1138 for(;;) {
1139 t = *pt;
1140 if (!t)
1141 break;
1142 if (t->expire_time > expire_time)
1143 break;
1144 pt = &t->next;
1146 ts->expire_time = expire_time;
1147 ts->next = *pt;
1148 *pt = ts;
1150 /* Rearm if necessary */
1151 if (pt == &active_timers[ts->clock->type]) {
1152 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1153 qemu_rearm_alarm_timer(alarm_timer);
1155 /* Interrupt execution to force deadline recalculation. */
1156 if (use_icount && cpu_single_env) {
1157 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1162 int qemu_timer_pending(QEMUTimer *ts)
1164 QEMUTimer *t;
1165 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1166 if (t == ts)
1167 return 1;
1169 return 0;
1172 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1174 if (!timer_head)
1175 return 0;
1176 return (timer_head->expire_time <= current_time);
1179 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1181 QEMUTimer *ts;
1183 for(;;) {
1184 ts = *ptimer_head;
1185 if (!ts || ts->expire_time > current_time)
1186 break;
1187 /* remove timer from the list before calling the callback */
1188 *ptimer_head = ts->next;
1189 ts->next = NULL;
1191 /* run the callback (the timer list can be modified) */
1192 ts->cb(ts->opaque);
1196 int64_t qemu_get_clock(QEMUClock *clock)
1198 switch(clock->type) {
1199 case QEMU_TIMER_REALTIME:
1200 return get_clock() / 1000000;
1201 default:
1202 case QEMU_TIMER_VIRTUAL:
1203 if (use_icount) {
1204 return cpu_get_icount();
1205 } else {
1206 return cpu_get_clock();
1211 static void init_timers(void)
1213 init_get_clock();
1214 ticks_per_sec = QEMU_TIMER_BASE;
1215 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1216 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1219 /* save a timer */
1220 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1222 uint64_t expire_time;
1224 if (qemu_timer_pending(ts)) {
1225 expire_time = ts->expire_time;
1226 } else {
1227 expire_time = -1;
1229 qemu_put_be64(f, expire_time);
1232 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1234 uint64_t expire_time;
1236 expire_time = qemu_get_be64(f);
1237 if (expire_time != -1) {
1238 qemu_mod_timer(ts, expire_time);
1239 } else {
1240 qemu_del_timer(ts);
1244 static void timer_save(QEMUFile *f, void *opaque)
1246 if (cpu_ticks_enabled) {
1247 hw_error("cannot save state if virtual timers are running");
1249 qemu_put_be64(f, cpu_ticks_offset);
1250 qemu_put_be64(f, ticks_per_sec);
1251 qemu_put_be64(f, cpu_clock_offset);
1254 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1256 if (version_id != 1 && version_id != 2)
1257 return -EINVAL;
1258 if (cpu_ticks_enabled) {
1259 return -EINVAL;
1261 cpu_ticks_offset=qemu_get_be64(f);
1262 ticks_per_sec=qemu_get_be64(f);
1263 if (version_id == 2) {
1264 cpu_clock_offset=qemu_get_be64(f);
1266 return 0;
1269 #ifdef _WIN32
1270 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1271 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1272 #else
1273 static void host_alarm_handler(int host_signum)
1274 #endif
1276 #if 0
1277 #define DISP_FREQ 1000
1279 static int64_t delta_min = INT64_MAX;
1280 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1281 static int count;
1282 ti = qemu_get_clock(vm_clock);
1283 if (last_clock != 0) {
1284 delta = ti - last_clock;
1285 if (delta < delta_min)
1286 delta_min = delta;
1287 if (delta > delta_max)
1288 delta_max = delta;
1289 delta_cum += delta;
1290 if (++count == DISP_FREQ) {
1291 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1292 muldiv64(delta_min, 1000000, ticks_per_sec),
1293 muldiv64(delta_max, 1000000, ticks_per_sec),
1294 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1295 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1296 count = 0;
1297 delta_min = INT64_MAX;
1298 delta_max = 0;
1299 delta_cum = 0;
1302 last_clock = ti;
1304 #endif
1305 if (alarm_has_dynticks(alarm_timer) ||
1306 (!use_icount &&
1307 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1308 qemu_get_clock(vm_clock))) ||
1309 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1310 qemu_get_clock(rt_clock))) {
1311 #ifdef _WIN32
1312 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1313 SetEvent(data->host_alarm);
1314 #endif
1315 CPUState *env = next_cpu;
1317 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1319 if (env) {
1320 /* stop the currently executing cpu because a timer occured */
1321 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1322 #ifdef USE_KQEMU
1323 if (env->kqemu_enabled) {
1324 kqemu_cpu_interrupt(env);
1326 #endif
1328 event_pending = 1;
1332 static int64_t qemu_next_deadline(void)
1334 int64_t delta;
1336 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1337 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1338 qemu_get_clock(vm_clock);
1339 } else {
1340 /* To avoid problems with overflow limit this to 2^32. */
1341 delta = INT32_MAX;
1344 if (delta < 0)
1345 delta = 0;
1347 return delta;
1350 #if defined(__linux__) || defined(_WIN32)
1351 static uint64_t qemu_next_deadline_dyntick(void)
1353 int64_t delta;
1354 int64_t rtdelta;
1356 if (use_icount)
1357 delta = INT32_MAX;
1358 else
1359 delta = (qemu_next_deadline() + 999) / 1000;
1361 if (active_timers[QEMU_TIMER_REALTIME]) {
1362 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1363 qemu_get_clock(rt_clock))*1000;
1364 if (rtdelta < delta)
1365 delta = rtdelta;
1368 if (delta < MIN_TIMER_REARM_US)
1369 delta = MIN_TIMER_REARM_US;
1371 return delta;
1373 #endif
1375 #ifndef _WIN32
1377 #if defined(__linux__)
1379 #define RTC_FREQ 1024
1381 static void enable_sigio_timer(int fd)
1383 struct sigaction act;
1385 /* timer signal */
1386 sigfillset(&act.sa_mask);
1387 act.sa_flags = 0;
1388 act.sa_handler = host_alarm_handler;
1390 sigaction(SIGIO, &act, NULL);
1391 fcntl(fd, F_SETFL, O_ASYNC);
1392 fcntl(fd, F_SETOWN, getpid());
1395 static int hpet_start_timer(struct qemu_alarm_timer *t)
1397 struct hpet_info info;
1398 int r, fd;
1400 fd = open("/dev/hpet", O_RDONLY);
1401 if (fd < 0)
1402 return -1;
1404 /* Set frequency */
1405 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1406 if (r < 0) {
1407 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1408 "error, but for better emulation accuracy type:\n"
1409 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1410 goto fail;
1413 /* Check capabilities */
1414 r = ioctl(fd, HPET_INFO, &info);
1415 if (r < 0)
1416 goto fail;
1418 /* Enable periodic mode */
1419 r = ioctl(fd, HPET_EPI, 0);
1420 if (info.hi_flags && (r < 0))
1421 goto fail;
1423 /* Enable interrupt */
1424 r = ioctl(fd, HPET_IE_ON, 0);
1425 if (r < 0)
1426 goto fail;
1428 enable_sigio_timer(fd);
1429 t->priv = (void *)(long)fd;
1431 return 0;
1432 fail:
1433 close(fd);
1434 return -1;
1437 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1439 int fd = (long)t->priv;
1441 close(fd);
1444 static int rtc_start_timer(struct qemu_alarm_timer *t)
1446 int rtc_fd;
1447 unsigned long current_rtc_freq = 0;
1449 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1450 if (rtc_fd < 0)
1451 return -1;
1452 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1453 if (current_rtc_freq != RTC_FREQ &&
1454 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1455 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1456 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1457 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1458 goto fail;
1460 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1461 fail:
1462 close(rtc_fd);
1463 return -1;
1466 enable_sigio_timer(rtc_fd);
1468 t->priv = (void *)(long)rtc_fd;
1470 return 0;
1473 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1475 int rtc_fd = (long)t->priv;
1477 close(rtc_fd);
1480 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1482 struct sigevent ev;
1483 timer_t host_timer;
1484 struct sigaction act;
1486 sigfillset(&act.sa_mask);
1487 act.sa_flags = 0;
1488 act.sa_handler = host_alarm_handler;
1490 sigaction(SIGALRM, &act, NULL);
1492 ev.sigev_value.sival_int = 0;
1493 ev.sigev_notify = SIGEV_SIGNAL;
1494 ev.sigev_signo = SIGALRM;
1496 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1497 perror("timer_create");
1499 /* disable dynticks */
1500 fprintf(stderr, "Dynamic Ticks disabled\n");
1502 return -1;
1505 t->priv = (void *)host_timer;
1507 return 0;
1510 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1512 timer_t host_timer = (timer_t)t->priv;
1514 timer_delete(host_timer);
1517 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1519 timer_t host_timer = (timer_t)t->priv;
1520 struct itimerspec timeout;
1521 int64_t nearest_delta_us = INT64_MAX;
1522 int64_t current_us;
1524 if (!active_timers[QEMU_TIMER_REALTIME] &&
1525 !active_timers[QEMU_TIMER_VIRTUAL])
1526 return;
1528 nearest_delta_us = qemu_next_deadline_dyntick();
1530 /* check whether a timer is already running */
1531 if (timer_gettime(host_timer, &timeout)) {
1532 perror("gettime");
1533 fprintf(stderr, "Internal timer error: aborting\n");
1534 exit(1);
1536 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1537 if (current_us && current_us <= nearest_delta_us)
1538 return;
1540 timeout.it_interval.tv_sec = 0;
1541 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1542 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1543 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1544 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1545 perror("settime");
1546 fprintf(stderr, "Internal timer error: aborting\n");
1547 exit(1);
1551 #endif /* defined(__linux__) */
1553 static int unix_start_timer(struct qemu_alarm_timer *t)
1555 struct sigaction act;
1556 struct itimerval itv;
1557 int err;
1559 /* timer signal */
1560 sigfillset(&act.sa_mask);
1561 act.sa_flags = 0;
1562 act.sa_handler = host_alarm_handler;
1564 sigaction(SIGALRM, &act, NULL);
1566 itv.it_interval.tv_sec = 0;
1567 /* for i386 kernel 2.6 to get 1 ms */
1568 itv.it_interval.tv_usec = 999;
1569 itv.it_value.tv_sec = 0;
1570 itv.it_value.tv_usec = 10 * 1000;
1572 err = setitimer(ITIMER_REAL, &itv, NULL);
1573 if (err)
1574 return -1;
1576 return 0;
1579 static void unix_stop_timer(struct qemu_alarm_timer *t)
1581 struct itimerval itv;
1583 memset(&itv, 0, sizeof(itv));
1584 setitimer(ITIMER_REAL, &itv, NULL);
1587 #endif /* !defined(_WIN32) */
1589 #ifdef _WIN32
1591 static int win32_start_timer(struct qemu_alarm_timer *t)
1593 TIMECAPS tc;
1594 struct qemu_alarm_win32 *data = t->priv;
1595 UINT flags;
1597 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1598 if (!data->host_alarm) {
1599 perror("Failed CreateEvent");
1600 return -1;
1603 memset(&tc, 0, sizeof(tc));
1604 timeGetDevCaps(&tc, sizeof(tc));
1606 if (data->period < tc.wPeriodMin)
1607 data->period = tc.wPeriodMin;
1609 timeBeginPeriod(data->period);
1611 flags = TIME_CALLBACK_FUNCTION;
1612 if (alarm_has_dynticks(t))
1613 flags |= TIME_ONESHOT;
1614 else
1615 flags |= TIME_PERIODIC;
1617 data->timerId = timeSetEvent(1, // interval (ms)
1618 data->period, // resolution
1619 host_alarm_handler, // function
1620 (DWORD)t, // parameter
1621 flags);
1623 if (!data->timerId) {
1624 perror("Failed to initialize win32 alarm timer");
1626 timeEndPeriod(data->period);
1627 CloseHandle(data->host_alarm);
1628 return -1;
1631 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1633 return 0;
1636 static void win32_stop_timer(struct qemu_alarm_timer *t)
1638 struct qemu_alarm_win32 *data = t->priv;
1640 timeKillEvent(data->timerId);
1641 timeEndPeriod(data->period);
1643 CloseHandle(data->host_alarm);
1646 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1648 struct qemu_alarm_win32 *data = t->priv;
1649 uint64_t nearest_delta_us;
1651 if (!active_timers[QEMU_TIMER_REALTIME] &&
1652 !active_timers[QEMU_TIMER_VIRTUAL])
1653 return;
1655 nearest_delta_us = qemu_next_deadline_dyntick();
1656 nearest_delta_us /= 1000;
1658 timeKillEvent(data->timerId);
1660 data->timerId = timeSetEvent(1,
1661 data->period,
1662 host_alarm_handler,
1663 (DWORD)t,
1664 TIME_ONESHOT | TIME_PERIODIC);
1666 if (!data->timerId) {
1667 perror("Failed to re-arm win32 alarm timer");
1669 timeEndPeriod(data->period);
1670 CloseHandle(data->host_alarm);
1671 exit(1);
1675 #endif /* _WIN32 */
1677 static void init_timer_alarm(void)
1679 struct qemu_alarm_timer *t;
1680 int i, err = -1;
1682 for (i = 0; alarm_timers[i].name; i++) {
1683 t = &alarm_timers[i];
1685 err = t->start(t);
1686 if (!err)
1687 break;
1690 if (err) {
1691 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1692 fprintf(stderr, "Terminating\n");
1693 exit(1);
1696 alarm_timer = t;
1699 static void quit_timers(void)
1701 alarm_timer->stop(alarm_timer);
1702 alarm_timer = NULL;
1705 /***********************************************************/
1706 /* host time/date access */
1707 void qemu_get_timedate(struct tm *tm, int offset)
1709 time_t ti;
1710 struct tm *ret;
1712 time(&ti);
1713 ti += offset;
1714 if (rtc_date_offset == -1) {
1715 if (rtc_utc)
1716 ret = gmtime(&ti);
1717 else
1718 ret = localtime(&ti);
1719 } else {
1720 ti -= rtc_date_offset;
1721 ret = gmtime(&ti);
1724 memcpy(tm, ret, sizeof(struct tm));
1727 int qemu_timedate_diff(struct tm *tm)
1729 time_t seconds;
1731 if (rtc_date_offset == -1)
1732 if (rtc_utc)
1733 seconds = mktimegm(tm);
1734 else
1735 seconds = mktime(tm);
1736 else
1737 seconds = mktimegm(tm) + rtc_date_offset;
1739 return seconds - time(NULL);
1742 /***********************************************************/
1743 /* character device */
1745 static void qemu_chr_event(CharDriverState *s, int event)
1747 if (!s->chr_event)
1748 return;
1749 s->chr_event(s->handler_opaque, event);
1752 static void qemu_chr_reset_bh(void *opaque)
1754 CharDriverState *s = opaque;
1755 qemu_chr_event(s, CHR_EVENT_RESET);
1756 qemu_bh_delete(s->bh);
1757 s->bh = NULL;
1760 void qemu_chr_reset(CharDriverState *s)
1762 if (s->bh == NULL) {
1763 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1764 qemu_bh_schedule(s->bh);
1768 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1770 return s->chr_write(s, buf, len);
1773 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1775 if (!s->chr_ioctl)
1776 return -ENOTSUP;
1777 return s->chr_ioctl(s, cmd, arg);
1780 int qemu_chr_can_read(CharDriverState *s)
1782 if (!s->chr_can_read)
1783 return 0;
1784 return s->chr_can_read(s->handler_opaque);
1787 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1789 s->chr_read(s->handler_opaque, buf, len);
1792 void qemu_chr_accept_input(CharDriverState *s)
1794 if (s->chr_accept_input)
1795 s->chr_accept_input(s);
1798 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1800 char buf[4096];
1801 va_list ap;
1802 va_start(ap, fmt);
1803 vsnprintf(buf, sizeof(buf), fmt, ap);
1804 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1805 va_end(ap);
1808 void qemu_chr_send_event(CharDriverState *s, int event)
1810 if (s->chr_send_event)
1811 s->chr_send_event(s, event);
1814 void qemu_chr_add_handlers(CharDriverState *s,
1815 IOCanRWHandler *fd_can_read,
1816 IOReadHandler *fd_read,
1817 IOEventHandler *fd_event,
1818 void *opaque)
1820 s->chr_can_read = fd_can_read;
1821 s->chr_read = fd_read;
1822 s->chr_event = fd_event;
1823 s->handler_opaque = opaque;
1824 if (s->chr_update_read_handler)
1825 s->chr_update_read_handler(s);
1828 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1830 return len;
1833 static CharDriverState *qemu_chr_open_null(void)
1835 CharDriverState *chr;
1837 chr = qemu_mallocz(sizeof(CharDriverState));
1838 if (!chr)
1839 return NULL;
1840 chr->chr_write = null_chr_write;
1841 return chr;
1844 /* MUX driver for serial I/O splitting */
1845 static int term_timestamps;
1846 static int64_t term_timestamps_start;
1847 #define MAX_MUX 4
1848 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1849 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1850 typedef struct {
1851 IOCanRWHandler *chr_can_read[MAX_MUX];
1852 IOReadHandler *chr_read[MAX_MUX];
1853 IOEventHandler *chr_event[MAX_MUX];
1854 void *ext_opaque[MAX_MUX];
1855 CharDriverState *drv;
1856 unsigned char buffer[MUX_BUFFER_SIZE];
1857 int prod;
1858 int cons;
1859 int mux_cnt;
1860 int term_got_escape;
1861 int max_size;
1862 } MuxDriver;
1865 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1867 MuxDriver *d = chr->opaque;
1868 int ret;
1869 if (!term_timestamps) {
1870 ret = d->drv->chr_write(d->drv, buf, len);
1871 } else {
1872 int i;
1874 ret = 0;
1875 for(i = 0; i < len; i++) {
1876 ret += d->drv->chr_write(d->drv, buf+i, 1);
1877 if (buf[i] == '\n') {
1878 char buf1[64];
1879 int64_t ti;
1880 int secs;
1882 ti = get_clock();
1883 if (term_timestamps_start == -1)
1884 term_timestamps_start = ti;
1885 ti -= term_timestamps_start;
1886 secs = ti / 1000000000;
1887 snprintf(buf1, sizeof(buf1),
1888 "[%02d:%02d:%02d.%03d] ",
1889 secs / 3600,
1890 (secs / 60) % 60,
1891 secs % 60,
1892 (int)((ti / 1000000) % 1000));
1893 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1897 return ret;
1900 static const char * const mux_help[] = {
1901 "% h print this help\n\r",
1902 "% x exit emulator\n\r",
1903 "% s save disk data back to file (if -snapshot)\n\r",
1904 "% t toggle console timestamps\n\r"
1905 "% b send break (magic sysrq)\n\r",
1906 "% c switch between console and monitor\n\r",
1907 "% % sends %\n\r",
1908 NULL
1911 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1912 static void mux_print_help(CharDriverState *chr)
1914 int i, j;
1915 char ebuf[15] = "Escape-Char";
1916 char cbuf[50] = "\n\r";
1918 if (term_escape_char > 0 && term_escape_char < 26) {
1919 snprintf(cbuf, sizeof(cbuf), "\n\r");
1920 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1921 } else {
1922 snprintf(cbuf, sizeof(cbuf),
1923 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1924 term_escape_char);
1926 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1927 for (i = 0; mux_help[i] != NULL; i++) {
1928 for (j=0; mux_help[i][j] != '\0'; j++) {
1929 if (mux_help[i][j] == '%')
1930 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1931 else
1932 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1937 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1939 if (d->term_got_escape) {
1940 d->term_got_escape = 0;
1941 if (ch == term_escape_char)
1942 goto send_char;
1943 switch(ch) {
1944 case '?':
1945 case 'h':
1946 mux_print_help(chr);
1947 break;
1948 case 'x':
1950 const char *term = "QEMU: Terminated\n\r";
1951 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1952 exit(0);
1953 break;
1955 case 's':
1957 int i;
1958 for (i = 0; i < nb_drives; i++) {
1959 bdrv_commit(drives_table[i].bdrv);
1962 break;
1963 case 'b':
1964 qemu_chr_event(chr, CHR_EVENT_BREAK);
1965 break;
1966 case 'c':
1967 /* Switch to the next registered device */
1968 chr->focus++;
1969 if (chr->focus >= d->mux_cnt)
1970 chr->focus = 0;
1971 break;
1972 case 't':
1973 term_timestamps = !term_timestamps;
1974 term_timestamps_start = -1;
1975 break;
1977 } else if (ch == term_escape_char) {
1978 d->term_got_escape = 1;
1979 } else {
1980 send_char:
1981 return 1;
1983 return 0;
1986 static void mux_chr_accept_input(CharDriverState *chr)
1988 int m = chr->focus;
1989 MuxDriver *d = chr->opaque;
1991 while (d->prod != d->cons &&
1992 d->chr_can_read[m] &&
1993 d->chr_can_read[m](d->ext_opaque[m])) {
1994 d->chr_read[m](d->ext_opaque[m],
1995 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1999 static int mux_chr_can_read(void *opaque)
2001 CharDriverState *chr = opaque;
2002 MuxDriver *d = chr->opaque;
2004 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2005 return 1;
2006 if (d->chr_can_read[chr->focus])
2007 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2008 return 0;
2011 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2013 CharDriverState *chr = opaque;
2014 MuxDriver *d = chr->opaque;
2015 int m = chr->focus;
2016 int i;
2018 mux_chr_accept_input (opaque);
2020 for(i = 0; i < size; i++)
2021 if (mux_proc_byte(chr, d, buf[i])) {
2022 if (d->prod == d->cons &&
2023 d->chr_can_read[m] &&
2024 d->chr_can_read[m](d->ext_opaque[m]))
2025 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2026 else
2027 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2031 static void mux_chr_event(void *opaque, int event)
2033 CharDriverState *chr = opaque;
2034 MuxDriver *d = chr->opaque;
2035 int i;
2037 /* Send the event to all registered listeners */
2038 for (i = 0; i < d->mux_cnt; i++)
2039 if (d->chr_event[i])
2040 d->chr_event[i](d->ext_opaque[i], event);
2043 static void mux_chr_update_read_handler(CharDriverState *chr)
2045 MuxDriver *d = chr->opaque;
2047 if (d->mux_cnt >= MAX_MUX) {
2048 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2049 return;
2051 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2052 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2053 d->chr_read[d->mux_cnt] = chr->chr_read;
2054 d->chr_event[d->mux_cnt] = chr->chr_event;
2055 /* Fix up the real driver with mux routines */
2056 if (d->mux_cnt == 0) {
2057 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2058 mux_chr_event, chr);
2060 chr->focus = d->mux_cnt;
2061 d->mux_cnt++;
2064 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2066 CharDriverState *chr;
2067 MuxDriver *d;
2069 chr = qemu_mallocz(sizeof(CharDriverState));
2070 if (!chr)
2071 return NULL;
2072 d = qemu_mallocz(sizeof(MuxDriver));
2073 if (!d) {
2074 free(chr);
2075 return NULL;
2078 chr->opaque = d;
2079 d->drv = drv;
2080 chr->focus = -1;
2081 chr->chr_write = mux_chr_write;
2082 chr->chr_update_read_handler = mux_chr_update_read_handler;
2083 chr->chr_accept_input = mux_chr_accept_input;
2084 return chr;
2088 #ifdef _WIN32
2090 static void socket_cleanup(void)
2092 WSACleanup();
2095 static int socket_init(void)
2097 WSADATA Data;
2098 int ret, err;
2100 ret = WSAStartup(MAKEWORD(2,2), &Data);
2101 if (ret != 0) {
2102 err = WSAGetLastError();
2103 fprintf(stderr, "WSAStartup: %d\n", err);
2104 return -1;
2106 atexit(socket_cleanup);
2107 return 0;
2110 static int send_all(int fd, const uint8_t *buf, int len1)
2112 int ret, len;
2114 len = len1;
2115 while (len > 0) {
2116 ret = send(fd, buf, len, 0);
2117 if (ret < 0) {
2118 int errno;
2119 errno = WSAGetLastError();
2120 if (errno != WSAEWOULDBLOCK) {
2121 return -1;
2123 } else if (ret == 0) {
2124 break;
2125 } else {
2126 buf += ret;
2127 len -= ret;
2130 return len1 - len;
2133 #else
2135 static int unix_write(int fd, const uint8_t *buf, int len1)
2137 int ret, len;
2139 len = len1;
2140 while (len > 0) {
2141 ret = write(fd, buf, len);
2142 if (ret < 0) {
2143 if (errno != EINTR && errno != EAGAIN)
2144 return -1;
2145 } else if (ret == 0) {
2146 break;
2147 } else {
2148 buf += ret;
2149 len -= ret;
2152 return len1 - len;
2155 static inline int send_all(int fd, const uint8_t *buf, int len1)
2157 return unix_write(fd, buf, len1);
2159 #endif /* !_WIN32 */
2161 #ifndef _WIN32
2163 typedef struct {
2164 int fd_in, fd_out;
2165 int max_size;
2166 } FDCharDriver;
2168 #define STDIO_MAX_CLIENTS 1
2169 static int stdio_nb_clients = 0;
2171 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2173 FDCharDriver *s = chr->opaque;
2174 return unix_write(s->fd_out, buf, len);
2177 static int fd_chr_read_poll(void *opaque)
2179 CharDriverState *chr = opaque;
2180 FDCharDriver *s = chr->opaque;
2182 s->max_size = qemu_chr_can_read(chr);
2183 return s->max_size;
2186 static void fd_chr_read(void *opaque)
2188 CharDriverState *chr = opaque;
2189 FDCharDriver *s = chr->opaque;
2190 int size, len;
2191 uint8_t buf[1024];
2193 len = sizeof(buf);
2194 if (len > s->max_size)
2195 len = s->max_size;
2196 if (len == 0)
2197 return;
2198 size = read(s->fd_in, buf, len);
2199 if (size == 0) {
2200 /* FD has been closed. Remove it from the active list. */
2201 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2202 return;
2204 if (size > 0) {
2205 qemu_chr_read(chr, buf, size);
2209 static void fd_chr_update_read_handler(CharDriverState *chr)
2211 FDCharDriver *s = chr->opaque;
2213 if (s->fd_in >= 0) {
2214 if (nographic && s->fd_in == 0) {
2215 } else {
2216 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2217 fd_chr_read, NULL, chr);
2222 static void fd_chr_close(struct CharDriverState *chr)
2224 FDCharDriver *s = chr->opaque;
2226 if (s->fd_in >= 0) {
2227 if (nographic && s->fd_in == 0) {
2228 } else {
2229 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2233 qemu_free(s);
2236 /* open a character device to a unix fd */
2237 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2239 CharDriverState *chr;
2240 FDCharDriver *s;
2242 chr = qemu_mallocz(sizeof(CharDriverState));
2243 if (!chr)
2244 return NULL;
2245 s = qemu_mallocz(sizeof(FDCharDriver));
2246 if (!s) {
2247 free(chr);
2248 return NULL;
2250 s->fd_in = fd_in;
2251 s->fd_out = fd_out;
2252 chr->opaque = s;
2253 chr->chr_write = fd_chr_write;
2254 chr->chr_update_read_handler = fd_chr_update_read_handler;
2255 chr->chr_close = fd_chr_close;
2257 qemu_chr_reset(chr);
2259 return chr;
2262 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2264 int fd_out;
2266 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2267 if (fd_out < 0)
2268 return NULL;
2269 return qemu_chr_open_fd(-1, fd_out);
2272 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2274 int fd_in, fd_out;
2275 char filename_in[256], filename_out[256];
2277 snprintf(filename_in, 256, "%s.in", filename);
2278 snprintf(filename_out, 256, "%s.out", filename);
2279 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2280 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2281 if (fd_in < 0 || fd_out < 0) {
2282 if (fd_in >= 0)
2283 close(fd_in);
2284 if (fd_out >= 0)
2285 close(fd_out);
2286 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2287 if (fd_in < 0)
2288 return NULL;
2290 return qemu_chr_open_fd(fd_in, fd_out);
2294 /* for STDIO, we handle the case where several clients use it
2295 (nographic mode) */
2297 #define TERM_FIFO_MAX_SIZE 1
2299 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2300 static int term_fifo_size;
2302 static int stdio_read_poll(void *opaque)
2304 CharDriverState *chr = opaque;
2306 /* try to flush the queue if needed */
2307 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2308 qemu_chr_read(chr, term_fifo, 1);
2309 term_fifo_size = 0;
2311 /* see if we can absorb more chars */
2312 if (term_fifo_size == 0)
2313 return 1;
2314 else
2315 return 0;
2318 static void stdio_read(void *opaque)
2320 int size;
2321 uint8_t buf[1];
2322 CharDriverState *chr = opaque;
2324 size = read(0, buf, 1);
2325 if (size == 0) {
2326 /* stdin has been closed. Remove it from the active list. */
2327 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2328 return;
2330 if (size > 0) {
2331 if (qemu_chr_can_read(chr) > 0) {
2332 qemu_chr_read(chr, buf, 1);
2333 } else if (term_fifo_size == 0) {
2334 term_fifo[term_fifo_size++] = buf[0];
2339 /* init terminal so that we can grab keys */
2340 static struct termios oldtty;
2341 static int old_fd0_flags;
2342 static int term_atexit_done;
2344 static void term_exit(void)
2346 tcsetattr (0, TCSANOW, &oldtty);
2347 fcntl(0, F_SETFL, old_fd0_flags);
2350 static void term_init(void)
2352 struct termios tty;
2354 tcgetattr (0, &tty);
2355 oldtty = tty;
2356 old_fd0_flags = fcntl(0, F_GETFL);
2358 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2359 |INLCR|IGNCR|ICRNL|IXON);
2360 tty.c_oflag |= OPOST;
2361 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2362 /* if graphical mode, we allow Ctrl-C handling */
2363 if (nographic)
2364 tty.c_lflag &= ~ISIG;
2365 tty.c_cflag &= ~(CSIZE|PARENB);
2366 tty.c_cflag |= CS8;
2367 tty.c_cc[VMIN] = 1;
2368 tty.c_cc[VTIME] = 0;
2370 tcsetattr (0, TCSANOW, &tty);
2372 if (!term_atexit_done++)
2373 atexit(term_exit);
2375 fcntl(0, F_SETFL, O_NONBLOCK);
2378 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2380 term_exit();
2381 stdio_nb_clients--;
2382 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2383 fd_chr_close(chr);
2386 static CharDriverState *qemu_chr_open_stdio(void)
2388 CharDriverState *chr;
2390 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2391 return NULL;
2392 chr = qemu_chr_open_fd(0, 1);
2393 chr->chr_close = qemu_chr_close_stdio;
2394 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2395 stdio_nb_clients++;
2396 term_init();
2398 return chr;
2401 #ifdef __sun__
2402 /* Once Solaris has openpty(), this is going to be removed. */
2403 int openpty(int *amaster, int *aslave, char *name,
2404 struct termios *termp, struct winsize *winp)
2406 const char *slave;
2407 int mfd = -1, sfd = -1;
2409 *amaster = *aslave = -1;
2411 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2412 if (mfd < 0)
2413 goto err;
2415 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2416 goto err;
2418 if ((slave = ptsname(mfd)) == NULL)
2419 goto err;
2421 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2422 goto err;
2424 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2425 (termp != NULL && tcgetattr(sfd, termp) < 0))
2426 goto err;
2428 if (amaster)
2429 *amaster = mfd;
2430 if (aslave)
2431 *aslave = sfd;
2432 if (winp)
2433 ioctl(sfd, TIOCSWINSZ, winp);
2435 return 0;
2437 err:
2438 if (sfd != -1)
2439 close(sfd);
2440 close(mfd);
2441 return -1;
2444 void cfmakeraw (struct termios *termios_p)
2446 termios_p->c_iflag &=
2447 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2448 termios_p->c_oflag &= ~OPOST;
2449 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2450 termios_p->c_cflag &= ~(CSIZE|PARENB);
2451 termios_p->c_cflag |= CS8;
2453 termios_p->c_cc[VMIN] = 0;
2454 termios_p->c_cc[VTIME] = 0;
2456 #endif
2458 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2459 || defined(__NetBSD__) || defined(__OpenBSD__)
2461 typedef struct {
2462 int fd;
2463 int connected;
2464 int polling;
2465 int read_bytes;
2466 QEMUTimer *timer;
2467 } PtyCharDriver;
2469 static void pty_chr_update_read_handler(CharDriverState *chr);
2470 static void pty_chr_state(CharDriverState *chr, int connected);
2472 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2474 PtyCharDriver *s = chr->opaque;
2476 if (!s->connected) {
2477 /* guest sends data, check for (re-)connect */
2478 pty_chr_update_read_handler(chr);
2479 return 0;
2481 return unix_write(s->fd, buf, len);
2484 static int pty_chr_read_poll(void *opaque)
2486 CharDriverState *chr = opaque;
2487 PtyCharDriver *s = chr->opaque;
2489 s->read_bytes = qemu_chr_can_read(chr);
2490 return s->read_bytes;
2493 static void pty_chr_read(void *opaque)
2495 CharDriverState *chr = opaque;
2496 PtyCharDriver *s = chr->opaque;
2497 int size, len;
2498 uint8_t buf[1024];
2500 len = sizeof(buf);
2501 if (len > s->read_bytes)
2502 len = s->read_bytes;
2503 if (len == 0)
2504 return;
2505 size = read(s->fd, buf, len);
2506 if ((size == -1 && errno == EIO) ||
2507 (size == 0)) {
2508 pty_chr_state(chr, 0);
2509 return;
2511 if (size > 0) {
2512 pty_chr_state(chr, 1);
2513 qemu_chr_read(chr, buf, size);
2517 static void pty_chr_update_read_handler(CharDriverState *chr)
2519 PtyCharDriver *s = chr->opaque;
2521 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2522 pty_chr_read, NULL, chr);
2523 s->polling = 1;
2525 * Short timeout here: just need wait long enougth that qemu makes
2526 * it through the poll loop once. When reconnected we want a
2527 * short timeout so we notice it almost instantly. Otherwise
2528 * read() gives us -EIO instantly, making pty_chr_state() reset the
2529 * timeout to the normal (much longer) poll interval before the
2530 * timer triggers.
2532 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2535 static void pty_chr_state(CharDriverState *chr, int connected)
2537 PtyCharDriver *s = chr->opaque;
2539 if (!connected) {
2540 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2541 s->connected = 0;
2542 s->polling = 0;
2543 /* (re-)connect poll interval for idle guests: once per second.
2544 * We check more frequently in case the guests sends data to
2545 * the virtual device linked to our pty. */
2546 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2547 } else {
2548 if (!s->connected)
2549 qemu_chr_reset(chr);
2550 s->connected = 1;
2554 static void pty_chr_timer(void *opaque)
2556 struct CharDriverState *chr = opaque;
2557 PtyCharDriver *s = chr->opaque;
2559 if (s->connected)
2560 return;
2561 if (s->polling) {
2562 /* If we arrive here without polling being cleared due
2563 * read returning -EIO, then we are (re-)connected */
2564 pty_chr_state(chr, 1);
2565 return;
2568 /* Next poll ... */
2569 pty_chr_update_read_handler(chr);
2572 static void pty_chr_close(struct CharDriverState *chr)
2574 PtyCharDriver *s = chr->opaque;
2576 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2577 close(s->fd);
2578 qemu_free(s);
2581 static CharDriverState *qemu_chr_open_pty(void)
2583 CharDriverState *chr;
2584 PtyCharDriver *s;
2585 struct termios tty;
2586 int slave_fd;
2587 #if defined(__OpenBSD__)
2588 char pty_name[PATH_MAX];
2589 #define q_ptsname(x) pty_name
2590 #else
2591 char *pty_name = NULL;
2592 #define q_ptsname(x) ptsname(x)
2593 #endif
2595 chr = qemu_mallocz(sizeof(CharDriverState));
2596 if (!chr)
2597 return NULL;
2598 s = qemu_mallocz(sizeof(PtyCharDriver));
2599 if (!s) {
2600 qemu_free(chr);
2601 return NULL;
2604 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2605 return NULL;
2608 /* Set raw attributes on the pty. */
2609 cfmakeraw(&tty);
2610 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2611 close(slave_fd);
2613 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2615 chr->opaque = s;
2616 chr->chr_write = pty_chr_write;
2617 chr->chr_update_read_handler = pty_chr_update_read_handler;
2618 chr->chr_close = pty_chr_close;
2620 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2622 return chr;
2625 static void tty_serial_init(int fd, int speed,
2626 int parity, int data_bits, int stop_bits)
2628 struct termios tty;
2629 speed_t spd;
2631 #if 0
2632 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2633 speed, parity, data_bits, stop_bits);
2634 #endif
2635 tcgetattr (fd, &tty);
2637 #define MARGIN 1.1
2638 if (speed <= 50 * MARGIN)
2639 spd = B50;
2640 else if (speed <= 75 * MARGIN)
2641 spd = B75;
2642 else if (speed <= 300 * MARGIN)
2643 spd = B300;
2644 else if (speed <= 600 * MARGIN)
2645 spd = B600;
2646 else if (speed <= 1200 * MARGIN)
2647 spd = B1200;
2648 else if (speed <= 2400 * MARGIN)
2649 spd = B2400;
2650 else if (speed <= 4800 * MARGIN)
2651 spd = B4800;
2652 else if (speed <= 9600 * MARGIN)
2653 spd = B9600;
2654 else if (speed <= 19200 * MARGIN)
2655 spd = B19200;
2656 else if (speed <= 38400 * MARGIN)
2657 spd = B38400;
2658 else if (speed <= 57600 * MARGIN)
2659 spd = B57600;
2660 else if (speed <= 115200 * MARGIN)
2661 spd = B115200;
2662 else
2663 spd = B115200;
2665 cfsetispeed(&tty, spd);
2666 cfsetospeed(&tty, spd);
2668 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2669 |INLCR|IGNCR|ICRNL|IXON);
2670 tty.c_oflag |= OPOST;
2671 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2672 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2673 switch(data_bits) {
2674 default:
2675 case 8:
2676 tty.c_cflag |= CS8;
2677 break;
2678 case 7:
2679 tty.c_cflag |= CS7;
2680 break;
2681 case 6:
2682 tty.c_cflag |= CS6;
2683 break;
2684 case 5:
2685 tty.c_cflag |= CS5;
2686 break;
2688 switch(parity) {
2689 default:
2690 case 'N':
2691 break;
2692 case 'E':
2693 tty.c_cflag |= PARENB;
2694 break;
2695 case 'O':
2696 tty.c_cflag |= PARENB | PARODD;
2697 break;
2699 if (stop_bits == 2)
2700 tty.c_cflag |= CSTOPB;
2702 tcsetattr (fd, TCSANOW, &tty);
2705 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2707 FDCharDriver *s = chr->opaque;
2709 switch(cmd) {
2710 case CHR_IOCTL_SERIAL_SET_PARAMS:
2712 QEMUSerialSetParams *ssp = arg;
2713 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2714 ssp->data_bits, ssp->stop_bits);
2716 break;
2717 case CHR_IOCTL_SERIAL_SET_BREAK:
2719 int enable = *(int *)arg;
2720 if (enable)
2721 tcsendbreak(s->fd_in, 1);
2723 break;
2724 case CHR_IOCTL_SERIAL_GET_TIOCM:
2726 int sarg = 0;
2727 int *targ = (int *)arg;
2728 ioctl(s->fd_in, TIOCMGET, &sarg);
2729 *targ = 0;
2730 if (sarg | TIOCM_CTS)
2731 *targ |= CHR_TIOCM_CTS;
2732 if (sarg | TIOCM_CAR)
2733 *targ |= CHR_TIOCM_CAR;
2734 if (sarg | TIOCM_DSR)
2735 *targ |= CHR_TIOCM_DSR;
2736 if (sarg | TIOCM_RI)
2737 *targ |= CHR_TIOCM_RI;
2738 if (sarg | TIOCM_DTR)
2739 *targ |= CHR_TIOCM_DTR;
2740 if (sarg | TIOCM_RTS)
2741 *targ |= CHR_TIOCM_RTS;
2743 break;
2744 case CHR_IOCTL_SERIAL_SET_TIOCM:
2746 int sarg = *(int *)arg;
2747 int targ = 0;
2748 if (sarg | CHR_TIOCM_DTR)
2749 targ |= TIOCM_DTR;
2750 if (sarg | CHR_TIOCM_RTS)
2751 targ |= TIOCM_RTS;
2752 ioctl(s->fd_in, TIOCMSET, &targ);
2754 break;
2755 default:
2756 return -ENOTSUP;
2758 return 0;
2761 static CharDriverState *qemu_chr_open_tty(const char *filename)
2763 CharDriverState *chr;
2764 int fd;
2766 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2767 tty_serial_init(fd, 115200, 'N', 8, 1);
2768 chr = qemu_chr_open_fd(fd, fd);
2769 if (!chr) {
2770 close(fd);
2771 return NULL;
2773 chr->chr_ioctl = tty_serial_ioctl;
2774 qemu_chr_reset(chr);
2775 return chr;
2777 #else /* ! __linux__ && ! __sun__ */
2778 static CharDriverState *qemu_chr_open_pty(void)
2780 return NULL;
2782 #endif /* __linux__ || __sun__ */
2784 #if defined(__linux__)
2785 typedef struct {
2786 int fd;
2787 int mode;
2788 } ParallelCharDriver;
2790 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2792 if (s->mode != mode) {
2793 int m = mode;
2794 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2795 return 0;
2796 s->mode = mode;
2798 return 1;
2801 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2803 ParallelCharDriver *drv = chr->opaque;
2804 int fd = drv->fd;
2805 uint8_t b;
2807 switch(cmd) {
2808 case CHR_IOCTL_PP_READ_DATA:
2809 if (ioctl(fd, PPRDATA, &b) < 0)
2810 return -ENOTSUP;
2811 *(uint8_t *)arg = b;
2812 break;
2813 case CHR_IOCTL_PP_WRITE_DATA:
2814 b = *(uint8_t *)arg;
2815 if (ioctl(fd, PPWDATA, &b) < 0)
2816 return -ENOTSUP;
2817 break;
2818 case CHR_IOCTL_PP_READ_CONTROL:
2819 if (ioctl(fd, PPRCONTROL, &b) < 0)
2820 return -ENOTSUP;
2821 /* Linux gives only the lowest bits, and no way to know data
2822 direction! For better compatibility set the fixed upper
2823 bits. */
2824 *(uint8_t *)arg = b | 0xc0;
2825 break;
2826 case CHR_IOCTL_PP_WRITE_CONTROL:
2827 b = *(uint8_t *)arg;
2828 if (ioctl(fd, PPWCONTROL, &b) < 0)
2829 return -ENOTSUP;
2830 break;
2831 case CHR_IOCTL_PP_READ_STATUS:
2832 if (ioctl(fd, PPRSTATUS, &b) < 0)
2833 return -ENOTSUP;
2834 *(uint8_t *)arg = b;
2835 break;
2836 case CHR_IOCTL_PP_DATA_DIR:
2837 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2838 return -ENOTSUP;
2839 break;
2840 case CHR_IOCTL_PP_EPP_READ_ADDR:
2841 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2842 struct ParallelIOArg *parg = arg;
2843 int n = read(fd, parg->buffer, parg->count);
2844 if (n != parg->count) {
2845 return -EIO;
2848 break;
2849 case CHR_IOCTL_PP_EPP_READ:
2850 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2851 struct ParallelIOArg *parg = arg;
2852 int n = read(fd, parg->buffer, parg->count);
2853 if (n != parg->count) {
2854 return -EIO;
2857 break;
2858 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2859 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2860 struct ParallelIOArg *parg = arg;
2861 int n = write(fd, parg->buffer, parg->count);
2862 if (n != parg->count) {
2863 return -EIO;
2866 break;
2867 case CHR_IOCTL_PP_EPP_WRITE:
2868 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2869 struct ParallelIOArg *parg = arg;
2870 int n = write(fd, parg->buffer, parg->count);
2871 if (n != parg->count) {
2872 return -EIO;
2875 break;
2876 default:
2877 return -ENOTSUP;
2879 return 0;
2882 static void pp_close(CharDriverState *chr)
2884 ParallelCharDriver *drv = chr->opaque;
2885 int fd = drv->fd;
2887 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2888 ioctl(fd, PPRELEASE);
2889 close(fd);
2890 qemu_free(drv);
2893 static CharDriverState *qemu_chr_open_pp(const char *filename)
2895 CharDriverState *chr;
2896 ParallelCharDriver *drv;
2897 int fd;
2899 TFR(fd = open(filename, O_RDWR));
2900 if (fd < 0)
2901 return NULL;
2903 if (ioctl(fd, PPCLAIM) < 0) {
2904 close(fd);
2905 return NULL;
2908 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2909 if (!drv) {
2910 close(fd);
2911 return NULL;
2913 drv->fd = fd;
2914 drv->mode = IEEE1284_MODE_COMPAT;
2916 chr = qemu_mallocz(sizeof(CharDriverState));
2917 if (!chr) {
2918 qemu_free(drv);
2919 close(fd);
2920 return NULL;
2922 chr->chr_write = null_chr_write;
2923 chr->chr_ioctl = pp_ioctl;
2924 chr->chr_close = pp_close;
2925 chr->opaque = drv;
2927 qemu_chr_reset(chr);
2929 return chr;
2931 #endif /* __linux__ */
2933 #else /* _WIN32 */
2935 typedef struct {
2936 int max_size;
2937 HANDLE hcom, hrecv, hsend;
2938 OVERLAPPED orecv, osend;
2939 BOOL fpipe;
2940 DWORD len;
2941 } WinCharState;
2943 #define NSENDBUF 2048
2944 #define NRECVBUF 2048
2945 #define MAXCONNECT 1
2946 #define NTIMEOUT 5000
2948 static int win_chr_poll(void *opaque);
2949 static int win_chr_pipe_poll(void *opaque);
2951 static void win_chr_close(CharDriverState *chr)
2953 WinCharState *s = chr->opaque;
2955 if (s->hsend) {
2956 CloseHandle(s->hsend);
2957 s->hsend = NULL;
2959 if (s->hrecv) {
2960 CloseHandle(s->hrecv);
2961 s->hrecv = NULL;
2963 if (s->hcom) {
2964 CloseHandle(s->hcom);
2965 s->hcom = NULL;
2967 if (s->fpipe)
2968 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2969 else
2970 qemu_del_polling_cb(win_chr_poll, chr);
2973 static int win_chr_init(CharDriverState *chr, const char *filename)
2975 WinCharState *s = chr->opaque;
2976 COMMCONFIG comcfg;
2977 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2978 COMSTAT comstat;
2979 DWORD size;
2980 DWORD err;
2982 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2983 if (!s->hsend) {
2984 fprintf(stderr, "Failed CreateEvent\n");
2985 goto fail;
2987 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2988 if (!s->hrecv) {
2989 fprintf(stderr, "Failed CreateEvent\n");
2990 goto fail;
2993 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2994 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2995 if (s->hcom == INVALID_HANDLE_VALUE) {
2996 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2997 s->hcom = NULL;
2998 goto fail;
3001 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3002 fprintf(stderr, "Failed SetupComm\n");
3003 goto fail;
3006 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3007 size = sizeof(COMMCONFIG);
3008 GetDefaultCommConfig(filename, &comcfg, &size);
3009 comcfg.dcb.DCBlength = sizeof(DCB);
3010 CommConfigDialog(filename, NULL, &comcfg);
3012 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3013 fprintf(stderr, "Failed SetCommState\n");
3014 goto fail;
3017 if (!SetCommMask(s->hcom, EV_ERR)) {
3018 fprintf(stderr, "Failed SetCommMask\n");
3019 goto fail;
3022 cto.ReadIntervalTimeout = MAXDWORD;
3023 if (!SetCommTimeouts(s->hcom, &cto)) {
3024 fprintf(stderr, "Failed SetCommTimeouts\n");
3025 goto fail;
3028 if (!ClearCommError(s->hcom, &err, &comstat)) {
3029 fprintf(stderr, "Failed ClearCommError\n");
3030 goto fail;
3032 qemu_add_polling_cb(win_chr_poll, chr);
3033 return 0;
3035 fail:
3036 win_chr_close(chr);
3037 return -1;
3040 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3042 WinCharState *s = chr->opaque;
3043 DWORD len, ret, size, err;
3045 len = len1;
3046 ZeroMemory(&s->osend, sizeof(s->osend));
3047 s->osend.hEvent = s->hsend;
3048 while (len > 0) {
3049 if (s->hsend)
3050 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3051 else
3052 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3053 if (!ret) {
3054 err = GetLastError();
3055 if (err == ERROR_IO_PENDING) {
3056 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3057 if (ret) {
3058 buf += size;
3059 len -= size;
3060 } else {
3061 break;
3063 } else {
3064 break;
3066 } else {
3067 buf += size;
3068 len -= size;
3071 return len1 - len;
3074 static int win_chr_read_poll(CharDriverState *chr)
3076 WinCharState *s = chr->opaque;
3078 s->max_size = qemu_chr_can_read(chr);
3079 return s->max_size;
3082 static void win_chr_readfile(CharDriverState *chr)
3084 WinCharState *s = chr->opaque;
3085 int ret, err;
3086 uint8_t buf[1024];
3087 DWORD size;
3089 ZeroMemory(&s->orecv, sizeof(s->orecv));
3090 s->orecv.hEvent = s->hrecv;
3091 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3092 if (!ret) {
3093 err = GetLastError();
3094 if (err == ERROR_IO_PENDING) {
3095 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3099 if (size > 0) {
3100 qemu_chr_read(chr, buf, size);
3104 static void win_chr_read(CharDriverState *chr)
3106 WinCharState *s = chr->opaque;
3108 if (s->len > s->max_size)
3109 s->len = s->max_size;
3110 if (s->len == 0)
3111 return;
3113 win_chr_readfile(chr);
3116 static int win_chr_poll(void *opaque)
3118 CharDriverState *chr = opaque;
3119 WinCharState *s = chr->opaque;
3120 COMSTAT status;
3121 DWORD comerr;
3123 ClearCommError(s->hcom, &comerr, &status);
3124 if (status.cbInQue > 0) {
3125 s->len = status.cbInQue;
3126 win_chr_read_poll(chr);
3127 win_chr_read(chr);
3128 return 1;
3130 return 0;
3133 static CharDriverState *qemu_chr_open_win(const char *filename)
3135 CharDriverState *chr;
3136 WinCharState *s;
3138 chr = qemu_mallocz(sizeof(CharDriverState));
3139 if (!chr)
3140 return NULL;
3141 s = qemu_mallocz(sizeof(WinCharState));
3142 if (!s) {
3143 free(chr);
3144 return NULL;
3146 chr->opaque = s;
3147 chr->chr_write = win_chr_write;
3148 chr->chr_close = win_chr_close;
3150 if (win_chr_init(chr, filename) < 0) {
3151 free(s);
3152 free(chr);
3153 return NULL;
3155 qemu_chr_reset(chr);
3156 return chr;
3159 static int win_chr_pipe_poll(void *opaque)
3161 CharDriverState *chr = opaque;
3162 WinCharState *s = chr->opaque;
3163 DWORD size;
3165 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3166 if (size > 0) {
3167 s->len = size;
3168 win_chr_read_poll(chr);
3169 win_chr_read(chr);
3170 return 1;
3172 return 0;
3175 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3177 WinCharState *s = chr->opaque;
3178 OVERLAPPED ov;
3179 int ret;
3180 DWORD size;
3181 char openname[256];
3183 s->fpipe = TRUE;
3185 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3186 if (!s->hsend) {
3187 fprintf(stderr, "Failed CreateEvent\n");
3188 goto fail;
3190 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3191 if (!s->hrecv) {
3192 fprintf(stderr, "Failed CreateEvent\n");
3193 goto fail;
3196 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3197 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3198 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3199 PIPE_WAIT,
3200 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3201 if (s->hcom == INVALID_HANDLE_VALUE) {
3202 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3203 s->hcom = NULL;
3204 goto fail;
3207 ZeroMemory(&ov, sizeof(ov));
3208 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3209 ret = ConnectNamedPipe(s->hcom, &ov);
3210 if (ret) {
3211 fprintf(stderr, "Failed ConnectNamedPipe\n");
3212 goto fail;
3215 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3216 if (!ret) {
3217 fprintf(stderr, "Failed GetOverlappedResult\n");
3218 if (ov.hEvent) {
3219 CloseHandle(ov.hEvent);
3220 ov.hEvent = NULL;
3222 goto fail;
3225 if (ov.hEvent) {
3226 CloseHandle(ov.hEvent);
3227 ov.hEvent = NULL;
3229 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3230 return 0;
3232 fail:
3233 win_chr_close(chr);
3234 return -1;
3238 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3240 CharDriverState *chr;
3241 WinCharState *s;
3243 chr = qemu_mallocz(sizeof(CharDriverState));
3244 if (!chr)
3245 return NULL;
3246 s = qemu_mallocz(sizeof(WinCharState));
3247 if (!s) {
3248 free(chr);
3249 return NULL;
3251 chr->opaque = s;
3252 chr->chr_write = win_chr_write;
3253 chr->chr_close = win_chr_close;
3255 if (win_chr_pipe_init(chr, filename) < 0) {
3256 free(s);
3257 free(chr);
3258 return NULL;
3260 qemu_chr_reset(chr);
3261 return chr;
3264 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3266 CharDriverState *chr;
3267 WinCharState *s;
3269 chr = qemu_mallocz(sizeof(CharDriverState));
3270 if (!chr)
3271 return NULL;
3272 s = qemu_mallocz(sizeof(WinCharState));
3273 if (!s) {
3274 free(chr);
3275 return NULL;
3277 s->hcom = fd_out;
3278 chr->opaque = s;
3279 chr->chr_write = win_chr_write;
3280 qemu_chr_reset(chr);
3281 return chr;
3284 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3286 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3289 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3291 HANDLE fd_out;
3293 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3294 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3295 if (fd_out == INVALID_HANDLE_VALUE)
3296 return NULL;
3298 return qemu_chr_open_win_file(fd_out);
3300 #endif /* !_WIN32 */
3302 /***********************************************************/
3303 /* UDP Net console */
3305 typedef struct {
3306 int fd;
3307 struct sockaddr_in daddr;
3308 uint8_t buf[1024];
3309 int bufcnt;
3310 int bufptr;
3311 int max_size;
3312 } NetCharDriver;
3314 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3316 NetCharDriver *s = chr->opaque;
3318 return sendto(s->fd, buf, len, 0,
3319 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3322 static int udp_chr_read_poll(void *opaque)
3324 CharDriverState *chr = opaque;
3325 NetCharDriver *s = chr->opaque;
3327 s->max_size = qemu_chr_can_read(chr);
3329 /* If there were any stray characters in the queue process them
3330 * first
3332 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3333 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3334 s->bufptr++;
3335 s->max_size = qemu_chr_can_read(chr);
3337 return s->max_size;
3340 static void udp_chr_read(void *opaque)
3342 CharDriverState *chr = opaque;
3343 NetCharDriver *s = chr->opaque;
3345 if (s->max_size == 0)
3346 return;
3347 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3348 s->bufptr = s->bufcnt;
3349 if (s->bufcnt <= 0)
3350 return;
3352 s->bufptr = 0;
3353 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3354 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3355 s->bufptr++;
3356 s->max_size = qemu_chr_can_read(chr);
3360 static void udp_chr_update_read_handler(CharDriverState *chr)
3362 NetCharDriver *s = chr->opaque;
3364 if (s->fd >= 0) {
3365 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3366 udp_chr_read, NULL, chr);
3370 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3371 #ifndef _WIN32
3372 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3373 #endif
3374 int parse_host_src_port(struct sockaddr_in *haddr,
3375 struct sockaddr_in *saddr,
3376 const char *str);
3378 static CharDriverState *qemu_chr_open_udp(const char *def)
3380 CharDriverState *chr = NULL;
3381 NetCharDriver *s = NULL;
3382 int fd = -1;
3383 struct sockaddr_in saddr;
3385 chr = qemu_mallocz(sizeof(CharDriverState));
3386 if (!chr)
3387 goto return_err;
3388 s = qemu_mallocz(sizeof(NetCharDriver));
3389 if (!s)
3390 goto return_err;
3392 fd = socket(PF_INET, SOCK_DGRAM, 0);
3393 if (fd < 0) {
3394 perror("socket(PF_INET, SOCK_DGRAM)");
3395 goto return_err;
3398 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3399 printf("Could not parse: %s\n", def);
3400 goto return_err;
3403 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3405 perror("bind");
3406 goto return_err;
3409 s->fd = fd;
3410 s->bufcnt = 0;
3411 s->bufptr = 0;
3412 chr->opaque = s;
3413 chr->chr_write = udp_chr_write;
3414 chr->chr_update_read_handler = udp_chr_update_read_handler;
3415 return chr;
3417 return_err:
3418 if (chr)
3419 free(chr);
3420 if (s)
3421 free(s);
3422 if (fd >= 0)
3423 closesocket(fd);
3424 return NULL;
3427 /***********************************************************/
3428 /* TCP Net console */
3430 typedef struct {
3431 int fd, listen_fd;
3432 int connected;
3433 int max_size;
3434 int do_telnetopt;
3435 int do_nodelay;
3436 int is_unix;
3437 } TCPCharDriver;
3439 static void tcp_chr_accept(void *opaque);
3441 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3443 TCPCharDriver *s = chr->opaque;
3444 if (s->connected) {
3445 return send_all(s->fd, buf, len);
3446 } else {
3447 /* XXX: indicate an error ? */
3448 return len;
3452 static int tcp_chr_read_poll(void *opaque)
3454 CharDriverState *chr = opaque;
3455 TCPCharDriver *s = chr->opaque;
3456 if (!s->connected)
3457 return 0;
3458 s->max_size = qemu_chr_can_read(chr);
3459 return s->max_size;
3462 #define IAC 255
3463 #define IAC_BREAK 243
3464 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3465 TCPCharDriver *s,
3466 uint8_t *buf, int *size)
3468 /* Handle any telnet client's basic IAC options to satisfy char by
3469 * char mode with no echo. All IAC options will be removed from
3470 * the buf and the do_telnetopt variable will be used to track the
3471 * state of the width of the IAC information.
3473 * IAC commands come in sets of 3 bytes with the exception of the
3474 * "IAC BREAK" command and the double IAC.
3477 int i;
3478 int j = 0;
3480 for (i = 0; i < *size; i++) {
3481 if (s->do_telnetopt > 1) {
3482 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3483 /* Double IAC means send an IAC */
3484 if (j != i)
3485 buf[j] = buf[i];
3486 j++;
3487 s->do_telnetopt = 1;
3488 } else {
3489 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3490 /* Handle IAC break commands by sending a serial break */
3491 qemu_chr_event(chr, CHR_EVENT_BREAK);
3492 s->do_telnetopt++;
3494 s->do_telnetopt++;
3496 if (s->do_telnetopt >= 4) {
3497 s->do_telnetopt = 1;
3499 } else {
3500 if ((unsigned char)buf[i] == IAC) {
3501 s->do_telnetopt = 2;
3502 } else {
3503 if (j != i)
3504 buf[j] = buf[i];
3505 j++;
3509 *size = j;
3512 static void tcp_chr_read(void *opaque)
3514 CharDriverState *chr = opaque;
3515 TCPCharDriver *s = chr->opaque;
3516 uint8_t buf[1024];
3517 int len, size;
3519 if (!s->connected || s->max_size <= 0)
3520 return;
3521 len = sizeof(buf);
3522 if (len > s->max_size)
3523 len = s->max_size;
3524 size = recv(s->fd, buf, len, 0);
3525 if (size == 0) {
3526 /* connection closed */
3527 s->connected = 0;
3528 if (s->listen_fd >= 0) {
3529 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3531 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3532 closesocket(s->fd);
3533 s->fd = -1;
3534 } else if (size > 0) {
3535 if (s->do_telnetopt)
3536 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3537 if (size > 0)
3538 qemu_chr_read(chr, buf, size);
3542 static void tcp_chr_connect(void *opaque)
3544 CharDriverState *chr = opaque;
3545 TCPCharDriver *s = chr->opaque;
3547 s->connected = 1;
3548 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3549 tcp_chr_read, NULL, chr);
3550 qemu_chr_reset(chr);
3553 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3554 static void tcp_chr_telnet_init(int fd)
3556 char buf[3];
3557 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3558 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3559 send(fd, (char *)buf, 3, 0);
3560 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3561 send(fd, (char *)buf, 3, 0);
3562 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3563 send(fd, (char *)buf, 3, 0);
3564 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3565 send(fd, (char *)buf, 3, 0);
3568 static void socket_set_nodelay(int fd)
3570 int val = 1;
3571 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3574 static void tcp_chr_accept(void *opaque)
3576 CharDriverState *chr = opaque;
3577 TCPCharDriver *s = chr->opaque;
3578 struct sockaddr_in saddr;
3579 #ifndef _WIN32
3580 struct sockaddr_un uaddr;
3581 #endif
3582 struct sockaddr *addr;
3583 socklen_t len;
3584 int fd;
3586 for(;;) {
3587 #ifndef _WIN32
3588 if (s->is_unix) {
3589 len = sizeof(uaddr);
3590 addr = (struct sockaddr *)&uaddr;
3591 } else
3592 #endif
3594 len = sizeof(saddr);
3595 addr = (struct sockaddr *)&saddr;
3597 fd = accept(s->listen_fd, addr, &len);
3598 if (fd < 0 && errno != EINTR) {
3599 return;
3600 } else if (fd >= 0) {
3601 if (s->do_telnetopt)
3602 tcp_chr_telnet_init(fd);
3603 break;
3606 socket_set_nonblock(fd);
3607 if (s->do_nodelay)
3608 socket_set_nodelay(fd);
3609 s->fd = fd;
3610 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3611 tcp_chr_connect(chr);
3614 static void tcp_chr_close(CharDriverState *chr)
3616 TCPCharDriver *s = chr->opaque;
3617 if (s->fd >= 0)
3618 closesocket(s->fd);
3619 if (s->listen_fd >= 0)
3620 closesocket(s->listen_fd);
3621 qemu_free(s);
3624 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3625 int is_telnet,
3626 int is_unix)
3628 CharDriverState *chr = NULL;
3629 TCPCharDriver *s = NULL;
3630 int fd = -1, ret, err, val;
3631 int is_listen = 0;
3632 int is_waitconnect = 1;
3633 int do_nodelay = 0;
3634 const char *ptr;
3635 struct sockaddr_in saddr;
3636 #ifndef _WIN32
3637 struct sockaddr_un uaddr;
3638 #endif
3639 struct sockaddr *addr;
3640 socklen_t addrlen;
3642 #ifndef _WIN32
3643 if (is_unix) {
3644 addr = (struct sockaddr *)&uaddr;
3645 addrlen = sizeof(uaddr);
3646 if (parse_unix_path(&uaddr, host_str) < 0)
3647 goto fail;
3648 } else
3649 #endif
3651 addr = (struct sockaddr *)&saddr;
3652 addrlen = sizeof(saddr);
3653 if (parse_host_port(&saddr, host_str) < 0)
3654 goto fail;
3657 ptr = host_str;
3658 while((ptr = strchr(ptr,','))) {
3659 ptr++;
3660 if (!strncmp(ptr,"server",6)) {
3661 is_listen = 1;
3662 } else if (!strncmp(ptr,"nowait",6)) {
3663 is_waitconnect = 0;
3664 } else if (!strncmp(ptr,"nodelay",6)) {
3665 do_nodelay = 1;
3666 } else {
3667 printf("Unknown option: %s\n", ptr);
3668 goto fail;
3671 if (!is_listen)
3672 is_waitconnect = 0;
3674 chr = qemu_mallocz(sizeof(CharDriverState));
3675 if (!chr)
3676 goto fail;
3677 s = qemu_mallocz(sizeof(TCPCharDriver));
3678 if (!s)
3679 goto fail;
3681 #ifndef _WIN32
3682 if (is_unix)
3683 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3684 else
3685 #endif
3686 fd = socket(PF_INET, SOCK_STREAM, 0);
3688 if (fd < 0)
3689 goto fail;
3691 if (!is_waitconnect)
3692 socket_set_nonblock(fd);
3694 s->connected = 0;
3695 s->fd = -1;
3696 s->listen_fd = -1;
3697 s->is_unix = is_unix;
3698 s->do_nodelay = do_nodelay && !is_unix;
3700 chr->opaque = s;
3701 chr->chr_write = tcp_chr_write;
3702 chr->chr_close = tcp_chr_close;
3704 if (is_listen) {
3705 /* allow fast reuse */
3706 #ifndef _WIN32
3707 if (is_unix) {
3708 char path[109];
3709 pstrcpy(path, sizeof(path), uaddr.sun_path);
3710 unlink(path);
3711 } else
3712 #endif
3714 val = 1;
3715 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3718 ret = bind(fd, addr, addrlen);
3719 if (ret < 0)
3720 goto fail;
3722 ret = listen(fd, 0);
3723 if (ret < 0)
3724 goto fail;
3726 s->listen_fd = fd;
3727 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3728 if (is_telnet)
3729 s->do_telnetopt = 1;
3730 } else {
3731 for(;;) {
3732 ret = connect(fd, addr, addrlen);
3733 if (ret < 0) {
3734 err = socket_error();
3735 if (err == EINTR || err == EWOULDBLOCK) {
3736 } else if (err == EINPROGRESS) {
3737 break;
3738 #ifdef _WIN32
3739 } else if (err == WSAEALREADY) {
3740 break;
3741 #endif
3742 } else {
3743 goto fail;
3745 } else {
3746 s->connected = 1;
3747 break;
3750 s->fd = fd;
3751 socket_set_nodelay(fd);
3752 if (s->connected)
3753 tcp_chr_connect(chr);
3754 else
3755 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3758 if (is_listen && is_waitconnect) {
3759 printf("QEMU waiting for connection on: %s\n", host_str);
3760 tcp_chr_accept(chr);
3761 socket_set_nonblock(s->listen_fd);
3764 return chr;
3765 fail:
3766 if (fd >= 0)
3767 closesocket(fd);
3768 qemu_free(s);
3769 qemu_free(chr);
3770 return NULL;
3773 CharDriverState *qemu_chr_open(const char *filename)
3775 const char *p;
3777 if (!strcmp(filename, "vc")) {
3778 return text_console_init(&display_state, 0);
3779 } else if (strstart(filename, "vc:", &p)) {
3780 return text_console_init(&display_state, p);
3781 } else if (!strcmp(filename, "null")) {
3782 return qemu_chr_open_null();
3783 } else
3784 if (strstart(filename, "tcp:", &p)) {
3785 return qemu_chr_open_tcp(p, 0, 0);
3786 } else
3787 if (strstart(filename, "telnet:", &p)) {
3788 return qemu_chr_open_tcp(p, 1, 0);
3789 } else
3790 if (strstart(filename, "udp:", &p)) {
3791 return qemu_chr_open_udp(p);
3792 } else
3793 if (strstart(filename, "mon:", &p)) {
3794 CharDriverState *drv = qemu_chr_open(p);
3795 if (drv) {
3796 drv = qemu_chr_open_mux(drv);
3797 monitor_init(drv, !nographic);
3798 return drv;
3800 printf("Unable to open driver: %s\n", p);
3801 return 0;
3802 } else
3803 #ifndef _WIN32
3804 if (strstart(filename, "unix:", &p)) {
3805 return qemu_chr_open_tcp(p, 0, 1);
3806 } else if (strstart(filename, "file:", &p)) {
3807 return qemu_chr_open_file_out(p);
3808 } else if (strstart(filename, "pipe:", &p)) {
3809 return qemu_chr_open_pipe(p);
3810 } else if (!strcmp(filename, "pty")) {
3811 return qemu_chr_open_pty();
3812 } else if (!strcmp(filename, "stdio")) {
3813 return qemu_chr_open_stdio();
3814 } else
3815 #if defined(__linux__)
3816 if (strstart(filename, "/dev/parport", NULL)) {
3817 return qemu_chr_open_pp(filename);
3818 } else
3819 #endif
3820 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3821 || defined(__NetBSD__) || defined(__OpenBSD__)
3822 if (strstart(filename, "/dev/", NULL)) {
3823 return qemu_chr_open_tty(filename);
3824 } else
3825 #endif
3826 #else /* !_WIN32 */
3827 if (strstart(filename, "COM", NULL)) {
3828 return qemu_chr_open_win(filename);
3829 } else
3830 if (strstart(filename, "pipe:", &p)) {
3831 return qemu_chr_open_win_pipe(p);
3832 } else
3833 if (strstart(filename, "con:", NULL)) {
3834 return qemu_chr_open_win_con(filename);
3835 } else
3836 if (strstart(filename, "file:", &p)) {
3837 return qemu_chr_open_win_file_out(p);
3838 } else
3839 #endif
3840 #ifdef CONFIG_BRLAPI
3841 if (!strcmp(filename, "braille")) {
3842 return chr_baum_init();
3843 } else
3844 #endif
3846 return NULL;
3850 void qemu_chr_close(CharDriverState *chr)
3852 if (chr->chr_close)
3853 chr->chr_close(chr);
3854 qemu_free(chr);
3857 /***********************************************************/
3858 /* network device redirectors */
3860 __attribute__ (( unused ))
3861 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3863 int len, i, j, c;
3865 for(i=0;i<size;i+=16) {
3866 len = size - i;
3867 if (len > 16)
3868 len = 16;
3869 fprintf(f, "%08x ", i);
3870 for(j=0;j<16;j++) {
3871 if (j < len)
3872 fprintf(f, " %02x", buf[i+j]);
3873 else
3874 fprintf(f, " ");
3876 fprintf(f, " ");
3877 for(j=0;j<len;j++) {
3878 c = buf[i+j];
3879 if (c < ' ' || c > '~')
3880 c = '.';
3881 fprintf(f, "%c", c);
3883 fprintf(f, "\n");
3887 static int parse_macaddr(uint8_t *macaddr, const char *p)
3889 int i;
3890 char *last_char;
3891 long int offset;
3893 errno = 0;
3894 offset = strtol(p, &last_char, 0);
3895 if (0 == errno && '\0' == *last_char &&
3896 offset >= 0 && offset <= 0xFFFFFF) {
3897 macaddr[3] = (offset & 0xFF0000) >> 16;
3898 macaddr[4] = (offset & 0xFF00) >> 8;
3899 macaddr[5] = offset & 0xFF;
3900 return 0;
3901 } else {
3902 for(i = 0; i < 6; i++) {
3903 macaddr[i] = strtol(p, (char **)&p, 16);
3904 if (i == 5) {
3905 if (*p != '\0')
3906 return -1;
3907 } else {
3908 if (*p != ':' && *p != '-')
3909 return -1;
3910 p++;
3913 return 0;
3916 return -1;
3919 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3921 const char *p, *p1;
3922 int len;
3923 p = *pp;
3924 p1 = strchr(p, sep);
3925 if (!p1)
3926 return -1;
3927 len = p1 - p;
3928 p1++;
3929 if (buf_size > 0) {
3930 if (len > buf_size - 1)
3931 len = buf_size - 1;
3932 memcpy(buf, p, len);
3933 buf[len] = '\0';
3935 *pp = p1;
3936 return 0;
3939 int parse_host_src_port(struct sockaddr_in *haddr,
3940 struct sockaddr_in *saddr,
3941 const char *input_str)
3943 char *str = strdup(input_str);
3944 char *host_str = str;
3945 char *src_str;
3946 const char *src_str2;
3947 char *ptr;
3950 * Chop off any extra arguments at the end of the string which
3951 * would start with a comma, then fill in the src port information
3952 * if it was provided else use the "any address" and "any port".
3954 if ((ptr = strchr(str,',')))
3955 *ptr = '\0';
3957 if ((src_str = strchr(input_str,'@'))) {
3958 *src_str = '\0';
3959 src_str++;
3962 if (parse_host_port(haddr, host_str) < 0)
3963 goto fail;
3965 src_str2 = src_str;
3966 if (!src_str || *src_str == '\0')
3967 src_str2 = ":0";
3969 if (parse_host_port(saddr, src_str2) < 0)
3970 goto fail;
3972 free(str);
3973 return(0);
3975 fail:
3976 free(str);
3977 return -1;
3980 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3982 char buf[512];
3983 struct hostent *he;
3984 const char *p, *r;
3985 int port;
3987 p = str;
3988 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3989 return -1;
3990 saddr->sin_family = AF_INET;
3991 if (buf[0] == '\0') {
3992 saddr->sin_addr.s_addr = 0;
3993 } else {
3994 if (isdigit(buf[0])) {
3995 if (!inet_aton(buf, &saddr->sin_addr))
3996 return -1;
3997 } else {
3998 if ((he = gethostbyname(buf)) == NULL)
3999 return - 1;
4000 saddr->sin_addr = *(struct in_addr *)he->h_addr;
4003 port = strtol(p, (char **)&r, 0);
4004 if (r == p)
4005 return -1;
4006 saddr->sin_port = htons(port);
4007 return 0;
4010 #ifndef _WIN32
4011 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4013 const char *p;
4014 int len;
4016 len = MIN(108, strlen(str));
4017 p = strchr(str, ',');
4018 if (p)
4019 len = MIN(len, p - str);
4021 memset(uaddr, 0, sizeof(*uaddr));
4023 uaddr->sun_family = AF_UNIX;
4024 memcpy(uaddr->sun_path, str, len);
4026 return 0;
4028 #endif
4030 /* find or alloc a new VLAN */
4031 VLANState *qemu_find_vlan(int id)
4033 VLANState **pvlan, *vlan;
4034 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4035 if (vlan->id == id)
4036 return vlan;
4038 vlan = qemu_mallocz(sizeof(VLANState));
4039 if (!vlan)
4040 return NULL;
4041 vlan->id = id;
4042 vlan->next = NULL;
4043 pvlan = &first_vlan;
4044 while (*pvlan != NULL)
4045 pvlan = &(*pvlan)->next;
4046 *pvlan = vlan;
4047 return vlan;
4050 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4051 IOReadHandler *fd_read,
4052 IOCanRWHandler *fd_can_read,
4053 void *opaque)
4055 VLANClientState *vc, **pvc;
4056 vc = qemu_mallocz(sizeof(VLANClientState));
4057 if (!vc)
4058 return NULL;
4059 vc->fd_read = fd_read;
4060 vc->fd_can_read = fd_can_read;
4061 vc->opaque = opaque;
4062 vc->vlan = vlan;
4064 vc->next = NULL;
4065 pvc = &vlan->first_client;
4066 while (*pvc != NULL)
4067 pvc = &(*pvc)->next;
4068 *pvc = vc;
4069 return vc;
4072 void qemu_del_vlan_client(VLANClientState *vc)
4074 VLANClientState **pvc = &vc->vlan->first_client;
4076 while (*pvc != NULL)
4077 if (*pvc == vc) {
4078 *pvc = vc->next;
4079 free(vc);
4080 break;
4081 } else
4082 pvc = &(*pvc)->next;
4085 int qemu_can_send_packet(VLANClientState *vc1)
4087 VLANState *vlan = vc1->vlan;
4088 VLANClientState *vc;
4090 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4091 if (vc != vc1) {
4092 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4093 return 1;
4096 return 0;
4099 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4101 VLANState *vlan = vc1->vlan;
4102 VLANClientState *vc;
4104 #if 0
4105 printf("vlan %d send:\n", vlan->id);
4106 hex_dump(stdout, buf, size);
4107 #endif
4108 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4109 if (vc != vc1) {
4110 vc->fd_read(vc->opaque, buf, size);
4115 #if defined(CONFIG_SLIRP)
4117 /* slirp network adapter */
4119 static int slirp_inited;
4120 static VLANClientState *slirp_vc;
4122 int slirp_can_output(void)
4124 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4127 void slirp_output(const uint8_t *pkt, int pkt_len)
4129 #if 0
4130 printf("slirp output:\n");
4131 hex_dump(stdout, pkt, pkt_len);
4132 #endif
4133 if (!slirp_vc)
4134 return;
4135 qemu_send_packet(slirp_vc, pkt, pkt_len);
4138 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4140 #if 0
4141 printf("slirp input:\n");
4142 hex_dump(stdout, buf, size);
4143 #endif
4144 slirp_input(buf, size);
4147 static int net_slirp_init(VLANState *vlan)
4149 if (!slirp_inited) {
4150 slirp_inited = 1;
4151 slirp_init();
4153 slirp_vc = qemu_new_vlan_client(vlan,
4154 slirp_receive, NULL, NULL);
4155 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4156 return 0;
4159 static void net_slirp_redir(const char *redir_str)
4161 int is_udp;
4162 char buf[256], *r;
4163 const char *p;
4164 struct in_addr guest_addr;
4165 int host_port, guest_port;
4167 if (!slirp_inited) {
4168 slirp_inited = 1;
4169 slirp_init();
4172 p = redir_str;
4173 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4174 goto fail;
4175 if (!strcmp(buf, "tcp")) {
4176 is_udp = 0;
4177 } else if (!strcmp(buf, "udp")) {
4178 is_udp = 1;
4179 } else {
4180 goto fail;
4183 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4184 goto fail;
4185 host_port = strtol(buf, &r, 0);
4186 if (r == buf)
4187 goto fail;
4189 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4190 goto fail;
4191 if (buf[0] == '\0') {
4192 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4194 if (!inet_aton(buf, &guest_addr))
4195 goto fail;
4197 guest_port = strtol(p, &r, 0);
4198 if (r == p)
4199 goto fail;
4201 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4202 fprintf(stderr, "qemu: could not set up redirection\n");
4203 exit(1);
4205 return;
4206 fail:
4207 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4208 exit(1);
4211 #ifndef _WIN32
4213 char smb_dir[1024];
4215 static void erase_dir(char *dir_name)
4217 DIR *d;
4218 struct dirent *de;
4219 char filename[1024];
4221 /* erase all the files in the directory */
4222 if ((d = opendir(dir_name)) != 0) {
4223 for(;;) {
4224 de = readdir(d);
4225 if (!de)
4226 break;
4227 if (strcmp(de->d_name, ".") != 0 &&
4228 strcmp(de->d_name, "..") != 0) {
4229 snprintf(filename, sizeof(filename), "%s/%s",
4230 smb_dir, de->d_name);
4231 if (unlink(filename) != 0) /* is it a directory? */
4232 erase_dir(filename);
4235 closedir(d);
4236 rmdir(dir_name);
4240 /* automatic user mode samba server configuration */
4241 static void smb_exit(void)
4243 erase_dir(smb_dir);
4246 /* automatic user mode samba server configuration */
4247 static void net_slirp_smb(const char *exported_dir)
4249 char smb_conf[1024];
4250 char smb_cmdline[1024];
4251 FILE *f;
4253 if (!slirp_inited) {
4254 slirp_inited = 1;
4255 slirp_init();
4258 /* XXX: better tmp dir construction */
4259 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4260 if (mkdir(smb_dir, 0700) < 0) {
4261 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4262 exit(1);
4264 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4266 f = fopen(smb_conf, "w");
4267 if (!f) {
4268 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4269 exit(1);
4271 fprintf(f,
4272 "[global]\n"
4273 "private dir=%s\n"
4274 "smb ports=0\n"
4275 "socket address=127.0.0.1\n"
4276 "pid directory=%s\n"
4277 "lock directory=%s\n"
4278 "log file=%s/log.smbd\n"
4279 "smb passwd file=%s/smbpasswd\n"
4280 "security = share\n"
4281 "[qemu]\n"
4282 "path=%s\n"
4283 "read only=no\n"
4284 "guest ok=yes\n",
4285 smb_dir,
4286 smb_dir,
4287 smb_dir,
4288 smb_dir,
4289 smb_dir,
4290 exported_dir
4292 fclose(f);
4293 atexit(smb_exit);
4295 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4296 SMBD_COMMAND, smb_conf);
4298 slirp_add_exec(0, smb_cmdline, 4, 139);
4301 #endif /* !defined(_WIN32) */
4302 void do_info_slirp(void)
4304 slirp_stats();
4307 #endif /* CONFIG_SLIRP */
4309 #if !defined(_WIN32)
4311 typedef struct TAPState {
4312 VLANClientState *vc;
4313 int fd;
4314 char down_script[1024];
4315 } TAPState;
4317 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4319 TAPState *s = opaque;
4320 int ret;
4321 for(;;) {
4322 ret = write(s->fd, buf, size);
4323 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4324 } else {
4325 break;
4330 static void tap_send(void *opaque)
4332 TAPState *s = opaque;
4333 uint8_t buf[4096];
4334 int size;
4336 #ifdef __sun__
4337 struct strbuf sbuf;
4338 int f = 0;
4339 sbuf.maxlen = sizeof(buf);
4340 sbuf.buf = buf;
4341 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4342 #else
4343 size = read(s->fd, buf, sizeof(buf));
4344 #endif
4345 if (size > 0) {
4346 qemu_send_packet(s->vc, buf, size);
4350 /* fd support */
4352 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4354 TAPState *s;
4356 s = qemu_mallocz(sizeof(TAPState));
4357 if (!s)
4358 return NULL;
4359 s->fd = fd;
4360 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4361 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4362 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4363 return s;
4366 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4367 static int tap_open(char *ifname, int ifname_size)
4369 int fd;
4370 char *dev;
4371 struct stat s;
4373 TFR(fd = open("/dev/tap", O_RDWR));
4374 if (fd < 0) {
4375 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4376 return -1;
4379 fstat(fd, &s);
4380 dev = devname(s.st_rdev, S_IFCHR);
4381 pstrcpy(ifname, ifname_size, dev);
4383 fcntl(fd, F_SETFL, O_NONBLOCK);
4384 return fd;
4386 #elif defined(__sun__)
4387 #define TUNNEWPPA (('T'<<16) | 0x0001)
4389 * Allocate TAP device, returns opened fd.
4390 * Stores dev name in the first arg(must be large enough).
4392 int tap_alloc(char *dev, size_t dev_size)
4394 int tap_fd, if_fd, ppa = -1;
4395 static int ip_fd = 0;
4396 char *ptr;
4398 static int arp_fd = 0;
4399 int ip_muxid, arp_muxid;
4400 struct strioctl strioc_if, strioc_ppa;
4401 int link_type = I_PLINK;;
4402 struct lifreq ifr;
4403 char actual_name[32] = "";
4405 memset(&ifr, 0x0, sizeof(ifr));
4407 if( *dev ){
4408 ptr = dev;
4409 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4410 ppa = atoi(ptr);
4413 /* Check if IP device was opened */
4414 if( ip_fd )
4415 close(ip_fd);
4417 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4418 if (ip_fd < 0) {
4419 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4420 return -1;
4423 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4424 if (tap_fd < 0) {
4425 syslog(LOG_ERR, "Can't open /dev/tap");
4426 return -1;
4429 /* Assign a new PPA and get its unit number. */
4430 strioc_ppa.ic_cmd = TUNNEWPPA;
4431 strioc_ppa.ic_timout = 0;
4432 strioc_ppa.ic_len = sizeof(ppa);
4433 strioc_ppa.ic_dp = (char *)&ppa;
4434 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4435 syslog (LOG_ERR, "Can't assign new interface");
4437 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4438 if (if_fd < 0) {
4439 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4440 return -1;
4442 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4443 syslog(LOG_ERR, "Can't push IP module");
4444 return -1;
4447 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4448 syslog(LOG_ERR, "Can't get flags\n");
4450 snprintf (actual_name, 32, "tap%d", ppa);
4451 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4453 ifr.lifr_ppa = ppa;
4454 /* Assign ppa according to the unit number returned by tun device */
4456 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4457 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4458 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4459 syslog (LOG_ERR, "Can't get flags\n");
4460 /* Push arp module to if_fd */
4461 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4462 syslog (LOG_ERR, "Can't push ARP module (2)");
4464 /* Push arp module to ip_fd */
4465 if (ioctl (ip_fd, I_POP, NULL) < 0)
4466 syslog (LOG_ERR, "I_POP failed\n");
4467 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4468 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4469 /* Open arp_fd */
4470 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4471 if (arp_fd < 0)
4472 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4474 /* Set ifname to arp */
4475 strioc_if.ic_cmd = SIOCSLIFNAME;
4476 strioc_if.ic_timout = 0;
4477 strioc_if.ic_len = sizeof(ifr);
4478 strioc_if.ic_dp = (char *)&ifr;
4479 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4480 syslog (LOG_ERR, "Can't set ifname to arp\n");
4483 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4484 syslog(LOG_ERR, "Can't link TAP device to IP");
4485 return -1;
4488 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4489 syslog (LOG_ERR, "Can't link TAP device to ARP");
4491 close (if_fd);
4493 memset(&ifr, 0x0, sizeof(ifr));
4494 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4495 ifr.lifr_ip_muxid = ip_muxid;
4496 ifr.lifr_arp_muxid = arp_muxid;
4498 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4500 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4501 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4502 syslog (LOG_ERR, "Can't set multiplexor id");
4505 snprintf(dev, dev_size, "tap%d", ppa);
4506 return tap_fd;
4509 static int tap_open(char *ifname, int ifname_size)
4511 char dev[10]="";
4512 int fd;
4513 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4514 fprintf(stderr, "Cannot allocate TAP device\n");
4515 return -1;
4517 pstrcpy(ifname, ifname_size, dev);
4518 fcntl(fd, F_SETFL, O_NONBLOCK);
4519 return fd;
4521 #else
4522 static int tap_open(char *ifname, int ifname_size)
4524 struct ifreq ifr;
4525 int fd, ret;
4527 TFR(fd = open("/dev/net/tun", O_RDWR));
4528 if (fd < 0) {
4529 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4530 return -1;
4532 memset(&ifr, 0, sizeof(ifr));
4533 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4534 if (ifname[0] != '\0')
4535 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4536 else
4537 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4538 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4539 if (ret != 0) {
4540 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4541 close(fd);
4542 return -1;
4544 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4545 fcntl(fd, F_SETFL, O_NONBLOCK);
4546 return fd;
4548 #endif
4550 static int launch_script(const char *setup_script, const char *ifname, int fd)
4552 int pid, status;
4553 char *args[3];
4554 char **parg;
4556 /* try to launch network script */
4557 pid = fork();
4558 if (pid >= 0) {
4559 if (pid == 0) {
4560 int open_max = sysconf (_SC_OPEN_MAX), i;
4561 for (i = 0; i < open_max; i++)
4562 if (i != STDIN_FILENO &&
4563 i != STDOUT_FILENO &&
4564 i != STDERR_FILENO &&
4565 i != fd)
4566 close(i);
4568 parg = args;
4569 *parg++ = (char *)setup_script;
4570 *parg++ = (char *)ifname;
4571 *parg++ = NULL;
4572 execv(setup_script, args);
4573 _exit(1);
4575 while (waitpid(pid, &status, 0) != pid);
4576 if (!WIFEXITED(status) ||
4577 WEXITSTATUS(status) != 0) {
4578 fprintf(stderr, "%s: could not launch network script\n",
4579 setup_script);
4580 return -1;
4583 return 0;
4586 static int net_tap_init(VLANState *vlan, const char *ifname1,
4587 const char *setup_script, const char *down_script)
4589 TAPState *s;
4590 int fd;
4591 char ifname[128];
4593 if (ifname1 != NULL)
4594 pstrcpy(ifname, sizeof(ifname), ifname1);
4595 else
4596 ifname[0] = '\0';
4597 TFR(fd = tap_open(ifname, sizeof(ifname)));
4598 if (fd < 0)
4599 return -1;
4601 if (!setup_script || !strcmp(setup_script, "no"))
4602 setup_script = "";
4603 if (setup_script[0] != '\0') {
4604 if (launch_script(setup_script, ifname, fd))
4605 return -1;
4607 s = net_tap_fd_init(vlan, fd);
4608 if (!s)
4609 return -1;
4610 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4611 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4612 if (down_script && strcmp(down_script, "no"))
4613 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4614 return 0;
4617 #endif /* !_WIN32 */
4619 #if defined(CONFIG_VDE)
4620 typedef struct VDEState {
4621 VLANClientState *vc;
4622 VDECONN *vde;
4623 } VDEState;
4625 static void vde_to_qemu(void *opaque)
4627 VDEState *s = opaque;
4628 uint8_t buf[4096];
4629 int size;
4631 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4632 if (size > 0) {
4633 qemu_send_packet(s->vc, buf, size);
4637 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4639 VDEState *s = opaque;
4640 int ret;
4641 for(;;) {
4642 ret = vde_send(s->vde, buf, size, 0);
4643 if (ret < 0 && errno == EINTR) {
4644 } else {
4645 break;
4650 static int net_vde_init(VLANState *vlan, const char *sock, int port,
4651 const char *group, int mode)
4653 VDEState *s;
4654 char *init_group = strlen(group) ? (char *)group : NULL;
4655 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4657 struct vde_open_args args = {
4658 .port = port,
4659 .group = init_group,
4660 .mode = mode,
4663 s = qemu_mallocz(sizeof(VDEState));
4664 if (!s)
4665 return -1;
4666 s->vde = vde_open(init_sock, "QEMU", &args);
4667 if (!s->vde){
4668 free(s);
4669 return -1;
4671 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4672 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4673 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4674 sock, vde_datafd(s->vde));
4675 return 0;
4677 #endif
4679 /* network connection */
4680 typedef struct NetSocketState {
4681 VLANClientState *vc;
4682 int fd;
4683 int state; /* 0 = getting length, 1 = getting data */
4684 int index;
4685 int packet_len;
4686 uint8_t buf[4096];
4687 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4688 } NetSocketState;
4690 typedef struct NetSocketListenState {
4691 VLANState *vlan;
4692 int fd;
4693 } NetSocketListenState;
4695 /* XXX: we consider we can send the whole packet without blocking */
4696 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4698 NetSocketState *s = opaque;
4699 uint32_t len;
4700 len = htonl(size);
4702 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4703 send_all(s->fd, buf, size);
4706 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4708 NetSocketState *s = opaque;
4709 sendto(s->fd, buf, size, 0,
4710 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4713 static void net_socket_send(void *opaque)
4715 NetSocketState *s = opaque;
4716 int l, size, err;
4717 uint8_t buf1[4096];
4718 const uint8_t *buf;
4720 size = recv(s->fd, buf1, sizeof(buf1), 0);
4721 if (size < 0) {
4722 err = socket_error();
4723 if (err != EWOULDBLOCK)
4724 goto eoc;
4725 } else if (size == 0) {
4726 /* end of connection */
4727 eoc:
4728 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4729 closesocket(s->fd);
4730 return;
4732 buf = buf1;
4733 while (size > 0) {
4734 /* reassemble a packet from the network */
4735 switch(s->state) {
4736 case 0:
4737 l = 4 - s->index;
4738 if (l > size)
4739 l = size;
4740 memcpy(s->buf + s->index, buf, l);
4741 buf += l;
4742 size -= l;
4743 s->index += l;
4744 if (s->index == 4) {
4745 /* got length */
4746 s->packet_len = ntohl(*(uint32_t *)s->buf);
4747 s->index = 0;
4748 s->state = 1;
4750 break;
4751 case 1:
4752 l = s->packet_len - s->index;
4753 if (l > size)
4754 l = size;
4755 memcpy(s->buf + s->index, buf, l);
4756 s->index += l;
4757 buf += l;
4758 size -= l;
4759 if (s->index >= s->packet_len) {
4760 qemu_send_packet(s->vc, s->buf, s->packet_len);
4761 s->index = 0;
4762 s->state = 0;
4764 break;
4769 static void net_socket_send_dgram(void *opaque)
4771 NetSocketState *s = opaque;
4772 int size;
4774 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4775 if (size < 0)
4776 return;
4777 if (size == 0) {
4778 /* end of connection */
4779 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4780 return;
4782 qemu_send_packet(s->vc, s->buf, size);
4785 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4787 struct ip_mreq imr;
4788 int fd;
4789 int val, ret;
4790 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4791 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4792 inet_ntoa(mcastaddr->sin_addr),
4793 (int)ntohl(mcastaddr->sin_addr.s_addr));
4794 return -1;
4797 fd = socket(PF_INET, SOCK_DGRAM, 0);
4798 if (fd < 0) {
4799 perror("socket(PF_INET, SOCK_DGRAM)");
4800 return -1;
4803 val = 1;
4804 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4805 (const char *)&val, sizeof(val));
4806 if (ret < 0) {
4807 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4808 goto fail;
4811 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4812 if (ret < 0) {
4813 perror("bind");
4814 goto fail;
4817 /* Add host to multicast group */
4818 imr.imr_multiaddr = mcastaddr->sin_addr;
4819 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4821 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4822 (const char *)&imr, sizeof(struct ip_mreq));
4823 if (ret < 0) {
4824 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4825 goto fail;
4828 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4829 val = 1;
4830 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4831 (const char *)&val, sizeof(val));
4832 if (ret < 0) {
4833 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4834 goto fail;
4837 socket_set_nonblock(fd);
4838 return fd;
4839 fail:
4840 if (fd >= 0)
4841 closesocket(fd);
4842 return -1;
4845 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4846 int is_connected)
4848 struct sockaddr_in saddr;
4849 int newfd;
4850 socklen_t saddr_len;
4851 NetSocketState *s;
4853 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4854 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4855 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4858 if (is_connected) {
4859 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4860 /* must be bound */
4861 if (saddr.sin_addr.s_addr==0) {
4862 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4863 fd);
4864 return NULL;
4866 /* clone dgram socket */
4867 newfd = net_socket_mcast_create(&saddr);
4868 if (newfd < 0) {
4869 /* error already reported by net_socket_mcast_create() */
4870 close(fd);
4871 return NULL;
4873 /* clone newfd to fd, close newfd */
4874 dup2(newfd, fd);
4875 close(newfd);
4877 } else {
4878 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4879 fd, strerror(errno));
4880 return NULL;
4884 s = qemu_mallocz(sizeof(NetSocketState));
4885 if (!s)
4886 return NULL;
4887 s->fd = fd;
4889 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4890 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4892 /* mcast: save bound address as dst */
4893 if (is_connected) s->dgram_dst=saddr;
4895 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4896 "socket: fd=%d (%s mcast=%s:%d)",
4897 fd, is_connected? "cloned" : "",
4898 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4899 return s;
4902 static void net_socket_connect(void *opaque)
4904 NetSocketState *s = opaque;
4905 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4908 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4909 int is_connected)
4911 NetSocketState *s;
4912 s = qemu_mallocz(sizeof(NetSocketState));
4913 if (!s)
4914 return NULL;
4915 s->fd = fd;
4916 s->vc = qemu_new_vlan_client(vlan,
4917 net_socket_receive, NULL, s);
4918 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4919 "socket: fd=%d", fd);
4920 if (is_connected) {
4921 net_socket_connect(s);
4922 } else {
4923 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4925 return s;
4928 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4929 int is_connected)
4931 int so_type=-1, optlen=sizeof(so_type);
4933 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4934 (socklen_t *)&optlen)< 0) {
4935 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4936 return NULL;
4938 switch(so_type) {
4939 case SOCK_DGRAM:
4940 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4941 case SOCK_STREAM:
4942 return net_socket_fd_init_stream(vlan, fd, is_connected);
4943 default:
4944 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4945 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4946 return net_socket_fd_init_stream(vlan, fd, is_connected);
4948 return NULL;
4951 static void net_socket_accept(void *opaque)
4953 NetSocketListenState *s = opaque;
4954 NetSocketState *s1;
4955 struct sockaddr_in saddr;
4956 socklen_t len;
4957 int fd;
4959 for(;;) {
4960 len = sizeof(saddr);
4961 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4962 if (fd < 0 && errno != EINTR) {
4963 return;
4964 } else if (fd >= 0) {
4965 break;
4968 s1 = net_socket_fd_init(s->vlan, fd, 1);
4969 if (!s1) {
4970 closesocket(fd);
4971 } else {
4972 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4973 "socket: connection from %s:%d",
4974 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4978 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4980 NetSocketListenState *s;
4981 int fd, val, ret;
4982 struct sockaddr_in saddr;
4984 if (parse_host_port(&saddr, host_str) < 0)
4985 return -1;
4987 s = qemu_mallocz(sizeof(NetSocketListenState));
4988 if (!s)
4989 return -1;
4991 fd = socket(PF_INET, SOCK_STREAM, 0);
4992 if (fd < 0) {
4993 perror("socket");
4994 return -1;
4996 socket_set_nonblock(fd);
4998 /* allow fast reuse */
4999 val = 1;
5000 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5002 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5003 if (ret < 0) {
5004 perror("bind");
5005 return -1;
5007 ret = listen(fd, 0);
5008 if (ret < 0) {
5009 perror("listen");
5010 return -1;
5012 s->vlan = vlan;
5013 s->fd = fd;
5014 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5015 return 0;
5018 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5020 NetSocketState *s;
5021 int fd, connected, ret, err;
5022 struct sockaddr_in saddr;
5024 if (parse_host_port(&saddr, host_str) < 0)
5025 return -1;
5027 fd = socket(PF_INET, SOCK_STREAM, 0);
5028 if (fd < 0) {
5029 perror("socket");
5030 return -1;
5032 socket_set_nonblock(fd);
5034 connected = 0;
5035 for(;;) {
5036 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5037 if (ret < 0) {
5038 err = socket_error();
5039 if (err == EINTR || err == EWOULDBLOCK) {
5040 } else if (err == EINPROGRESS) {
5041 break;
5042 #ifdef _WIN32
5043 } else if (err == WSAEALREADY) {
5044 break;
5045 #endif
5046 } else {
5047 perror("connect");
5048 closesocket(fd);
5049 return -1;
5051 } else {
5052 connected = 1;
5053 break;
5056 s = net_socket_fd_init(vlan, fd, connected);
5057 if (!s)
5058 return -1;
5059 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5060 "socket: connect to %s:%d",
5061 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5062 return 0;
5065 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5067 NetSocketState *s;
5068 int fd;
5069 struct sockaddr_in saddr;
5071 if (parse_host_port(&saddr, host_str) < 0)
5072 return -1;
5075 fd = net_socket_mcast_create(&saddr);
5076 if (fd < 0)
5077 return -1;
5079 s = net_socket_fd_init(vlan, fd, 0);
5080 if (!s)
5081 return -1;
5083 s->dgram_dst = saddr;
5085 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5086 "socket: mcast=%s:%d",
5087 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5088 return 0;
5092 static const char *get_opt_name(char *buf, int buf_size, const char *p)
5094 char *q;
5096 q = buf;
5097 while (*p != '\0' && *p != '=') {
5098 if (q && (q - buf) < buf_size - 1)
5099 *q++ = *p;
5100 p++;
5102 if (q)
5103 *q = '\0';
5105 return p;
5108 static const char *get_opt_value(char *buf, int buf_size, const char *p)
5110 char *q;
5112 q = buf;
5113 while (*p != '\0') {
5114 if (*p == ',') {
5115 if (*(p + 1) != ',')
5116 break;
5117 p++;
5119 if (q && (q - buf) < buf_size - 1)
5120 *q++ = *p;
5121 p++;
5123 if (q)
5124 *q = '\0';
5126 return p;
5129 static int get_param_value(char *buf, int buf_size,
5130 const char *tag, const char *str)
5132 const char *p;
5133 char option[128];
5135 p = str;
5136 for(;;) {
5137 p = get_opt_name(option, sizeof(option), p);
5138 if (*p != '=')
5139 break;
5140 p++;
5141 if (!strcmp(tag, option)) {
5142 (void)get_opt_value(buf, buf_size, p);
5143 return strlen(buf);
5144 } else {
5145 p = get_opt_value(NULL, 0, p);
5147 if (*p != ',')
5148 break;
5149 p++;
5151 return 0;
5154 static int check_params(char *buf, int buf_size,
5155 const char * const *params, const char *str)
5157 const char *p;
5158 int i;
5160 p = str;
5161 for(;;) {
5162 p = get_opt_name(buf, buf_size, p);
5163 if (*p != '=')
5164 return -1;
5165 p++;
5166 for(i = 0; params[i] != NULL; i++)
5167 if (!strcmp(params[i], buf))
5168 break;
5169 if (params[i] == NULL)
5170 return -1;
5171 p = get_opt_value(NULL, 0, p);
5172 if (*p != ',')
5173 break;
5174 p++;
5176 return 0;
5179 static int net_client_init(const char *device, const char *p)
5181 char buf[1024];
5182 int vlan_id, ret;
5183 VLANState *vlan;
5185 vlan_id = 0;
5186 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5187 vlan_id = strtol(buf, NULL, 0);
5189 vlan = qemu_find_vlan(vlan_id);
5190 if (!vlan) {
5191 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5192 return -1;
5194 if (!strcmp(device, "nic")) {
5195 NICInfo *nd;
5196 uint8_t *macaddr;
5198 if (nb_nics >= MAX_NICS) {
5199 fprintf(stderr, "Too Many NICs\n");
5200 return -1;
5202 nd = &nd_table[nb_nics];
5203 macaddr = nd->macaddr;
5204 macaddr[0] = 0x52;
5205 macaddr[1] = 0x54;
5206 macaddr[2] = 0x00;
5207 macaddr[3] = 0x12;
5208 macaddr[4] = 0x34;
5209 macaddr[5] = 0x56 + nb_nics;
5211 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5212 if (parse_macaddr(macaddr, buf) < 0) {
5213 fprintf(stderr, "invalid syntax for ethernet address\n");
5214 return -1;
5217 if (get_param_value(buf, sizeof(buf), "model", p)) {
5218 nd->model = strdup(buf);
5220 nd->vlan = vlan;
5221 nb_nics++;
5222 vlan->nb_guest_devs++;
5223 ret = 0;
5224 } else
5225 if (!strcmp(device, "none")) {
5226 /* does nothing. It is needed to signal that no network cards
5227 are wanted */
5228 ret = 0;
5229 } else
5230 #ifdef CONFIG_SLIRP
5231 if (!strcmp(device, "user")) {
5232 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5233 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5235 vlan->nb_host_devs++;
5236 ret = net_slirp_init(vlan);
5237 } else
5238 #endif
5239 #ifdef _WIN32
5240 if (!strcmp(device, "tap")) {
5241 char ifname[64];
5242 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5243 fprintf(stderr, "tap: no interface name\n");
5244 return -1;
5246 vlan->nb_host_devs++;
5247 ret = tap_win32_init(vlan, ifname);
5248 } else
5249 #else
5250 if (!strcmp(device, "tap")) {
5251 char ifname[64];
5252 char setup_script[1024], down_script[1024];
5253 int fd;
5254 vlan->nb_host_devs++;
5255 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5256 fd = strtol(buf, NULL, 0);
5257 fcntl(fd, F_SETFL, O_NONBLOCK);
5258 ret = -1;
5259 if (net_tap_fd_init(vlan, fd))
5260 ret = 0;
5261 } else {
5262 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5263 ifname[0] = '\0';
5265 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5266 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5268 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5269 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5271 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5273 } else
5274 #endif
5275 if (!strcmp(device, "socket")) {
5276 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5277 int fd;
5278 fd = strtol(buf, NULL, 0);
5279 ret = -1;
5280 if (net_socket_fd_init(vlan, fd, 1))
5281 ret = 0;
5282 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5283 ret = net_socket_listen_init(vlan, buf);
5284 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5285 ret = net_socket_connect_init(vlan, buf);
5286 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5287 ret = net_socket_mcast_init(vlan, buf);
5288 } else {
5289 fprintf(stderr, "Unknown socket options: %s\n", p);
5290 return -1;
5292 vlan->nb_host_devs++;
5293 } else
5294 #ifdef CONFIG_VDE
5295 if (!strcmp(device, "vde")) {
5296 char vde_sock[1024], vde_group[512];
5297 int vde_port, vde_mode;
5298 vlan->nb_host_devs++;
5299 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5300 vde_sock[0] = '\0';
5302 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5303 vde_port = strtol(buf, NULL, 10);
5304 } else {
5305 vde_port = 0;
5307 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5308 vde_group[0] = '\0';
5310 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5311 vde_mode = strtol(buf, NULL, 8);
5312 } else {
5313 vde_mode = 0700;
5315 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5316 } else
5317 #endif
5319 fprintf(stderr, "Unknown network device: %s\n", device);
5320 return -1;
5322 if (ret < 0) {
5323 fprintf(stderr, "Could not initialize device '%s'\n", device);
5326 return ret;
5329 static int net_client_parse(const char *str)
5331 const char *p;
5332 char *q;
5333 char device[64];
5335 p = str;
5336 q = device;
5337 while (*p != '\0' && *p != ',') {
5338 if ((q - device) < sizeof(device) - 1)
5339 *q++ = *p;
5340 p++;
5342 *q = '\0';
5343 if (*p == ',')
5344 p++;
5346 return net_client_init(device, p);
5349 void do_info_network(void)
5351 VLANState *vlan;
5352 VLANClientState *vc;
5354 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5355 term_printf("VLAN %d devices:\n", vlan->id);
5356 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5357 term_printf(" %s\n", vc->info_str);
5361 #define HD_ALIAS "index=%d,media=disk"
5362 #ifdef TARGET_PPC
5363 #define CDROM_ALIAS "index=1,media=cdrom"
5364 #else
5365 #define CDROM_ALIAS "index=2,media=cdrom"
5366 #endif
5367 #define FD_ALIAS "index=%d,if=floppy"
5368 #define PFLASH_ALIAS "if=pflash"
5369 #define MTD_ALIAS "if=mtd"
5370 #define SD_ALIAS "index=0,if=sd"
5372 static int drive_add(const char *file, const char *fmt, ...)
5374 va_list ap;
5376 if (nb_drives_opt >= MAX_DRIVES) {
5377 fprintf(stderr, "qemu: too many drives\n");
5378 exit(1);
5381 drives_opt[nb_drives_opt].file = file;
5382 va_start(ap, fmt);
5383 vsnprintf(drives_opt[nb_drives_opt].opt,
5384 sizeof(drives_opt[0].opt), fmt, ap);
5385 va_end(ap);
5387 return nb_drives_opt++;
5390 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5392 int index;
5394 /* seek interface, bus and unit */
5396 for (index = 0; index < nb_drives; index++)
5397 if (drives_table[index].type == type &&
5398 drives_table[index].bus == bus &&
5399 drives_table[index].unit == unit)
5400 return index;
5402 return -1;
5405 int drive_get_max_bus(BlockInterfaceType type)
5407 int max_bus;
5408 int index;
5410 max_bus = -1;
5411 for (index = 0; index < nb_drives; index++) {
5412 if(drives_table[index].type == type &&
5413 drives_table[index].bus > max_bus)
5414 max_bus = drives_table[index].bus;
5416 return max_bus;
5419 static void bdrv_format_print(void *opaque, const char *name)
5421 fprintf(stderr, " %s", name);
5424 static int drive_init(struct drive_opt *arg, int snapshot,
5425 QEMUMachine *machine)
5427 char buf[128];
5428 char file[1024];
5429 char devname[128];
5430 const char *mediastr = "";
5431 BlockInterfaceType type;
5432 enum { MEDIA_DISK, MEDIA_CDROM } media;
5433 int bus_id, unit_id;
5434 int cyls, heads, secs, translation;
5435 BlockDriverState *bdrv;
5436 BlockDriver *drv = NULL;
5437 int max_devs;
5438 int index;
5439 int cache;
5440 int bdrv_flags;
5441 char *str = arg->opt;
5442 static const char * const params[] = { "bus", "unit", "if", "index",
5443 "cyls", "heads", "secs", "trans",
5444 "media", "snapshot", "file",
5445 "cache", "format", NULL };
5447 if (check_params(buf, sizeof(buf), params, str) < 0) {
5448 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5449 buf, str);
5450 return -1;
5453 file[0] = 0;
5454 cyls = heads = secs = 0;
5455 bus_id = 0;
5456 unit_id = -1;
5457 translation = BIOS_ATA_TRANSLATION_AUTO;
5458 index = -1;
5459 cache = 1;
5461 if (!strcmp(machine->name, "realview") ||
5462 !strcmp(machine->name, "SS-5") ||
5463 !strcmp(machine->name, "SS-10") ||
5464 !strcmp(machine->name, "SS-600MP") ||
5465 !strcmp(machine->name, "versatilepb") ||
5466 !strcmp(machine->name, "versatileab")) {
5467 type = IF_SCSI;
5468 max_devs = MAX_SCSI_DEVS;
5469 pstrcpy(devname, sizeof(devname), "scsi");
5470 } else {
5471 type = IF_IDE;
5472 max_devs = MAX_IDE_DEVS;
5473 pstrcpy(devname, sizeof(devname), "ide");
5475 media = MEDIA_DISK;
5477 /* extract parameters */
5479 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5480 bus_id = strtol(buf, NULL, 0);
5481 if (bus_id < 0) {
5482 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5483 return -1;
5487 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5488 unit_id = strtol(buf, NULL, 0);
5489 if (unit_id < 0) {
5490 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5491 return -1;
5495 if (get_param_value(buf, sizeof(buf), "if", str)) {
5496 pstrcpy(devname, sizeof(devname), buf);
5497 if (!strcmp(buf, "ide")) {
5498 type = IF_IDE;
5499 max_devs = MAX_IDE_DEVS;
5500 } else if (!strcmp(buf, "scsi")) {
5501 type = IF_SCSI;
5502 max_devs = MAX_SCSI_DEVS;
5503 } else if (!strcmp(buf, "floppy")) {
5504 type = IF_FLOPPY;
5505 max_devs = 0;
5506 } else if (!strcmp(buf, "pflash")) {
5507 type = IF_PFLASH;
5508 max_devs = 0;
5509 } else if (!strcmp(buf, "mtd")) {
5510 type = IF_MTD;
5511 max_devs = 0;
5512 } else if (!strcmp(buf, "sd")) {
5513 type = IF_SD;
5514 max_devs = 0;
5515 } else {
5516 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5517 return -1;
5521 if (get_param_value(buf, sizeof(buf), "index", str)) {
5522 index = strtol(buf, NULL, 0);
5523 if (index < 0) {
5524 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5525 return -1;
5529 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5530 cyls = strtol(buf, NULL, 0);
5533 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5534 heads = strtol(buf, NULL, 0);
5537 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5538 secs = strtol(buf, NULL, 0);
5541 if (cyls || heads || secs) {
5542 if (cyls < 1 || cyls > 16383) {
5543 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5544 return -1;
5546 if (heads < 1 || heads > 16) {
5547 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5548 return -1;
5550 if (secs < 1 || secs > 63) {
5551 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5552 return -1;
5556 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5557 if (!cyls) {
5558 fprintf(stderr,
5559 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5560 str);
5561 return -1;
5563 if (!strcmp(buf, "none"))
5564 translation = BIOS_ATA_TRANSLATION_NONE;
5565 else if (!strcmp(buf, "lba"))
5566 translation = BIOS_ATA_TRANSLATION_LBA;
5567 else if (!strcmp(buf, "auto"))
5568 translation = BIOS_ATA_TRANSLATION_AUTO;
5569 else {
5570 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5571 return -1;
5575 if (get_param_value(buf, sizeof(buf), "media", str)) {
5576 if (!strcmp(buf, "disk")) {
5577 media = MEDIA_DISK;
5578 } else if (!strcmp(buf, "cdrom")) {
5579 if (cyls || secs || heads) {
5580 fprintf(stderr,
5581 "qemu: '%s' invalid physical CHS format\n", str);
5582 return -1;
5584 media = MEDIA_CDROM;
5585 } else {
5586 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5587 return -1;
5591 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5592 if (!strcmp(buf, "on"))
5593 snapshot = 1;
5594 else if (!strcmp(buf, "off"))
5595 snapshot = 0;
5596 else {
5597 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5598 return -1;
5602 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5603 if (!strcmp(buf, "off"))
5604 cache = 0;
5605 else if (!strcmp(buf, "on"))
5606 cache = 1;
5607 else {
5608 fprintf(stderr, "qemu: invalid cache option\n");
5609 return -1;
5613 if (get_param_value(buf, sizeof(buf), "format", str)) {
5614 if (strcmp(buf, "?") == 0) {
5615 fprintf(stderr, "qemu: Supported formats:");
5616 bdrv_iterate_format(bdrv_format_print, NULL);
5617 fprintf(stderr, "\n");
5618 return -1;
5620 drv = bdrv_find_format(buf);
5621 if (!drv) {
5622 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5623 return -1;
5627 if (arg->file == NULL)
5628 get_param_value(file, sizeof(file), "file", str);
5629 else
5630 pstrcpy(file, sizeof(file), arg->file);
5632 /* compute bus and unit according index */
5634 if (index != -1) {
5635 if (bus_id != 0 || unit_id != -1) {
5636 fprintf(stderr,
5637 "qemu: '%s' index cannot be used with bus and unit\n", str);
5638 return -1;
5640 if (max_devs == 0)
5642 unit_id = index;
5643 bus_id = 0;
5644 } else {
5645 unit_id = index % max_devs;
5646 bus_id = index / max_devs;
5650 /* if user doesn't specify a unit_id,
5651 * try to find the first free
5654 if (unit_id == -1) {
5655 unit_id = 0;
5656 while (drive_get_index(type, bus_id, unit_id) != -1) {
5657 unit_id++;
5658 if (max_devs && unit_id >= max_devs) {
5659 unit_id -= max_devs;
5660 bus_id++;
5665 /* check unit id */
5667 if (max_devs && unit_id >= max_devs) {
5668 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5669 str, unit_id, max_devs - 1);
5670 return -1;
5674 * ignore multiple definitions
5677 if (drive_get_index(type, bus_id, unit_id) != -1)
5678 return 0;
5680 /* init */
5682 if (type == IF_IDE || type == IF_SCSI)
5683 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5684 if (max_devs)
5685 snprintf(buf, sizeof(buf), "%s%i%s%i",
5686 devname, bus_id, mediastr, unit_id);
5687 else
5688 snprintf(buf, sizeof(buf), "%s%s%i",
5689 devname, mediastr, unit_id);
5690 bdrv = bdrv_new(buf);
5691 drives_table[nb_drives].bdrv = bdrv;
5692 drives_table[nb_drives].type = type;
5693 drives_table[nb_drives].bus = bus_id;
5694 drives_table[nb_drives].unit = unit_id;
5695 nb_drives++;
5697 switch(type) {
5698 case IF_IDE:
5699 case IF_SCSI:
5700 switch(media) {
5701 case MEDIA_DISK:
5702 if (cyls != 0) {
5703 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5704 bdrv_set_translation_hint(bdrv, translation);
5706 break;
5707 case MEDIA_CDROM:
5708 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5709 break;
5711 break;
5712 case IF_SD:
5713 /* FIXME: This isn't really a floppy, but it's a reasonable
5714 approximation. */
5715 case IF_FLOPPY:
5716 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5717 break;
5718 case IF_PFLASH:
5719 case IF_MTD:
5720 break;
5722 if (!file[0])
5723 return 0;
5724 bdrv_flags = 0;
5725 if (snapshot)
5726 bdrv_flags |= BDRV_O_SNAPSHOT;
5727 if (!cache)
5728 bdrv_flags |= BDRV_O_DIRECT;
5729 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5730 fprintf(stderr, "qemu: could not open disk image %s\n",
5731 file);
5732 return -1;
5734 return 0;
5737 /***********************************************************/
5738 /* USB devices */
5740 static USBPort *used_usb_ports;
5741 static USBPort *free_usb_ports;
5743 /* ??? Maybe change this to register a hub to keep track of the topology. */
5744 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5745 usb_attachfn attach)
5747 port->opaque = opaque;
5748 port->index = index;
5749 port->attach = attach;
5750 port->next = free_usb_ports;
5751 free_usb_ports = port;
5754 int usb_device_add_dev(USBDevice *dev)
5756 USBPort *port;
5758 /* Find a USB port to add the device to. */
5759 port = free_usb_ports;
5760 if (!port->next) {
5761 USBDevice *hub;
5763 /* Create a new hub and chain it on. */
5764 free_usb_ports = NULL;
5765 port->next = used_usb_ports;
5766 used_usb_ports = port;
5768 hub = usb_hub_init(VM_USB_HUB_SIZE);
5769 usb_attach(port, hub);
5770 port = free_usb_ports;
5773 free_usb_ports = port->next;
5774 port->next = used_usb_ports;
5775 used_usb_ports = port;
5776 usb_attach(port, dev);
5777 return 0;
5780 static int usb_device_add(const char *devname)
5782 const char *p;
5783 USBDevice *dev;
5785 if (!free_usb_ports)
5786 return -1;
5788 if (strstart(devname, "host:", &p)) {
5789 dev = usb_host_device_open(p);
5790 } else if (!strcmp(devname, "mouse")) {
5791 dev = usb_mouse_init();
5792 } else if (!strcmp(devname, "tablet")) {
5793 dev = usb_tablet_init();
5794 } else if (!strcmp(devname, "keyboard")) {
5795 dev = usb_keyboard_init();
5796 } else if (strstart(devname, "disk:", &p)) {
5797 dev = usb_msd_init(p);
5798 } else if (!strcmp(devname, "wacom-tablet")) {
5799 dev = usb_wacom_init();
5800 } else if (strstart(devname, "serial:", &p)) {
5801 dev = usb_serial_init(p);
5802 #ifdef CONFIG_BRLAPI
5803 } else if (!strcmp(devname, "braille")) {
5804 dev = usb_baum_init();
5805 #endif
5806 } else if (strstart(devname, "net:", &p)) {
5807 int nic = nb_nics;
5809 if (net_client_init("nic", p) < 0)
5810 return -1;
5811 nd_table[nic].model = "usb";
5812 dev = usb_net_init(&nd_table[nic]);
5813 } else {
5814 return -1;
5816 if (!dev)
5817 return -1;
5819 return usb_device_add_dev(dev);
5822 int usb_device_del_addr(int bus_num, int addr)
5824 USBPort *port;
5825 USBPort **lastp;
5826 USBDevice *dev;
5828 if (!used_usb_ports)
5829 return -1;
5831 if (bus_num != 0)
5832 return -1;
5834 lastp = &used_usb_ports;
5835 port = used_usb_ports;
5836 while (port && port->dev->addr != addr) {
5837 lastp = &port->next;
5838 port = port->next;
5841 if (!port)
5842 return -1;
5844 dev = port->dev;
5845 *lastp = port->next;
5846 usb_attach(port, NULL);
5847 dev->handle_destroy(dev);
5848 port->next = free_usb_ports;
5849 free_usb_ports = port;
5850 return 0;
5853 static int usb_device_del(const char *devname)
5855 int bus_num, addr;
5856 const char *p;
5858 if (strstart(devname, "host:", &p))
5859 return usb_host_device_close(p);
5861 if (!used_usb_ports)
5862 return -1;
5864 p = strchr(devname, '.');
5865 if (!p)
5866 return -1;
5867 bus_num = strtoul(devname, NULL, 0);
5868 addr = strtoul(p + 1, NULL, 0);
5870 return usb_device_del_addr(bus_num, addr);
5873 void do_usb_add(const char *devname)
5875 usb_device_add(devname);
5878 void do_usb_del(const char *devname)
5880 usb_device_del(devname);
5883 void usb_info(void)
5885 USBDevice *dev;
5886 USBPort *port;
5887 const char *speed_str;
5889 if (!usb_enabled) {
5890 term_printf("USB support not enabled\n");
5891 return;
5894 for (port = used_usb_ports; port; port = port->next) {
5895 dev = port->dev;
5896 if (!dev)
5897 continue;
5898 switch(dev->speed) {
5899 case USB_SPEED_LOW:
5900 speed_str = "1.5";
5901 break;
5902 case USB_SPEED_FULL:
5903 speed_str = "12";
5904 break;
5905 case USB_SPEED_HIGH:
5906 speed_str = "480";
5907 break;
5908 default:
5909 speed_str = "?";
5910 break;
5912 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5913 0, dev->addr, speed_str, dev->devname);
5917 /***********************************************************/
5918 /* PCMCIA/Cardbus */
5920 static struct pcmcia_socket_entry_s {
5921 struct pcmcia_socket_s *socket;
5922 struct pcmcia_socket_entry_s *next;
5923 } *pcmcia_sockets = 0;
5925 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5927 struct pcmcia_socket_entry_s *entry;
5929 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5930 entry->socket = socket;
5931 entry->next = pcmcia_sockets;
5932 pcmcia_sockets = entry;
5935 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5937 struct pcmcia_socket_entry_s *entry, **ptr;
5939 ptr = &pcmcia_sockets;
5940 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5941 if (entry->socket == socket) {
5942 *ptr = entry->next;
5943 qemu_free(entry);
5947 void pcmcia_info(void)
5949 struct pcmcia_socket_entry_s *iter;
5950 if (!pcmcia_sockets)
5951 term_printf("No PCMCIA sockets\n");
5953 for (iter = pcmcia_sockets; iter; iter = iter->next)
5954 term_printf("%s: %s\n", iter->socket->slot_string,
5955 iter->socket->attached ? iter->socket->card_string :
5956 "Empty");
5959 /***********************************************************/
5960 /* dumb display */
5962 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5966 static void dumb_resize(DisplayState *ds, int w, int h)
5970 static void dumb_refresh(DisplayState *ds)
5972 #if defined(CONFIG_SDL)
5973 vga_hw_update();
5974 #endif
5977 static void dumb_display_init(DisplayState *ds)
5979 ds->data = NULL;
5980 ds->linesize = 0;
5981 ds->depth = 0;
5982 ds->dpy_update = dumb_update;
5983 ds->dpy_resize = dumb_resize;
5984 ds->dpy_refresh = dumb_refresh;
5985 ds->gui_timer_interval = 500;
5986 ds->idle = 1;
5989 /***********************************************************/
5990 /* I/O handling */
5992 #define MAX_IO_HANDLERS 64
5994 typedef struct IOHandlerRecord {
5995 int fd;
5996 IOCanRWHandler *fd_read_poll;
5997 IOHandler *fd_read;
5998 IOHandler *fd_write;
5999 int deleted;
6000 void *opaque;
6001 /* temporary data */
6002 struct pollfd *ufd;
6003 struct IOHandlerRecord *next;
6004 } IOHandlerRecord;
6006 static IOHandlerRecord *first_io_handler;
6008 /* XXX: fd_read_poll should be suppressed, but an API change is
6009 necessary in the character devices to suppress fd_can_read(). */
6010 int qemu_set_fd_handler2(int fd,
6011 IOCanRWHandler *fd_read_poll,
6012 IOHandler *fd_read,
6013 IOHandler *fd_write,
6014 void *opaque)
6016 IOHandlerRecord **pioh, *ioh;
6018 if (!fd_read && !fd_write) {
6019 pioh = &first_io_handler;
6020 for(;;) {
6021 ioh = *pioh;
6022 if (ioh == NULL)
6023 break;
6024 if (ioh->fd == fd) {
6025 ioh->deleted = 1;
6026 break;
6028 pioh = &ioh->next;
6030 } else {
6031 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6032 if (ioh->fd == fd)
6033 goto found;
6035 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6036 if (!ioh)
6037 return -1;
6038 ioh->next = first_io_handler;
6039 first_io_handler = ioh;
6040 found:
6041 ioh->fd = fd;
6042 ioh->fd_read_poll = fd_read_poll;
6043 ioh->fd_read = fd_read;
6044 ioh->fd_write = fd_write;
6045 ioh->opaque = opaque;
6046 ioh->deleted = 0;
6048 return 0;
6051 int qemu_set_fd_handler(int fd,
6052 IOHandler *fd_read,
6053 IOHandler *fd_write,
6054 void *opaque)
6056 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6059 /***********************************************************/
6060 /* Polling handling */
6062 typedef struct PollingEntry {
6063 PollingFunc *func;
6064 void *opaque;
6065 struct PollingEntry *next;
6066 } PollingEntry;
6068 static PollingEntry *first_polling_entry;
6070 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6072 PollingEntry **ppe, *pe;
6073 pe = qemu_mallocz(sizeof(PollingEntry));
6074 if (!pe)
6075 return -1;
6076 pe->func = func;
6077 pe->opaque = opaque;
6078 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6079 *ppe = pe;
6080 return 0;
6083 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6085 PollingEntry **ppe, *pe;
6086 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6087 pe = *ppe;
6088 if (pe->func == func && pe->opaque == opaque) {
6089 *ppe = pe->next;
6090 qemu_free(pe);
6091 break;
6096 #ifdef _WIN32
6097 /***********************************************************/
6098 /* Wait objects support */
6099 typedef struct WaitObjects {
6100 int num;
6101 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6102 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6103 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6104 } WaitObjects;
6106 static WaitObjects wait_objects = {0};
6108 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6110 WaitObjects *w = &wait_objects;
6112 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6113 return -1;
6114 w->events[w->num] = handle;
6115 w->func[w->num] = func;
6116 w->opaque[w->num] = opaque;
6117 w->num++;
6118 return 0;
6121 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6123 int i, found;
6124 WaitObjects *w = &wait_objects;
6126 found = 0;
6127 for (i = 0; i < w->num; i++) {
6128 if (w->events[i] == handle)
6129 found = 1;
6130 if (found) {
6131 w->events[i] = w->events[i + 1];
6132 w->func[i] = w->func[i + 1];
6133 w->opaque[i] = w->opaque[i + 1];
6136 if (found)
6137 w->num--;
6139 #endif
6141 /***********************************************************/
6142 /* savevm/loadvm support */
6144 #define IO_BUF_SIZE 32768
6146 struct QEMUFile {
6147 FILE *outfile;
6148 BlockDriverState *bs;
6149 int is_file;
6150 int is_writable;
6151 int64_t base_offset;
6152 int64_t buf_offset; /* start of buffer when writing, end of buffer
6153 when reading */
6154 int buf_index;
6155 int buf_size; /* 0 when writing */
6156 uint8_t buf[IO_BUF_SIZE];
6159 QEMUFile *qemu_fopen(const char *filename, const char *mode)
6161 QEMUFile *f;
6163 f = qemu_mallocz(sizeof(QEMUFile));
6164 if (!f)
6165 return NULL;
6166 if (!strcmp(mode, "wb")) {
6167 f->is_writable = 1;
6168 } else if (!strcmp(mode, "rb")) {
6169 f->is_writable = 0;
6170 } else {
6171 goto fail;
6173 f->outfile = fopen(filename, mode);
6174 if (!f->outfile)
6175 goto fail;
6176 f->is_file = 1;
6177 return f;
6178 fail:
6179 if (f->outfile)
6180 fclose(f->outfile);
6181 qemu_free(f);
6182 return NULL;
6185 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6187 QEMUFile *f;
6189 f = qemu_mallocz(sizeof(QEMUFile));
6190 if (!f)
6191 return NULL;
6192 f->is_file = 0;
6193 f->bs = bs;
6194 f->is_writable = is_writable;
6195 f->base_offset = offset;
6196 return f;
6199 void qemu_fflush(QEMUFile *f)
6201 if (!f->is_writable)
6202 return;
6203 if (f->buf_index > 0) {
6204 if (f->is_file) {
6205 fseek(f->outfile, f->buf_offset, SEEK_SET);
6206 fwrite(f->buf, 1, f->buf_index, f->outfile);
6207 } else {
6208 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
6209 f->buf, f->buf_index);
6211 f->buf_offset += f->buf_index;
6212 f->buf_index = 0;
6216 static void qemu_fill_buffer(QEMUFile *f)
6218 int len;
6220 if (f->is_writable)
6221 return;
6222 if (f->is_file) {
6223 fseek(f->outfile, f->buf_offset, SEEK_SET);
6224 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
6225 if (len < 0)
6226 len = 0;
6227 } else {
6228 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
6229 f->buf, IO_BUF_SIZE);
6230 if (len < 0)
6231 len = 0;
6233 f->buf_index = 0;
6234 f->buf_size = len;
6235 f->buf_offset += len;
6238 void qemu_fclose(QEMUFile *f)
6240 if (f->is_writable)
6241 qemu_fflush(f);
6242 if (f->is_file) {
6243 fclose(f->outfile);
6245 qemu_free(f);
6248 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6250 int l;
6251 while (size > 0) {
6252 l = IO_BUF_SIZE - f->buf_index;
6253 if (l > size)
6254 l = size;
6255 memcpy(f->buf + f->buf_index, buf, l);
6256 f->buf_index += l;
6257 buf += l;
6258 size -= l;
6259 if (f->buf_index >= IO_BUF_SIZE)
6260 qemu_fflush(f);
6264 void qemu_put_byte(QEMUFile *f, int v)
6266 f->buf[f->buf_index++] = v;
6267 if (f->buf_index >= IO_BUF_SIZE)
6268 qemu_fflush(f);
6271 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6273 int size, l;
6275 size = size1;
6276 while (size > 0) {
6277 l = f->buf_size - f->buf_index;
6278 if (l == 0) {
6279 qemu_fill_buffer(f);
6280 l = f->buf_size - f->buf_index;
6281 if (l == 0)
6282 break;
6284 if (l > size)
6285 l = size;
6286 memcpy(buf, f->buf + f->buf_index, l);
6287 f->buf_index += l;
6288 buf += l;
6289 size -= l;
6291 return size1 - size;
6294 int qemu_get_byte(QEMUFile *f)
6296 if (f->buf_index >= f->buf_size) {
6297 qemu_fill_buffer(f);
6298 if (f->buf_index >= f->buf_size)
6299 return 0;
6301 return f->buf[f->buf_index++];
6304 int64_t qemu_ftell(QEMUFile *f)
6306 return f->buf_offset - f->buf_size + f->buf_index;
6309 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6311 if (whence == SEEK_SET) {
6312 /* nothing to do */
6313 } else if (whence == SEEK_CUR) {
6314 pos += qemu_ftell(f);
6315 } else {
6316 /* SEEK_END not supported */
6317 return -1;
6319 if (f->is_writable) {
6320 qemu_fflush(f);
6321 f->buf_offset = pos;
6322 } else {
6323 f->buf_offset = pos;
6324 f->buf_index = 0;
6325 f->buf_size = 0;
6327 return pos;
6330 void qemu_put_be16(QEMUFile *f, unsigned int v)
6332 qemu_put_byte(f, v >> 8);
6333 qemu_put_byte(f, v);
6336 void qemu_put_be32(QEMUFile *f, unsigned int v)
6338 qemu_put_byte(f, v >> 24);
6339 qemu_put_byte(f, v >> 16);
6340 qemu_put_byte(f, v >> 8);
6341 qemu_put_byte(f, v);
6344 void qemu_put_be64(QEMUFile *f, uint64_t v)
6346 qemu_put_be32(f, v >> 32);
6347 qemu_put_be32(f, v);
6350 unsigned int qemu_get_be16(QEMUFile *f)
6352 unsigned int v;
6353 v = qemu_get_byte(f) << 8;
6354 v |= qemu_get_byte(f);
6355 return v;
6358 unsigned int qemu_get_be32(QEMUFile *f)
6360 unsigned int v;
6361 v = qemu_get_byte(f) << 24;
6362 v |= qemu_get_byte(f) << 16;
6363 v |= qemu_get_byte(f) << 8;
6364 v |= qemu_get_byte(f);
6365 return v;
6368 uint64_t qemu_get_be64(QEMUFile *f)
6370 uint64_t v;
6371 v = (uint64_t)qemu_get_be32(f) << 32;
6372 v |= qemu_get_be32(f);
6373 return v;
6376 typedef struct SaveStateEntry {
6377 char idstr[256];
6378 int instance_id;
6379 int version_id;
6380 SaveStateHandler *save_state;
6381 LoadStateHandler *load_state;
6382 void *opaque;
6383 struct SaveStateEntry *next;
6384 } SaveStateEntry;
6386 static SaveStateEntry *first_se;
6388 /* TODO: Individual devices generally have very little idea about the rest
6389 of the system, so instance_id should be removed/replaced.
6390 Meanwhile pass -1 as instance_id if you do not already have a clearly
6391 distinguishing id for all instances of your device class. */
6392 int register_savevm(const char *idstr,
6393 int instance_id,
6394 int version_id,
6395 SaveStateHandler *save_state,
6396 LoadStateHandler *load_state,
6397 void *opaque)
6399 SaveStateEntry *se, **pse;
6401 se = qemu_malloc(sizeof(SaveStateEntry));
6402 if (!se)
6403 return -1;
6404 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6405 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6406 se->version_id = version_id;
6407 se->save_state = save_state;
6408 se->load_state = load_state;
6409 se->opaque = opaque;
6410 se->next = NULL;
6412 /* add at the end of list */
6413 pse = &first_se;
6414 while (*pse != NULL) {
6415 if (instance_id == -1
6416 && strcmp(se->idstr, (*pse)->idstr) == 0
6417 && se->instance_id <= (*pse)->instance_id)
6418 se->instance_id = (*pse)->instance_id + 1;
6419 pse = &(*pse)->next;
6421 *pse = se;
6422 return 0;
6425 #define QEMU_VM_FILE_MAGIC 0x5145564d
6426 #define QEMU_VM_FILE_VERSION 0x00000002
6428 static int qemu_savevm_state(QEMUFile *f)
6430 SaveStateEntry *se;
6431 int len, ret;
6432 int64_t cur_pos, len_pos, total_len_pos;
6434 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6435 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6436 total_len_pos = qemu_ftell(f);
6437 qemu_put_be64(f, 0); /* total size */
6439 for(se = first_se; se != NULL; se = se->next) {
6440 if (se->save_state == NULL)
6441 /* this one has a loader only, for backwards compatibility */
6442 continue;
6444 /* ID string */
6445 len = strlen(se->idstr);
6446 qemu_put_byte(f, len);
6447 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6449 qemu_put_be32(f, se->instance_id);
6450 qemu_put_be32(f, se->version_id);
6452 /* record size: filled later */
6453 len_pos = qemu_ftell(f);
6454 qemu_put_be32(f, 0);
6455 se->save_state(f, se->opaque);
6457 /* fill record size */
6458 cur_pos = qemu_ftell(f);
6459 len = cur_pos - len_pos - 4;
6460 qemu_fseek(f, len_pos, SEEK_SET);
6461 qemu_put_be32(f, len);
6462 qemu_fseek(f, cur_pos, SEEK_SET);
6464 cur_pos = qemu_ftell(f);
6465 qemu_fseek(f, total_len_pos, SEEK_SET);
6466 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6467 qemu_fseek(f, cur_pos, SEEK_SET);
6469 ret = 0;
6470 return ret;
6473 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6475 SaveStateEntry *se;
6477 for(se = first_se; se != NULL; se = se->next) {
6478 if (!strcmp(se->idstr, idstr) &&
6479 instance_id == se->instance_id)
6480 return se;
6482 return NULL;
6485 static int qemu_loadvm_state(QEMUFile *f)
6487 SaveStateEntry *se;
6488 int len, ret, instance_id, record_len, version_id;
6489 int64_t total_len, end_pos, cur_pos;
6490 unsigned int v;
6491 char idstr[256];
6493 v = qemu_get_be32(f);
6494 if (v != QEMU_VM_FILE_MAGIC)
6495 goto fail;
6496 v = qemu_get_be32(f);
6497 if (v != QEMU_VM_FILE_VERSION) {
6498 fail:
6499 ret = -1;
6500 goto the_end;
6502 total_len = qemu_get_be64(f);
6503 end_pos = total_len + qemu_ftell(f);
6504 for(;;) {
6505 if (qemu_ftell(f) >= end_pos)
6506 break;
6507 len = qemu_get_byte(f);
6508 qemu_get_buffer(f, (uint8_t *)idstr, len);
6509 idstr[len] = '\0';
6510 instance_id = qemu_get_be32(f);
6511 version_id = qemu_get_be32(f);
6512 record_len = qemu_get_be32(f);
6513 #if 0
6514 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6515 idstr, instance_id, version_id, record_len);
6516 #endif
6517 cur_pos = qemu_ftell(f);
6518 se = find_se(idstr, instance_id);
6519 if (!se) {
6520 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6521 instance_id, idstr);
6522 } else {
6523 ret = se->load_state(f, se->opaque, version_id);
6524 if (ret < 0) {
6525 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6526 instance_id, idstr);
6529 /* always seek to exact end of record */
6530 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6532 ret = 0;
6533 the_end:
6534 return ret;
6537 /* device can contain snapshots */
6538 static int bdrv_can_snapshot(BlockDriverState *bs)
6540 return (bs &&
6541 !bdrv_is_removable(bs) &&
6542 !bdrv_is_read_only(bs));
6545 /* device must be snapshots in order to have a reliable snapshot */
6546 static int bdrv_has_snapshot(BlockDriverState *bs)
6548 return (bs &&
6549 !bdrv_is_removable(bs) &&
6550 !bdrv_is_read_only(bs));
6553 static BlockDriverState *get_bs_snapshots(void)
6555 BlockDriverState *bs;
6556 int i;
6558 if (bs_snapshots)
6559 return bs_snapshots;
6560 for(i = 0; i <= nb_drives; i++) {
6561 bs = drives_table[i].bdrv;
6562 if (bdrv_can_snapshot(bs))
6563 goto ok;
6565 return NULL;
6567 bs_snapshots = bs;
6568 return bs;
6571 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6572 const char *name)
6574 QEMUSnapshotInfo *sn_tab, *sn;
6575 int nb_sns, i, ret;
6577 ret = -ENOENT;
6578 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6579 if (nb_sns < 0)
6580 return ret;
6581 for(i = 0; i < nb_sns; i++) {
6582 sn = &sn_tab[i];
6583 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6584 *sn_info = *sn;
6585 ret = 0;
6586 break;
6589 qemu_free(sn_tab);
6590 return ret;
6593 void do_savevm(const char *name)
6595 BlockDriverState *bs, *bs1;
6596 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6597 int must_delete, ret, i;
6598 BlockDriverInfo bdi1, *bdi = &bdi1;
6599 QEMUFile *f;
6600 int saved_vm_running;
6601 #ifdef _WIN32
6602 struct _timeb tb;
6603 #else
6604 struct timeval tv;
6605 #endif
6607 bs = get_bs_snapshots();
6608 if (!bs) {
6609 term_printf("No block device can accept snapshots\n");
6610 return;
6613 /* ??? Should this occur after vm_stop? */
6614 qemu_aio_flush();
6616 saved_vm_running = vm_running;
6617 vm_stop(0);
6619 must_delete = 0;
6620 if (name) {
6621 ret = bdrv_snapshot_find(bs, old_sn, name);
6622 if (ret >= 0) {
6623 must_delete = 1;
6626 memset(sn, 0, sizeof(*sn));
6627 if (must_delete) {
6628 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6629 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6630 } else {
6631 if (name)
6632 pstrcpy(sn->name, sizeof(sn->name), name);
6635 /* fill auxiliary fields */
6636 #ifdef _WIN32
6637 _ftime(&tb);
6638 sn->date_sec = tb.time;
6639 sn->date_nsec = tb.millitm * 1000000;
6640 #else
6641 gettimeofday(&tv, NULL);
6642 sn->date_sec = tv.tv_sec;
6643 sn->date_nsec = tv.tv_usec * 1000;
6644 #endif
6645 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6647 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6648 term_printf("Device %s does not support VM state snapshots\n",
6649 bdrv_get_device_name(bs));
6650 goto the_end;
6653 /* save the VM state */
6654 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6655 if (!f) {
6656 term_printf("Could not open VM state file\n");
6657 goto the_end;
6659 ret = qemu_savevm_state(f);
6660 sn->vm_state_size = qemu_ftell(f);
6661 qemu_fclose(f);
6662 if (ret < 0) {
6663 term_printf("Error %d while writing VM\n", ret);
6664 goto the_end;
6667 /* create the snapshots */
6669 for(i = 0; i < nb_drives; i++) {
6670 bs1 = drives_table[i].bdrv;
6671 if (bdrv_has_snapshot(bs1)) {
6672 if (must_delete) {
6673 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6674 if (ret < 0) {
6675 term_printf("Error while deleting snapshot on '%s'\n",
6676 bdrv_get_device_name(bs1));
6679 ret = bdrv_snapshot_create(bs1, sn);
6680 if (ret < 0) {
6681 term_printf("Error while creating snapshot on '%s'\n",
6682 bdrv_get_device_name(bs1));
6687 the_end:
6688 if (saved_vm_running)
6689 vm_start();
6692 void do_loadvm(const char *name)
6694 BlockDriverState *bs, *bs1;
6695 BlockDriverInfo bdi1, *bdi = &bdi1;
6696 QEMUFile *f;
6697 int i, ret;
6698 int saved_vm_running;
6700 bs = get_bs_snapshots();
6701 if (!bs) {
6702 term_printf("No block device supports snapshots\n");
6703 return;
6706 /* Flush all IO requests so they don't interfere with the new state. */
6707 qemu_aio_flush();
6709 saved_vm_running = vm_running;
6710 vm_stop(0);
6712 for(i = 0; i <= nb_drives; i++) {
6713 bs1 = drives_table[i].bdrv;
6714 if (bdrv_has_snapshot(bs1)) {
6715 ret = bdrv_snapshot_goto(bs1, name);
6716 if (ret < 0) {
6717 if (bs != bs1)
6718 term_printf("Warning: ");
6719 switch(ret) {
6720 case -ENOTSUP:
6721 term_printf("Snapshots not supported on device '%s'\n",
6722 bdrv_get_device_name(bs1));
6723 break;
6724 case -ENOENT:
6725 term_printf("Could not find snapshot '%s' on device '%s'\n",
6726 name, bdrv_get_device_name(bs1));
6727 break;
6728 default:
6729 term_printf("Error %d while activating snapshot on '%s'\n",
6730 ret, bdrv_get_device_name(bs1));
6731 break;
6733 /* fatal on snapshot block device */
6734 if (bs == bs1)
6735 goto the_end;
6740 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6741 term_printf("Device %s does not support VM state snapshots\n",
6742 bdrv_get_device_name(bs));
6743 return;
6746 /* restore the VM state */
6747 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6748 if (!f) {
6749 term_printf("Could not open VM state file\n");
6750 goto the_end;
6752 ret = qemu_loadvm_state(f);
6753 qemu_fclose(f);
6754 if (ret < 0) {
6755 term_printf("Error %d while loading VM state\n", ret);
6757 the_end:
6758 if (saved_vm_running)
6759 vm_start();
6762 void do_delvm(const char *name)
6764 BlockDriverState *bs, *bs1;
6765 int i, ret;
6767 bs = get_bs_snapshots();
6768 if (!bs) {
6769 term_printf("No block device supports snapshots\n");
6770 return;
6773 for(i = 0; i <= nb_drives; i++) {
6774 bs1 = drives_table[i].bdrv;
6775 if (bdrv_has_snapshot(bs1)) {
6776 ret = bdrv_snapshot_delete(bs1, name);
6777 if (ret < 0) {
6778 if (ret == -ENOTSUP)
6779 term_printf("Snapshots not supported on device '%s'\n",
6780 bdrv_get_device_name(bs1));
6781 else
6782 term_printf("Error %d while deleting snapshot on '%s'\n",
6783 ret, bdrv_get_device_name(bs1));
6789 void do_info_snapshots(void)
6791 BlockDriverState *bs, *bs1;
6792 QEMUSnapshotInfo *sn_tab, *sn;
6793 int nb_sns, i;
6794 char buf[256];
6796 bs = get_bs_snapshots();
6797 if (!bs) {
6798 term_printf("No available block device supports snapshots\n");
6799 return;
6801 term_printf("Snapshot devices:");
6802 for(i = 0; i <= nb_drives; i++) {
6803 bs1 = drives_table[i].bdrv;
6804 if (bdrv_has_snapshot(bs1)) {
6805 if (bs == bs1)
6806 term_printf(" %s", bdrv_get_device_name(bs1));
6809 term_printf("\n");
6811 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6812 if (nb_sns < 0) {
6813 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6814 return;
6816 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6817 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6818 for(i = 0; i < nb_sns; i++) {
6819 sn = &sn_tab[i];
6820 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6822 qemu_free(sn_tab);
6825 /***********************************************************/
6826 /* ram save/restore */
6828 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6830 int v;
6832 v = qemu_get_byte(f);
6833 switch(v) {
6834 case 0:
6835 if (qemu_get_buffer(f, buf, len) != len)
6836 return -EIO;
6837 break;
6838 case 1:
6839 v = qemu_get_byte(f);
6840 memset(buf, v, len);
6841 break;
6842 default:
6843 return -EINVAL;
6845 return 0;
6848 static int ram_load_v1(QEMUFile *f, void *opaque)
6850 int ret;
6851 ram_addr_t i;
6853 if (qemu_get_be32(f) != phys_ram_size)
6854 return -EINVAL;
6855 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6856 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6857 if (ret)
6858 return ret;
6860 return 0;
6863 #define BDRV_HASH_BLOCK_SIZE 1024
6864 #define IOBUF_SIZE 4096
6865 #define RAM_CBLOCK_MAGIC 0xfabe
6867 typedef struct RamCompressState {
6868 z_stream zstream;
6869 QEMUFile *f;
6870 uint8_t buf[IOBUF_SIZE];
6871 } RamCompressState;
6873 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6875 int ret;
6876 memset(s, 0, sizeof(*s));
6877 s->f = f;
6878 ret = deflateInit2(&s->zstream, 1,
6879 Z_DEFLATED, 15,
6880 9, Z_DEFAULT_STRATEGY);
6881 if (ret != Z_OK)
6882 return -1;
6883 s->zstream.avail_out = IOBUF_SIZE;
6884 s->zstream.next_out = s->buf;
6885 return 0;
6888 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6890 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6891 qemu_put_be16(s->f, len);
6892 qemu_put_buffer(s->f, buf, len);
6895 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6897 int ret;
6899 s->zstream.avail_in = len;
6900 s->zstream.next_in = (uint8_t *)buf;
6901 while (s->zstream.avail_in > 0) {
6902 ret = deflate(&s->zstream, Z_NO_FLUSH);
6903 if (ret != Z_OK)
6904 return -1;
6905 if (s->zstream.avail_out == 0) {
6906 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6907 s->zstream.avail_out = IOBUF_SIZE;
6908 s->zstream.next_out = s->buf;
6911 return 0;
6914 static void ram_compress_close(RamCompressState *s)
6916 int len, ret;
6918 /* compress last bytes */
6919 for(;;) {
6920 ret = deflate(&s->zstream, Z_FINISH);
6921 if (ret == Z_OK || ret == Z_STREAM_END) {
6922 len = IOBUF_SIZE - s->zstream.avail_out;
6923 if (len > 0) {
6924 ram_put_cblock(s, s->buf, len);
6926 s->zstream.avail_out = IOBUF_SIZE;
6927 s->zstream.next_out = s->buf;
6928 if (ret == Z_STREAM_END)
6929 break;
6930 } else {
6931 goto fail;
6934 fail:
6935 deflateEnd(&s->zstream);
6938 typedef struct RamDecompressState {
6939 z_stream zstream;
6940 QEMUFile *f;
6941 uint8_t buf[IOBUF_SIZE];
6942 } RamDecompressState;
6944 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6946 int ret;
6947 memset(s, 0, sizeof(*s));
6948 s->f = f;
6949 ret = inflateInit(&s->zstream);
6950 if (ret != Z_OK)
6951 return -1;
6952 return 0;
6955 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6957 int ret, clen;
6959 s->zstream.avail_out = len;
6960 s->zstream.next_out = buf;
6961 while (s->zstream.avail_out > 0) {
6962 if (s->zstream.avail_in == 0) {
6963 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6964 return -1;
6965 clen = qemu_get_be16(s->f);
6966 if (clen > IOBUF_SIZE)
6967 return -1;
6968 qemu_get_buffer(s->f, s->buf, clen);
6969 s->zstream.avail_in = clen;
6970 s->zstream.next_in = s->buf;
6972 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6973 if (ret != Z_OK && ret != Z_STREAM_END) {
6974 return -1;
6977 return 0;
6980 static void ram_decompress_close(RamDecompressState *s)
6982 inflateEnd(&s->zstream);
6985 static void ram_save(QEMUFile *f, void *opaque)
6987 ram_addr_t i;
6988 RamCompressState s1, *s = &s1;
6989 uint8_t buf[10];
6991 qemu_put_be32(f, phys_ram_size);
6992 if (ram_compress_open(s, f) < 0)
6993 return;
6994 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6995 #if 0
6996 if (tight_savevm_enabled) {
6997 int64_t sector_num;
6998 int j;
7000 /* find if the memory block is available on a virtual
7001 block device */
7002 sector_num = -1;
7003 for(j = 0; j < nb_drives; j++) {
7004 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7005 phys_ram_base + i,
7006 BDRV_HASH_BLOCK_SIZE);
7007 if (sector_num >= 0)
7008 break;
7010 if (j == nb_drives)
7011 goto normal_compress;
7012 buf[0] = 1;
7013 buf[1] = j;
7014 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7015 ram_compress_buf(s, buf, 10);
7016 } else
7017 #endif
7019 // normal_compress:
7020 buf[0] = 0;
7021 ram_compress_buf(s, buf, 1);
7022 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7025 ram_compress_close(s);
7028 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7030 RamDecompressState s1, *s = &s1;
7031 uint8_t buf[10];
7032 ram_addr_t i;
7034 if (version_id == 1)
7035 return ram_load_v1(f, opaque);
7036 if (version_id != 2)
7037 return -EINVAL;
7038 if (qemu_get_be32(f) != phys_ram_size)
7039 return -EINVAL;
7040 if (ram_decompress_open(s, f) < 0)
7041 return -EINVAL;
7042 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7043 if (ram_decompress_buf(s, buf, 1) < 0) {
7044 fprintf(stderr, "Error while reading ram block header\n");
7045 goto error;
7047 if (buf[0] == 0) {
7048 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7049 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7050 goto error;
7052 } else
7053 #if 0
7054 if (buf[0] == 1) {
7055 int bs_index;
7056 int64_t sector_num;
7058 ram_decompress_buf(s, buf + 1, 9);
7059 bs_index = buf[1];
7060 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7061 if (bs_index >= nb_drives) {
7062 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7063 goto error;
7065 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7066 phys_ram_base + i,
7067 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7068 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7069 bs_index, sector_num);
7070 goto error;
7072 } else
7073 #endif
7075 error:
7076 printf("Error block header\n");
7077 return -EINVAL;
7080 ram_decompress_close(s);
7081 return 0;
7084 /***********************************************************/
7085 /* bottom halves (can be seen as timers which expire ASAP) */
7087 struct QEMUBH {
7088 QEMUBHFunc *cb;
7089 void *opaque;
7090 int scheduled;
7091 QEMUBH *next;
7094 static QEMUBH *first_bh = NULL;
7096 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7098 QEMUBH *bh;
7099 bh = qemu_mallocz(sizeof(QEMUBH));
7100 if (!bh)
7101 return NULL;
7102 bh->cb = cb;
7103 bh->opaque = opaque;
7104 return bh;
7107 int qemu_bh_poll(void)
7109 QEMUBH *bh, **pbh;
7110 int ret;
7112 ret = 0;
7113 for(;;) {
7114 pbh = &first_bh;
7115 bh = *pbh;
7116 if (!bh)
7117 break;
7118 ret = 1;
7119 *pbh = bh->next;
7120 bh->scheduled = 0;
7121 bh->cb(bh->opaque);
7123 return ret;
7126 void qemu_bh_schedule(QEMUBH *bh)
7128 CPUState *env = cpu_single_env;
7129 if (bh->scheduled)
7130 return;
7131 bh->scheduled = 1;
7132 bh->next = first_bh;
7133 first_bh = bh;
7135 /* stop the currently executing CPU to execute the BH ASAP */
7136 if (env) {
7137 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7141 void qemu_bh_cancel(QEMUBH *bh)
7143 QEMUBH **pbh;
7144 if (bh->scheduled) {
7145 pbh = &first_bh;
7146 while (*pbh != bh)
7147 pbh = &(*pbh)->next;
7148 *pbh = bh->next;
7149 bh->scheduled = 0;
7153 void qemu_bh_delete(QEMUBH *bh)
7155 qemu_bh_cancel(bh);
7156 qemu_free(bh);
7159 /***********************************************************/
7160 /* machine registration */
7162 QEMUMachine *first_machine = NULL;
7164 int qemu_register_machine(QEMUMachine *m)
7166 QEMUMachine **pm;
7167 pm = &first_machine;
7168 while (*pm != NULL)
7169 pm = &(*pm)->next;
7170 m->next = NULL;
7171 *pm = m;
7172 return 0;
7175 static QEMUMachine *find_machine(const char *name)
7177 QEMUMachine *m;
7179 for(m = first_machine; m != NULL; m = m->next) {
7180 if (!strcmp(m->name, name))
7181 return m;
7183 return NULL;
7186 /***********************************************************/
7187 /* main execution loop */
7189 static void gui_update(void *opaque)
7191 DisplayState *ds = opaque;
7192 ds->dpy_refresh(ds);
7193 qemu_mod_timer(ds->gui_timer,
7194 (ds->gui_timer_interval ?
7195 ds->gui_timer_interval :
7196 GUI_REFRESH_INTERVAL)
7197 + qemu_get_clock(rt_clock));
7200 struct vm_change_state_entry {
7201 VMChangeStateHandler *cb;
7202 void *opaque;
7203 LIST_ENTRY (vm_change_state_entry) entries;
7206 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7208 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7209 void *opaque)
7211 VMChangeStateEntry *e;
7213 e = qemu_mallocz(sizeof (*e));
7214 if (!e)
7215 return NULL;
7217 e->cb = cb;
7218 e->opaque = opaque;
7219 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7220 return e;
7223 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7225 LIST_REMOVE (e, entries);
7226 qemu_free (e);
7229 static void vm_state_notify(int running)
7231 VMChangeStateEntry *e;
7233 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7234 e->cb(e->opaque, running);
7238 /* XXX: support several handlers */
7239 static VMStopHandler *vm_stop_cb;
7240 static void *vm_stop_opaque;
7242 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7244 vm_stop_cb = cb;
7245 vm_stop_opaque = opaque;
7246 return 0;
7249 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7251 vm_stop_cb = NULL;
7254 void vm_start(void)
7256 if (!vm_running) {
7257 cpu_enable_ticks();
7258 vm_running = 1;
7259 vm_state_notify(1);
7260 qemu_rearm_alarm_timer(alarm_timer);
7264 void vm_stop(int reason)
7266 if (vm_running) {
7267 cpu_disable_ticks();
7268 vm_running = 0;
7269 if (reason != 0) {
7270 if (vm_stop_cb) {
7271 vm_stop_cb(vm_stop_opaque, reason);
7274 vm_state_notify(0);
7278 /* reset/shutdown handler */
7280 typedef struct QEMUResetEntry {
7281 QEMUResetHandler *func;
7282 void *opaque;
7283 struct QEMUResetEntry *next;
7284 } QEMUResetEntry;
7286 static QEMUResetEntry *first_reset_entry;
7287 static int reset_requested;
7288 static int shutdown_requested;
7289 static int powerdown_requested;
7291 int qemu_shutdown_requested(void)
7293 int r = shutdown_requested;
7294 shutdown_requested = 0;
7295 return r;
7298 int qemu_reset_requested(void)
7300 int r = reset_requested;
7301 reset_requested = 0;
7302 return r;
7305 int qemu_powerdown_requested(void)
7307 int r = powerdown_requested;
7308 powerdown_requested = 0;
7309 return r;
7312 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7314 QEMUResetEntry **pre, *re;
7316 pre = &first_reset_entry;
7317 while (*pre != NULL)
7318 pre = &(*pre)->next;
7319 re = qemu_mallocz(sizeof(QEMUResetEntry));
7320 re->func = func;
7321 re->opaque = opaque;
7322 re->next = NULL;
7323 *pre = re;
7326 void qemu_system_reset(void)
7328 QEMUResetEntry *re;
7330 /* reset all devices */
7331 for(re = first_reset_entry; re != NULL; re = re->next) {
7332 re->func(re->opaque);
7336 void qemu_system_reset_request(void)
7338 if (no_reboot) {
7339 shutdown_requested = 1;
7340 } else {
7341 reset_requested = 1;
7343 if (cpu_single_env)
7344 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7347 void qemu_system_shutdown_request(void)
7349 shutdown_requested = 1;
7350 if (cpu_single_env)
7351 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7354 void qemu_system_powerdown_request(void)
7356 powerdown_requested = 1;
7357 if (cpu_single_env)
7358 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7361 void main_loop_wait(int timeout)
7363 IOHandlerRecord *ioh;
7364 fd_set rfds, wfds, xfds;
7365 int ret, nfds;
7366 #ifdef _WIN32
7367 int ret2, i;
7368 #endif
7369 struct timeval tv;
7370 PollingEntry *pe;
7373 /* XXX: need to suppress polling by better using win32 events */
7374 ret = 0;
7375 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7376 ret |= pe->func(pe->opaque);
7378 #ifdef _WIN32
7379 if (ret == 0) {
7380 int err;
7381 WaitObjects *w = &wait_objects;
7383 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7384 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7385 if (w->func[ret - WAIT_OBJECT_0])
7386 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7388 /* Check for additional signaled events */
7389 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7391 /* Check if event is signaled */
7392 ret2 = WaitForSingleObject(w->events[i], 0);
7393 if(ret2 == WAIT_OBJECT_0) {
7394 if (w->func[i])
7395 w->func[i](w->opaque[i]);
7396 } else if (ret2 == WAIT_TIMEOUT) {
7397 } else {
7398 err = GetLastError();
7399 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7402 } else if (ret == WAIT_TIMEOUT) {
7403 } else {
7404 err = GetLastError();
7405 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7408 #endif
7409 /* poll any events */
7410 /* XXX: separate device handlers from system ones */
7411 nfds = -1;
7412 FD_ZERO(&rfds);
7413 FD_ZERO(&wfds);
7414 FD_ZERO(&xfds);
7415 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7416 if (ioh->deleted)
7417 continue;
7418 if (ioh->fd_read &&
7419 (!ioh->fd_read_poll ||
7420 ioh->fd_read_poll(ioh->opaque) != 0)) {
7421 FD_SET(ioh->fd, &rfds);
7422 if (ioh->fd > nfds)
7423 nfds = ioh->fd;
7425 if (ioh->fd_write) {
7426 FD_SET(ioh->fd, &wfds);
7427 if (ioh->fd > nfds)
7428 nfds = ioh->fd;
7432 tv.tv_sec = 0;
7433 #ifdef _WIN32
7434 tv.tv_usec = 0;
7435 #else
7436 tv.tv_usec = timeout * 1000;
7437 #endif
7438 #if defined(CONFIG_SLIRP)
7439 if (slirp_inited) {
7440 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7442 #endif
7443 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7444 if (ret > 0) {
7445 IOHandlerRecord **pioh;
7447 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7448 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7449 ioh->fd_read(ioh->opaque);
7451 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7452 ioh->fd_write(ioh->opaque);
7456 /* remove deleted IO handlers */
7457 pioh = &first_io_handler;
7458 while (*pioh) {
7459 ioh = *pioh;
7460 if (ioh->deleted) {
7461 *pioh = ioh->next;
7462 qemu_free(ioh);
7463 } else
7464 pioh = &ioh->next;
7467 #if defined(CONFIG_SLIRP)
7468 if (slirp_inited) {
7469 if (ret < 0) {
7470 FD_ZERO(&rfds);
7471 FD_ZERO(&wfds);
7472 FD_ZERO(&xfds);
7474 slirp_select_poll(&rfds, &wfds, &xfds);
7476 #endif
7478 if (vm_running) {
7479 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7480 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7481 qemu_get_clock(vm_clock));
7482 /* run dma transfers, if any */
7483 DMA_run();
7486 /* real time timers */
7487 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7488 qemu_get_clock(rt_clock));
7490 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7491 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7492 qemu_rearm_alarm_timer(alarm_timer);
7495 /* Check bottom-halves last in case any of the earlier events triggered
7496 them. */
7497 qemu_bh_poll();
7501 static int main_loop(void)
7503 int ret, timeout;
7504 #ifdef CONFIG_PROFILER
7505 int64_t ti;
7506 #endif
7507 CPUState *env;
7509 cur_cpu = first_cpu;
7510 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7511 for(;;) {
7512 if (vm_running) {
7514 for(;;) {
7515 /* get next cpu */
7516 env = next_cpu;
7517 #ifdef CONFIG_PROFILER
7518 ti = profile_getclock();
7519 #endif
7520 if (use_icount) {
7521 int64_t count;
7522 int decr;
7523 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7524 env->icount_decr.u16.low = 0;
7525 env->icount_extra = 0;
7526 count = qemu_next_deadline();
7527 count = (count + (1 << icount_time_shift) - 1)
7528 >> icount_time_shift;
7529 qemu_icount += count;
7530 decr = (count > 0xffff) ? 0xffff : count;
7531 count -= decr;
7532 env->icount_decr.u16.low = decr;
7533 env->icount_extra = count;
7535 ret = cpu_exec(env);
7536 #ifdef CONFIG_PROFILER
7537 qemu_time += profile_getclock() - ti;
7538 #endif
7539 if (use_icount) {
7540 /* Fold pending instructions back into the
7541 instruction counter, and clear the interrupt flag. */
7542 qemu_icount -= (env->icount_decr.u16.low
7543 + env->icount_extra);
7544 env->icount_decr.u32 = 0;
7545 env->icount_extra = 0;
7547 next_cpu = env->next_cpu ?: first_cpu;
7548 if (event_pending && likely(ret != EXCP_DEBUG)) {
7549 ret = EXCP_INTERRUPT;
7550 event_pending = 0;
7551 break;
7553 if (ret == EXCP_HLT) {
7554 /* Give the next CPU a chance to run. */
7555 cur_cpu = env;
7556 continue;
7558 if (ret != EXCP_HALTED)
7559 break;
7560 /* all CPUs are halted ? */
7561 if (env == cur_cpu)
7562 break;
7564 cur_cpu = env;
7566 if (shutdown_requested) {
7567 ret = EXCP_INTERRUPT;
7568 if (no_shutdown) {
7569 vm_stop(0);
7570 no_shutdown = 0;
7572 else
7573 break;
7575 if (reset_requested) {
7576 reset_requested = 0;
7577 qemu_system_reset();
7578 ret = EXCP_INTERRUPT;
7580 if (powerdown_requested) {
7581 powerdown_requested = 0;
7582 qemu_system_powerdown();
7583 ret = EXCP_INTERRUPT;
7585 if (unlikely(ret == EXCP_DEBUG)) {
7586 vm_stop(EXCP_DEBUG);
7588 /* If all cpus are halted then wait until the next IRQ */
7589 /* XXX: use timeout computed from timers */
7590 if (ret == EXCP_HALTED) {
7591 if (use_icount) {
7592 int64_t add;
7593 int64_t delta;
7594 /* Advance virtual time to the next event. */
7595 if (use_icount == 1) {
7596 /* When not using an adaptive execution frequency
7597 we tend to get badly out of sync with real time,
7598 so just delay for a reasonable amount of time. */
7599 delta = 0;
7600 } else {
7601 delta = cpu_get_icount() - cpu_get_clock();
7603 if (delta > 0) {
7604 /* If virtual time is ahead of real time then just
7605 wait for IO. */
7606 timeout = (delta / 1000000) + 1;
7607 } else {
7608 /* Wait for either IO to occur or the next
7609 timer event. */
7610 add = qemu_next_deadline();
7611 /* We advance the timer before checking for IO.
7612 Limit the amount we advance so that early IO
7613 activity won't get the guest too far ahead. */
7614 if (add > 10000000)
7615 add = 10000000;
7616 delta += add;
7617 add = (add + (1 << icount_time_shift) - 1)
7618 >> icount_time_shift;
7619 qemu_icount += add;
7620 timeout = delta / 1000000;
7621 if (timeout < 0)
7622 timeout = 0;
7624 } else {
7625 timeout = 10;
7627 } else {
7628 timeout = 0;
7630 } else {
7631 if (shutdown_requested)
7632 break;
7633 timeout = 10;
7635 #ifdef CONFIG_PROFILER
7636 ti = profile_getclock();
7637 #endif
7638 main_loop_wait(timeout);
7639 #ifdef CONFIG_PROFILER
7640 dev_time += profile_getclock() - ti;
7641 #endif
7643 cpu_disable_ticks();
7644 return ret;
7647 static void help(int exitcode)
7649 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7650 "usage: %s [options] [disk_image]\n"
7651 "\n"
7652 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7653 "\n"
7654 "Standard options:\n"
7655 "-M machine select emulated machine (-M ? for list)\n"
7656 "-cpu cpu select CPU (-cpu ? for list)\n"
7657 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7658 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7659 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7660 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7661 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7662 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7663 " [,cache=on|off][,format=f]\n"
7664 " use 'file' as a drive image\n"
7665 "-mtdblock file use 'file' as on-board Flash memory image\n"
7666 "-sd file use 'file' as SecureDigital card image\n"
7667 "-pflash file use 'file' as a parallel flash image\n"
7668 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7669 "-snapshot write to temporary files instead of disk image files\n"
7670 #ifdef CONFIG_SDL
7671 "-no-frame open SDL window without a frame and window decorations\n"
7672 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7673 "-no-quit disable SDL window close capability\n"
7674 #endif
7675 #ifdef TARGET_I386
7676 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7677 #endif
7678 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7679 "-smp n set the number of CPUs to 'n' [default=1]\n"
7680 "-nographic disable graphical output and redirect serial I/Os to console\n"
7681 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7682 #ifndef _WIN32
7683 "-k language use keyboard layout (for example \"fr\" for French)\n"
7684 #endif
7685 #ifdef HAS_AUDIO
7686 "-audio-help print list of audio drivers and their options\n"
7687 "-soundhw c1,... enable audio support\n"
7688 " and only specified sound cards (comma separated list)\n"
7689 " use -soundhw ? to get the list of supported cards\n"
7690 " use -soundhw all to enable all of them\n"
7691 #endif
7692 "-localtime set the real time clock to local time [default=utc]\n"
7693 "-full-screen start in full screen\n"
7694 #ifdef TARGET_I386
7695 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7696 #endif
7697 "-usb enable the USB driver (will be the default soon)\n"
7698 "-usbdevice name add the host or guest USB device 'name'\n"
7699 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7700 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7701 #endif
7702 "-name string set the name of the guest\n"
7703 "\n"
7704 "Network options:\n"
7705 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7706 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7707 #ifdef CONFIG_SLIRP
7708 "-net user[,vlan=n][,hostname=host]\n"
7709 " connect the user mode network stack to VLAN 'n' and send\n"
7710 " hostname 'host' to DHCP clients\n"
7711 #endif
7712 #ifdef _WIN32
7713 "-net tap[,vlan=n],ifname=name\n"
7714 " connect the host TAP network interface to VLAN 'n'\n"
7715 #else
7716 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7717 " connect the host TAP network interface to VLAN 'n' and use the\n"
7718 " network scripts 'file' (default=%s)\n"
7719 " and 'dfile' (default=%s);\n"
7720 " use '[down]script=no' to disable script execution;\n"
7721 " use 'fd=h' to connect to an already opened TAP interface\n"
7722 #endif
7723 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7724 " connect the vlan 'n' to another VLAN using a socket connection\n"
7725 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7726 " connect the vlan 'n' to multicast maddr and port\n"
7727 #ifdef CONFIG_VDE
7728 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7729 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7730 " on host and listening for incoming connections on 'socketpath'.\n"
7731 " Use group 'groupname' and mode 'octalmode' to change default\n"
7732 " ownership and permissions for communication port.\n"
7733 #endif
7734 "-net none use it alone to have zero network devices; if no -net option\n"
7735 " is provided, the default is '-net nic -net user'\n"
7736 "\n"
7737 #ifdef CONFIG_SLIRP
7738 "-tftp dir allow tftp access to files in dir [-net user]\n"
7739 "-bootp file advertise file in BOOTP replies\n"
7740 #ifndef _WIN32
7741 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7742 #endif
7743 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7744 " redirect TCP or UDP connections from host to guest [-net user]\n"
7745 #endif
7746 "\n"
7747 "Linux boot specific:\n"
7748 "-kernel bzImage use 'bzImage' as kernel image\n"
7749 "-append cmdline use 'cmdline' as kernel command line\n"
7750 "-initrd file use 'file' as initial ram disk\n"
7751 "\n"
7752 "Debug/Expert options:\n"
7753 "-monitor dev redirect the monitor to char device 'dev'\n"
7754 "-serial dev redirect the serial port to char device 'dev'\n"
7755 "-parallel dev redirect the parallel port to char device 'dev'\n"
7756 "-pidfile file Write PID to 'file'\n"
7757 "-S freeze CPU at startup (use 'c' to start execution)\n"
7758 "-s wait gdb connection to port\n"
7759 "-p port set gdb connection port [default=%s]\n"
7760 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7761 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7762 " translation (t=none or lba) (usually qemu can guess them)\n"
7763 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7764 #ifdef USE_KQEMU
7765 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7766 "-no-kqemu disable KQEMU kernel module usage\n"
7767 #endif
7768 #ifdef TARGET_I386
7769 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7770 " (default is CL-GD5446 PCI VGA)\n"
7771 "-no-acpi disable ACPI\n"
7772 #endif
7773 #ifdef CONFIG_CURSES
7774 "-curses use a curses/ncurses interface instead of SDL\n"
7775 #endif
7776 "-no-reboot exit instead of rebooting\n"
7777 "-no-shutdown stop before shutdown\n"
7778 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7779 "-vnc display start a VNC server on display\n"
7780 #ifndef _WIN32
7781 "-daemonize daemonize QEMU after initializing\n"
7782 #endif
7783 "-option-rom rom load a file, rom, into the option ROM space\n"
7784 #ifdef TARGET_SPARC
7785 "-prom-env variable=value set OpenBIOS nvram variables\n"
7786 #endif
7787 "-clock force the use of the given methods for timer alarm.\n"
7788 " To see what timers are available use -clock ?\n"
7789 "-startdate select initial date of the clock\n"
7790 "-icount [N|auto]\n"
7791 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7792 "\n"
7793 "During emulation, the following keys are useful:\n"
7794 "ctrl-alt-f toggle full screen\n"
7795 "ctrl-alt-n switch to virtual console 'n'\n"
7796 "ctrl-alt toggle mouse and keyboard grab\n"
7797 "\n"
7798 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7800 "qemu",
7801 DEFAULT_RAM_SIZE,
7802 #ifndef _WIN32
7803 DEFAULT_NETWORK_SCRIPT,
7804 DEFAULT_NETWORK_DOWN_SCRIPT,
7805 #endif
7806 DEFAULT_GDBSTUB_PORT,
7807 "/tmp/qemu.log");
7808 exit(exitcode);
7811 #define HAS_ARG 0x0001
7813 enum {
7814 QEMU_OPTION_h,
7816 QEMU_OPTION_M,
7817 QEMU_OPTION_cpu,
7818 QEMU_OPTION_fda,
7819 QEMU_OPTION_fdb,
7820 QEMU_OPTION_hda,
7821 QEMU_OPTION_hdb,
7822 QEMU_OPTION_hdc,
7823 QEMU_OPTION_hdd,
7824 QEMU_OPTION_drive,
7825 QEMU_OPTION_cdrom,
7826 QEMU_OPTION_mtdblock,
7827 QEMU_OPTION_sd,
7828 QEMU_OPTION_pflash,
7829 QEMU_OPTION_boot,
7830 QEMU_OPTION_snapshot,
7831 #ifdef TARGET_I386
7832 QEMU_OPTION_no_fd_bootchk,
7833 #endif
7834 QEMU_OPTION_m,
7835 QEMU_OPTION_nographic,
7836 QEMU_OPTION_portrait,
7837 #ifdef HAS_AUDIO
7838 QEMU_OPTION_audio_help,
7839 QEMU_OPTION_soundhw,
7840 #endif
7842 QEMU_OPTION_net,
7843 QEMU_OPTION_tftp,
7844 QEMU_OPTION_bootp,
7845 QEMU_OPTION_smb,
7846 QEMU_OPTION_redir,
7848 QEMU_OPTION_kernel,
7849 QEMU_OPTION_append,
7850 QEMU_OPTION_initrd,
7852 QEMU_OPTION_S,
7853 QEMU_OPTION_s,
7854 QEMU_OPTION_p,
7855 QEMU_OPTION_d,
7856 QEMU_OPTION_hdachs,
7857 QEMU_OPTION_L,
7858 QEMU_OPTION_bios,
7859 QEMU_OPTION_k,
7860 QEMU_OPTION_localtime,
7861 QEMU_OPTION_cirrusvga,
7862 QEMU_OPTION_vmsvga,
7863 QEMU_OPTION_g,
7864 QEMU_OPTION_std_vga,
7865 QEMU_OPTION_echr,
7866 QEMU_OPTION_monitor,
7867 QEMU_OPTION_serial,
7868 QEMU_OPTION_parallel,
7869 QEMU_OPTION_loadvm,
7870 QEMU_OPTION_full_screen,
7871 QEMU_OPTION_no_frame,
7872 QEMU_OPTION_alt_grab,
7873 QEMU_OPTION_no_quit,
7874 QEMU_OPTION_pidfile,
7875 QEMU_OPTION_no_kqemu,
7876 QEMU_OPTION_kernel_kqemu,
7877 QEMU_OPTION_win2k_hack,
7878 QEMU_OPTION_usb,
7879 QEMU_OPTION_usbdevice,
7880 QEMU_OPTION_smp,
7881 QEMU_OPTION_vnc,
7882 QEMU_OPTION_no_acpi,
7883 QEMU_OPTION_curses,
7884 QEMU_OPTION_no_reboot,
7885 QEMU_OPTION_no_shutdown,
7886 QEMU_OPTION_show_cursor,
7887 QEMU_OPTION_daemonize,
7888 QEMU_OPTION_option_rom,
7889 QEMU_OPTION_semihosting,
7890 QEMU_OPTION_name,
7891 QEMU_OPTION_prom_env,
7892 QEMU_OPTION_old_param,
7893 QEMU_OPTION_clock,
7894 QEMU_OPTION_startdate,
7895 QEMU_OPTION_tb_size,
7896 QEMU_OPTION_icount,
7899 typedef struct QEMUOption {
7900 const char *name;
7901 int flags;
7902 int index;
7903 } QEMUOption;
7905 const QEMUOption qemu_options[] = {
7906 { "h", 0, QEMU_OPTION_h },
7907 { "help", 0, QEMU_OPTION_h },
7909 { "M", HAS_ARG, QEMU_OPTION_M },
7910 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7911 { "fda", HAS_ARG, QEMU_OPTION_fda },
7912 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7913 { "hda", HAS_ARG, QEMU_OPTION_hda },
7914 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7915 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7916 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7917 { "drive", HAS_ARG, QEMU_OPTION_drive },
7918 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7919 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7920 { "sd", HAS_ARG, QEMU_OPTION_sd },
7921 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7922 { "boot", HAS_ARG, QEMU_OPTION_boot },
7923 { "snapshot", 0, QEMU_OPTION_snapshot },
7924 #ifdef TARGET_I386
7925 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7926 #endif
7927 { "m", HAS_ARG, QEMU_OPTION_m },
7928 { "nographic", 0, QEMU_OPTION_nographic },
7929 { "portrait", 0, QEMU_OPTION_portrait },
7930 { "k", HAS_ARG, QEMU_OPTION_k },
7931 #ifdef HAS_AUDIO
7932 { "audio-help", 0, QEMU_OPTION_audio_help },
7933 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7934 #endif
7936 { "net", HAS_ARG, QEMU_OPTION_net},
7937 #ifdef CONFIG_SLIRP
7938 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7939 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7940 #ifndef _WIN32
7941 { "smb", HAS_ARG, QEMU_OPTION_smb },
7942 #endif
7943 { "redir", HAS_ARG, QEMU_OPTION_redir },
7944 #endif
7946 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7947 { "append", HAS_ARG, QEMU_OPTION_append },
7948 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7950 { "S", 0, QEMU_OPTION_S },
7951 { "s", 0, QEMU_OPTION_s },
7952 { "p", HAS_ARG, QEMU_OPTION_p },
7953 { "d", HAS_ARG, QEMU_OPTION_d },
7954 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7955 { "L", HAS_ARG, QEMU_OPTION_L },
7956 { "bios", HAS_ARG, QEMU_OPTION_bios },
7957 #ifdef USE_KQEMU
7958 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7959 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7960 #endif
7961 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7962 { "g", 1, QEMU_OPTION_g },
7963 #endif
7964 { "localtime", 0, QEMU_OPTION_localtime },
7965 { "std-vga", 0, QEMU_OPTION_std_vga },
7966 { "echr", HAS_ARG, QEMU_OPTION_echr },
7967 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7968 { "serial", HAS_ARG, QEMU_OPTION_serial },
7969 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7970 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7971 { "full-screen", 0, QEMU_OPTION_full_screen },
7972 #ifdef CONFIG_SDL
7973 { "no-frame", 0, QEMU_OPTION_no_frame },
7974 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7975 { "no-quit", 0, QEMU_OPTION_no_quit },
7976 #endif
7977 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7978 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7979 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7980 { "smp", HAS_ARG, QEMU_OPTION_smp },
7981 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7982 #ifdef CONFIG_CURSES
7983 { "curses", 0, QEMU_OPTION_curses },
7984 #endif
7986 /* temporary options */
7987 { "usb", 0, QEMU_OPTION_usb },
7988 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7989 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7990 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7991 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7992 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7993 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7994 { "daemonize", 0, QEMU_OPTION_daemonize },
7995 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7996 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7997 { "semihosting", 0, QEMU_OPTION_semihosting },
7998 #endif
7999 { "name", HAS_ARG, QEMU_OPTION_name },
8000 #if defined(TARGET_SPARC)
8001 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8002 #endif
8003 #if defined(TARGET_ARM)
8004 { "old-param", 0, QEMU_OPTION_old_param },
8005 #endif
8006 { "clock", HAS_ARG, QEMU_OPTION_clock },
8007 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8008 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8009 { "icount", HAS_ARG, QEMU_OPTION_icount },
8010 { NULL },
8013 /* password input */
8015 int qemu_key_check(BlockDriverState *bs, const char *name)
8017 char password[256];
8018 int i;
8020 if (!bdrv_is_encrypted(bs))
8021 return 0;
8023 term_printf("%s is encrypted.\n", name);
8024 for(i = 0; i < 3; i++) {
8025 monitor_readline("Password: ", 1, password, sizeof(password));
8026 if (bdrv_set_key(bs, password) == 0)
8027 return 0;
8028 term_printf("invalid password\n");
8030 return -EPERM;
8033 static BlockDriverState *get_bdrv(int index)
8035 if (index > nb_drives)
8036 return NULL;
8037 return drives_table[index].bdrv;
8040 static void read_passwords(void)
8042 BlockDriverState *bs;
8043 int i;
8045 for(i = 0; i < 6; i++) {
8046 bs = get_bdrv(i);
8047 if (bs)
8048 qemu_key_check(bs, bdrv_get_device_name(bs));
8052 #ifdef HAS_AUDIO
8053 struct soundhw soundhw[] = {
8054 #ifdef HAS_AUDIO_CHOICE
8055 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8057 "pcspk",
8058 "PC speaker",
8061 { .init_isa = pcspk_audio_init }
8063 #endif
8065 "sb16",
8066 "Creative Sound Blaster 16",
8069 { .init_isa = SB16_init }
8072 #ifdef CONFIG_CS4231A
8074 "cs4231a",
8075 "CS4231A",
8078 { .init_isa = cs4231a_init }
8080 #endif
8082 #ifdef CONFIG_ADLIB
8084 "adlib",
8085 #ifdef HAS_YMF262
8086 "Yamaha YMF262 (OPL3)",
8087 #else
8088 "Yamaha YM3812 (OPL2)",
8089 #endif
8092 { .init_isa = Adlib_init }
8094 #endif
8096 #ifdef CONFIG_GUS
8098 "gus",
8099 "Gravis Ultrasound GF1",
8102 { .init_isa = GUS_init }
8104 #endif
8106 #ifdef CONFIG_AC97
8108 "ac97",
8109 "Intel 82801AA AC97 Audio",
8112 { .init_pci = ac97_init }
8114 #endif
8117 "es1370",
8118 "ENSONIQ AudioPCI ES1370",
8121 { .init_pci = es1370_init }
8123 #endif
8125 { NULL, NULL, 0, 0, { NULL } }
8128 static void select_soundhw (const char *optarg)
8130 struct soundhw *c;
8132 if (*optarg == '?') {
8133 show_valid_cards:
8135 printf ("Valid sound card names (comma separated):\n");
8136 for (c = soundhw; c->name; ++c) {
8137 printf ("%-11s %s\n", c->name, c->descr);
8139 printf ("\n-soundhw all will enable all of the above\n");
8140 exit (*optarg != '?');
8142 else {
8143 size_t l;
8144 const char *p;
8145 char *e;
8146 int bad_card = 0;
8148 if (!strcmp (optarg, "all")) {
8149 for (c = soundhw; c->name; ++c) {
8150 c->enabled = 1;
8152 return;
8155 p = optarg;
8156 while (*p) {
8157 e = strchr (p, ',');
8158 l = !e ? strlen (p) : (size_t) (e - p);
8160 for (c = soundhw; c->name; ++c) {
8161 if (!strncmp (c->name, p, l)) {
8162 c->enabled = 1;
8163 break;
8167 if (!c->name) {
8168 if (l > 80) {
8169 fprintf (stderr,
8170 "Unknown sound card name (too big to show)\n");
8172 else {
8173 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8174 (int) l, p);
8176 bad_card = 1;
8178 p += l + (e != NULL);
8181 if (bad_card)
8182 goto show_valid_cards;
8185 #endif
8187 #ifdef _WIN32
8188 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8190 exit(STATUS_CONTROL_C_EXIT);
8191 return TRUE;
8193 #endif
8195 #define MAX_NET_CLIENTS 32
8197 #ifndef _WIN32
8199 static void termsig_handler(int signal)
8201 qemu_system_shutdown_request();
8204 static void termsig_setup(void)
8206 struct sigaction act;
8208 memset(&act, 0, sizeof(act));
8209 act.sa_handler = termsig_handler;
8210 sigaction(SIGINT, &act, NULL);
8211 sigaction(SIGHUP, &act, NULL);
8212 sigaction(SIGTERM, &act, NULL);
8215 #endif
8217 int main(int argc, char **argv)
8219 #ifdef CONFIG_GDBSTUB
8220 int use_gdbstub;
8221 const char *gdbstub_port;
8222 #endif
8223 uint32_t boot_devices_bitmap = 0;
8224 int i;
8225 int snapshot, linux_boot, net_boot;
8226 const char *initrd_filename;
8227 const char *kernel_filename, *kernel_cmdline;
8228 const char *boot_devices = "";
8229 DisplayState *ds = &display_state;
8230 int cyls, heads, secs, translation;
8231 const char *net_clients[MAX_NET_CLIENTS];
8232 int nb_net_clients;
8233 int hda_index;
8234 int optind;
8235 const char *r, *optarg;
8236 CharDriverState *monitor_hd;
8237 const char *monitor_device;
8238 const char *serial_devices[MAX_SERIAL_PORTS];
8239 int serial_device_index;
8240 const char *parallel_devices[MAX_PARALLEL_PORTS];
8241 int parallel_device_index;
8242 const char *loadvm = NULL;
8243 QEMUMachine *machine;
8244 const char *cpu_model;
8245 const char *usb_devices[MAX_USB_CMDLINE];
8246 int usb_devices_index;
8247 int fds[2];
8248 int tb_size;
8249 const char *pid_file = NULL;
8250 VLANState *vlan;
8252 LIST_INIT (&vm_change_state_head);
8253 #ifndef _WIN32
8255 struct sigaction act;
8256 sigfillset(&act.sa_mask);
8257 act.sa_flags = 0;
8258 act.sa_handler = SIG_IGN;
8259 sigaction(SIGPIPE, &act, NULL);
8261 #else
8262 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8263 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8264 QEMU to run on a single CPU */
8266 HANDLE h;
8267 DWORD mask, smask;
8268 int i;
8269 h = GetCurrentProcess();
8270 if (GetProcessAffinityMask(h, &mask, &smask)) {
8271 for(i = 0; i < 32; i++) {
8272 if (mask & (1 << i))
8273 break;
8275 if (i != 32) {
8276 mask = 1 << i;
8277 SetProcessAffinityMask(h, mask);
8281 #endif
8283 register_machines();
8284 machine = first_machine;
8285 cpu_model = NULL;
8286 initrd_filename = NULL;
8287 ram_size = 0;
8288 vga_ram_size = VGA_RAM_SIZE;
8289 #ifdef CONFIG_GDBSTUB
8290 use_gdbstub = 0;
8291 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8292 #endif
8293 snapshot = 0;
8294 nographic = 0;
8295 curses = 0;
8296 kernel_filename = NULL;
8297 kernel_cmdline = "";
8298 cyls = heads = secs = 0;
8299 translation = BIOS_ATA_TRANSLATION_AUTO;
8300 monitor_device = "vc";
8302 serial_devices[0] = "vc:80Cx24C";
8303 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8304 serial_devices[i] = NULL;
8305 serial_device_index = 0;
8307 parallel_devices[0] = "vc:640x480";
8308 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8309 parallel_devices[i] = NULL;
8310 parallel_device_index = 0;
8312 usb_devices_index = 0;
8314 nb_net_clients = 0;
8315 nb_drives = 0;
8316 nb_drives_opt = 0;
8317 hda_index = -1;
8319 nb_nics = 0;
8321 tb_size = 0;
8323 optind = 1;
8324 for(;;) {
8325 if (optind >= argc)
8326 break;
8327 r = argv[optind];
8328 if (r[0] != '-') {
8329 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8330 } else {
8331 const QEMUOption *popt;
8333 optind++;
8334 /* Treat --foo the same as -foo. */
8335 if (r[1] == '-')
8336 r++;
8337 popt = qemu_options;
8338 for(;;) {
8339 if (!popt->name) {
8340 fprintf(stderr, "%s: invalid option -- '%s'\n",
8341 argv[0], r);
8342 exit(1);
8344 if (!strcmp(popt->name, r + 1))
8345 break;
8346 popt++;
8348 if (popt->flags & HAS_ARG) {
8349 if (optind >= argc) {
8350 fprintf(stderr, "%s: option '%s' requires an argument\n",
8351 argv[0], r);
8352 exit(1);
8354 optarg = argv[optind++];
8355 } else {
8356 optarg = NULL;
8359 switch(popt->index) {
8360 case QEMU_OPTION_M:
8361 machine = find_machine(optarg);
8362 if (!machine) {
8363 QEMUMachine *m;
8364 printf("Supported machines are:\n");
8365 for(m = first_machine; m != NULL; m = m->next) {
8366 printf("%-10s %s%s\n",
8367 m->name, m->desc,
8368 m == first_machine ? " (default)" : "");
8370 exit(*optarg != '?');
8372 break;
8373 case QEMU_OPTION_cpu:
8374 /* hw initialization will check this */
8375 if (*optarg == '?') {
8376 /* XXX: implement xxx_cpu_list for targets that still miss it */
8377 #if defined(cpu_list)
8378 cpu_list(stdout, &fprintf);
8379 #endif
8380 exit(0);
8381 } else {
8382 cpu_model = optarg;
8384 break;
8385 case QEMU_OPTION_initrd:
8386 initrd_filename = optarg;
8387 break;
8388 case QEMU_OPTION_hda:
8389 if (cyls == 0)
8390 hda_index = drive_add(optarg, HD_ALIAS, 0);
8391 else
8392 hda_index = drive_add(optarg, HD_ALIAS
8393 ",cyls=%d,heads=%d,secs=%d%s",
8394 0, cyls, heads, secs,
8395 translation == BIOS_ATA_TRANSLATION_LBA ?
8396 ",trans=lba" :
8397 translation == BIOS_ATA_TRANSLATION_NONE ?
8398 ",trans=none" : "");
8399 break;
8400 case QEMU_OPTION_hdb:
8401 case QEMU_OPTION_hdc:
8402 case QEMU_OPTION_hdd:
8403 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8404 break;
8405 case QEMU_OPTION_drive:
8406 drive_add(NULL, "%s", optarg);
8407 break;
8408 case QEMU_OPTION_mtdblock:
8409 drive_add(optarg, MTD_ALIAS);
8410 break;
8411 case QEMU_OPTION_sd:
8412 drive_add(optarg, SD_ALIAS);
8413 break;
8414 case QEMU_OPTION_pflash:
8415 drive_add(optarg, PFLASH_ALIAS);
8416 break;
8417 case QEMU_OPTION_snapshot:
8418 snapshot = 1;
8419 break;
8420 case QEMU_OPTION_hdachs:
8422 const char *p;
8423 p = optarg;
8424 cyls = strtol(p, (char **)&p, 0);
8425 if (cyls < 1 || cyls > 16383)
8426 goto chs_fail;
8427 if (*p != ',')
8428 goto chs_fail;
8429 p++;
8430 heads = strtol(p, (char **)&p, 0);
8431 if (heads < 1 || heads > 16)
8432 goto chs_fail;
8433 if (*p != ',')
8434 goto chs_fail;
8435 p++;
8436 secs = strtol(p, (char **)&p, 0);
8437 if (secs < 1 || secs > 63)
8438 goto chs_fail;
8439 if (*p == ',') {
8440 p++;
8441 if (!strcmp(p, "none"))
8442 translation = BIOS_ATA_TRANSLATION_NONE;
8443 else if (!strcmp(p, "lba"))
8444 translation = BIOS_ATA_TRANSLATION_LBA;
8445 else if (!strcmp(p, "auto"))
8446 translation = BIOS_ATA_TRANSLATION_AUTO;
8447 else
8448 goto chs_fail;
8449 } else if (*p != '\0') {
8450 chs_fail:
8451 fprintf(stderr, "qemu: invalid physical CHS format\n");
8452 exit(1);
8454 if (hda_index != -1)
8455 snprintf(drives_opt[hda_index].opt,
8456 sizeof(drives_opt[hda_index].opt),
8457 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8458 0, cyls, heads, secs,
8459 translation == BIOS_ATA_TRANSLATION_LBA ?
8460 ",trans=lba" :
8461 translation == BIOS_ATA_TRANSLATION_NONE ?
8462 ",trans=none" : "");
8464 break;
8465 case QEMU_OPTION_nographic:
8466 nographic = 1;
8467 break;
8468 #ifdef CONFIG_CURSES
8469 case QEMU_OPTION_curses:
8470 curses = 1;
8471 break;
8472 #endif
8473 case QEMU_OPTION_portrait:
8474 graphic_rotate = 1;
8475 break;
8476 case QEMU_OPTION_kernel:
8477 kernel_filename = optarg;
8478 break;
8479 case QEMU_OPTION_append:
8480 kernel_cmdline = optarg;
8481 break;
8482 case QEMU_OPTION_cdrom:
8483 drive_add(optarg, CDROM_ALIAS);
8484 break;
8485 case QEMU_OPTION_boot:
8486 boot_devices = optarg;
8487 /* We just do some generic consistency checks */
8489 /* Could easily be extended to 64 devices if needed */
8490 const char *p;
8492 boot_devices_bitmap = 0;
8493 for (p = boot_devices; *p != '\0'; p++) {
8494 /* Allowed boot devices are:
8495 * a b : floppy disk drives
8496 * c ... f : IDE disk drives
8497 * g ... m : machine implementation dependant drives
8498 * n ... p : network devices
8499 * It's up to each machine implementation to check
8500 * if the given boot devices match the actual hardware
8501 * implementation and firmware features.
8503 if (*p < 'a' || *p > 'q') {
8504 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8505 exit(1);
8507 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8508 fprintf(stderr,
8509 "Boot device '%c' was given twice\n",*p);
8510 exit(1);
8512 boot_devices_bitmap |= 1 << (*p - 'a');
8515 break;
8516 case QEMU_OPTION_fda:
8517 case QEMU_OPTION_fdb:
8518 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8519 break;
8520 #ifdef TARGET_I386
8521 case QEMU_OPTION_no_fd_bootchk:
8522 fd_bootchk = 0;
8523 break;
8524 #endif
8525 case QEMU_OPTION_net:
8526 if (nb_net_clients >= MAX_NET_CLIENTS) {
8527 fprintf(stderr, "qemu: too many network clients\n");
8528 exit(1);
8530 net_clients[nb_net_clients] = optarg;
8531 nb_net_clients++;
8532 break;
8533 #ifdef CONFIG_SLIRP
8534 case QEMU_OPTION_tftp:
8535 tftp_prefix = optarg;
8536 break;
8537 case QEMU_OPTION_bootp:
8538 bootp_filename = optarg;
8539 break;
8540 #ifndef _WIN32
8541 case QEMU_OPTION_smb:
8542 net_slirp_smb(optarg);
8543 break;
8544 #endif
8545 case QEMU_OPTION_redir:
8546 net_slirp_redir(optarg);
8547 break;
8548 #endif
8549 #ifdef HAS_AUDIO
8550 case QEMU_OPTION_audio_help:
8551 AUD_help ();
8552 exit (0);
8553 break;
8554 case QEMU_OPTION_soundhw:
8555 select_soundhw (optarg);
8556 break;
8557 #endif
8558 case QEMU_OPTION_h:
8559 help(0);
8560 break;
8561 case QEMU_OPTION_m: {
8562 uint64_t value;
8563 char *ptr;
8565 value = strtoul(optarg, &ptr, 10);
8566 switch (*ptr) {
8567 case 0: case 'M': case 'm':
8568 value <<= 20;
8569 break;
8570 case 'G': case 'g':
8571 value <<= 30;
8572 break;
8573 default:
8574 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8575 exit(1);
8578 /* On 32-bit hosts, QEMU is limited by virtual address space */
8579 if (value > (2047 << 20)
8580 #ifndef USE_KQEMU
8581 && HOST_LONG_BITS == 32
8582 #endif
8584 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8585 exit(1);
8587 if (value != (uint64_t)(ram_addr_t)value) {
8588 fprintf(stderr, "qemu: ram size too large\n");
8589 exit(1);
8591 ram_size = value;
8592 break;
8594 case QEMU_OPTION_d:
8596 int mask;
8597 CPULogItem *item;
8599 mask = cpu_str_to_log_mask(optarg);
8600 if (!mask) {
8601 printf("Log items (comma separated):\n");
8602 for(item = cpu_log_items; item->mask != 0; item++) {
8603 printf("%-10s %s\n", item->name, item->help);
8605 exit(1);
8607 cpu_set_log(mask);
8609 break;
8610 #ifdef CONFIG_GDBSTUB
8611 case QEMU_OPTION_s:
8612 use_gdbstub = 1;
8613 break;
8614 case QEMU_OPTION_p:
8615 gdbstub_port = optarg;
8616 break;
8617 #endif
8618 case QEMU_OPTION_L:
8619 bios_dir = optarg;
8620 break;
8621 case QEMU_OPTION_bios:
8622 bios_name = optarg;
8623 break;
8624 case QEMU_OPTION_S:
8625 autostart = 0;
8626 break;
8627 case QEMU_OPTION_k:
8628 keyboard_layout = optarg;
8629 break;
8630 case QEMU_OPTION_localtime:
8631 rtc_utc = 0;
8632 break;
8633 case QEMU_OPTION_cirrusvga:
8634 cirrus_vga_enabled = 1;
8635 vmsvga_enabled = 0;
8636 break;
8637 case QEMU_OPTION_vmsvga:
8638 cirrus_vga_enabled = 0;
8639 vmsvga_enabled = 1;
8640 break;
8641 case QEMU_OPTION_std_vga:
8642 cirrus_vga_enabled = 0;
8643 vmsvga_enabled = 0;
8644 break;
8645 case QEMU_OPTION_g:
8647 const char *p;
8648 int w, h, depth;
8649 p = optarg;
8650 w = strtol(p, (char **)&p, 10);
8651 if (w <= 0) {
8652 graphic_error:
8653 fprintf(stderr, "qemu: invalid resolution or depth\n");
8654 exit(1);
8656 if (*p != 'x')
8657 goto graphic_error;
8658 p++;
8659 h = strtol(p, (char **)&p, 10);
8660 if (h <= 0)
8661 goto graphic_error;
8662 if (*p == 'x') {
8663 p++;
8664 depth = strtol(p, (char **)&p, 10);
8665 if (depth != 8 && depth != 15 && depth != 16 &&
8666 depth != 24 && depth != 32)
8667 goto graphic_error;
8668 } else if (*p == '\0') {
8669 depth = graphic_depth;
8670 } else {
8671 goto graphic_error;
8674 graphic_width = w;
8675 graphic_height = h;
8676 graphic_depth = depth;
8678 break;
8679 case QEMU_OPTION_echr:
8681 char *r;
8682 term_escape_char = strtol(optarg, &r, 0);
8683 if (r == optarg)
8684 printf("Bad argument to echr\n");
8685 break;
8687 case QEMU_OPTION_monitor:
8688 monitor_device = optarg;
8689 break;
8690 case QEMU_OPTION_serial:
8691 if (serial_device_index >= MAX_SERIAL_PORTS) {
8692 fprintf(stderr, "qemu: too many serial ports\n");
8693 exit(1);
8695 serial_devices[serial_device_index] = optarg;
8696 serial_device_index++;
8697 break;
8698 case QEMU_OPTION_parallel:
8699 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8700 fprintf(stderr, "qemu: too many parallel ports\n");
8701 exit(1);
8703 parallel_devices[parallel_device_index] = optarg;
8704 parallel_device_index++;
8705 break;
8706 case QEMU_OPTION_loadvm:
8707 loadvm = optarg;
8708 break;
8709 case QEMU_OPTION_full_screen:
8710 full_screen = 1;
8711 break;
8712 #ifdef CONFIG_SDL
8713 case QEMU_OPTION_no_frame:
8714 no_frame = 1;
8715 break;
8716 case QEMU_OPTION_alt_grab:
8717 alt_grab = 1;
8718 break;
8719 case QEMU_OPTION_no_quit:
8720 no_quit = 1;
8721 break;
8722 #endif
8723 case QEMU_OPTION_pidfile:
8724 pid_file = optarg;
8725 break;
8726 #ifdef TARGET_I386
8727 case QEMU_OPTION_win2k_hack:
8728 win2k_install_hack = 1;
8729 break;
8730 #endif
8731 #ifdef USE_KQEMU
8732 case QEMU_OPTION_no_kqemu:
8733 kqemu_allowed = 0;
8734 break;
8735 case QEMU_OPTION_kernel_kqemu:
8736 kqemu_allowed = 2;
8737 break;
8738 #endif
8739 case QEMU_OPTION_usb:
8740 usb_enabled = 1;
8741 break;
8742 case QEMU_OPTION_usbdevice:
8743 usb_enabled = 1;
8744 if (usb_devices_index >= MAX_USB_CMDLINE) {
8745 fprintf(stderr, "Too many USB devices\n");
8746 exit(1);
8748 usb_devices[usb_devices_index] = optarg;
8749 usb_devices_index++;
8750 break;
8751 case QEMU_OPTION_smp:
8752 smp_cpus = atoi(optarg);
8753 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8754 fprintf(stderr, "Invalid number of CPUs\n");
8755 exit(1);
8757 break;
8758 case QEMU_OPTION_vnc:
8759 vnc_display = optarg;
8760 break;
8761 case QEMU_OPTION_no_acpi:
8762 acpi_enabled = 0;
8763 break;
8764 case QEMU_OPTION_no_reboot:
8765 no_reboot = 1;
8766 break;
8767 case QEMU_OPTION_no_shutdown:
8768 no_shutdown = 1;
8769 break;
8770 case QEMU_OPTION_show_cursor:
8771 cursor_hide = 0;
8772 break;
8773 case QEMU_OPTION_daemonize:
8774 daemonize = 1;
8775 break;
8776 case QEMU_OPTION_option_rom:
8777 if (nb_option_roms >= MAX_OPTION_ROMS) {
8778 fprintf(stderr, "Too many option ROMs\n");
8779 exit(1);
8781 option_rom[nb_option_roms] = optarg;
8782 nb_option_roms++;
8783 break;
8784 case QEMU_OPTION_semihosting:
8785 semihosting_enabled = 1;
8786 break;
8787 case QEMU_OPTION_name:
8788 qemu_name = optarg;
8789 break;
8790 #ifdef TARGET_SPARC
8791 case QEMU_OPTION_prom_env:
8792 if (nb_prom_envs >= MAX_PROM_ENVS) {
8793 fprintf(stderr, "Too many prom variables\n");
8794 exit(1);
8796 prom_envs[nb_prom_envs] = optarg;
8797 nb_prom_envs++;
8798 break;
8799 #endif
8800 #ifdef TARGET_ARM
8801 case QEMU_OPTION_old_param:
8802 old_param = 1;
8803 break;
8804 #endif
8805 case QEMU_OPTION_clock:
8806 configure_alarms(optarg);
8807 break;
8808 case QEMU_OPTION_startdate:
8810 struct tm tm;
8811 time_t rtc_start_date;
8812 if (!strcmp(optarg, "now")) {
8813 rtc_date_offset = -1;
8814 } else {
8815 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8816 &tm.tm_year,
8817 &tm.tm_mon,
8818 &tm.tm_mday,
8819 &tm.tm_hour,
8820 &tm.tm_min,
8821 &tm.tm_sec) == 6) {
8822 /* OK */
8823 } else if (sscanf(optarg, "%d-%d-%d",
8824 &tm.tm_year,
8825 &tm.tm_mon,
8826 &tm.tm_mday) == 3) {
8827 tm.tm_hour = 0;
8828 tm.tm_min = 0;
8829 tm.tm_sec = 0;
8830 } else {
8831 goto date_fail;
8833 tm.tm_year -= 1900;
8834 tm.tm_mon--;
8835 rtc_start_date = mktimegm(&tm);
8836 if (rtc_start_date == -1) {
8837 date_fail:
8838 fprintf(stderr, "Invalid date format. Valid format are:\n"
8839 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8840 exit(1);
8842 rtc_date_offset = time(NULL) - rtc_start_date;
8845 break;
8846 case QEMU_OPTION_tb_size:
8847 tb_size = strtol(optarg, NULL, 0);
8848 if (tb_size < 0)
8849 tb_size = 0;
8850 break;
8851 case QEMU_OPTION_icount:
8852 use_icount = 1;
8853 if (strcmp(optarg, "auto") == 0) {
8854 icount_time_shift = -1;
8855 } else {
8856 icount_time_shift = strtol(optarg, NULL, 0);
8858 break;
8863 if (nographic) {
8864 if (serial_device_index == 0)
8865 serial_devices[0] = "stdio";
8866 if (parallel_device_index == 0)
8867 parallel_devices[0] = "null";
8868 if (strncmp(monitor_device, "vc", 2) == 0)
8869 monitor_device = "stdio";
8872 #ifndef _WIN32
8873 if (daemonize) {
8874 pid_t pid;
8876 if (pipe(fds) == -1)
8877 exit(1);
8879 pid = fork();
8880 if (pid > 0) {
8881 uint8_t status;
8882 ssize_t len;
8884 close(fds[1]);
8886 again:
8887 len = read(fds[0], &status, 1);
8888 if (len == -1 && (errno == EINTR))
8889 goto again;
8891 if (len != 1)
8892 exit(1);
8893 else if (status == 1) {
8894 fprintf(stderr, "Could not acquire pidfile\n");
8895 exit(1);
8896 } else
8897 exit(0);
8898 } else if (pid < 0)
8899 exit(1);
8901 setsid();
8903 pid = fork();
8904 if (pid > 0)
8905 exit(0);
8906 else if (pid < 0)
8907 exit(1);
8909 umask(027);
8911 signal(SIGTSTP, SIG_IGN);
8912 signal(SIGTTOU, SIG_IGN);
8913 signal(SIGTTIN, SIG_IGN);
8915 #endif
8917 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8918 if (daemonize) {
8919 uint8_t status = 1;
8920 write(fds[1], &status, 1);
8921 } else
8922 fprintf(stderr, "Could not acquire pid file\n");
8923 exit(1);
8926 #ifdef USE_KQEMU
8927 if (smp_cpus > 1)
8928 kqemu_allowed = 0;
8929 #endif
8930 linux_boot = (kernel_filename != NULL);
8931 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8933 if (!linux_boot && net_boot == 0 &&
8934 !machine->nodisk_ok && nb_drives_opt == 0)
8935 help(1);
8937 if (!linux_boot && *kernel_cmdline != '\0') {
8938 fprintf(stderr, "-append only allowed with -kernel option\n");
8939 exit(1);
8942 if (!linux_boot && initrd_filename != NULL) {
8943 fprintf(stderr, "-initrd only allowed with -kernel option\n");
8944 exit(1);
8947 /* boot to floppy or the default cd if no hard disk defined yet */
8948 if (!boot_devices[0]) {
8949 boot_devices = "cad";
8951 setvbuf(stdout, NULL, _IOLBF, 0);
8953 init_timers();
8954 init_timer_alarm();
8955 qemu_aio_init();
8956 if (use_icount && icount_time_shift < 0) {
8957 use_icount = 2;
8958 /* 125MIPS seems a reasonable initial guess at the guest speed.
8959 It will be corrected fairly quickly anyway. */
8960 icount_time_shift = 3;
8961 init_icount_adjust();
8964 #ifdef _WIN32
8965 socket_init();
8966 #endif
8968 /* init network clients */
8969 if (nb_net_clients == 0) {
8970 /* if no clients, we use a default config */
8971 net_clients[nb_net_clients++] = "nic";
8972 #ifdef CONFIG_SLIRP
8973 net_clients[nb_net_clients++] = "user";
8974 #endif
8977 for(i = 0;i < nb_net_clients; i++) {
8978 if (net_client_parse(net_clients[i]) < 0)
8979 exit(1);
8981 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8982 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8983 continue;
8984 if (vlan->nb_guest_devs == 0)
8985 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
8986 if (vlan->nb_host_devs == 0)
8987 fprintf(stderr,
8988 "Warning: vlan %d is not connected to host network\n",
8989 vlan->id);
8992 #ifdef TARGET_I386
8993 /* XXX: this should be moved in the PC machine instantiation code */
8994 if (net_boot != 0) {
8995 int netroms = 0;
8996 for (i = 0; i < nb_nics && i < 4; i++) {
8997 const char *model = nd_table[i].model;
8998 char buf[1024];
8999 if (net_boot & (1 << i)) {
9000 if (model == NULL)
9001 model = "ne2k_pci";
9002 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9003 if (get_image_size(buf) > 0) {
9004 if (nb_option_roms >= MAX_OPTION_ROMS) {
9005 fprintf(stderr, "Too many option ROMs\n");
9006 exit(1);
9008 option_rom[nb_option_roms] = strdup(buf);
9009 nb_option_roms++;
9010 netroms++;
9014 if (netroms == 0) {
9015 fprintf(stderr, "No valid PXE rom found for network device\n");
9016 exit(1);
9019 #endif
9021 /* init the memory */
9022 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9024 if (machine->ram_require & RAMSIZE_FIXED) {
9025 if (ram_size > 0) {
9026 if (ram_size < phys_ram_size) {
9027 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9028 machine->name, (unsigned long long) phys_ram_size);
9029 exit(-1);
9032 phys_ram_size = ram_size;
9033 } else
9034 ram_size = phys_ram_size;
9035 } else {
9036 if (ram_size == 0)
9037 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9039 phys_ram_size += ram_size;
9042 phys_ram_base = qemu_vmalloc(phys_ram_size);
9043 if (!phys_ram_base) {
9044 fprintf(stderr, "Could not allocate physical memory\n");
9045 exit(1);
9048 /* init the dynamic translator */
9049 cpu_exec_init_all(tb_size * 1024 * 1024);
9051 bdrv_init();
9053 /* we always create the cdrom drive, even if no disk is there */
9055 if (nb_drives_opt < MAX_DRIVES)
9056 drive_add(NULL, CDROM_ALIAS);
9058 /* we always create at least one floppy */
9060 if (nb_drives_opt < MAX_DRIVES)
9061 drive_add(NULL, FD_ALIAS, 0);
9063 /* we always create one sd slot, even if no card is in it */
9065 if (nb_drives_opt < MAX_DRIVES)
9066 drive_add(NULL, SD_ALIAS);
9068 /* open the virtual block devices */
9070 for(i = 0; i < nb_drives_opt; i++)
9071 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9072 exit(1);
9074 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9075 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9077 /* terminal init */
9078 memset(&display_state, 0, sizeof(display_state));
9079 if (nographic) {
9080 if (curses) {
9081 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9082 exit(1);
9084 /* nearly nothing to do */
9085 dumb_display_init(ds);
9086 } else if (vnc_display != NULL) {
9087 vnc_display_init(ds);
9088 if (vnc_display_open(ds, vnc_display) < 0)
9089 exit(1);
9090 } else
9091 #if defined(CONFIG_CURSES)
9092 if (curses) {
9093 curses_display_init(ds, full_screen);
9094 } else
9095 #endif
9097 #if defined(CONFIG_SDL)
9098 sdl_display_init(ds, full_screen, no_frame);
9099 #elif defined(CONFIG_COCOA)
9100 cocoa_display_init(ds, full_screen);
9101 #else
9102 dumb_display_init(ds);
9103 #endif
9106 #ifndef _WIN32
9107 /* must be after terminal init, SDL library changes signal handlers */
9108 termsig_setup();
9109 #endif
9111 /* Maintain compatibility with multiple stdio monitors */
9112 if (!strcmp(monitor_device,"stdio")) {
9113 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9114 const char *devname = serial_devices[i];
9115 if (devname && !strcmp(devname,"mon:stdio")) {
9116 monitor_device = NULL;
9117 break;
9118 } else if (devname && !strcmp(devname,"stdio")) {
9119 monitor_device = NULL;
9120 serial_devices[i] = "mon:stdio";
9121 break;
9125 if (monitor_device) {
9126 monitor_hd = qemu_chr_open(monitor_device);
9127 if (!monitor_hd) {
9128 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9129 exit(1);
9131 monitor_init(monitor_hd, !nographic);
9134 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9135 const char *devname = serial_devices[i];
9136 if (devname && strcmp(devname, "none")) {
9137 serial_hds[i] = qemu_chr_open(devname);
9138 if (!serial_hds[i]) {
9139 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9140 devname);
9141 exit(1);
9143 if (strstart(devname, "vc", 0))
9144 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9148 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9149 const char *devname = parallel_devices[i];
9150 if (devname && strcmp(devname, "none")) {
9151 parallel_hds[i] = qemu_chr_open(devname);
9152 if (!parallel_hds[i]) {
9153 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9154 devname);
9155 exit(1);
9157 if (strstart(devname, "vc", 0))
9158 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9162 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9163 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9165 /* init USB devices */
9166 if (usb_enabled) {
9167 for(i = 0; i < usb_devices_index; i++) {
9168 if (usb_device_add(usb_devices[i]) < 0) {
9169 fprintf(stderr, "Warning: could not add USB device %s\n",
9170 usb_devices[i]);
9175 if (display_state.dpy_refresh) {
9176 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9177 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9180 #ifdef CONFIG_GDBSTUB
9181 if (use_gdbstub) {
9182 /* XXX: use standard host:port notation and modify options
9183 accordingly. */
9184 if (gdbserver_start(gdbstub_port) < 0) {
9185 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9186 gdbstub_port);
9187 exit(1);
9190 #endif
9192 if (loadvm)
9193 do_loadvm(loadvm);
9196 /* XXX: simplify init */
9197 read_passwords();
9198 if (autostart) {
9199 vm_start();
9203 if (daemonize) {
9204 uint8_t status = 0;
9205 ssize_t len;
9206 int fd;
9208 again1:
9209 len = write(fds[1], &status, 1);
9210 if (len == -1 && (errno == EINTR))
9211 goto again1;
9213 if (len != 1)
9214 exit(1);
9216 chdir("/");
9217 TFR(fd = open("/dev/null", O_RDWR));
9218 if (fd == -1)
9219 exit(1);
9221 dup2(fd, 0);
9222 dup2(fd, 1);
9223 dup2(fd, 2);
9225 close(fd);
9228 main_loop();
9229 quit_timers();
9231 #if !defined(_WIN32)
9232 /* close network clients */
9233 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9234 VLANClientState *vc;
9236 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9237 if (vc->fd_read == tap_receive) {
9238 char ifname[64];
9239 TAPState *s = vc->opaque;
9241 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9242 s->down_script[0])
9243 launch_script(s->down_script, ifname, s->fd);
9245 #if defined(CONFIG_VDE)
9246 if (vc->fd_read == vde_from_qemu) {
9247 VDEState *s = vc->opaque;
9248 vde_close(s->vde);
9250 #endif
9253 #endif
9254 return 0;