ia64/xen-unstable

view tools/ioemu/vl.c @ 14617:9c1367368ee3

[ioemu] Don't enable monitor or serial console on virtual consoles by default.

Signed-off-by: Christian Limpach <Christian.Limpach@xensource.com>
author Christian Limpach <Christian.Limpach@xensource.com>
date Wed Mar 28 10:36:49 2007 +0100 (2007-03-28)
parents 2955b0677310
children 7e431ea834a8
line source
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24 #include "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #else
51 #ifndef __sun__
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <pty.h>
55 #include <malloc.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #endif
59 #endif
60 #endif
62 #if defined(CONFIG_SLIRP)
63 #include "libslirp.h"
64 #endif
66 #ifdef _WIN32
67 #include <malloc.h>
68 #include <sys/timeb.h>
69 #include <windows.h>
70 #define getopt_long_only getopt_long
71 #define memalign(align, size) malloc(size)
72 #endif
74 #include "qemu_socket.h"
76 #ifdef CONFIG_SDL
77 #ifdef __APPLE__
78 #include <SDL/SDL.h>
79 #endif
80 #endif /* CONFIG_SDL */
82 #ifdef CONFIG_COCOA
83 #undef main
84 #define main qemu_main
85 #endif /* CONFIG_COCOA */
87 #include "disas.h"
89 #include "exec-all.h"
91 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
92 #define DEFAULT_BRIDGE "xenbr0"
94 //#define DEBUG_UNUSED_IOPORT
95 //#define DEBUG_IOPORT
97 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
99 #ifdef TARGET_PPC
100 #define DEFAULT_RAM_SIZE 144
101 #else
102 #define DEFAULT_RAM_SIZE 128
103 #endif
104 /* in ms */
105 #define GUI_REFRESH_INTERVAL 30
107 /* Max number of USB devices that can be specified on the commandline. */
108 #define MAX_USB_CMDLINE 8
110 /* XXX: use a two level table to limit memory usage */
111 #define MAX_IOPORTS 65536
113 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
114 char phys_ram_file[1024];
115 void *ioport_opaque[MAX_IOPORTS];
116 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
117 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
118 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
119 int vga_ram_size;
120 int bios_size;
121 static DisplayState display_state;
122 int nographic;
123 int vncviewer;
124 int vncunused;
125 struct sockaddr_in vnclisten_addr;
126 const char* keyboard_layout = NULL;
127 int64_t ticks_per_sec;
128 char *boot_device = NULL;
129 uint64_t ram_size;
130 int pit_min_timer_count = 0;
131 int nb_nics;
132 NICInfo nd_table[MAX_NICS];
133 QEMUTimer *gui_timer;
134 int vm_running;
135 int rtc_utc = 1;
136 int cirrus_vga_enabled = 1;
137 #ifdef TARGET_SPARC
138 int graphic_width = 1024;
139 int graphic_height = 768;
140 #else
141 int graphic_width = 800;
142 int graphic_height = 600;
143 #endif
144 int graphic_depth = 15;
145 int full_screen = 0;
146 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
147 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
148 #ifdef TARGET_I386
149 int win2k_install_hack = 0;
150 #endif
151 int usb_enabled = 0;
152 static VLANState *first_vlan;
153 int smp_cpus = 1;
154 int vnc_display = -1;
155 #if defined(TARGET_SPARC)
156 #define MAX_CPUS 16
157 #elif defined(TARGET_I386)
158 #define MAX_CPUS 255
159 #else
160 #define MAX_CPUS 1
161 #endif
162 int acpi_enabled = 0;
163 int fd_bootchk = 1;
165 extern int vcpus;
167 int xc_handle;
169 time_t timeoffset = 0;
171 char domain_name[1024] = { 'H','V', 'M', 'X', 'E', 'N', '-'};
172 extern int domid;
174 char vncpasswd[64];
175 unsigned char challenge[AUTHCHALLENGESIZE];
177 /***********************************************************/
178 /* x86 ISA bus support */
180 target_phys_addr_t isa_mem_base = 0;
181 PicState2 *isa_pic;
183 uint32_t default_ioport_readb(void *opaque, uint32_t address)
184 {
185 #ifdef DEBUG_UNUSED_IOPORT
186 fprintf(stderr, "inb: port=0x%04x\n", address);
187 #endif
188 return 0xff;
189 }
191 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
192 {
193 #ifdef DEBUG_UNUSED_IOPORT
194 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
195 #endif
196 }
198 /* default is to make two byte accesses */
199 uint32_t default_ioport_readw(void *opaque, uint32_t address)
200 {
201 uint32_t data;
202 data = ioport_read_table[0][address](ioport_opaque[address], address);
203 address = (address + 1) & (MAX_IOPORTS - 1);
204 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
205 return data;
206 }
208 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
209 {
210 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
211 address = (address + 1) & (MAX_IOPORTS - 1);
212 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
213 }
215 uint32_t default_ioport_readl(void *opaque, uint32_t address)
216 {
217 #ifdef DEBUG_UNUSED_IOPORT
218 fprintf(stderr, "inl: port=0x%04x\n", address);
219 #endif
220 return 0xffffffff;
221 }
223 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
224 {
225 #ifdef DEBUG_UNUSED_IOPORT
226 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
227 #endif
228 }
230 void init_ioports(void)
231 {
232 int i;
234 for(i = 0; i < MAX_IOPORTS; i++) {
235 ioport_read_table[0][i] = default_ioport_readb;
236 ioport_write_table[0][i] = default_ioport_writeb;
237 ioport_read_table[1][i] = default_ioport_readw;
238 ioport_write_table[1][i] = default_ioport_writew;
239 ioport_read_table[2][i] = default_ioport_readl;
240 ioport_write_table[2][i] = default_ioport_writel;
241 }
242 }
244 /* size is the word size in byte */
245 int register_ioport_read(int start, int length, int size,
246 IOPortReadFunc *func, void *opaque)
247 {
248 int i, bsize;
250 if (size == 1) {
251 bsize = 0;
252 } else if (size == 2) {
253 bsize = 1;
254 } else if (size == 4) {
255 bsize = 2;
256 } else {
257 hw_error("register_ioport_read: invalid size");
258 return -1;
259 }
260 for(i = start; i < start + length; i += size) {
261 ioport_read_table[bsize][i] = func;
262 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
263 hw_error("register_ioport_read: invalid opaque");
264 ioport_opaque[i] = opaque;
265 }
266 return 0;
267 }
269 /* size is the word size in byte */
270 int register_ioport_write(int start, int length, int size,
271 IOPortWriteFunc *func, void *opaque)
272 {
273 int i, bsize;
275 if (size == 1) {
276 bsize = 0;
277 } else if (size == 2) {
278 bsize = 1;
279 } else if (size == 4) {
280 bsize = 2;
281 } else {
282 hw_error("register_ioport_write: invalid size");
283 return -1;
284 }
285 for(i = start; i < start + length; i += size) {
286 ioport_write_table[bsize][i] = func;
287 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
288 hw_error("register_ioport_write: invalid opaque");
289 ioport_opaque[i] = opaque;
290 }
291 return 0;
292 }
294 void isa_unassign_ioport(int start, int length)
295 {
296 int i;
298 for(i = start; i < start + length; i++) {
299 ioport_read_table[0][i] = default_ioport_readb;
300 ioport_read_table[1][i] = default_ioport_readw;
301 ioport_read_table[2][i] = default_ioport_readl;
303 ioport_write_table[0][i] = default_ioport_writeb;
304 ioport_write_table[1][i] = default_ioport_writew;
305 ioport_write_table[2][i] = default_ioport_writel;
306 }
307 }
309 /***********************************************************/
311 void pstrcpy(char *buf, int buf_size, const char *str)
312 {
313 int c;
314 char *q = buf;
316 if (buf_size <= 0)
317 return;
319 for(;;) {
320 c = *str++;
321 if (c == 0 || q >= buf + buf_size - 1)
322 break;
323 *q++ = c;
324 }
325 *q = '\0';
326 }
328 /* strcat and truncate. */
329 char *pstrcat(char *buf, int buf_size, const char *s)
330 {
331 int len;
332 len = strlen(buf);
333 if (len < buf_size)
334 pstrcpy(buf + len, buf_size - len, s);
335 return buf;
336 }
338 int strstart(const char *str, const char *val, const char **ptr)
339 {
340 const char *p, *q;
341 p = str;
342 q = val;
343 while (*q != '\0') {
344 if (*p != *q)
345 return 0;
346 p++;
347 q++;
348 }
349 if (ptr)
350 *ptr = p;
351 return 1;
352 }
354 void cpu_outb(CPUState *env, int addr, int val)
355 {
356 #ifdef DEBUG_IOPORT
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outb: %04x %02x\n", addr, val);
359 #endif
360 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
361 #ifdef USE_KQEMU
362 if (env)
363 env->last_io_time = cpu_get_time_fast();
364 #endif
365 }
367 void cpu_outw(CPUState *env, int addr, int val)
368 {
369 #ifdef DEBUG_IOPORT
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "outw: %04x %04x\n", addr, val);
372 #endif
373 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
374 #ifdef USE_KQEMU
375 if (env)
376 env->last_io_time = cpu_get_time_fast();
377 #endif
378 }
380 void cpu_outl(CPUState *env, int addr, int val)
381 {
382 #ifdef DEBUG_IOPORT
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "outl: %04x %08x\n", addr, val);
385 #endif
386 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
387 #ifdef USE_KQEMU
388 if (env)
389 env->last_io_time = cpu_get_time_fast();
390 #endif
391 }
393 int cpu_inb(CPUState *env, int addr)
394 {
395 int val;
396 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
397 #ifdef DEBUG_IOPORT
398 if (loglevel & CPU_LOG_IOPORT)
399 fprintf(logfile, "inb : %04x %02x\n", addr, val);
400 #endif
401 #ifdef USE_KQEMU
402 if (env)
403 env->last_io_time = cpu_get_time_fast();
404 #endif
405 return val;
406 }
408 int cpu_inw(CPUState *env, int addr)
409 {
410 int val;
411 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
412 #ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "inw : %04x %04x\n", addr, val);
415 #endif
416 #ifdef USE_KQEMU
417 if (env)
418 env->last_io_time = cpu_get_time_fast();
419 #endif
420 return val;
421 }
423 int cpu_inl(CPUState *env, int addr)
424 {
425 int val;
426 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
427 #ifdef DEBUG_IOPORT
428 if (loglevel & CPU_LOG_IOPORT)
429 fprintf(logfile, "inl : %04x %08x\n", addr, val);
430 #endif
431 #ifdef USE_KQEMU
432 if (env)
433 env->last_io_time = cpu_get_time_fast();
434 #endif
435 return val;
436 }
438 /***********************************************************/
439 void hw_error(const char *fmt, ...)
440 {
441 va_list ap;
442 #ifndef CONFIG_DM
443 CPUState *env;
444 #endif /* !CONFIG_DM */
446 va_start(ap, fmt);
447 fprintf(stderr, "qemu: hardware error: ");
448 vfprintf(stderr, fmt, ap);
449 fprintf(stderr, "\n");
450 #ifndef CONFIG_DM
451 for(env = first_cpu; env != NULL; env = env->next_cpu) {
452 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
453 #ifdef TARGET_I386
454 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
455 #else
456 cpu_dump_state(env, stderr, fprintf, 0);
457 #endif
458 }
459 #endif /* !CONFIG_DM */
460 va_end(ap);
461 abort();
462 }
464 /***********************************************************/
465 /* keyboard/mouse */
467 static QEMUPutKBDEvent *qemu_put_kbd_event;
468 static void *qemu_put_kbd_event_opaque;
469 static QEMUPutMouseEvent *qemu_put_mouse_event;
470 static void *qemu_put_mouse_event_opaque;
471 static int qemu_put_mouse_event_absolute;
473 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
474 {
475 qemu_put_kbd_event_opaque = opaque;
476 qemu_put_kbd_event = func;
477 }
479 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
480 {
481 qemu_put_mouse_event_opaque = opaque;
482 qemu_put_mouse_event = func;
483 qemu_put_mouse_event_absolute = absolute;
484 }
486 void kbd_put_keycode(int keycode)
487 {
488 if (qemu_put_kbd_event) {
489 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
490 }
491 }
493 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
494 {
495 if (qemu_put_mouse_event) {
496 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
497 dx, dy, dz, buttons_state);
498 }
499 }
501 int kbd_mouse_is_absolute(void)
502 {
503 return qemu_put_mouse_event_absolute;
504 }
506 /* compute with 96 bit intermediate result: (a*b)/c */
507 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
508 {
509 union {
510 uint64_t ll;
511 struct {
512 #ifdef WORDS_BIGENDIAN
513 uint32_t high, low;
514 #else
515 uint32_t low, high;
516 #endif
517 } l;
518 } u, res;
519 uint64_t rl, rh;
521 u.ll = a;
522 rl = (uint64_t)u.l.low * (uint64_t)b;
523 rh = (uint64_t)u.l.high * (uint64_t)b;
524 rh += (rl >> 32);
525 res.l.high = rh / c;
526 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
527 return res.ll;
528 }
530 /***********************************************************/
531 /* real time host monotonic timer */
533 #define QEMU_TIMER_BASE 1000000000LL
535 #ifdef WIN32
537 static int64_t clock_freq;
539 static void init_get_clock(void)
540 {
541 LARGE_INTEGER freq;
542 int ret;
543 ret = QueryPerformanceFrequency(&freq);
544 if (ret == 0) {
545 fprintf(stderr, "Could not calibrate ticks\n");
546 exit(1);
547 }
548 clock_freq = freq.QuadPart;
549 }
551 static int64_t get_clock(void)
552 {
553 LARGE_INTEGER ti;
554 QueryPerformanceCounter(&ti);
555 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
556 }
558 #else
560 static int use_rt_clock;
562 static void init_get_clock(void)
563 {
564 use_rt_clock = 0;
565 #if defined(__linux__)
566 {
567 struct timespec ts;
568 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
569 use_rt_clock = 1;
570 }
571 }
572 #endif
573 }
575 static int64_t get_clock(void)
576 {
577 #if defined(__linux__)
578 if (use_rt_clock) {
579 struct timespec ts;
580 clock_gettime(CLOCK_MONOTONIC, &ts);
581 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
582 } else
583 #endif
584 {
585 /* XXX: using gettimeofday leads to problems if the date
586 changes, so it should be avoided. */
587 struct timeval tv;
588 gettimeofday(&tv, NULL);
589 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
590 }
591 }
593 #endif
595 /***********************************************************/
596 /* guest cycle counter */
598 static int64_t cpu_ticks_prev;
599 static int64_t cpu_ticks_offset;
600 static int64_t cpu_clock_offset;
601 static int cpu_ticks_enabled;
603 /* return the host CPU cycle counter and handle stop/restart */
604 int64_t cpu_get_ticks(void)
605 {
606 if (!cpu_ticks_enabled) {
607 return cpu_ticks_offset;
608 } else {
609 int64_t ticks;
610 ticks = cpu_get_real_ticks();
611 if (cpu_ticks_prev > ticks) {
612 /* Note: non increasing ticks may happen if the host uses
613 software suspend */
614 cpu_ticks_offset += cpu_ticks_prev - ticks;
615 }
616 cpu_ticks_prev = ticks;
617 return ticks + cpu_ticks_offset;
618 }
619 }
621 /* return the host CPU monotonic timer and handle stop/restart */
622 static int64_t cpu_get_clock(void)
623 {
624 int64_t ti;
625 if (!cpu_ticks_enabled) {
626 return cpu_clock_offset;
627 } else {
628 ti = get_clock();
629 return ti + cpu_clock_offset;
630 }
631 }
633 /* enable cpu_get_ticks() */
634 void cpu_enable_ticks(void)
635 {
636 if (!cpu_ticks_enabled) {
637 cpu_ticks_offset -= cpu_get_real_ticks();
638 cpu_clock_offset -= get_clock();
639 cpu_ticks_enabled = 1;
640 }
641 }
643 /* disable cpu_get_ticks() : the clock is stopped. You must not call
644 cpu_get_ticks() after that. */
645 void cpu_disable_ticks(void)
646 {
647 if (cpu_ticks_enabled) {
648 cpu_ticks_offset = cpu_get_ticks();
649 cpu_clock_offset = cpu_get_clock();
650 cpu_ticks_enabled = 0;
651 }
652 }
654 /***********************************************************/
655 /* timers */
657 #define QEMU_TIMER_REALTIME 0
658 #define QEMU_TIMER_VIRTUAL 1
660 struct QEMUClock {
661 int type;
662 /* XXX: add frequency */
663 };
665 struct QEMUTimer {
666 QEMUClock *clock;
667 int64_t expire_time;
668 QEMUTimerCB *cb;
669 void *opaque;
670 struct QEMUTimer *next;
671 };
673 QEMUClock *rt_clock;
674 QEMUClock *vm_clock;
676 static QEMUTimer *active_timers[2];
677 #ifdef _WIN32
678 static MMRESULT timerID;
679 static HANDLE host_alarm = NULL;
680 static unsigned int period = 1;
681 #else
682 /* frequency of the times() clock tick */
683 static int timer_freq;
684 #endif
686 QEMUClock *qemu_new_clock(int type)
687 {
688 QEMUClock *clock;
689 clock = qemu_mallocz(sizeof(QEMUClock));
690 if (!clock)
691 return NULL;
692 clock->type = type;
693 return clock;
694 }
696 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
697 {
698 QEMUTimer *ts;
700 ts = qemu_mallocz(sizeof(QEMUTimer));
701 ts->clock = clock;
702 ts->cb = cb;
703 ts->opaque = opaque;
704 return ts;
705 }
707 void qemu_free_timer(QEMUTimer *ts)
708 {
709 qemu_free(ts);
710 }
712 /* stop a timer, but do not dealloc it */
713 void qemu_del_timer(QEMUTimer *ts)
714 {
715 QEMUTimer **pt, *t;
717 /* NOTE: this code must be signal safe because
718 qemu_timer_expired() can be called from a signal. */
719 pt = &active_timers[ts->clock->type];
720 for(;;) {
721 t = *pt;
722 if (!t)
723 break;
724 if (t == ts) {
725 *pt = t->next;
726 break;
727 }
728 pt = &t->next;
729 }
730 }
732 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
733 {
734 if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
735 qemu_mod_timer(ts, expire_time);
736 }
738 /* modify the current timer so that it will be fired when current_time
739 >= expire_time. The corresponding callback will be called. */
740 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
741 {
742 QEMUTimer **pt, *t;
744 qemu_del_timer(ts);
746 /* add the timer in the sorted list */
747 /* NOTE: this code must be signal safe because
748 qemu_timer_expired() can be called from a signal. */
749 pt = &active_timers[ts->clock->type];
750 for(;;) {
751 t = *pt;
752 if (!t)
753 break;
754 if (t->expire_time > expire_time)
755 break;
756 pt = &t->next;
757 }
758 ts->expire_time = expire_time;
759 ts->next = *pt;
760 *pt = ts;
761 }
763 int qemu_timer_pending(QEMUTimer *ts)
764 {
765 QEMUTimer *t;
766 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
767 if (t == ts)
768 return 1;
769 }
770 return 0;
771 }
773 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
774 {
775 if (!timer_head)
776 return 0;
777 return (timer_head->expire_time <= current_time);
778 }
780 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
781 {
782 QEMUTimer *ts;
784 for(;;) {
785 ts = *ptimer_head;
786 if (!ts || ts->expire_time > current_time)
787 break;
788 /* remove timer from the list before calling the callback */
789 *ptimer_head = ts->next;
790 ts->next = NULL;
792 /* run the callback (the timer list can be modified) */
793 ts->cb(ts->opaque);
794 }
795 }
797 int64_t qemu_get_clock(QEMUClock *clock)
798 {
799 switch(clock->type) {
800 case QEMU_TIMER_REALTIME:
801 return get_clock() / 1000000;
802 default:
803 case QEMU_TIMER_VIRTUAL:
804 return cpu_get_clock();
805 }
806 }
808 static void init_timers(void)
809 {
810 init_get_clock();
811 ticks_per_sec = QEMU_TIMER_BASE;
812 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
813 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
814 }
816 /* save a timer */
817 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
818 {
819 uint64_t expire_time;
821 if (qemu_timer_pending(ts)) {
822 expire_time = ts->expire_time;
823 } else {
824 expire_time = -1;
825 }
826 qemu_put_be64(f, expire_time);
827 }
829 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
830 {
831 uint64_t expire_time;
833 expire_time = qemu_get_be64(f);
834 if (expire_time != -1) {
835 qemu_mod_timer(ts, expire_time);
836 } else {
837 qemu_del_timer(ts);
838 }
839 }
841 #ifdef CONFIG_DM
842 static void timer_save(QEMUFile *f, void *opaque)
843 {
844 /* need timer for save/restoe qemu_timer in usb_uhci */
845 if (cpu_ticks_enabled) {
846 hw_error("cannot save state if virtual timers are running");
847 }
848 qemu_put_be64s(f, &cpu_clock_offset);
849 }
851 static int timer_load(QEMUFile *f, void *opaque, int version_id)
852 {
853 if (version_id != 1)
854 return -EINVAL;
855 if (cpu_ticks_enabled) {
856 return -EINVAL;
857 }
859 qemu_get_be64s(f, &cpu_clock_offset);
860 return 0;
861 }
862 #else /* !CONFIG_DM */
863 static void timer_save(QEMUFile *f, void *opaque)
864 {
865 if (cpu_ticks_enabled) {
866 hw_error("cannot save state if virtual timers are running");
867 }
868 qemu_put_be64s(f, &cpu_ticks_offset);
869 qemu_put_be64s(f, &ticks_per_sec);
870 }
872 static int timer_load(QEMUFile *f, void *opaque, int version_id)
873 {
874 if (version_id != 1)
875 return -EINVAL;
876 if (cpu_ticks_enabled) {
877 return -EINVAL;
878 }
879 qemu_get_be64s(f, &cpu_ticks_offset);
880 qemu_get_be64s(f, &ticks_per_sec);
881 return 0;
882 }
884 #ifdef _WIN32
885 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
886 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
887 #else
888 static void host_alarm_handler(int host_signum)
889 #endif
890 {
891 #if 0
892 #define DISP_FREQ 1000
893 {
894 static int64_t delta_min = INT64_MAX;
895 static int64_t delta_max, delta_cum, last_clock, delta, ti;
896 static int count;
897 ti = qemu_get_clock(vm_clock);
898 if (last_clock != 0) {
899 delta = ti - last_clock;
900 if (delta < delta_min)
901 delta_min = delta;
902 if (delta > delta_max)
903 delta_max = delta;
904 delta_cum += delta;
905 if (++count == DISP_FREQ) {
906 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
907 muldiv64(delta_min, 1000000, ticks_per_sec),
908 muldiv64(delta_max, 1000000, ticks_per_sec),
909 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
910 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
911 count = 0;
912 delta_min = INT64_MAX;
913 delta_max = 0;
914 delta_cum = 0;
915 }
916 }
917 last_clock = ti;
918 }
919 #endif
920 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
921 qemu_get_clock(vm_clock)) ||
922 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
923 qemu_get_clock(rt_clock))) {
924 #ifdef _WIN32
925 SetEvent(host_alarm);
926 #endif
927 CPUState *env = cpu_single_env;
928 if (env) {
929 /* stop the currently executing cpu because a timer occured */
930 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
931 #ifdef USE_KQEMU
932 if (env->kqemu_enabled) {
933 kqemu_cpu_interrupt(env);
934 }
935 #endif
936 }
937 }
938 }
940 #ifndef _WIN32
942 #if defined(__linux__)
944 #define RTC_FREQ 1024
946 static int rtc_fd;
948 static int start_rtc_timer(void)
949 {
950 rtc_fd = open("/dev/rtc", O_RDONLY);
951 if (rtc_fd < 0)
952 return -1;
953 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
954 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
955 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
956 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
957 goto fail;
958 }
959 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
960 fail:
961 close(rtc_fd);
962 return -1;
963 }
964 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
965 return 0;
966 }
968 #else
970 static int start_rtc_timer(void)
971 {
972 return -1;
973 }
975 #endif /* !defined(__linux__) */
977 #endif /* !defined(_WIN32) */
979 #endif /* !CONFIG_DM */
981 static void init_timer_alarm(void)
982 {
983 #ifdef _WIN32
984 {
985 int count=0;
986 TIMECAPS tc;
988 ZeroMemory(&tc, sizeof(TIMECAPS));
989 timeGetDevCaps(&tc, sizeof(TIMECAPS));
990 if (period < tc.wPeriodMin)
991 period = tc.wPeriodMin;
992 timeBeginPeriod(period);
993 timerID = timeSetEvent(1, // interval (ms)
994 period, // resolution
995 host_alarm_handler, // function
996 (DWORD)&count, // user parameter
997 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
998 if( !timerID ) {
999 perror("failed timer alarm");
1000 exit(1);
1002 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1003 if (!host_alarm) {
1004 perror("failed CreateEvent");
1005 exit(1);
1007 qemu_add_wait_object(host_alarm, NULL, NULL);
1009 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1010 #else
1012 #ifndef CONFIG_DM
1013 struct sigaction act;
1014 struct itimerval itv;
1015 #endif
1017 /* get times() syscall frequency */
1018 timer_freq = sysconf(_SC_CLK_TCK);
1020 #ifndef CONFIG_DM
1021 /* timer signal */
1022 sigfillset(&act.sa_mask);
1023 act.sa_flags = 0;
1024 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1025 act.sa_flags |= SA_ONSTACK;
1026 #endif
1027 act.sa_handler = host_alarm_handler;
1028 sigaction(SIGALRM, &act, NULL);
1030 itv.it_interval.tv_sec = 0;
1031 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1032 itv.it_value.tv_sec = 0;
1033 itv.it_value.tv_usec = 10 * 1000;
1034 setitimer(ITIMER_REAL, &itv, NULL);
1035 /* we probe the tick duration of the kernel to inform the user if
1036 the emulated kernel requested a too high timer frequency */
1037 getitimer(ITIMER_REAL, &itv);
1039 #if defined(__linux__)
1040 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1041 have timers with 1 ms resolution. The correct solution will
1042 be to use the POSIX real time timers available in recent
1043 2.6 kernels */
1044 if (itv.it_interval.tv_usec > 1000 || 1) {
1045 /* try to use /dev/rtc to have a faster timer */
1046 if (start_rtc_timer() < 0)
1047 goto use_itimer;
1048 /* disable itimer */
1049 itv.it_interval.tv_sec = 0;
1050 itv.it_interval.tv_usec = 0;
1051 itv.it_value.tv_sec = 0;
1052 itv.it_value.tv_usec = 0;
1053 setitimer(ITIMER_REAL, &itv, NULL);
1055 /* use the RTC */
1056 sigaction(SIGIO, &act, NULL);
1057 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1058 fcntl(rtc_fd, F_SETOWN, getpid());
1059 } else
1060 #endif /* defined(__linux__) */
1062 use_itimer:
1063 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1064 PIT_FREQ) / 1000000;
1066 #endif /* CONFIG_DM */
1068 #endif
1071 void quit_timers(void)
1073 #ifdef _WIN32
1074 timeKillEvent(timerID);
1075 timeEndPeriod(period);
1076 if (host_alarm) {
1077 CloseHandle(host_alarm);
1078 host_alarm = NULL;
1080 #endif
1083 /***********************************************************/
1084 /* character device */
1086 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1088 return s->chr_write(s, buf, len);
1091 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1093 if (!s->chr_ioctl)
1094 return -ENOTSUP;
1095 return s->chr_ioctl(s, cmd, arg);
1098 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1100 char buf[4096];
1101 va_list ap;
1102 va_start(ap, fmt);
1103 vsnprintf(buf, sizeof(buf), fmt, ap);
1104 qemu_chr_write(s, buf, strlen(buf));
1105 va_end(ap);
1108 void qemu_chr_send_event(CharDriverState *s, int event)
1110 if (s->chr_send_event)
1111 s->chr_send_event(s, event);
1114 void qemu_chr_add_read_handler(CharDriverState *s,
1115 IOCanRWHandler *fd_can_read,
1116 IOReadHandler *fd_read, void *opaque)
1118 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1121 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1123 s->chr_event = chr_event;
1126 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1128 return len;
1131 static void null_chr_add_read_handler(CharDriverState *chr,
1132 IOCanRWHandler *fd_can_read,
1133 IOReadHandler *fd_read, void *opaque)
1137 CharDriverState *qemu_chr_open_null(void)
1139 CharDriverState *chr;
1141 chr = qemu_mallocz(sizeof(CharDriverState));
1142 if (!chr)
1143 return NULL;
1144 chr->chr_write = null_chr_write;
1145 chr->chr_add_read_handler = null_chr_add_read_handler;
1146 return chr;
1149 #ifdef _WIN32
1151 static void socket_cleanup(void)
1153 WSACleanup();
1156 static int socket_init(void)
1158 WSADATA Data;
1159 int ret, err;
1161 ret = WSAStartup(MAKEWORD(2,2), &Data);
1162 if (ret != 0) {
1163 err = WSAGetLastError();
1164 fprintf(stderr, "WSAStartup: %d\n", err);
1165 return -1;
1167 atexit(socket_cleanup);
1168 return 0;
1171 static int send_all(int fd, const uint8_t *buf, int len1)
1173 int ret, len;
1175 len = len1;
1176 while (len > 0) {
1177 ret = send(fd, buf, len, 0);
1178 if (ret < 0) {
1179 int errno;
1180 errno = WSAGetLastError();
1181 if (errno != WSAEWOULDBLOCK) {
1182 return -1;
1184 } else if (ret == 0) {
1185 break;
1186 } else {
1187 buf += ret;
1188 len -= ret;
1191 return len1 - len;
1194 void socket_set_nonblock(int fd)
1196 unsigned long opt = 1;
1197 ioctlsocket(fd, FIONBIO, &opt);
1200 #else
1202 static int unix_write(int fd, const uint8_t *buf, int len1)
1204 int ret, sel_ret, len;
1205 int max_fd;
1206 fd_set writefds;
1207 struct timeval timeout;
1209 max_fd = fd;
1211 len = len1;
1212 while (len > 0) {
1213 FD_ZERO(&writefds);
1214 FD_SET(fd, &writefds);
1215 timeout.tv_sec = 0;
1216 timeout.tv_usec = 0;
1217 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1218 if (sel_ret <= 0) {
1219 /* Timeout or select error */
1220 return -1;
1221 } else {
1222 ret = write(fd, buf, len);
1223 if (ret < 0) {
1224 if (errno != EINTR && errno != EAGAIN)
1225 return -1;
1226 } else if (ret == 0) {
1227 break;
1228 } else {
1229 buf += ret;
1230 len -= ret;
1234 return len1 - len;
1237 static inline int send_all(int fd, const uint8_t *buf, int len1)
1239 return unix_write(fd, buf, len1);
1242 void socket_set_nonblock(int fd)
1244 fcntl(fd, F_SETFL, O_NONBLOCK);
1246 #endif /* !_WIN32 */
1248 #ifndef _WIN32
1250 typedef struct {
1251 int fd_in, fd_out;
1252 IOCanRWHandler *fd_can_read;
1253 IOReadHandler *fd_read;
1254 void *fd_opaque;
1255 int max_size;
1256 } FDCharDriver;
1258 #define STDIO_MAX_CLIENTS 2
1260 static int stdio_nb_clients;
1261 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1263 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1265 FDCharDriver *s = chr->opaque;
1266 return unix_write(s->fd_out, buf, len);
1269 static int fd_chr_read_poll(void *opaque)
1271 CharDriverState *chr = opaque;
1272 FDCharDriver *s = chr->opaque;
1274 s->max_size = s->fd_can_read(s->fd_opaque);
1275 return s->max_size;
1278 static void fd_chr_read(void *opaque)
1280 CharDriverState *chr = opaque;
1281 FDCharDriver *s = chr->opaque;
1282 int size, len;
1283 uint8_t buf[1024];
1285 len = sizeof(buf);
1286 if (len > s->max_size)
1287 len = s->max_size;
1288 if (len == 0)
1289 return;
1290 size = read(s->fd_in, buf, len);
1291 if (size > 0) {
1292 s->fd_read(s->fd_opaque, buf, size);
1296 static void fd_chr_add_read_handler(CharDriverState *chr,
1297 IOCanRWHandler *fd_can_read,
1298 IOReadHandler *fd_read, void *opaque)
1300 FDCharDriver *s = chr->opaque;
1302 if (s->fd_in >= 0) {
1303 s->fd_can_read = fd_can_read;
1304 s->fd_read = fd_read;
1305 s->fd_opaque = opaque;
1306 if (nographic && s->fd_in == 0) {
1307 } else {
1308 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1309 fd_chr_read, NULL, chr);
1314 /* open a character device to a unix fd */
1315 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1317 CharDriverState *chr;
1318 FDCharDriver *s;
1320 chr = qemu_mallocz(sizeof(CharDriverState));
1321 if (!chr)
1322 return NULL;
1323 s = qemu_mallocz(sizeof(FDCharDriver));
1324 if (!s) {
1325 free(chr);
1326 return NULL;
1328 s->fd_in = fd_in;
1329 s->fd_out = fd_out;
1330 chr->opaque = s;
1331 chr->chr_write = fd_chr_write;
1332 chr->chr_add_read_handler = fd_chr_add_read_handler;
1333 return chr;
1336 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1338 int fd_out;
1340 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1341 if (fd_out < 0)
1342 return NULL;
1343 return qemu_chr_open_fd(-1, fd_out);
1346 CharDriverState *qemu_chr_open_pipe(const char *filename)
1348 int fd;
1350 fd = open(filename, O_RDWR | O_BINARY);
1351 if (fd < 0)
1352 return NULL;
1353 return qemu_chr_open_fd(fd, fd);
1357 /* for STDIO, we handle the case where several clients use it
1358 (nographic mode) */
1360 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1362 #define TERM_FIFO_MAX_SIZE 1
1364 static int term_got_escape, client_index;
1365 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1366 static int term_fifo_size;
1367 static int term_timestamps;
1368 static int64_t term_timestamps_start;
1370 void term_print_help(void)
1372 printf("\n"
1373 "C-a h print this help\n"
1374 "C-a x exit emulator\n"
1375 "C-a s save disk data back to file (if -snapshot)\n"
1376 "C-a b send break (magic sysrq)\n"
1377 "C-a t toggle console timestamps\n"
1378 "C-a c switch between console and monitor\n"
1379 "C-a C-a send C-a\n"
1380 );
1383 /* called when a char is received */
1384 static void stdio_received_byte(int ch)
1386 if (term_got_escape) {
1387 term_got_escape = 0;
1388 switch(ch) {
1389 case 'h':
1390 term_print_help();
1391 break;
1392 case 'x':
1393 exit(0);
1394 break;
1395 case 's':
1397 int i;
1398 for (i = 0; i < MAX_DISKS; i++) {
1399 if (bs_table[i])
1400 bdrv_commit(bs_table[i]);
1403 break;
1404 case 'b':
1405 if (client_index < stdio_nb_clients) {
1406 CharDriverState *chr;
1407 FDCharDriver *s;
1409 chr = stdio_clients[client_index];
1410 s = chr->opaque;
1411 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1413 break;
1414 case 'c':
1415 client_index++;
1416 if (client_index >= stdio_nb_clients)
1417 client_index = 0;
1418 if (client_index == 0) {
1419 /* send a new line in the monitor to get the prompt */
1420 ch = '\r';
1421 goto send_char;
1423 break;
1424 case 't':
1425 term_timestamps = !term_timestamps;
1426 term_timestamps_start = -1;
1427 break;
1428 case TERM_ESCAPE:
1429 goto send_char;
1431 } else if (ch == TERM_ESCAPE) {
1432 term_got_escape = 1;
1433 } else {
1434 send_char:
1435 if (client_index < stdio_nb_clients) {
1436 uint8_t buf[1];
1437 CharDriverState *chr;
1438 FDCharDriver *s;
1440 chr = stdio_clients[client_index];
1441 s = chr->opaque;
1442 if (s->fd_can_read(s->fd_opaque) > 0) {
1443 buf[0] = ch;
1444 s->fd_read(s->fd_opaque, buf, 1);
1445 } else if (term_fifo_size == 0) {
1446 term_fifo[term_fifo_size++] = ch;
1452 static int stdio_read_poll(void *opaque)
1454 CharDriverState *chr;
1455 FDCharDriver *s;
1457 if (client_index < stdio_nb_clients) {
1458 chr = stdio_clients[client_index];
1459 s = chr->opaque;
1460 /* try to flush the queue if needed */
1461 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1462 s->fd_read(s->fd_opaque, term_fifo, 1);
1463 term_fifo_size = 0;
1465 /* see if we can absorb more chars */
1466 if (term_fifo_size == 0)
1467 return 1;
1468 else
1469 return 0;
1470 } else {
1471 return 1;
1475 static void stdio_read(void *opaque)
1477 int size;
1478 uint8_t buf[1];
1480 size = read(0, buf, 1);
1481 if (size > 0)
1482 stdio_received_byte(buf[0]);
1485 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1487 FDCharDriver *s = chr->opaque;
1488 if (!term_timestamps) {
1489 return unix_write(s->fd_out, buf, len);
1490 } else {
1491 int i;
1492 char buf1[64];
1494 for(i = 0; i < len; i++) {
1495 unix_write(s->fd_out, buf + i, 1);
1496 if (buf[i] == '\n') {
1497 int64_t ti;
1498 int secs;
1500 ti = get_clock();
1501 if (term_timestamps_start == -1)
1502 term_timestamps_start = ti;
1503 ti -= term_timestamps_start;
1504 secs = ti / 1000000000;
1505 snprintf(buf1, sizeof(buf1),
1506 "[%02d:%02d:%02d.%03d] ",
1507 secs / 3600,
1508 (secs / 60) % 60,
1509 secs % 60,
1510 (int)((ti / 1000000) % 1000));
1511 unix_write(s->fd_out, buf1, strlen(buf1));
1514 return len;
1518 /* init terminal so that we can grab keys */
1519 static struct termios oldtty;
1520 static int old_fd0_flags;
1522 static void term_exit(void)
1524 tcsetattr (0, TCSANOW, &oldtty);
1525 fcntl(0, F_SETFL, old_fd0_flags);
1528 static void term_init(void)
1530 struct termios tty;
1532 tcgetattr (0, &tty);
1533 oldtty = tty;
1534 old_fd0_flags = fcntl(0, F_GETFL);
1536 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1537 |INLCR|IGNCR|ICRNL|IXON);
1538 tty.c_oflag |= OPOST;
1539 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1540 /* if graphical mode, we allow Ctrl-C handling */
1541 if (nographic)
1542 tty.c_lflag &= ~ISIG;
1543 tty.c_cflag &= ~(CSIZE|PARENB);
1544 tty.c_cflag |= CS8;
1545 tty.c_cc[VMIN] = 1;
1546 tty.c_cc[VTIME] = 0;
1548 tcsetattr (0, TCSANOW, &tty);
1550 atexit(term_exit);
1552 fcntl(0, F_SETFL, O_NONBLOCK);
1555 CharDriverState *qemu_chr_open_stdio(void)
1557 CharDriverState *chr;
1559 if (nographic) {
1560 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1561 return NULL;
1562 chr = qemu_chr_open_fd(0, 1);
1563 chr->chr_write = stdio_write;
1564 if (stdio_nb_clients == 0)
1565 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1566 client_index = stdio_nb_clients;
1567 } else {
1568 if (stdio_nb_clients != 0)
1569 return NULL;
1570 chr = qemu_chr_open_fd(0, 1);
1572 stdio_clients[stdio_nb_clients++] = chr;
1573 if (stdio_nb_clients == 1) {
1574 /* set the terminal in raw mode */
1575 term_init();
1577 return chr;
1580 /*
1581 * Create a store entry for a device (e.g., monitor, serial/parallel lines).
1582 * The entry is <domain-path><storeString>/tty and the value is the name
1583 * of the pty associated with the device.
1584 */
1585 static int store_dev_info(char *devName, int domid,
1586 CharDriverState *cState, char *storeString)
1588 int xc_handle;
1589 struct xs_handle *xs;
1590 char *path;
1591 char *newpath;
1592 FDCharDriver *s;
1593 char *pts;
1595 /* Check for valid arguments (at least, prevent segfaults). */
1596 if ((devName == NULL) || (cState == NULL) || (storeString == NULL)) {
1597 fprintf(logfile, "%s - invalid arguments\n", __FUNCTION__);
1598 return EINVAL;
1601 /*
1602 * Only continue if we're talking to a pty
1603 * Actually, the following code works for any CharDriverState using
1604 * FDCharDriver, but we really only care about pty's here
1605 */
1606 if (strcmp(devName, "pty"))
1607 return 0;
1609 s = cState->opaque;
1610 if (s == NULL) {
1611 fprintf(logfile, "%s - unable to retrieve fd for '%s'/'%s'\n",
1612 __FUNCTION__, storeString, devName);
1613 return EBADF;
1616 pts = ptsname(s->fd_in);
1617 if (pts == NULL) {
1618 fprintf(logfile, "%s - unable to determine ptsname '%s'/'%s', "
1619 "error %d (%s)\n",
1620 __FUNCTION__, storeString, devName, errno, strerror(errno));
1621 return errno;
1624 /* We now have everything we need to set the xenstore entry. */
1625 xs = xs_daemon_open();
1626 if (xs == NULL) {
1627 fprintf(logfile, "Could not contact XenStore\n");
1628 return -1;
1631 xc_handle = xc_interface_open();
1632 if (xc_handle == -1) {
1633 fprintf(logfile, "xc_interface_open() error\n");
1634 return -1;
1637 path = xs_get_domain_path(xs, domid);
1638 if (path == NULL) {
1639 fprintf(logfile, "xs_get_domain_path() error\n");
1640 return -1;
1642 newpath = realloc(path, (strlen(path) + strlen(storeString) +
1643 strlen("/tty") + 1));
1644 if (newpath == NULL) {
1645 free(path); /* realloc errors leave old block */
1646 fprintf(logfile, "realloc error\n");
1647 return -1;
1649 path = newpath;
1651 strcat(path, storeString);
1652 strcat(path, "/tty");
1653 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1654 fprintf(logfile, "xs_write for '%s' fail", storeString);
1655 return -1;
1658 free(path);
1659 xs_daemon_close(xs);
1660 close(xc_handle);
1662 return 0;
1665 #if defined(__linux__)
1666 CharDriverState *qemu_chr_open_pty(void)
1668 struct termios tty;
1669 int master_fd, slave_fd;
1671 /* Not satisfying */
1672 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1673 return NULL;
1676 /* Set raw attributes on the pty. */
1677 cfmakeraw(&tty);
1678 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1680 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1682 return qemu_chr_open_fd(master_fd, master_fd);
1685 static void tty_serial_init(int fd, int speed,
1686 int parity, int data_bits, int stop_bits)
1688 struct termios tty;
1689 speed_t spd;
1691 #if 0
1692 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1693 speed, parity, data_bits, stop_bits);
1694 #endif
1695 tcgetattr (fd, &tty);
1697 switch(speed) {
1698 case 50:
1699 spd = B50;
1700 break;
1701 case 75:
1702 spd = B75;
1703 break;
1704 case 300:
1705 spd = B300;
1706 break;
1707 case 600:
1708 spd = B600;
1709 break;
1710 case 1200:
1711 spd = B1200;
1712 break;
1713 case 2400:
1714 spd = B2400;
1715 break;
1716 case 4800:
1717 spd = B4800;
1718 break;
1719 case 9600:
1720 spd = B9600;
1721 break;
1722 case 19200:
1723 spd = B19200;
1724 break;
1725 case 38400:
1726 spd = B38400;
1727 break;
1728 case 57600:
1729 spd = B57600;
1730 break;
1731 default:
1732 case 115200:
1733 spd = B115200;
1734 break;
1737 cfsetispeed(&tty, spd);
1738 cfsetospeed(&tty, spd);
1740 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1741 |INLCR|IGNCR|ICRNL|IXON);
1742 tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1743 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1744 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1745 switch(data_bits) {
1746 default:
1747 case 8:
1748 tty.c_cflag |= CS8;
1749 break;
1750 case 7:
1751 tty.c_cflag |= CS7;
1752 break;
1753 case 6:
1754 tty.c_cflag |= CS6;
1755 break;
1756 case 5:
1757 tty.c_cflag |= CS5;
1758 break;
1760 switch(parity) {
1761 default:
1762 case 'N':
1763 break;
1764 case 'E':
1765 tty.c_cflag |= PARENB;
1766 break;
1767 case 'O':
1768 tty.c_cflag |= PARENB | PARODD;
1769 break;
1772 tcsetattr (fd, TCSANOW, &tty);
1775 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1777 FDCharDriver *s = chr->opaque;
1779 switch(cmd) {
1780 case CHR_IOCTL_SERIAL_SET_PARAMS:
1782 QEMUSerialSetParams *ssp = arg;
1783 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1784 ssp->data_bits, ssp->stop_bits);
1786 break;
1787 case CHR_IOCTL_SERIAL_SET_BREAK:
1789 int enable = *(int *)arg;
1790 if (enable)
1791 tcsendbreak(s->fd_in, 1);
1793 break;
1794 default:
1795 return -ENOTSUP;
1797 return 0;
1800 CharDriverState *qemu_chr_open_tty(const char *filename)
1802 CharDriverState *chr;
1803 int fd;
1805 fd = open(filename, O_RDWR | O_NONBLOCK);
1806 if (fd < 0)
1807 return NULL;
1808 fcntl(fd, F_SETFL, O_NONBLOCK);
1809 tty_serial_init(fd, 115200, 'N', 8, 1);
1810 chr = qemu_chr_open_fd(fd, fd);
1811 if (!chr)
1812 return NULL;
1813 chr->chr_ioctl = tty_serial_ioctl;
1814 return chr;
1817 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1819 int fd = (int)chr->opaque;
1820 uint8_t b;
1822 switch(cmd) {
1823 case CHR_IOCTL_PP_READ_DATA:
1824 if (ioctl(fd, PPRDATA, &b) < 0)
1825 return -ENOTSUP;
1826 *(uint8_t *)arg = b;
1827 break;
1828 case CHR_IOCTL_PP_WRITE_DATA:
1829 b = *(uint8_t *)arg;
1830 if (ioctl(fd, PPWDATA, &b) < 0)
1831 return -ENOTSUP;
1832 break;
1833 case CHR_IOCTL_PP_READ_CONTROL:
1834 if (ioctl(fd, PPRCONTROL, &b) < 0)
1835 return -ENOTSUP;
1836 *(uint8_t *)arg = b;
1837 break;
1838 case CHR_IOCTL_PP_WRITE_CONTROL:
1839 b = *(uint8_t *)arg;
1840 if (ioctl(fd, PPWCONTROL, &b) < 0)
1841 return -ENOTSUP;
1842 break;
1843 case CHR_IOCTL_PP_READ_STATUS:
1844 if (ioctl(fd, PPRSTATUS, &b) < 0)
1845 return -ENOTSUP;
1846 *(uint8_t *)arg = b;
1847 break;
1848 default:
1849 return -ENOTSUP;
1851 return 0;
1854 CharDriverState *qemu_chr_open_pp(const char *filename)
1856 CharDriverState *chr;
1857 int fd;
1859 fd = open(filename, O_RDWR);
1860 if (fd < 0)
1861 return NULL;
1863 if (ioctl(fd, PPCLAIM) < 0) {
1864 close(fd);
1865 return NULL;
1868 chr = qemu_mallocz(sizeof(CharDriverState));
1869 if (!chr) {
1870 close(fd);
1871 return NULL;
1873 chr->opaque = (void *)fd;
1874 chr->chr_write = null_chr_write;
1875 chr->chr_add_read_handler = null_chr_add_read_handler;
1876 chr->chr_ioctl = pp_ioctl;
1877 return chr;
1880 #else
1881 CharDriverState *qemu_chr_open_pty(void)
1883 return NULL;
1885 #endif
1887 #endif /* !defined(_WIN32) */
1889 #ifdef _WIN32
1890 typedef struct {
1891 IOCanRWHandler *fd_can_read;
1892 IOReadHandler *fd_read;
1893 void *win_opaque;
1894 int max_size;
1895 HANDLE hcom, hrecv, hsend;
1896 OVERLAPPED orecv, osend;
1897 BOOL fpipe;
1898 DWORD len;
1899 } WinCharState;
1901 #define NSENDBUF 2048
1902 #define NRECVBUF 2048
1903 #define MAXCONNECT 1
1904 #define NTIMEOUT 5000
1906 static int win_chr_poll(void *opaque);
1907 static int win_chr_pipe_poll(void *opaque);
1909 static void win_chr_close2(WinCharState *s)
1911 if (s->hsend) {
1912 CloseHandle(s->hsend);
1913 s->hsend = NULL;
1915 if (s->hrecv) {
1916 CloseHandle(s->hrecv);
1917 s->hrecv = NULL;
1919 if (s->hcom) {
1920 CloseHandle(s->hcom);
1921 s->hcom = NULL;
1923 if (s->fpipe)
1924 qemu_del_polling_cb(win_chr_pipe_poll, s);
1925 else
1926 qemu_del_polling_cb(win_chr_poll, s);
1929 static void win_chr_close(CharDriverState *chr)
1931 WinCharState *s = chr->opaque;
1932 win_chr_close2(s);
1935 static int win_chr_init(WinCharState *s, const char *filename)
1937 COMMCONFIG comcfg;
1938 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1939 COMSTAT comstat;
1940 DWORD size;
1941 DWORD err;
1943 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1944 if (!s->hsend) {
1945 fprintf(stderr, "Failed CreateEvent\n");
1946 goto fail;
1948 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1949 if (!s->hrecv) {
1950 fprintf(stderr, "Failed CreateEvent\n");
1951 goto fail;
1954 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1955 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1956 if (s->hcom == INVALID_HANDLE_VALUE) {
1957 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1958 s->hcom = NULL;
1959 goto fail;
1962 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1963 fprintf(stderr, "Failed SetupComm\n");
1964 goto fail;
1967 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1968 size = sizeof(COMMCONFIG);
1969 GetDefaultCommConfig(filename, &comcfg, &size);
1970 comcfg.dcb.DCBlength = sizeof(DCB);
1971 CommConfigDialog(filename, NULL, &comcfg);
1973 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1974 fprintf(stderr, "Failed SetCommState\n");
1975 goto fail;
1978 if (!SetCommMask(s->hcom, EV_ERR)) {
1979 fprintf(stderr, "Failed SetCommMask\n");
1980 goto fail;
1983 cto.ReadIntervalTimeout = MAXDWORD;
1984 if (!SetCommTimeouts(s->hcom, &cto)) {
1985 fprintf(stderr, "Failed SetCommTimeouts\n");
1986 goto fail;
1989 if (!ClearCommError(s->hcom, &err, &comstat)) {
1990 fprintf(stderr, "Failed ClearCommError\n");
1991 goto fail;
1993 qemu_add_polling_cb(win_chr_poll, s);
1994 return 0;
1996 fail:
1997 win_chr_close2(s);
1998 return -1;
2001 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2003 WinCharState *s = chr->opaque;
2004 DWORD len, ret, size, err;
2006 len = len1;
2007 ZeroMemory(&s->osend, sizeof(s->osend));
2008 s->osend.hEvent = s->hsend;
2009 while (len > 0) {
2010 if (s->hsend)
2011 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2012 else
2013 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2014 if (!ret) {
2015 err = GetLastError();
2016 if (err == ERROR_IO_PENDING) {
2017 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2018 if (ret) {
2019 buf += size;
2020 len -= size;
2021 } else {
2022 break;
2024 } else {
2025 break;
2027 } else {
2028 buf += size;
2029 len -= size;
2032 return len1 - len;
2035 static int win_chr_read_poll(WinCharState *s)
2037 s->max_size = s->fd_can_read(s->win_opaque);
2038 return s->max_size;
2041 static void win_chr_readfile(WinCharState *s)
2043 int ret, err;
2044 uint8_t buf[1024];
2045 DWORD size;
2047 ZeroMemory(&s->orecv, sizeof(s->orecv));
2048 s->orecv.hEvent = s->hrecv;
2049 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2050 if (!ret) {
2051 err = GetLastError();
2052 if (err == ERROR_IO_PENDING) {
2053 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2057 if (size > 0) {
2058 s->fd_read(s->win_opaque, buf, size);
2062 static void win_chr_read(WinCharState *s)
2064 if (s->len > s->max_size)
2065 s->len = s->max_size;
2066 if (s->len == 0)
2067 return;
2069 win_chr_readfile(s);
2072 static int win_chr_poll(void *opaque)
2074 WinCharState *s = opaque;
2075 COMSTAT status;
2076 DWORD comerr;
2078 ClearCommError(s->hcom, &comerr, &status);
2079 if (status.cbInQue > 0) {
2080 s->len = status.cbInQue;
2081 win_chr_read_poll(s);
2082 win_chr_read(s);
2083 return 1;
2085 return 0;
2088 static void win_chr_add_read_handler(CharDriverState *chr,
2089 IOCanRWHandler *fd_can_read,
2090 IOReadHandler *fd_read, void *opaque)
2092 WinCharState *s = chr->opaque;
2094 s->fd_can_read = fd_can_read;
2095 s->fd_read = fd_read;
2096 s->win_opaque = opaque;
2099 CharDriverState *qemu_chr_open_win(const char *filename)
2101 CharDriverState *chr;
2102 WinCharState *s;
2104 chr = qemu_mallocz(sizeof(CharDriverState));
2105 if (!chr)
2106 return NULL;
2107 s = qemu_mallocz(sizeof(WinCharState));
2108 if (!s) {
2109 free(chr);
2110 return NULL;
2112 chr->opaque = s;
2113 chr->chr_write = win_chr_write;
2114 chr->chr_add_read_handler = win_chr_add_read_handler;
2115 chr->chr_close = win_chr_close;
2117 if (win_chr_init(s, filename) < 0) {
2118 free(s);
2119 free(chr);
2120 return NULL;
2122 return chr;
2125 static int win_chr_pipe_poll(void *opaque)
2127 WinCharState *s = opaque;
2128 DWORD size;
2130 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2131 if (size > 0) {
2132 s->len = size;
2133 win_chr_read_poll(s);
2134 win_chr_read(s);
2135 return 1;
2137 return 0;
2140 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2142 OVERLAPPED ov;
2143 int ret;
2144 DWORD size;
2145 char openname[256];
2147 s->fpipe = TRUE;
2149 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2150 if (!s->hsend) {
2151 fprintf(stderr, "Failed CreateEvent\n");
2152 goto fail;
2154 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2155 if (!s->hrecv) {
2156 fprintf(stderr, "Failed CreateEvent\n");
2157 goto fail;
2160 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2161 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2162 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2163 PIPE_WAIT,
2164 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2165 if (s->hcom == INVALID_HANDLE_VALUE) {
2166 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2167 s->hcom = NULL;
2168 goto fail;
2171 ZeroMemory(&ov, sizeof(ov));
2172 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2173 ret = ConnectNamedPipe(s->hcom, &ov);
2174 if (ret) {
2175 fprintf(stderr, "Failed ConnectNamedPipe\n");
2176 goto fail;
2179 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2180 if (!ret) {
2181 fprintf(stderr, "Failed GetOverlappedResult\n");
2182 if (ov.hEvent) {
2183 CloseHandle(ov.hEvent);
2184 ov.hEvent = NULL;
2186 goto fail;
2189 if (ov.hEvent) {
2190 CloseHandle(ov.hEvent);
2191 ov.hEvent = NULL;
2193 qemu_add_polling_cb(win_chr_pipe_poll, s);
2194 return 0;
2196 fail:
2197 win_chr_close2(s);
2198 return -1;
2202 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2204 CharDriverState *chr;
2205 WinCharState *s;
2207 chr = qemu_mallocz(sizeof(CharDriverState));
2208 if (!chr)
2209 return NULL;
2210 s = qemu_mallocz(sizeof(WinCharState));
2211 if (!s) {
2212 free(chr);
2213 return NULL;
2215 chr->opaque = s;
2216 chr->chr_write = win_chr_write;
2217 chr->chr_add_read_handler = win_chr_add_read_handler;
2218 chr->chr_close = win_chr_close;
2220 if (win_chr_pipe_init(s, filename) < 0) {
2221 free(s);
2222 free(chr);
2223 return NULL;
2225 return chr;
2228 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2230 CharDriverState *chr;
2231 WinCharState *s;
2233 chr = qemu_mallocz(sizeof(CharDriverState));
2234 if (!chr)
2235 return NULL;
2236 s = qemu_mallocz(sizeof(WinCharState));
2237 if (!s) {
2238 free(chr);
2239 return NULL;
2241 s->hcom = fd_out;
2242 chr->opaque = s;
2243 chr->chr_write = win_chr_write;
2244 chr->chr_add_read_handler = win_chr_add_read_handler;
2245 return chr;
2248 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2250 HANDLE fd_out;
2252 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2253 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2254 if (fd_out == INVALID_HANDLE_VALUE)
2255 return NULL;
2257 return qemu_chr_open_win_file(fd_out);
2259 #endif
2261 /***********************************************************/
2262 /* UDP Net console */
2264 typedef struct {
2265 IOCanRWHandler *fd_can_read;
2266 IOReadHandler *fd_read;
2267 void *fd_opaque;
2268 int fd;
2269 struct sockaddr_in daddr;
2270 char buf[1024];
2271 int bufcnt;
2272 int bufptr;
2273 int max_size;
2274 } NetCharDriver;
2276 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2278 NetCharDriver *s = chr->opaque;
2280 return sendto(s->fd, buf, len, 0,
2281 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2284 static int udp_chr_read_poll(void *opaque)
2286 CharDriverState *chr = opaque;
2287 NetCharDriver *s = chr->opaque;
2289 s->max_size = s->fd_can_read(s->fd_opaque);
2291 /* If there were any stray characters in the queue process them
2292 * first
2293 */
2294 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2295 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2296 s->bufptr++;
2297 s->max_size = s->fd_can_read(s->fd_opaque);
2299 return s->max_size;
2302 static void udp_chr_read(void *opaque)
2304 CharDriverState *chr = opaque;
2305 NetCharDriver *s = chr->opaque;
2307 if (s->max_size == 0)
2308 return;
2309 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2310 s->bufptr = s->bufcnt;
2311 if (s->bufcnt <= 0)
2312 return;
2314 s->bufptr = 0;
2315 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2316 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2317 s->bufptr++;
2318 s->max_size = s->fd_can_read(s->fd_opaque);
2322 static void udp_chr_add_read_handler(CharDriverState *chr,
2323 IOCanRWHandler *fd_can_read,
2324 IOReadHandler *fd_read, void *opaque)
2326 NetCharDriver *s = chr->opaque;
2328 if (s->fd >= 0) {
2329 s->fd_can_read = fd_can_read;
2330 s->fd_read = fd_read;
2331 s->fd_opaque = opaque;
2332 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2333 udp_chr_read, NULL, chr);
2337 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2338 int parse_host_src_port(struct sockaddr_in *haddr,
2339 struct sockaddr_in *saddr,
2340 const char *str);
2342 CharDriverState *qemu_chr_open_udp(const char *def)
2344 CharDriverState *chr = NULL;
2345 NetCharDriver *s = NULL;
2346 int fd = -1;
2347 struct sockaddr_in saddr;
2349 chr = qemu_mallocz(sizeof(CharDriverState));
2350 if (!chr)
2351 goto return_err;
2352 s = qemu_mallocz(sizeof(NetCharDriver));
2353 if (!s)
2354 goto return_err;
2356 fd = socket(PF_INET, SOCK_DGRAM, 0);
2357 if (fd < 0) {
2358 perror("socket(PF_INET, SOCK_DGRAM)");
2359 goto return_err;
2362 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2363 printf("Could not parse: %s\n", def);
2364 goto return_err;
2367 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2369 perror("bind");
2370 goto return_err;
2373 s->fd = fd;
2374 s->bufcnt = 0;
2375 s->bufptr = 0;
2376 chr->opaque = s;
2377 chr->chr_write = udp_chr_write;
2378 chr->chr_add_read_handler = udp_chr_add_read_handler;
2379 return chr;
2381 return_err:
2382 if (chr)
2383 free(chr);
2384 if (s)
2385 free(s);
2386 if (fd >= 0)
2387 closesocket(fd);
2388 return NULL;
2391 /***********************************************************/
2392 /* TCP Net console */
2394 typedef struct {
2395 IOCanRWHandler *fd_can_read;
2396 IOReadHandler *fd_read;
2397 void *fd_opaque;
2398 int fd, listen_fd;
2399 int connected;
2400 int max_size;
2401 int do_telnetopt;
2402 } TCPCharDriver;
2404 static void tcp_chr_accept(void *opaque);
2406 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2408 TCPCharDriver *s = chr->opaque;
2409 if (s->connected) {
2410 return send_all(s->fd, buf, len);
2411 } else {
2412 /* XXX: indicate an error ? */
2413 return len;
2417 static int tcp_chr_read_poll(void *opaque)
2419 CharDriverState *chr = opaque;
2420 TCPCharDriver *s = chr->opaque;
2421 if (!s->connected)
2422 return 0;
2423 s->max_size = s->fd_can_read(s->fd_opaque);
2424 return s->max_size;
2427 #define IAC 255
2428 #define IAC_BREAK 243
2429 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2430 TCPCharDriver *s,
2431 char *buf, int *size)
2433 /* Handle any telnet client's basic IAC options to satisfy char by
2434 * char mode with no echo. All IAC options will be removed from
2435 * the buf and the do_telnetopt variable will be used to track the
2436 * state of the width of the IAC information.
2438 * IAC commands come in sets of 3 bytes with the exception of the
2439 * "IAC BREAK" command and the double IAC.
2440 */
2442 int i;
2443 int j = 0;
2445 for (i = 0; i < *size; i++) {
2446 if (s->do_telnetopt > 1) {
2447 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2448 /* Double IAC means send an IAC */
2449 if (j != i)
2450 buf[j] = buf[i];
2451 j++;
2452 s->do_telnetopt = 1;
2453 } else {
2454 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2455 /* Handle IAC break commands by sending a serial break */
2456 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2457 s->do_telnetopt++;
2459 s->do_telnetopt++;
2461 if (s->do_telnetopt >= 4) {
2462 s->do_telnetopt = 1;
2464 } else {
2465 if ((unsigned char)buf[i] == IAC) {
2466 s->do_telnetopt = 2;
2467 } else {
2468 if (j != i)
2469 buf[j] = buf[i];
2470 j++;
2474 *size = j;
2477 static void tcp_chr_read(void *opaque)
2479 CharDriverState *chr = opaque;
2480 TCPCharDriver *s = chr->opaque;
2481 uint8_t buf[1024];
2482 int len, size;
2484 if (!s->connected || s->max_size <= 0)
2485 return;
2486 len = sizeof(buf);
2487 if (len > s->max_size)
2488 len = s->max_size;
2489 size = recv(s->fd, buf, len, 0);
2490 if (size == 0) {
2491 /* connection closed */
2492 s->connected = 0;
2493 if (s->listen_fd >= 0) {
2494 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2496 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2497 closesocket(s->fd);
2498 s->fd = -1;
2499 } else if (size > 0) {
2500 if (s->do_telnetopt)
2501 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2502 if (size > 0)
2503 s->fd_read(s->fd_opaque, buf, size);
2507 static void tcp_chr_add_read_handler(CharDriverState *chr,
2508 IOCanRWHandler *fd_can_read,
2509 IOReadHandler *fd_read, void *opaque)
2511 TCPCharDriver *s = chr->opaque;
2513 s->fd_can_read = fd_can_read;
2514 s->fd_read = fd_read;
2515 s->fd_opaque = opaque;
2518 static void tcp_chr_connect(void *opaque)
2520 CharDriverState *chr = opaque;
2521 TCPCharDriver *s = chr->opaque;
2523 s->connected = 1;
2524 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2525 tcp_chr_read, NULL, chr);
2528 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2529 static void tcp_chr_telnet_init(int fd)
2531 char buf[3];
2532 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2533 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2534 send(fd, (char *)buf, 3, 0);
2535 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2536 send(fd, (char *)buf, 3, 0);
2537 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2538 send(fd, (char *)buf, 3, 0);
2539 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2540 send(fd, (char *)buf, 3, 0);
2543 static void tcp_chr_accept(void *opaque)
2545 CharDriverState *chr = opaque;
2546 TCPCharDriver *s = chr->opaque;
2547 struct sockaddr_in saddr;
2548 socklen_t len;
2549 int fd;
2551 for(;;) {
2552 len = sizeof(saddr);
2553 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2554 if (fd < 0 && errno != EINTR) {
2555 return;
2556 } else if (fd >= 0) {
2557 if (s->do_telnetopt)
2558 tcp_chr_telnet_init(fd);
2559 break;
2562 socket_set_nonblock(fd);
2563 s->fd = fd;
2564 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2565 tcp_chr_connect(chr);
2568 static void tcp_chr_close(CharDriverState *chr)
2570 TCPCharDriver *s = chr->opaque;
2571 if (s->fd >= 0)
2572 closesocket(s->fd);
2573 if (s->listen_fd >= 0)
2574 closesocket(s->listen_fd);
2575 qemu_free(s);
2578 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2579 int is_telnet)
2581 CharDriverState *chr = NULL;
2582 TCPCharDriver *s = NULL;
2583 int fd = -1, ret, err, val;
2584 int is_listen = 0;
2585 int is_waitconnect = 1;
2586 const char *ptr;
2587 struct sockaddr_in saddr;
2588 int opt;
2590 if (parse_host_port(&saddr, host_str) < 0)
2591 goto fail;
2593 ptr = host_str;
2594 while((ptr = strchr(ptr,','))) {
2595 ptr++;
2596 if (!strncmp(ptr,"server",6)) {
2597 is_listen = 1;
2598 } else if (!strncmp(ptr,"nowait",6)) {
2599 is_waitconnect = 0;
2600 } else {
2601 printf("Unknown option: %s\n", ptr);
2602 goto fail;
2605 if (!is_listen)
2606 is_waitconnect = 0;
2608 chr = qemu_mallocz(sizeof(CharDriverState));
2609 if (!chr)
2610 goto fail;
2611 s = qemu_mallocz(sizeof(TCPCharDriver));
2612 if (!s)
2613 goto fail;
2615 fd = socket(PF_INET, SOCK_STREAM, 0);
2616 if (fd < 0)
2617 goto fail;
2619 if (!is_waitconnect)
2620 socket_set_nonblock(fd);
2622 s->connected = 0;
2623 s->fd = -1;
2624 s->listen_fd = -1;
2625 if (is_listen) {
2626 /* allow fast reuse */
2627 val = 1;
2628 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2630 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2631 if (ret < 0)
2632 goto fail;
2633 ret = listen(fd, 0);
2634 if (ret < 0)
2635 goto fail;
2636 s->listen_fd = fd;
2637 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2638 if (is_telnet)
2639 s->do_telnetopt = 1;
2640 } else {
2641 for(;;) {
2642 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2643 if (ret < 0) {
2644 err = socket_error();
2645 if (err == EINTR || err == EWOULDBLOCK) {
2646 } else if (err == EINPROGRESS) {
2647 break;
2648 } else {
2649 goto fail;
2651 } else {
2652 s->connected = 1;
2653 break;
2656 s->fd = fd;
2657 opt = 1;
2658 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
2659 if (s->connected)
2660 tcp_chr_connect(chr);
2661 else
2662 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2665 chr->opaque = s;
2666 chr->chr_write = tcp_chr_write;
2667 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2668 chr->chr_close = tcp_chr_close;
2669 if (is_listen && is_waitconnect) {
2670 printf("QEMU waiting for connection on: %s\n", host_str);
2671 tcp_chr_accept(chr);
2672 socket_set_nonblock(s->listen_fd);
2675 return chr;
2676 fail:
2677 if (fd >= 0)
2678 closesocket(fd);
2679 qemu_free(s);
2680 qemu_free(chr);
2681 return NULL;
2684 CharDriverState *qemu_chr_open(const char *filename)
2686 const char *p;
2688 if (!strcmp(filename, "vc")) {
2689 return text_console_init(&display_state);
2690 } else if (!strcmp(filename, "null")) {
2691 return qemu_chr_open_null();
2692 } else
2693 if (strstart(filename, "tcp:", &p)) {
2694 return qemu_chr_open_tcp(p, 0);
2695 } else
2696 if (strstart(filename, "telnet:", &p)) {
2697 return qemu_chr_open_tcp(p, 1);
2698 } else
2699 if (strstart(filename, "udp:", &p)) {
2700 return qemu_chr_open_udp(p);
2701 } else
2702 #ifndef _WIN32
2703 if (strstart(filename, "file:", &p)) {
2704 return qemu_chr_open_file_out(p);
2705 } else if (strstart(filename, "pipe:", &p)) {
2706 return qemu_chr_open_pipe(p);
2707 } else if (!strcmp(filename, "pty")) {
2708 return qemu_chr_open_pty();
2709 } else if (!strcmp(filename, "stdio")) {
2710 return qemu_chr_open_stdio();
2711 } else
2712 #endif
2713 #if defined(__linux__)
2714 if (strstart(filename, "/dev/parport", NULL)) {
2715 return qemu_chr_open_pp(filename);
2716 } else
2717 if (strstart(filename, "/dev/", NULL)) {
2718 return qemu_chr_open_tty(filename);
2719 } else
2720 #endif
2721 #ifdef _WIN32
2722 if (strstart(filename, "COM", NULL)) {
2723 return qemu_chr_open_win(filename);
2724 } else
2725 if (strstart(filename, "pipe:", &p)) {
2726 return qemu_chr_open_win_pipe(p);
2727 } else
2728 if (strstart(filename, "file:", &p)) {
2729 return qemu_chr_open_win_file_out(p);
2731 #endif
2733 return NULL;
2737 void qemu_chr_close(CharDriverState *chr)
2739 if (chr->chr_close)
2740 chr->chr_close(chr);
2743 /***********************************************************/
2744 /* network device redirectors */
2746 void hex_dump(FILE *f, const uint8_t *buf, int size)
2748 int len, i, j, c;
2750 for(i=0;i<size;i+=16) {
2751 len = size - i;
2752 if (len > 16)
2753 len = 16;
2754 fprintf(f, "%08x ", i);
2755 for(j=0;j<16;j++) {
2756 if (j < len)
2757 fprintf(f, " %02x", buf[i+j]);
2758 else
2759 fprintf(f, " ");
2761 fprintf(f, " ");
2762 for(j=0;j<len;j++) {
2763 c = buf[i+j];
2764 if (c < ' ' || c > '~')
2765 c = '.';
2766 fprintf(f, "%c", c);
2768 fprintf(f, "\n");
2772 static int parse_macaddr(uint8_t *macaddr, const char *p)
2774 int i;
2775 for(i = 0; i < 6; i++) {
2776 macaddr[i] = strtol(p, (char **)&p, 16);
2777 if (i == 5) {
2778 if (*p != '\0')
2779 return -1;
2780 } else {
2781 if (*p != ':')
2782 return -1;
2783 p++;
2786 return 0;
2789 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2791 const char *p, *p1;
2792 int len;
2793 p = *pp;
2794 p1 = strchr(p, sep);
2795 if (!p1)
2796 return -1;
2797 len = p1 - p;
2798 p1++;
2799 if (buf_size > 0) {
2800 if (len > buf_size - 1)
2801 len = buf_size - 1;
2802 memcpy(buf, p, len);
2803 buf[len] = '\0';
2805 *pp = p1;
2806 return 0;
2809 int parse_host_src_port(struct sockaddr_in *haddr,
2810 struct sockaddr_in *saddr,
2811 const char *input_str)
2813 char *str = strdup(input_str);
2814 char *host_str = str;
2815 char *src_str;
2816 char *ptr;
2818 /*
2819 * Chop off any extra arguments at the end of the string which
2820 * would start with a comma, then fill in the src port information
2821 * if it was provided else use the "any address" and "any port".
2822 */
2823 if ((ptr = strchr(str,',')))
2824 *ptr = '\0';
2826 if ((src_str = strchr(input_str,'@'))) {
2827 *src_str = '\0';
2828 src_str++;
2831 if (parse_host_port(haddr, host_str) < 0)
2832 goto fail;
2834 if (!src_str || *src_str == '\0')
2835 src_str = ":0";
2837 if (parse_host_port(saddr, src_str) < 0)
2838 goto fail;
2840 free(str);
2841 return(0);
2843 fail:
2844 free(str);
2845 return -1;
2848 int parse_host(struct sockaddr_in *saddr, const char *buf)
2850 struct hostent *he;
2852 if ((he = gethostbyname(buf)) != NULL) {
2853 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2854 } else {
2855 if (!inet_aton(buf, &saddr->sin_addr))
2856 return -1;
2858 return 0;
2861 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2863 char buf[512];
2864 const char *p, *r;
2865 int port;
2867 p = str;
2868 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2869 return -1;
2870 saddr->sin_family = AF_INET;
2871 if (buf[0] == '\0') {
2872 saddr->sin_addr.s_addr = 0;
2873 } else {
2874 if (parse_host(saddr, buf) == -1)
2875 return -1;
2877 port = strtol(p, (char **)&r, 0);
2878 if (r == p)
2879 return -1;
2880 saddr->sin_port = htons(port);
2881 return 0;
2884 /* find or alloc a new VLAN */
2885 VLANState *qemu_find_vlan(int id)
2887 VLANState **pvlan, *vlan;
2888 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2889 if (vlan->id == id)
2890 return vlan;
2892 vlan = qemu_mallocz(sizeof(VLANState));
2893 if (!vlan)
2894 return NULL;
2895 vlan->id = id;
2896 vlan->next = NULL;
2897 pvlan = &first_vlan;
2898 while (*pvlan != NULL)
2899 pvlan = &(*pvlan)->next;
2900 *pvlan = vlan;
2901 return vlan;
2904 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2905 IOReadHandler *fd_read,
2906 IOCanRWHandler *fd_can_read,
2907 void *opaque)
2909 VLANClientState *vc, **pvc;
2910 vc = qemu_mallocz(sizeof(VLANClientState));
2911 if (!vc)
2912 return NULL;
2913 vc->fd_read = fd_read;
2914 vc->fd_can_read = fd_can_read;
2915 vc->opaque = opaque;
2916 vc->vlan = vlan;
2918 vc->next = NULL;
2919 pvc = &vlan->first_client;
2920 while (*pvc != NULL)
2921 pvc = &(*pvc)->next;
2922 *pvc = vc;
2923 return vc;
2926 int qemu_can_send_packet(VLANClientState *vc1)
2928 VLANState *vlan = vc1->vlan;
2929 VLANClientState *vc;
2931 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2932 if (vc != vc1) {
2933 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2934 return 0;
2937 return 1;
2940 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2942 VLANState *vlan = vc1->vlan;
2943 VLANClientState *vc;
2945 #if 0
2946 printf("vlan %d send:\n", vlan->id);
2947 hex_dump(stdout, buf, size);
2948 #endif
2949 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2950 if (vc != vc1) {
2951 vc->fd_read(vc->opaque, buf, size);
2956 #if defined(CONFIG_SLIRP)
2958 /* slirp network adapter */
2960 static int slirp_inited;
2961 static VLANClientState *slirp_vc;
2963 int slirp_can_output(void)
2965 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2968 void slirp_output(const uint8_t *pkt, int pkt_len)
2970 #if 0
2971 printf("slirp output:\n");
2972 hex_dump(stdout, pkt, pkt_len);
2973 #endif
2974 if (!slirp_vc)
2975 return;
2976 qemu_send_packet(slirp_vc, pkt, pkt_len);
2979 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2981 #if 0
2982 printf("slirp input:\n");
2983 hex_dump(stdout, buf, size);
2984 #endif
2985 slirp_input(buf, size);
2988 static int net_slirp_init(VLANState *vlan)
2990 if (!slirp_inited) {
2991 slirp_inited = 1;
2992 slirp_init();
2994 slirp_vc = qemu_new_vlan_client(vlan,
2995 slirp_receive, NULL, NULL);
2996 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2997 return 0;
3000 static void net_slirp_redir(const char *redir_str)
3002 int is_udp;
3003 char buf[256], *r;
3004 const char *p;
3005 struct in_addr guest_addr;
3006 int host_port, guest_port;
3008 if (!slirp_inited) {
3009 slirp_inited = 1;
3010 slirp_init();
3013 p = redir_str;
3014 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3015 goto fail;
3016 if (!strcmp(buf, "tcp")) {
3017 is_udp = 0;
3018 } else if (!strcmp(buf, "udp")) {
3019 is_udp = 1;
3020 } else {
3021 goto fail;
3024 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3025 goto fail;
3026 host_port = strtol(buf, &r, 0);
3027 if (r == buf)
3028 goto fail;
3030 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3031 goto fail;
3032 if (buf[0] == '\0') {
3033 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3035 if (!inet_aton(buf, &guest_addr))
3036 goto fail;
3038 guest_port = strtol(p, &r, 0);
3039 if (r == p)
3040 goto fail;
3042 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3043 fprintf(stderr, "qemu: could not set up redirection\n");
3044 exit(1);
3046 return;
3047 fail:
3048 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3049 exit(1);
3052 #ifndef _WIN32
3054 char smb_dir[1024];
3056 static void smb_exit(void)
3058 DIR *d;
3059 struct dirent *de;
3060 char filename[1024];
3062 /* erase all the files in the directory */
3063 d = opendir(smb_dir);
3064 for(;;) {
3065 de = readdir(d);
3066 if (!de)
3067 break;
3068 if (strcmp(de->d_name, ".") != 0 &&
3069 strcmp(de->d_name, "..") != 0) {
3070 snprintf(filename, sizeof(filename), "%s/%s",
3071 smb_dir, de->d_name);
3072 unlink(filename);
3075 closedir(d);
3076 rmdir(smb_dir);
3079 /* automatic user mode samba server configuration */
3080 void net_slirp_smb(const char *exported_dir)
3082 char smb_conf[1024];
3083 char smb_cmdline[1024];
3084 FILE *f;
3086 if (!slirp_inited) {
3087 slirp_inited = 1;
3088 slirp_init();
3091 /* XXX: better tmp dir construction */
3092 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3093 if (mkdir(smb_dir, 0700) < 0) {
3094 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3095 exit(1);
3097 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3099 f = fopen(smb_conf, "w");
3100 if (!f) {
3101 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3102 exit(1);
3104 fprintf(f,
3105 "[global]\n"
3106 "private dir=%s\n"
3107 "smb ports=0\n"
3108 "socket address=127.0.0.1\n"
3109 "pid directory=%s\n"
3110 "lock directory=%s\n"
3111 "log file=%s/log.smbd\n"
3112 "smb passwd file=%s/smbpasswd\n"
3113 "security = share\n"
3114 "[qemu]\n"
3115 "path=%s\n"
3116 "read only=no\n"
3117 "guest ok=yes\n",
3118 smb_dir,
3119 smb_dir,
3120 smb_dir,
3121 smb_dir,
3122 smb_dir,
3123 exported_dir
3124 );
3125 fclose(f);
3126 atexit(smb_exit);
3128 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3129 smb_conf);
3131 slirp_add_exec(0, smb_cmdline, 4, 139);
3134 #endif /* !defined(_WIN32) */
3136 #endif /* CONFIG_SLIRP */
3138 #if !defined(_WIN32)
3140 typedef struct TAPState {
3141 VLANClientState *vc;
3142 int fd;
3143 } TAPState;
3145 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3147 TAPState *s = opaque;
3148 int ret;
3149 for(;;) {
3150 ret = write(s->fd, buf, size);
3151 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3152 } else {
3153 break;
3158 static void tap_send(void *opaque)
3160 TAPState *s = opaque;
3161 uint8_t buf[4096];
3162 int size;
3164 size = read(s->fd, buf, sizeof(buf));
3165 if (size > 0) {
3166 qemu_send_packet(s->vc, buf, size);
3170 /* fd support */
3172 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3174 TAPState *s;
3176 s = qemu_mallocz(sizeof(TAPState));
3177 if (!s)
3178 return NULL;
3179 s->fd = fd;
3180 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3181 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3182 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3183 return s;
3186 #ifdef _BSD
3187 static int tap_open(char *ifname, int ifname_size)
3189 int fd;
3190 char *dev;
3191 struct stat s;
3193 fd = open("/dev/tap", O_RDWR);
3194 if (fd < 0) {
3195 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3196 return -1;
3199 fstat(fd, &s);
3200 dev = devname(s.st_rdev, S_IFCHR);
3201 pstrcpy(ifname, ifname_size, dev);
3203 fcntl(fd, F_SETFL, O_NONBLOCK);
3204 return fd;
3206 #elif defined(__sun__)
3207 static int tap_open(char *ifname, int ifname_size)
3209 fprintf(stderr, "warning: tap_open not yet implemented\n");
3210 return -1;
3212 #else
3213 static int tap_open(char *ifname, int ifname_size)
3215 struct ifreq ifr;
3216 int fd, ret;
3218 fd = open("/dev/net/tun", O_RDWR);
3219 if (fd < 0) {
3220 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3221 return -1;
3223 memset(&ifr, 0, sizeof(ifr));
3224 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3225 if (ifname[0] != '\0')
3226 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3227 else
3228 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3229 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3230 if (ret != 0) {
3231 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3232 close(fd);
3233 return -1;
3235 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3236 fcntl(fd, F_SETFL, O_NONBLOCK);
3237 return fd;
3239 #endif
3241 static int net_tap_init(VLANState *vlan, const char *ifname1,
3242 const char *setup_script, const char *bridge)
3244 TAPState *s;
3245 int pid, status, fd;
3246 char *args[4];
3247 char **parg;
3248 char ifname[128];
3250 if (ifname1 != NULL)
3251 pstrcpy(ifname, sizeof(ifname), ifname1);
3252 else
3253 ifname[0] = '\0';
3254 fd = tap_open(ifname, sizeof(ifname));
3255 if (fd < 0)
3256 return -1;
3258 if (!setup_script)
3259 setup_script = "";
3260 if (setup_script[0] != '\0') {
3261 /* try to launch network init script */
3262 pid = fork();
3263 if (pid >= 0) {
3264 if (pid == 0) {
3265 int open_max = sysconf(_SC_OPEN_MAX), i;
3266 for (i = 0; i < open_max; i++)
3267 if (i != STDIN_FILENO &&
3268 i != STDOUT_FILENO &&
3269 i != STDERR_FILENO &&
3270 i != fd)
3271 close(i);
3273 parg = args;
3274 *parg++ = (char *)setup_script;
3275 *parg++ = ifname;
3276 *parg++ = (char *)bridge;
3277 *parg++ = NULL;
3278 execv(setup_script, args);
3279 _exit(1);
3281 while (waitpid(pid, &status, 0) != pid);
3282 if (!WIFEXITED(status) ||
3283 WEXITSTATUS(status) != 0) {
3284 fprintf(stderr, "%s: could not launch network script\n",
3285 setup_script);
3286 return -1;
3290 s = net_tap_fd_init(vlan, fd);
3291 if (!s)
3292 return -1;
3293 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3294 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3295 return 0;
3298 #endif /* !_WIN32 */
3300 /* network connection */
3301 typedef struct NetSocketState {
3302 VLANClientState *vc;
3303 int fd;
3304 int state; /* 0 = getting length, 1 = getting data */
3305 int index;
3306 int packet_len;
3307 uint8_t buf[4096];
3308 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3309 } NetSocketState;
3311 typedef struct NetSocketListenState {
3312 VLANState *vlan;
3313 int fd;
3314 } NetSocketListenState;
3316 /* XXX: we consider we can send the whole packet without blocking */
3317 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3319 NetSocketState *s = opaque;
3320 uint32_t len;
3321 len = htonl(size);
3323 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3324 send_all(s->fd, buf, size);
3327 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3329 NetSocketState *s = opaque;
3330 sendto(s->fd, buf, size, 0,
3331 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3334 static void net_socket_send(void *opaque)
3336 NetSocketState *s = opaque;
3337 int l, size, err;
3338 uint8_t buf1[4096];
3339 const uint8_t *buf;
3341 size = recv(s->fd, buf1, sizeof(buf1), 0);
3342 if (size < 0) {
3343 err = socket_error();
3344 if (err != EWOULDBLOCK)
3345 goto eoc;
3346 } else if (size == 0) {
3347 /* end of connection */
3348 eoc:
3349 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3350 closesocket(s->fd);
3351 return;
3353 buf = buf1;
3354 while (size > 0) {
3355 /* reassemble a packet from the network */
3356 switch(s->state) {
3357 case 0:
3358 l = 4 - s->index;
3359 if (l > size)
3360 l = size;
3361 memcpy(s->buf + s->index, buf, l);
3362 buf += l;
3363 size -= l;
3364 s->index += l;
3365 if (s->index == 4) {
3366 /* got length */
3367 s->packet_len = ntohl(*(uint32_t *)s->buf);
3368 s->index = 0;
3369 s->state = 1;
3371 break;
3372 case 1:
3373 l = s->packet_len - s->index;
3374 if (l > size)
3375 l = size;
3376 memcpy(s->buf + s->index, buf, l);
3377 s->index += l;
3378 buf += l;
3379 size -= l;
3380 if (s->index >= s->packet_len) {
3381 qemu_send_packet(s->vc, s->buf, s->packet_len);
3382 s->index = 0;
3383 s->state = 0;
3385 break;
3390 static void net_socket_send_dgram(void *opaque)
3392 NetSocketState *s = opaque;
3393 int size;
3395 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3396 if (size < 0)
3397 return;
3398 if (size == 0) {
3399 /* end of connection */
3400 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3401 return;
3403 qemu_send_packet(s->vc, s->buf, size);
3406 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3408 struct ip_mreq imr;
3409 int fd;
3410 int val, ret;
3411 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3412 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3413 inet_ntoa(mcastaddr->sin_addr),
3414 (int)ntohl(mcastaddr->sin_addr.s_addr));
3415 return -1;
3418 fd = socket(PF_INET, SOCK_DGRAM, 0);
3419 if (fd < 0) {
3420 perror("socket(PF_INET, SOCK_DGRAM)");
3421 return -1;
3424 val = 1;
3425 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3426 (const char *)&val, sizeof(val));
3427 if (ret < 0) {
3428 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3429 goto fail;
3432 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3433 if (ret < 0) {
3434 perror("bind");
3435 goto fail;
3438 /* Add host to multicast group */
3439 imr.imr_multiaddr = mcastaddr->sin_addr;
3440 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3442 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3443 (const char *)&imr, sizeof(struct ip_mreq));
3444 if (ret < 0) {
3445 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3446 goto fail;
3449 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3450 val = 1;
3451 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3452 (const char *)&val, sizeof(val));
3453 if (ret < 0) {
3454 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3455 goto fail;
3458 socket_set_nonblock(fd);
3459 return fd;
3460 fail:
3461 if (fd >= 0)
3462 closesocket(fd);
3463 return -1;
3466 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3467 int is_connected)
3469 struct sockaddr_in saddr;
3470 int newfd;
3471 socklen_t saddr_len;
3472 NetSocketState *s;
3474 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3475 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3476 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3477 */
3479 if (is_connected) {
3480 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3481 /* must be bound */
3482 if (saddr.sin_addr.s_addr==0) {
3483 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3484 fd);
3485 return NULL;
3487 /* clone dgram socket */
3488 newfd = net_socket_mcast_create(&saddr);
3489 if (newfd < 0) {
3490 /* error already reported by net_socket_mcast_create() */
3491 close(fd);
3492 return NULL;
3494 /* clone newfd to fd, close newfd */
3495 dup2(newfd, fd);
3496 close(newfd);
3498 } else {
3499 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3500 fd, strerror(errno));
3501 return NULL;
3505 s = qemu_mallocz(sizeof(NetSocketState));
3506 if (!s)
3507 return NULL;
3508 s->fd = fd;
3510 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3511 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3513 /* mcast: save bound address as dst */
3514 if (is_connected) s->dgram_dst=saddr;
3516 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3517 "socket: fd=%d (%s mcast=%s:%d)",
3518 fd, is_connected? "cloned" : "",
3519 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3520 return s;
3523 static void net_socket_connect(void *opaque)
3525 NetSocketState *s = opaque;
3526 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3529 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3530 int is_connected)
3532 NetSocketState *s;
3533 s = qemu_mallocz(sizeof(NetSocketState));
3534 if (!s)
3535 return NULL;
3536 s->fd = fd;
3537 s->vc = qemu_new_vlan_client(vlan,
3538 net_socket_receive, NULL, s);
3539 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3540 "socket: fd=%d", fd);
3541 if (is_connected) {
3542 net_socket_connect(s);
3543 } else {
3544 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3546 return s;
3549 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3550 int is_connected)
3552 int so_type=-1, optlen=sizeof(so_type);
3554 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3555 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3556 return NULL;
3558 switch(so_type) {
3559 case SOCK_DGRAM:
3560 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3561 case SOCK_STREAM:
3562 return net_socket_fd_init_stream(vlan, fd, is_connected);
3563 default:
3564 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3565 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3566 return net_socket_fd_init_stream(vlan, fd, is_connected);
3568 return NULL;
3571 static void net_socket_accept(void *opaque)
3573 NetSocketListenState *s = opaque;
3574 NetSocketState *s1;
3575 struct sockaddr_in saddr;
3576 socklen_t len;
3577 int fd;
3579 for(;;) {
3580 len = sizeof(saddr);
3581 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3582 if (fd < 0 && errno != EINTR) {
3583 return;
3584 } else if (fd >= 0) {
3585 break;
3588 s1 = net_socket_fd_init(s->vlan, fd, 1);
3589 if (!s1) {
3590 closesocket(fd);
3591 } else {
3592 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3593 "socket: connection from %s:%d",
3594 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3598 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3600 NetSocketListenState *s;
3601 int fd, val, ret;
3602 struct sockaddr_in saddr;
3604 if (parse_host_port(&saddr, host_str) < 0)
3605 return -1;
3607 s = qemu_mallocz(sizeof(NetSocketListenState));
3608 if (!s)
3609 return -1;
3611 fd = socket(PF_INET, SOCK_STREAM, 0);
3612 if (fd < 0) {
3613 perror("socket");
3614 return -1;
3616 socket_set_nonblock(fd);
3618 /* allow fast reuse */
3619 val = 1;
3620 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3622 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3623 if (ret < 0) {
3624 perror("bind");
3625 return -1;
3627 ret = listen(fd, 0);
3628 if (ret < 0) {
3629 perror("listen");
3630 return -1;
3632 s->vlan = vlan;
3633 s->fd = fd;
3634 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3635 return 0;
3638 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3640 NetSocketState *s;
3641 int fd, connected, ret, err;
3642 struct sockaddr_in saddr;
3644 if (parse_host_port(&saddr, host_str) < 0)
3645 return -1;
3647 fd = socket(PF_INET, SOCK_STREAM, 0);
3648 if (fd < 0) {
3649 perror("socket");
3650 return -1;
3652 socket_set_nonblock(fd);
3654 connected = 0;
3655 for(;;) {
3656 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3657 if (ret < 0) {
3658 err = socket_error();
3659 if (err == EINTR || err == EWOULDBLOCK) {
3660 } else if (err == EINPROGRESS) {
3661 break;
3662 } else {
3663 perror("connect");
3664 closesocket(fd);
3665 return -1;
3667 } else {
3668 connected = 1;
3669 break;
3672 s = net_socket_fd_init(vlan, fd, connected);
3673 if (!s)
3674 return -1;
3675 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3676 "socket: connect to %s:%d",
3677 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3678 return 0;
3681 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3683 NetSocketState *s;
3684 int fd;
3685 struct sockaddr_in saddr;
3687 if (parse_host_port(&saddr, host_str) < 0)
3688 return -1;
3691 fd = net_socket_mcast_create(&saddr);
3692 if (fd < 0)
3693 return -1;
3695 s = net_socket_fd_init(vlan, fd, 0);
3696 if (!s)
3697 return -1;
3699 s->dgram_dst = saddr;
3701 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3702 "socket: mcast=%s:%d",
3703 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3704 return 0;
3708 static int get_param_value(char *buf, int buf_size,
3709 const char *tag, const char *str)
3711 const char *p;
3712 char *q;
3713 char option[128];
3715 p = str;
3716 for(;;) {
3717 q = option;
3718 while (*p != '\0' && *p != '=') {
3719 if ((q - option) < sizeof(option) - 1)
3720 *q++ = *p;
3721 p++;
3723 *q = '\0';
3724 if (*p != '=')
3725 break;
3726 p++;
3727 if (!strcmp(tag, option)) {
3728 q = buf;
3729 while (*p != '\0' && *p != ',') {
3730 if ((q - buf) < buf_size - 1)
3731 *q++ = *p;
3732 p++;
3734 *q = '\0';
3735 return q - buf;
3736 } else {
3737 while (*p != '\0' && *p != ',') {
3738 p++;
3741 if (*p != ',')
3742 break;
3743 p++;
3745 return 0;
3748 int net_client_init(const char *str)
3750 const char *p;
3751 char *q;
3752 char device[64];
3753 char buf[1024];
3754 int vlan_id, ret;
3755 VLANState *vlan;
3757 p = str;
3758 q = device;
3759 while (*p != '\0' && *p != ',') {
3760 if ((q - device) < sizeof(device) - 1)
3761 *q++ = *p;
3762 p++;
3764 *q = '\0';
3765 if (*p == ',')
3766 p++;
3767 vlan_id = 0;
3768 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3769 vlan_id = strtol(buf, NULL, 0);
3771 vlan = qemu_find_vlan(vlan_id);
3772 if (!vlan) {
3773 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3774 return -1;
3776 if (!strcmp(device, "nic")) {
3777 NICInfo *nd;
3778 uint8_t *macaddr;
3780 if (nb_nics >= MAX_NICS) {
3781 fprintf(stderr, "Too Many NICs\n");
3782 return -1;
3784 nd = &nd_table[nb_nics];
3785 macaddr = nd->macaddr;
3786 macaddr[0] = 0x52;
3787 macaddr[1] = 0x54;
3788 macaddr[2] = 0x00;
3789 macaddr[3] = 0x12;
3790 macaddr[4] = 0x34;
3791 macaddr[5] = 0x56 + nb_nics;
3793 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3794 if (parse_macaddr(macaddr, buf) < 0) {
3795 fprintf(stderr, "invalid syntax for ethernet address\n");
3796 return -1;
3799 if (get_param_value(buf, sizeof(buf), "model", p)) {
3800 nd->model = strdup(buf);
3802 nd->vlan = vlan;
3803 nb_nics++;
3804 ret = 0;
3805 } else
3806 if (!strcmp(device, "none")) {
3807 /* does nothing. It is needed to signal that no network cards
3808 are wanted */
3809 ret = 0;
3810 } else
3811 #ifdef CONFIG_SLIRP
3812 if (!strcmp(device, "user")) {
3813 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3814 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3816 ret = net_slirp_init(vlan);
3817 } else
3818 #endif
3819 #ifdef _WIN32
3820 if (!strcmp(device, "tap")) {
3821 char ifname[64];
3822 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3823 fprintf(stderr, "tap: no interface name\n");
3824 return -1;
3826 ret = tap_win32_init(vlan, ifname);
3827 } else
3828 #else
3829 if (!strcmp(device, "tap")) {
3830 char ifname[64];
3831 char setup_script[1024];
3832 char bridge[16];
3833 int fd;
3834 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3835 fd = strtol(buf, NULL, 0);
3836 ret = -1;
3837 if (net_tap_fd_init(vlan, fd))
3838 ret = 0;
3839 } else {
3840 ifname[0] = '\0';
3841 get_param_value(ifname, sizeof(ifname), "ifname", p);
3842 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3843 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3845 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
3846 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
3848 ret = net_tap_init(vlan, ifname, setup_script, bridge);
3850 } else
3851 #endif
3852 if (!strcmp(device, "socket")) {
3853 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3854 int fd;
3855 fd = strtol(buf, NULL, 0);
3856 ret = -1;
3857 if (net_socket_fd_init(vlan, fd, 1))
3858 ret = 0;
3859 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3860 ret = net_socket_listen_init(vlan, buf);
3861 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3862 ret = net_socket_connect_init(vlan, buf);
3863 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3864 ret = net_socket_mcast_init(vlan, buf);
3865 } else {
3866 fprintf(stderr, "Unknown socket options: %s\n", p);
3867 return -1;
3869 } else
3871 fprintf(stderr, "Unknown network device: %s\n", device);
3872 return -1;
3874 if (ret < 0) {
3875 fprintf(stderr, "Could not initialize device '%s'\n", device);
3878 return ret;
3881 void do_info_network(void)
3883 VLANState *vlan;
3884 VLANClientState *vc;
3886 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3887 term_printf("VLAN %d devices:\n", vlan->id);
3888 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3889 term_printf(" %s\n", vc->info_str);
3893 /***********************************************************/
3894 /* USB devices */
3896 static USBPort *used_usb_ports;
3897 static USBPort *free_usb_ports;
3899 /* ??? Maybe change this to register a hub to keep track of the topology. */
3900 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3901 usb_attachfn attach)
3903 port->opaque = opaque;
3904 port->index = index;
3905 port->attach = attach;
3906 port->next = free_usb_ports;
3907 free_usb_ports = port;
3910 static int usb_device_add(const char *devname)
3912 const char *p;
3913 USBDevice *dev;
3914 USBPort *port;
3915 char usb_name[256] = "USB ";
3917 if (!free_usb_ports)
3918 return -1;
3920 if (strstart(devname, "host:", &p)) {
3921 dev = usb_host_device_open(p);
3922 } else if (!strcmp(devname, "mouse")) {
3923 dev = usb_mouse_init();
3924 } else if (!strcmp(devname, "tablet")) {
3925 dev = usb_tablet_init();
3926 } else if (strstart(devname, "disk:", &p)) {
3927 dev = usb_msd_init(p);
3928 } else {
3929 return -1;
3931 if (!dev)
3932 return -1;
3934 /* Find a USB port to add the device to. */
3935 port = free_usb_ports;
3936 if (!port->next) {
3937 USBDevice *hub;
3939 /* Create a new hub and chain it on. */
3940 free_usb_ports = NULL;
3941 port->next = used_usb_ports;
3942 used_usb_ports = port;
3944 hub = usb_hub_init(VM_USB_HUB_SIZE);
3945 usb_attach(port, hub);
3946 port = free_usb_ports;
3949 free_usb_ports = port->next;
3950 port->next = used_usb_ports;
3951 used_usb_ports = port;
3953 pstrcpy(usb_name + strlen(usb_name),
3954 sizeof(usb_name) - strlen(usb_name),
3955 devname);
3956 register_savevm(usb_name, 0, 1, generic_usb_save, generic_usb_load, dev);
3958 usb_attach(port, dev);
3959 return 0;
3962 static int usb_device_del(const char *devname)
3964 USBPort *port;
3965 USBPort **lastp;
3966 USBDevice *dev;
3967 int bus_num, addr;
3968 const char *p;
3970 if (!used_usb_ports)
3971 return -1;
3973 p = strchr(devname, '.');
3974 if (!p)
3975 return -1;
3976 bus_num = strtoul(devname, NULL, 0);
3977 addr = strtoul(p + 1, NULL, 0);
3978 if (bus_num != 0)
3979 return -1;
3981 lastp = &used_usb_ports;
3982 port = used_usb_ports;
3983 while (port && port->dev->addr != addr) {
3984 lastp = &port->next;
3985 port = port->next;
3988 if (!port)
3989 return -1;
3991 dev = port->dev;
3992 *lastp = port->next;
3993 usb_attach(port, NULL);
3994 dev->handle_destroy(dev);
3995 port->next = free_usb_ports;
3996 free_usb_ports = port;
3997 return 0;
4000 void do_usb_add(const char *devname)
4002 int ret;
4003 ret = usb_device_add(devname);
4004 if (ret < 0)
4005 term_printf("Could not add USB device '%s'\n", devname);
4008 void do_usb_del(const char *devname)
4010 int ret;
4011 ret = usb_device_del(devname);
4012 if (ret < 0)
4013 term_printf("Could not remove USB device '%s'\n", devname);
4016 void usb_info(void)
4018 USBDevice *dev;
4019 USBPort *port;
4020 const char *speed_str;
4022 if (!usb_enabled) {
4023 term_printf("USB support not enabled\n");
4024 return;
4027 for (port = used_usb_ports; port; port = port->next) {
4028 dev = port->dev;
4029 if (!dev)
4030 continue;
4031 switch(dev->speed) {
4032 case USB_SPEED_LOW:
4033 speed_str = "1.5";
4034 break;
4035 case USB_SPEED_FULL:
4036 speed_str = "12";
4037 break;
4038 case USB_SPEED_HIGH:
4039 speed_str = "480";
4040 break;
4041 default:
4042 speed_str = "?";
4043 break;
4045 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4046 0, dev->addr, speed_str, dev->devname);
4050 /***********************************************************/
4051 /* pid file */
4053 static char *pid_filename;
4055 /* Remove PID file. Called on normal exit */
4057 static void remove_pidfile(void)
4059 unlink (pid_filename);
4062 static void create_pidfile(const char *filename)
4064 struct stat pidstat;
4065 FILE *f;
4067 /* Try to write our PID to the named file */
4068 if (stat(filename, &pidstat) < 0) {
4069 if (errno == ENOENT) {
4070 if ((f = fopen (filename, "w")) == NULL) {
4071 perror("Opening pidfile");
4072 exit(1);
4074 fprintf(f, "%ld\n", (long)getpid());
4075 fclose(f);
4076 pid_filename = qemu_strdup(filename);
4077 if (!pid_filename) {
4078 fprintf(stderr, "Could not save PID filename");
4079 exit(1);
4081 atexit(remove_pidfile);
4083 } else {
4084 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4085 filename);
4086 exit(1);
4090 /***********************************************************/
4091 /* dumb display */
4093 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4097 static void dumb_resize(DisplayState *ds, int w, int h)
4101 static void dumb_refresh(DisplayState *ds)
4103 vga_hw_update();
4106 void dumb_display_init(DisplayState *ds)
4108 ds->data = NULL;
4109 ds->linesize = 0;
4110 ds->depth = 0;
4111 ds->dpy_update = dumb_update;
4112 ds->dpy_resize = dumb_resize;
4113 ds->dpy_refresh = dumb_refresh;
4116 /***********************************************************/
4117 /* I/O handling */
4119 #define MAX_IO_HANDLERS 64
4121 typedef struct IOHandlerRecord {
4122 int fd;
4123 IOCanRWHandler *fd_read_poll;
4124 IOHandler *fd_read;
4125 IOHandler *fd_write;
4126 void *opaque;
4127 /* temporary data */
4128 struct pollfd *ufd;
4129 struct IOHandlerRecord *next;
4130 } IOHandlerRecord;
4132 static IOHandlerRecord *first_io_handler;
4134 /* XXX: fd_read_poll should be suppressed, but an API change is
4135 necessary in the character devices to suppress fd_can_read(). */
4136 int qemu_set_fd_handler2(int fd,
4137 IOCanRWHandler *fd_read_poll,
4138 IOHandler *fd_read,
4139 IOHandler *fd_write,
4140 void *opaque)
4142 IOHandlerRecord **pioh, *ioh;
4144 if (!fd_read && !fd_write) {
4145 pioh = &first_io_handler;
4146 for(;;) {
4147 ioh = *pioh;
4148 if (ioh == NULL)
4149 break;
4150 if (ioh->fd == fd) {
4151 *pioh = ioh->next;
4152 qemu_free(ioh);
4153 break;
4155 pioh = &ioh->next;
4157 } else {
4158 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4159 if (ioh->fd == fd)
4160 goto found;
4162 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4163 if (!ioh)
4164 return -1;
4165 ioh->next = first_io_handler;
4166 first_io_handler = ioh;
4167 found:
4168 ioh->fd = fd;
4169 ioh->fd_read_poll = fd_read_poll;
4170 ioh->fd_read = fd_read;
4171 ioh->fd_write = fd_write;
4172 ioh->opaque = opaque;
4174 return 0;
4177 int qemu_set_fd_handler(int fd,
4178 IOHandler *fd_read,
4179 IOHandler *fd_write,
4180 void *opaque)
4182 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4185 /***********************************************************/
4186 /* Polling handling */
4188 typedef struct PollingEntry {
4189 PollingFunc *func;
4190 void *opaque;
4191 struct PollingEntry *next;
4192 } PollingEntry;
4194 static PollingEntry *first_polling_entry;
4196 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4198 PollingEntry **ppe, *pe;
4199 pe = qemu_mallocz(sizeof(PollingEntry));
4200 if (!pe)
4201 return -1;
4202 pe->func = func;
4203 pe->opaque = opaque;
4204 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4205 *ppe = pe;
4206 return 0;
4209 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4211 PollingEntry **ppe, *pe;
4212 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4213 pe = *ppe;
4214 if (pe->func == func && pe->opaque == opaque) {
4215 *ppe = pe->next;
4216 qemu_free(pe);
4217 break;
4222 #ifdef _WIN32
4223 /***********************************************************/
4224 /* Wait objects support */
4225 typedef struct WaitObjects {
4226 int num;
4227 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4228 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4229 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4230 } WaitObjects;
4232 static WaitObjects wait_objects = {0};
4234 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4236 WaitObjects *w = &wait_objects;
4238 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4239 return -1;
4240 w->events[w->num] = handle;
4241 w->func[w->num] = func;
4242 w->opaque[w->num] = opaque;
4243 w->num++;
4244 return 0;
4247 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4249 int i, found;
4250 WaitObjects *w = &wait_objects;
4252 found = 0;
4253 for (i = 0; i < w->num; i++) {
4254 if (w->events[i] == handle)
4255 found = 1;
4256 if (found) {
4257 w->events[i] = w->events[i + 1];
4258 w->func[i] = w->func[i + 1];
4259 w->opaque[i] = w->opaque[i + 1];
4262 if (found)
4263 w->num--;
4265 #endif
4267 /***********************************************************/
4268 /* savevm/loadvm support */
4270 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4272 fwrite(buf, 1, size, f);
4275 void qemu_put_byte(QEMUFile *f, int v)
4277 fputc(v, f);
4280 void qemu_put_be16(QEMUFile *f, unsigned int v)
4282 qemu_put_byte(f, v >> 8);
4283 qemu_put_byte(f, v);
4286 void qemu_put_be32(QEMUFile *f, unsigned int v)
4288 qemu_put_byte(f, v >> 24);
4289 qemu_put_byte(f, v >> 16);
4290 qemu_put_byte(f, v >> 8);
4291 qemu_put_byte(f, v);
4294 void qemu_put_be64(QEMUFile *f, uint64_t v)
4296 qemu_put_be32(f, v >> 32);
4297 qemu_put_be32(f, v);
4300 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4302 return fread(buf, 1, size, f);
4305 int qemu_get_byte(QEMUFile *f)
4307 int v;
4308 v = fgetc(f);
4309 if (v == EOF)
4310 return 0;
4311 else
4312 return v;
4315 unsigned int qemu_get_be16(QEMUFile *f)
4317 unsigned int v;
4318 v = qemu_get_byte(f) << 8;
4319 v |= qemu_get_byte(f);
4320 return v;
4323 unsigned int qemu_get_be32(QEMUFile *f)
4325 unsigned int v;
4326 v = qemu_get_byte(f) << 24;
4327 v |= qemu_get_byte(f) << 16;
4328 v |= qemu_get_byte(f) << 8;
4329 v |= qemu_get_byte(f);
4330 return v;
4333 uint64_t qemu_get_be64(QEMUFile *f)
4335 uint64_t v;
4336 v = (uint64_t)qemu_get_be32(f) << 32;
4337 v |= qemu_get_be32(f);
4338 return v;
4341 int64_t qemu_ftell(QEMUFile *f)
4343 return ftell(f);
4346 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4348 if (fseek(f, pos, whence) < 0)
4349 return -1;
4350 return ftell(f);
4353 typedef struct SaveStateEntry {
4354 char idstr[256];
4355 int instance_id;
4356 int version_id;
4357 SaveStateHandler *save_state;
4358 LoadStateHandler *load_state;
4359 void *opaque;
4360 struct SaveStateEntry *next;
4361 } SaveStateEntry;
4363 static SaveStateEntry *first_se;
4365 int register_savevm(const char *idstr,
4366 int instance_id,
4367 int version_id,
4368 SaveStateHandler *save_state,
4369 LoadStateHandler *load_state,
4370 void *opaque)
4372 SaveStateEntry *se, **pse;
4374 se = qemu_malloc(sizeof(SaveStateEntry));
4375 if (!se)
4376 return -1;
4377 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4378 se->instance_id = instance_id;
4379 se->version_id = version_id;
4380 se->save_state = save_state;
4381 se->load_state = load_state;
4382 se->opaque = opaque;
4383 se->next = NULL;
4385 /* add at the end of list */
4386 pse = &first_se;
4387 while (*pse != NULL)
4388 pse = &(*pse)->next;
4389 *pse = se;
4390 return 0;
4393 #define QEMU_VM_FILE_MAGIC 0x5145564d
4394 #define QEMU_VM_FILE_VERSION 0x00000001
4396 int qemu_savevm(const char *filename)
4398 SaveStateEntry *se;
4399 QEMUFile *f;
4400 int len, len_pos, cur_pos, saved_vm_running, ret;
4402 saved_vm_running = vm_running;
4403 vm_stop(0);
4405 f = fopen(filename, "wb");
4406 if (!f) {
4407 ret = -1;
4408 goto the_end;
4411 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4412 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4414 for(se = first_se; se != NULL; se = se->next) {
4415 /* ID string */
4416 len = strlen(se->idstr);
4417 qemu_put_byte(f, len);
4418 qemu_put_buffer(f, se->idstr, len);
4420 qemu_put_be32(f, se->instance_id);
4421 qemu_put_be32(f, se->version_id);
4423 /* record size: filled later */
4424 len_pos = ftell(f);
4425 qemu_put_be32(f, 0);
4427 se->save_state(f, se->opaque);
4429 /* fill record size */
4430 cur_pos = ftell(f);
4431 len = ftell(f) - len_pos - 4;
4432 fseek(f, len_pos, SEEK_SET);
4433 qemu_put_be32(f, len);
4434 fseek(f, cur_pos, SEEK_SET);
4437 fclose(f);
4438 ret = 0;
4439 the_end:
4440 if (saved_vm_running)
4441 vm_start();
4442 return ret;
4445 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4447 SaveStateEntry *se;
4449 for(se = first_se; se != NULL; se = se->next) {
4450 if (!strcmp(se->idstr, idstr) &&
4451 instance_id == se->instance_id)
4452 return se;
4454 return NULL;
4457 int qemu_loadvm(const char *filename)
4459 SaveStateEntry *se;
4460 QEMUFile *f;
4461 int len, cur_pos, ret, instance_id, record_len, version_id;
4462 int saved_vm_running;
4463 unsigned int v;
4464 char idstr[256];
4466 saved_vm_running = vm_running;
4467 vm_stop(0);
4469 f = fopen(filename, "rb");
4470 if (!f) {
4471 ret = -1;
4472 goto the_end;
4475 v = qemu_get_be32(f);
4476 if (v != QEMU_VM_FILE_MAGIC)
4477 goto fail;
4478 v = qemu_get_be32(f);
4479 if (v != QEMU_VM_FILE_VERSION) {
4480 fail:
4481 fclose(f);
4482 ret = -1;
4483 goto the_end;
4485 for(;;) {
4486 len = qemu_get_byte(f);
4487 if (feof(f))
4488 break;
4489 qemu_get_buffer(f, idstr, len);
4490 idstr[len] = '\0';
4491 instance_id = qemu_get_be32(f);
4492 version_id = qemu_get_be32(f);
4493 record_len = qemu_get_be32(f);
4494 #if 0
4495 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4496 idstr, instance_id, version_id, record_len);
4497 #endif
4498 cur_pos = ftell(f);
4499 se = find_se(idstr, instance_id);
4500 if (!se) {
4501 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4502 instance_id, idstr);
4503 } else {
4504 ret = se->load_state(f, se->opaque, version_id);
4505 if (ret < 0) {
4506 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4507 instance_id, idstr);
4510 /* always seek to exact end of record */
4511 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4513 fclose(f);
4515 /* del tmp file */
4516 if (unlink(filename) == -1)
4517 fprintf(stderr, "delete tmp qemu state file failed.\n");
4519 ret = 0;
4520 the_end:
4521 if (saved_vm_running)
4522 vm_start();
4523 return ret;
4526 #ifndef CONFIG_DM
4527 /***********************************************************/
4528 /* cpu save/restore */
4530 #if defined(TARGET_I386)
4532 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4534 qemu_put_be32(f, dt->selector);
4535 qemu_put_betl(f, dt->base);
4536 qemu_put_be32(f, dt->limit);
4537 qemu_put_be32(f, dt->flags);
4540 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4542 dt->selector = qemu_get_be32(f);
4543 dt->base = qemu_get_betl(f);
4544 dt->limit = qemu_get_be32(f);
4545 dt->flags = qemu_get_be32(f);
4548 void cpu_save(QEMUFile *f, void *opaque)
4550 CPUState *env = opaque;
4551 uint16_t fptag, fpus, fpuc, fpregs_format;
4552 uint32_t hflags;
4553 int i;
4555 for(i = 0; i < CPU_NB_REGS; i++)
4556 qemu_put_betls(f, &env->regs[i]);
4557 qemu_put_betls(f, &env->eip);
4558 qemu_put_betls(f, &env->eflags);
4559 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4560 qemu_put_be32s(f, &hflags);
4562 /* FPU */
4563 fpuc = env->fpuc;
4564 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4565 fptag = 0;
4566 for(i = 0; i < 8; i++) {
4567 fptag |= ((!env->fptags[i]) << i);
4570 qemu_put_be16s(f, &fpuc);
4571 qemu_put_be16s(f, &fpus);
4572 qemu_put_be16s(f, &fptag);
4574 #ifdef USE_X86LDOUBLE
4575 fpregs_format = 0;
4576 #else
4577 fpregs_format = 1;
4578 #endif
4579 qemu_put_be16s(f, &fpregs_format);
4581 for(i = 0; i < 8; i++) {
4582 #ifdef USE_X86LDOUBLE
4584 uint64_t mant;
4585 uint16_t exp;
4586 /* we save the real CPU data (in case of MMX usage only 'mant'
4587 contains the MMX register */
4588 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4589 qemu_put_be64(f, mant);
4590 qemu_put_be16(f, exp);
4592 #else
4593 /* if we use doubles for float emulation, we save the doubles to
4594 avoid losing information in case of MMX usage. It can give
4595 problems if the image is restored on a CPU where long
4596 doubles are used instead. */
4597 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4598 #endif
4601 for(i = 0; i < 6; i++)
4602 cpu_put_seg(f, &env->segs[i]);
4603 cpu_put_seg(f, &env->ldt);
4604 cpu_put_seg(f, &env->tr);
4605 cpu_put_seg(f, &env->gdt);
4606 cpu_put_seg(f, &env->idt);
4608 qemu_put_be32s(f, &env->sysenter_cs);
4609 qemu_put_be32s(f, &env->sysenter_esp);
4610 qemu_put_be32s(f, &env->sysenter_eip);
4612 qemu_put_betls(f, &env->cr[0]);
4613 qemu_put_betls(f, &env->cr[2]);
4614 qemu_put_betls(f, &env->cr[3]);
4615 qemu_put_betls(f, &env->cr[4]);
4617 for(i = 0; i < 8; i++)
4618 qemu_put_betls(f, &env->dr[i]);
4620 /* MMU */
4621 qemu_put_be32s(f, &env->a20_mask);
4623 /* XMM */
4624 qemu_put_be32s(f, &env->mxcsr);
4625 for(i = 0; i < CPU_NB_REGS; i++) {
4626 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4627 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4630 #ifdef TARGET_X86_64
4631 qemu_put_be64s(f, &env->efer);
4632 qemu_put_be64s(f, &env->star);
4633 qemu_put_be64s(f, &env->lstar);
4634 qemu_put_be64s(f, &env->cstar);
4635 qemu_put_be64s(f, &env->fmask);
4636 qemu_put_be64s(f, &env->kernelgsbase);
4637 #endif
4640 #ifdef USE_X86LDOUBLE
4641 /* XXX: add that in a FPU generic layer */
4642 union x86_longdouble {
4643 uint64_t mant;
4644 uint16_t exp;
4645 };
4647 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4648 #define EXPBIAS1 1023
4649 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4650 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4652 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4654 int e;
4655 /* mantissa */
4656 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4657 /* exponent + sign */
4658 e = EXPD1(temp) - EXPBIAS1 + 16383;
4659 e |= SIGND1(temp) >> 16;
4660 p->exp = e;
4662 #endif
4664 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4666 CPUState *env = opaque;
4667 int i, guess_mmx;
4668 uint32_t hflags;
4669 uint16_t fpus, fpuc, fptag, fpregs_format;
4671 if (version_id != 3)
4672 return -EINVAL;
4673 for(i = 0; i < CPU_NB_REGS; i++)
4674 qemu_get_betls(f, &env->regs[i]);
4675 qemu_get_betls(f, &env->eip);
4676 qemu_get_betls(f, &env->eflags);
4677 qemu_get_be32s(f, &hflags);
4679 qemu_get_be16s(f, &fpuc);
4680 qemu_get_be16s(f, &fpus);
4681 qemu_get_be16s(f, &fptag);
4682 qemu_get_be16s(f, &fpregs_format);
4684 /* NOTE: we cannot always restore the FPU state if the image come
4685 from a host with a different 'USE_X86LDOUBLE' define. We guess
4686 if we are in an MMX state to restore correctly in that case. */
4687 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4688 for(i = 0; i < 8; i++) {
4689 uint64_t mant;
4690 uint16_t exp;
4692 switch(fpregs_format) {
4693 case 0:
4694 mant = qemu_get_be64(f);
4695 exp = qemu_get_be16(f);
4696 #ifdef USE_X86LDOUBLE
4697 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4698 #else
4699 /* difficult case */
4700 if (guess_mmx)
4701 env->fpregs[i].mmx.MMX_Q(0) = mant;
4702 else
4703 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4704 #endif
4705 break;
4706 case 1:
4707 mant = qemu_get_be64(f);
4708 #ifdef USE_X86LDOUBLE
4710 union x86_longdouble *p;
4711 /* difficult case */
4712 p = (void *)&env->fpregs[i];
4713 if (guess_mmx) {
4714 p->mant = mant;
4715 p->exp = 0xffff;
4716 } else {
4717 fp64_to_fp80(p, mant);
4720 #else
4721 env->fpregs[i].mmx.MMX_Q(0) = mant;
4722 #endif
4723 break;
4724 default:
4725 return -EINVAL;
4729 env->fpuc = fpuc;
4730 /* XXX: restore FPU round state */
4731 env->fpstt = (fpus >> 11) & 7;
4732 env->fpus = fpus & ~0x3800;
4733 fptag ^= 0xff;
4734 for(i = 0; i < 8; i++) {
4735 env->fptags[i] = (fptag >> i) & 1;
4738 for(i = 0; i < 6; i++)
4739 cpu_get_seg(f, &env->segs[i]);
4740 cpu_get_seg(f, &env->ldt);
4741 cpu_get_seg(f, &env->tr);
4742 cpu_get_seg(f, &env->gdt);
4743 cpu_get_seg(f, &env->idt);
4745 qemu_get_be32s(f, &env->sysenter_cs);
4746 qemu_get_be32s(f, &env->sysenter_esp);
4747 qemu_get_be32s(f, &env->sysenter_eip);
4749 qemu_get_betls(f, &env->cr[0]);
4750 qemu_get_betls(f, &env->cr[2]);
4751 qemu_get_betls(f, &env->cr[3]);
4752 qemu_get_betls(f, &env->cr[4]);
4754 for(i = 0; i < 8; i++)
4755 qemu_get_betls(f, &env->dr[i]);
4757 /* MMU */
4758 qemu_get_be32s(f, &env->a20_mask);
4760 qemu_get_be32s(f, &env->mxcsr);
4761 for(i = 0; i < CPU_NB_REGS; i++) {
4762 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4763 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4766 #ifdef TARGET_X86_64
4767 qemu_get_be64s(f, &env->efer);
4768 qemu_get_be64s(f, &env->star);
4769 qemu_get_be64s(f, &env->lstar);
4770 qemu_get_be64s(f, &env->cstar);
4771 qemu_get_be64s(f, &env->fmask);
4772 qemu_get_be64s(f, &env->kernelgsbase);
4773 #endif
4775 /* XXX: compute hflags from scratch, except for CPL and IIF */
4776 env->hflags = hflags;
4777 tlb_flush(env, 1);
4778 return 0;
4781 #elif defined(TARGET_PPC)
4782 void cpu_save(QEMUFile *f, void *opaque)
4786 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4788 return 0;
4791 #elif defined(TARGET_MIPS)
4792 void cpu_save(QEMUFile *f, void *opaque)
4796 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4798 return 0;
4801 #elif defined(TARGET_SPARC)
4802 void cpu_save(QEMUFile *f, void *opaque)
4804 CPUState *env = opaque;
4805 int i;
4806 uint32_t tmp;
4808 for(i = 0; i < 8; i++)
4809 qemu_put_betls(f, &env->gregs[i]);
4810 for(i = 0; i < NWINDOWS * 16; i++)
4811 qemu_put_betls(f, &env->regbase[i]);
4813 /* FPU */
4814 for(i = 0; i < TARGET_FPREGS; i++) {
4815 union {
4816 float32 f;
4817 uint32_t i;
4818 } u;
4819 u.f = env->fpr[i];
4820 qemu_put_be32(f, u.i);
4823 qemu_put_betls(f, &env->pc);
4824 qemu_put_betls(f, &env->npc);
4825 qemu_put_betls(f, &env->y);
4826 tmp = GET_PSR(env);
4827 qemu_put_be32(f, tmp);
4828 qemu_put_betls(f, &env->fsr);
4829 qemu_put_betls(f, &env->tbr);
4830 #ifndef TARGET_SPARC64
4831 qemu_put_be32s(f, &env->wim);
4832 /* MMU */
4833 for(i = 0; i < 16; i++)
4834 qemu_put_be32s(f, &env->mmuregs[i]);
4835 #endif
4838 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4840 CPUState *env = opaque;
4841 int i;
4842 uint32_t tmp;
4844 for(i = 0; i < 8; i++)
4845 qemu_get_betls(f, &env->gregs[i]);
4846 for(i = 0; i < NWINDOWS * 16; i++)
4847 qemu_get_betls(f, &env->regbase[i]);
4849 /* FPU */
4850 for(i = 0; i < TARGET_FPREGS; i++) {
4851 union {
4852 float32 f;
4853 uint32_t i;
4854 } u;
4855 u.i = qemu_get_be32(f);
4856 env->fpr[i] = u.f;
4859 qemu_get_betls(f, &env->pc);
4860 qemu_get_betls(f, &env->npc);
4861 qemu_get_betls(f, &env->y);
4862 tmp = qemu_get_be32(f);
4863 env->cwp = 0; /* needed to ensure that the wrapping registers are
4864 correctly updated */
4865 PUT_PSR(env, tmp);
4866 qemu_get_betls(f, &env->fsr);
4867 qemu_get_betls(f, &env->tbr);
4868 #ifndef TARGET_SPARC64
4869 qemu_get_be32s(f, &env->wim);
4870 /* MMU */
4871 for(i = 0; i < 16; i++)
4872 qemu_get_be32s(f, &env->mmuregs[i]);
4873 #endif
4874 tlb_flush(env, 1);
4875 return 0;
4878 #elif defined(TARGET_ARM)
4880 /* ??? Need to implement these. */
4881 void cpu_save(QEMUFile *f, void *opaque)
4885 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4887 return 0;
4890 #else
4892 #warning No CPU save/restore functions
4894 #endif
4896 /***********************************************************/
4897 /* ram save/restore */
4899 /* we just avoid storing empty pages */
4900 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4902 int i, v;
4904 v = buf[0];
4905 for(i = 1; i < len; i++) {
4906 if (buf[i] != v)
4907 goto normal_save;
4909 qemu_put_byte(f, 1);
4910 qemu_put_byte(f, v);
4911 return;
4912 normal_save:
4913 qemu_put_byte(f, 0);
4914 qemu_put_buffer(f, buf, len);
4917 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4919 int v;
4921 v = qemu_get_byte(f);
4922 switch(v) {
4923 case 0:
4924 if (qemu_get_buffer(f, buf, len) != len)
4925 return -EIO;
4926 break;
4927 case 1:
4928 v = qemu_get_byte(f);
4929 memset(buf, v, len);
4930 break;
4931 default:
4932 return -EINVAL;
4934 return 0;
4937 static void ram_save(QEMUFile *f, void *opaque)
4939 int i;
4940 qemu_put_be32(f, phys_ram_size);
4941 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4942 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4946 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4948 int i, ret;
4950 if (version_id != 1)
4951 return -EINVAL;
4952 if (qemu_get_be32(f) != phys_ram_size)
4953 return -EINVAL;
4954 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4955 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4956 if (ret)
4957 return ret;
4959 return 0;
4961 #else /* CONFIG_DM */
4962 void cpu_save(QEMUFile *f, void *opaque)
4966 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4968 return 0;
4971 static void ram_save(QEMUFile *f, void *opaque)
4975 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4977 return 0;
4979 #endif /* CONFIG_DM */
4981 /***********************************************************/
4982 /* machine registration */
4984 QEMUMachine *first_machine = NULL;
4986 int qemu_register_machine(QEMUMachine *m)
4988 QEMUMachine **pm;
4989 pm = &first_machine;
4990 while (*pm != NULL)
4991 pm = &(*pm)->next;
4992 m->next = NULL;
4993 *pm = m;
4994 return 0;
4997 QEMUMachine *find_machine(const char *name)
4999 QEMUMachine *m;
5001 for(m = first_machine; m != NULL; m = m->next) {
5002 if (!strcmp(m->name, name))
5003 return m;
5005 return NULL;
5008 /***********************************************************/
5009 /* main execution loop */
5011 void gui_update(void *opaque)
5013 display_state.dpy_refresh(&display_state);
5014 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5017 struct vm_change_state_entry {
5018 VMChangeStateHandler *cb;
5019 void *opaque;
5020 LIST_ENTRY (vm_change_state_entry) entries;
5021 };
5023 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5025 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5026 void *opaque)
5028 VMChangeStateEntry *e;
5030 e = qemu_mallocz(sizeof (*e));
5031 if (!e)
5032 return NULL;
5034 e->cb = cb;
5035 e->opaque = opaque;
5036 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5037 return e;
5040 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5042 LIST_REMOVE (e, entries);
5043 qemu_free (e);
5046 static void vm_state_notify(int running)
5048 VMChangeStateEntry *e;
5050 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5051 e->cb(e->opaque, running);
5055 /* XXX: support several handlers */
5056 static VMStopHandler *vm_stop_cb;
5057 static void *vm_stop_opaque;
5059 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5061 vm_stop_cb = cb;
5062 vm_stop_opaque = opaque;
5063 return 0;
5066 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5068 vm_stop_cb = NULL;
5071 void vm_start(void)
5073 if (!vm_running) {
5074 cpu_enable_ticks();
5075 vm_running = 1;
5076 vm_state_notify(1);
5080 void vm_stop(int reason)
5082 if (vm_running) {
5083 cpu_disable_ticks();
5084 vm_running = 0;
5085 if (reason != 0) {
5086 if (vm_stop_cb) {
5087 vm_stop_cb(vm_stop_opaque, reason);
5090 vm_state_notify(0);
5094 /* reset/shutdown handler */
5096 typedef struct QEMUResetEntry {
5097 QEMUResetHandler *func;
5098 void *opaque;
5099 struct QEMUResetEntry *next;
5100 } QEMUResetEntry;
5102 static QEMUResetEntry *first_reset_entry;
5103 int reset_requested;
5104 int shutdown_requested;
5105 int suspend_requested;
5106 static int powerdown_requested;
5108 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5110 QEMUResetEntry **pre, *re;
5112 pre = &first_reset_entry;
5113 while (*pre != NULL)
5114 pre = &(*pre)->next;
5115 re = qemu_mallocz(sizeof(QEMUResetEntry));
5116 re->func = func;
5117 re->opaque = opaque;
5118 re->next = NULL;
5119 *pre = re;
5122 void qemu_system_reset(void)
5124 QEMUResetEntry *re;
5126 /* reset all devices */
5127 for(re = first_reset_entry; re != NULL; re = re->next) {
5128 re->func(re->opaque);
5132 void qemu_system_reset_request(void)
5134 reset_requested = 1;
5135 if (cpu_single_env)
5136 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5139 void qemu_system_shutdown_request(void)
5141 shutdown_requested = 1;
5142 if (cpu_single_env)
5143 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5146 void qemu_system_powerdown_request(void)
5148 powerdown_requested = 1;
5149 if (cpu_single_env)
5150 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5153 void main_loop_wait(int timeout)
5155 IOHandlerRecord *ioh, *ioh_next;
5156 fd_set rfds, wfds, xfds;
5157 int ret, nfds;
5158 struct timeval tv;
5159 PollingEntry *pe;
5162 /* XXX: need to suppress polling by better using win32 events */
5163 ret = 0;
5164 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5165 ret |= pe->func(pe->opaque);
5167 #ifdef _WIN32
5168 if (ret == 0 && timeout > 0) {
5169 int err;
5170 WaitObjects *w = &wait_objects;
5172 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5173 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5174 if (w->func[ret - WAIT_OBJECT_0])
5175 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5176 } else if (ret == WAIT_TIMEOUT) {
5177 } else {
5178 err = GetLastError();
5179 fprintf(stderr, "Wait error %d %d\n", ret, err);
5182 #endif
5183 /* poll any events */
5184 /* XXX: separate device handlers from system ones */
5185 nfds = -1;
5186 FD_ZERO(&rfds);
5187 FD_ZERO(&wfds);
5188 FD_ZERO(&xfds);
5189 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5190 if (ioh->fd_read &&
5191 (!ioh->fd_read_poll ||
5192 ioh->fd_read_poll(ioh->opaque) != 0)) {
5193 FD_SET(ioh->fd, &rfds);
5194 if (ioh->fd > nfds)
5195 nfds = ioh->fd;
5197 if (ioh->fd_write) {
5198 FD_SET(ioh->fd, &wfds);
5199 if (ioh->fd > nfds)
5200 nfds = ioh->fd;
5204 tv.tv_sec = 0;
5205 #ifdef _WIN32
5206 tv.tv_usec = 0;
5207 #else
5208 tv.tv_usec = timeout * 1000;
5209 #endif
5210 #if defined(CONFIG_SLIRP)
5211 if (slirp_inited) {
5212 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5214 #endif
5215 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5216 if (ret > 0) {
5217 /* XXX: better handling of removal */
5218 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5219 ioh_next = ioh->next;
5220 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
5221 ioh->fd_read(ioh->opaque);
5223 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
5224 ioh->fd_write(ioh->opaque);
5228 #if defined(CONFIG_SLIRP)
5229 if (slirp_inited) {
5230 if (ret < 0) {
5231 FD_ZERO(&rfds);
5232 FD_ZERO(&wfds);
5233 FD_ZERO(&xfds);
5235 slirp_select_poll(&rfds, &wfds, &xfds);
5237 #endif
5238 #ifdef _WIN32
5239 tap_win32_poll();
5240 #endif
5242 if (vm_running) {
5243 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5244 qemu_get_clock(vm_clock));
5245 /* run dma transfers, if any */
5246 DMA_run();
5249 /* real time timers */
5250 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5251 qemu_get_clock(rt_clock));
5254 #ifndef CONFIG_DM
5255 static CPUState *cur_cpu;
5257 int main_loop(void)
5259 int ret, timeout;
5260 #ifdef CONFIG_PROFILER
5261 int64_t ti;
5262 #endif
5263 CPUState *env;
5265 cur_cpu = first_cpu;
5266 for(;;) {
5267 if (vm_running) {
5269 env = cur_cpu;
5270 for(;;) {
5271 /* get next cpu */
5272 env = env->next_cpu;
5273 if (!env)
5274 env = first_cpu;
5275 #ifdef CONFIG_PROFILER
5276 ti = profile_getclock();
5277 #endif
5278 ret = cpu_exec(env);
5279 #ifdef CONFIG_PROFILER
5280 qemu_time += profile_getclock() - ti;
5281 #endif
5282 if (ret != EXCP_HALTED)
5283 break;
5284 /* all CPUs are halted ? */
5285 if (env == cur_cpu) {
5286 ret = EXCP_HLT;
5287 break;
5290 cur_cpu = env;
5292 if (shutdown_requested) {
5293 ret = EXCP_INTERRUPT;
5294 break;
5296 if (reset_requested) {
5297 reset_requested = 0;
5298 qemu_system_reset();
5299 ret = EXCP_INTERRUPT;
5301 if (powerdown_requested) {
5302 powerdown_requested = 0;
5303 qemu_system_powerdown();
5304 ret = EXCP_INTERRUPT;
5306 if (ret == EXCP_DEBUG) {
5307 vm_stop(EXCP_DEBUG);
5309 /* if hlt instruction, we wait until the next IRQ */
5310 /* XXX: use timeout computed from timers */
5311 if (ret == EXCP_HLT)
5312 timeout = 10;
5313 else
5314 timeout = 0;
5315 } else {
5316 timeout = 10;
5318 #ifdef CONFIG_PROFILER
5319 ti = profile_getclock();
5320 #endif
5321 main_loop_wait(timeout);
5322 #ifdef CONFIG_PROFILER
5323 dev_time += profile_getclock() - ti;
5324 #endif
5326 cpu_disable_ticks();
5327 return ret;
5329 #endif /* !CONFIG_DM */
5331 void help(void)
5333 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5334 "usage: %s [options] [disk_image]\n"
5335 "\n"
5336 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5337 "\n"
5338 "Standard options:\n"
5339 "-M machine select emulated machine (-M ? for list)\n"
5340 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5341 #ifndef CONFIG_DM
5342 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5343 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5344 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5345 #endif /* !CONFIG_DM */
5346 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5347 "-snapshot write to temporary files instead of disk image files\n"
5348 #ifdef TARGET_I386
5349 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5350 #endif
5351 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5352 "-smp n set the number of CPUs to 'n' [default=1]\n"
5353 "-nographic disable graphical output and redirect serial I/Os to console\n"
5354 "-vcpus set CPU number of guest platform\n"
5355 #ifndef _WIN32
5356 "-k language use keyboard layout (for example \"fr\" for French)\n"
5357 #endif
5358 #ifdef HAS_AUDIO
5359 "-audio-help print list of audio drivers and their options\n"
5360 "-soundhw c1,... enable audio support\n"
5361 " and only specified sound cards (comma separated list)\n"
5362 " use -soundhw ? to get the list of supported cards\n"
5363 " use -soundhw all to enable all of them\n"
5364 #endif
5365 "-localtime set the real time clock to local time [default=utc]\n"
5366 "-full-screen start in full screen\n"
5367 #ifdef TARGET_I386
5368 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5369 #endif
5370 "-usb enable the USB driver (will be the default soon)\n"
5371 "-usbdevice name add the host or guest USB device 'name'\n"
5372 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5373 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5374 #endif
5375 "\n"
5376 "Network options:\n"
5377 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5378 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5379 #ifdef CONFIG_SLIRP
5380 "-net user[,vlan=n][,hostname=host]\n"
5381 " connect the user mode network stack to VLAN 'n' and send\n"
5382 " hostname 'host' to DHCP clients\n"
5383 #endif
5384 #ifdef _WIN32
5385 "-net tap[,vlan=n],ifname=name\n"
5386 " connect the host TAP network interface to VLAN 'n'\n"
5387 #else
5388 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
5389 " connect the host TAP network interface to VLAN 'n' and use\n"
5390 " the network script 'file' (default=%s);\n"
5391 " use 'fd=h' to connect to an already opened TAP interface\n"
5392 #endif
5393 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5394 " connect the vlan 'n' to another VLAN using a socket connection\n"
5395 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5396 " connect the vlan 'n' to multicast maddr and port\n"
5397 "-net none use it alone to have zero network devices; if no -net option\n"
5398 " is provided, the default is '-net nic -net user'\n"
5399 "\n"
5400 #ifdef CONFIG_SLIRP
5401 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5402 #ifndef _WIN32
5403 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5404 #endif
5405 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5406 " redirect TCP or UDP connections from host to guest [-net user]\n"
5407 #endif
5408 "\n"
5409 "Linux boot specific:\n"
5410 "-kernel bzImage use 'bzImage' as kernel image\n"
5411 "-append cmdline use 'cmdline' as kernel command line\n"
5412 "-initrd file use 'file' as initial ram disk\n"
5413 "\n"
5414 "Debug/Expert options:\n"
5415 "-monitor dev redirect the monitor to char device 'dev'\n"
5416 "-serial dev redirect the serial port to char device 'dev'\n"
5417 "-parallel dev redirect the parallel port to char device 'dev'\n"
5418 "-pidfile file Write PID to 'file'\n"
5419 "-S freeze CPU at startup (use 'c' to start execution)\n"
5420 "-s wait gdb connection to port %d\n"
5421 "-p port change gdb connection port\n"
5422 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
5423 "-d domain domain that we're serving\n"
5424 "-domain-name domain name that we're serving\n"
5425 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5426 " translation (t=none or lba) (usually qemu can guess them)\n"
5427 "-L path set the directory for the BIOS and VGA BIOS\n"
5428 #ifdef USE_KQEMU
5429 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5430 "-no-kqemu disable KQEMU kernel module usage\n"
5431 #endif
5432 #ifdef USE_CODE_COPY
5433 "-no-code-copy disable code copy acceleration\n"
5434 #endif
5435 #ifdef TARGET_I386
5436 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5437 " (default is CL-GD5446 PCI VGA)\n"
5438 "-no-acpi disable ACPI\n"
5439 #endif
5440 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5441 "-vnc display start a VNC server on display\n"
5442 "-vncviewer start a vncviewer process for this domain\n"
5443 "-vncunused bind the VNC server to an unused port\n"
5444 "-vnclisten bind the VNC server to this address\n"
5445 "-timeoffset time offset (in seconds) from local time\n"
5446 "-acpi disable or enable ACPI of HVM domain \n"
5447 "\n"
5448 "During emulation, the following keys are useful:\n"
5449 "ctrl-alt-f toggle full screen\n"
5450 "ctrl-alt-n switch to virtual console 'n'\n"
5451 "ctrl-alt toggle mouse and keyboard grab\n"
5452 "\n"
5453 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5455 "qemu",
5456 DEFAULT_RAM_SIZE,
5457 #ifndef _WIN32
5458 DEFAULT_NETWORK_SCRIPT,
5459 #endif
5460 DEFAULT_GDBSTUB_PORT,
5461 "/tmp/qemu.log");
5462 exit(1);
5465 #define HAS_ARG 0x0001
5467 enum {
5468 QEMU_OPTION_h,
5470 QEMU_OPTION_M,
5471 QEMU_OPTION_fda,
5472 QEMU_OPTION_fdb,
5473 #ifndef CONFIG_DM
5474 QEMU_OPTION_hda,
5475 QEMU_OPTION_hdb,
5476 QEMU_OPTION_hdc,
5477 QEMU_OPTION_hdd,
5478 QEMU_OPTION_cdrom,
5479 #endif /* !CONFIG_DM */
5480 QEMU_OPTION_boot,
5481 QEMU_OPTION_snapshot,
5482 #ifdef TARGET_I386
5483 QEMU_OPTION_no_fd_bootchk,
5484 #endif
5485 QEMU_OPTION_m,
5486 QEMU_OPTION_nographic,
5487 #ifdef HAS_AUDIO
5488 QEMU_OPTION_audio_help,
5489 QEMU_OPTION_soundhw,
5490 #endif
5492 QEMU_OPTION_net,
5493 QEMU_OPTION_tftp,
5494 QEMU_OPTION_smb,
5495 QEMU_OPTION_redir,
5497 QEMU_OPTION_kernel,
5498 QEMU_OPTION_append,
5499 QEMU_OPTION_initrd,
5501 QEMU_OPTION_S,
5502 QEMU_OPTION_s,
5503 QEMU_OPTION_p,
5504 QEMU_OPTION_l,
5505 QEMU_OPTION_hdachs,
5506 QEMU_OPTION_L,
5507 #ifdef USE_CODE_COPY
5508 QEMU_OPTION_no_code_copy,
5509 #endif
5510 QEMU_OPTION_k,
5511 QEMU_OPTION_localtime,
5512 QEMU_OPTION_cirrusvga,
5513 QEMU_OPTION_g,
5514 QEMU_OPTION_std_vga,
5515 QEMU_OPTION_monitor,
5516 QEMU_OPTION_domainname,
5517 QEMU_OPTION_serial,
5518 QEMU_OPTION_parallel,
5519 QEMU_OPTION_loadvm,
5520 QEMU_OPTION_full_screen,
5521 QEMU_OPTION_pidfile,
5522 QEMU_OPTION_no_kqemu,
5523 QEMU_OPTION_kernel_kqemu,
5524 QEMU_OPTION_win2k_hack,
5525 QEMU_OPTION_usb,
5526 QEMU_OPTION_usbdevice,
5527 QEMU_OPTION_smp,
5528 QEMU_OPTION_vnc,
5529 QEMU_OPTION_no_acpi,
5531 QEMU_OPTION_d,
5532 QEMU_OPTION_vcpus,
5533 QEMU_OPTION_timeoffset,
5534 QEMU_OPTION_acpi,
5535 QEMU_OPTION_vncviewer,
5536 QEMU_OPTION_vncunused,
5537 QEMU_OPTION_vnclisten,
5538 };
5540 typedef struct QEMUOption {
5541 const char *name;
5542 int flags;
5543 int index;
5544 } QEMUOption;
5546 const QEMUOption qemu_options[] = {
5547 { "h", 0, QEMU_OPTION_h },
5549 { "M", HAS_ARG, QEMU_OPTION_M },
5550 { "fda", HAS_ARG, QEMU_OPTION_fda },
5551 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5552 #ifndef CONFIG_DM
5553 { "hda", HAS_ARG, QEMU_OPTION_hda },
5554 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5555 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5556 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5557 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5558 #endif /* !CONFIG_DM */
5559 { "boot", HAS_ARG, QEMU_OPTION_boot },
5560 { "snapshot", 0, QEMU_OPTION_snapshot },
5561 #ifdef TARGET_I386
5562 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5563 #endif
5564 { "m", HAS_ARG, QEMU_OPTION_m },
5565 { "nographic", 0, QEMU_OPTION_nographic },
5566 { "k", HAS_ARG, QEMU_OPTION_k },
5567 #ifdef HAS_AUDIO
5568 { "audio-help", 0, QEMU_OPTION_audio_help },
5569 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5570 #endif
5572 { "net", HAS_ARG, QEMU_OPTION_net},
5573 #ifdef CONFIG_SLIRP
5574 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5575 #ifndef _WIN32
5576 { "smb", HAS_ARG, QEMU_OPTION_smb },
5577 #endif
5578 { "redir", HAS_ARG, QEMU_OPTION_redir },
5579 #endif
5581 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5582 { "append", HAS_ARG, QEMU_OPTION_append },
5583 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5585 { "S", 0, QEMU_OPTION_S },
5586 { "s", 0, QEMU_OPTION_s },
5587 { "p", HAS_ARG, QEMU_OPTION_p },
5588 { "l", HAS_ARG, QEMU_OPTION_l },
5589 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5590 { "L", HAS_ARG, QEMU_OPTION_L },
5591 #ifdef USE_CODE_COPY
5592 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5593 #endif
5594 #ifdef USE_KQEMU
5595 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5596 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5597 #endif
5598 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5599 { "g", 1, QEMU_OPTION_g },
5600 #endif
5601 { "localtime", 0, QEMU_OPTION_localtime },
5602 { "std-vga", 0, QEMU_OPTION_std_vga },
5603 { "monitor", 1, QEMU_OPTION_monitor },
5604 { "domain-name", 1, QEMU_OPTION_domainname },
5605 { "serial", 1, QEMU_OPTION_serial },
5606 { "parallel", 1, QEMU_OPTION_parallel },
5607 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5608 { "full-screen", 0, QEMU_OPTION_full_screen },
5609 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5610 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5611 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5612 { "smp", HAS_ARG, QEMU_OPTION_smp },
5613 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5614 { "vncviewer", 0, QEMU_OPTION_vncviewer },
5615 { "vncunused", 0, QEMU_OPTION_vncunused },
5616 { "vnclisten", HAS_ARG, QEMU_OPTION_vnclisten },
5618 /* temporary options */
5619 { "usb", 0, QEMU_OPTION_usb },
5620 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5621 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5623 { "d", HAS_ARG, QEMU_OPTION_d },
5624 { "vcpus", 1, QEMU_OPTION_vcpus },
5625 { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
5626 { "acpi", 0, QEMU_OPTION_acpi },
5627 { NULL },
5628 };
5630 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5632 /* this stack is only used during signal handling */
5633 #define SIGNAL_STACK_SIZE 32768
5635 static uint8_t *signal_stack;
5637 #endif
5639 /* password input */
5641 static BlockDriverState *get_bdrv(int index)
5643 BlockDriverState *bs;
5645 if (index < 4) {
5646 bs = bs_table[index];
5647 } else if (index < 6) {
5648 bs = fd_table[index - 4];
5649 } else {
5650 bs = NULL;
5652 return bs;
5655 static void read_passwords(void)
5657 BlockDriverState *bs;
5658 int i, j;
5659 char password[256];
5661 for(i = 0; i < 6; i++) {
5662 bs = get_bdrv(i);
5663 if (bs && bdrv_is_encrypted(bs)) {
5664 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5665 for(j = 0; j < 3; j++) {
5666 monitor_readline("Password: ",
5667 1, password, sizeof(password));
5668 if (bdrv_set_key(bs, password) == 0)
5669 break;
5670 term_printf("invalid password\n");
5676 /* XXX: currently we cannot use simultaneously different CPUs */
5677 void register_machines(void)
5679 #if defined(TARGET_I386)
5680 qemu_register_machine(&pc_machine);
5681 qemu_register_machine(&isapc_machine);
5682 #elif defined(TARGET_PPC)
5683 qemu_register_machine(&heathrow_machine);
5684 qemu_register_machine(&core99_machine);
5685 qemu_register_machine(&prep_machine);
5686 #elif defined(TARGET_MIPS)
5687 qemu_register_machine(&mips_machine);
5688 #elif defined(TARGET_SPARC)
5689 #ifdef TARGET_SPARC64
5690 qemu_register_machine(&sun4u_machine);
5691 #else
5692 qemu_register_machine(&sun4m_machine);
5693 #endif
5694 #elif defined(TARGET_ARM)
5695 qemu_register_machine(&integratorcp926_machine);
5696 qemu_register_machine(&integratorcp1026_machine);
5697 qemu_register_machine(&versatilepb_machine);
5698 qemu_register_machine(&versatileab_machine);
5699 #elif defined(TARGET_SH4)
5700 qemu_register_machine(&shix_machine);
5701 #else
5702 #error unsupported CPU
5703 #endif
5706 #ifdef HAS_AUDIO
5707 struct soundhw soundhw[] = {
5708 #ifndef CONFIG_DM
5709 #ifdef TARGET_I386
5711 "pcspk",
5712 "PC speaker",
5713 0,
5714 1,
5715 { .init_isa = pcspk_audio_init }
5716 },
5717 #endif
5718 #endif /* !CONFIG_DM */
5720 "sb16",
5721 "Creative Sound Blaster 16",
5722 0,
5723 1,
5724 { .init_isa = SB16_init }
5725 },
5727 #ifdef CONFIG_ADLIB
5729 "adlib",
5730 #ifdef HAS_YMF262
5731 "Yamaha YMF262 (OPL3)",
5732 #else
5733 "Yamaha YM3812 (OPL2)",
5734 #endif
5735 0,
5736 1,
5737 { .init_isa = Adlib_init }
5738 },
5739 #endif
5741 #ifdef CONFIG_GUS
5743 "gus",
5744 "Gravis Ultrasound GF1",
5745 0,
5746 1,
5747 { .init_isa = GUS_init }
5748 },
5749 #endif
5752 "es1370",
5753 "ENSONIQ AudioPCI ES1370",
5754 0,
5755 0,
5756 { .init_pci = es1370_init }
5757 },
5759 { NULL, NULL, 0, 0, { NULL } }
5760 };
5762 static void select_soundhw (const char *optarg)
5764 struct soundhw *c;
5766 if (*optarg == '?') {
5767 show_valid_cards:
5769 printf ("Valid sound card names (comma separated):\n");
5770 for (c = soundhw; c->name; ++c) {
5771 printf ("%-11s %s\n", c->name, c->descr);
5773 printf ("\n-soundhw all will enable all of the above\n");
5774 exit (*optarg != '?');
5776 else {
5777 size_t l;
5778 const char *p;
5779 char *e;
5780 int bad_card = 0;
5782 if (!strcmp (optarg, "all")) {
5783 for (c = soundhw; c->name; ++c) {
5784 c->enabled = 1;
5786 return;
5789 p = optarg;
5790 while (*p) {
5791 e = strchr (p, ',');
5792 l = !e ? strlen (p) : (size_t) (e - p);
5794 for (c = soundhw; c->name; ++c) {
5795 if (!strncmp (c->name, p, l)) {
5796 c->enabled = 1;
5797 break;
5801 if (!c->name) {
5802 if (l > 80) {
5803 fprintf (stderr,
5804 "Unknown sound card name (too big to show)\n");
5806 else {
5807 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5808 (int) l, p);
5810 bad_card = 1;
5812 p += l + (e != NULL);
5815 if (bad_card)
5816 goto show_valid_cards;
5819 #endif
5821 #ifdef _WIN32
5822 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5824 exit(STATUS_CONTROL_C_EXIT);
5825 return TRUE;
5827 #endif
5829 #define MAX_NET_CLIENTS 32
5831 #include <xg_private.h>
5833 /* FIXME Flush the shadow page */
5834 int unset_mm_mapping(int xc_handle, uint32_t domid,
5835 unsigned long nr_pages, unsigned int address_bits,
5836 xen_pfn_t *extent_start)
5838 int err = 0;
5839 xc_dominfo_t info;
5841 xc_domain_getinfo(xc_handle, domid, 1, &info);
5842 if ((info.nr_pages - nr_pages) <= 0) {
5843 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
5844 err = -1;
5847 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
5848 nr_pages, 0, extent_start);
5849 if (err)
5850 fprintf(stderr, "Failed to decrease physmap\n");
5853 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
5854 PAGE_SIZE/1024) != 0) {
5855 fprintf(logfile, "set maxmem returned error %d\n", errno);
5856 err = -1;
5859 return err;
5862 int set_mm_mapping(int xc_handle, uint32_t domid,
5863 unsigned long nr_pages, unsigned int address_bits,
5864 xen_pfn_t *extent_start)
5866 xc_dominfo_t info;
5867 int err = 0;
5869 xc_domain_getinfo(xc_handle, domid, 1, &info);
5871 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
5872 nr_pages * PAGE_SIZE/1024) != 0) {
5873 fprintf(logfile, "set maxmem returned error %d\n", errno);
5874 return -1;
5877 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
5878 address_bits, extent_start);
5879 if (err) {
5880 fprintf(stderr, "Failed to populate physmap\n");
5881 return -1;
5884 return 0;
5887 void suspend(int sig)
5889 fprintf(logfile, "suspend sig handler called with requested=%d!\n", suspend_requested);
5890 if (sig != SIGUSR1)
5891 fprintf(logfile, "suspend signal dismatch, get sig=%d!\n", sig);
5892 suspend_requested = 1;
5895 #if defined(__i386__) || defined(__x86_64__)
5896 static struct map_cache *mapcache_entry;
5897 static unsigned long nr_buckets;
5899 /* For most cases (>99.9%), the page address is the same. */
5900 static unsigned long last_address_index = ~0UL;
5901 static uint8_t *last_address_vaddr;
5903 static int qemu_map_cache_init(unsigned long nr_pages)
5905 unsigned long max_pages = MAX_MCACHE_SIZE >> PAGE_SHIFT;
5906 int i;
5908 if (nr_pages < max_pages)
5909 max_pages = nr_pages;
5911 nr_buckets = max_pages + (1UL << (MCACHE_BUCKET_SHIFT - PAGE_SHIFT)) - 1;
5912 nr_buckets >>= (MCACHE_BUCKET_SHIFT - PAGE_SHIFT);
5913 fprintf(logfile, "qemu_map_cache_init nr_buckets = %lx\n", nr_buckets);
5915 mapcache_entry = malloc(nr_buckets * sizeof(struct map_cache));
5916 if (mapcache_entry == NULL) {
5917 errno = ENOMEM;
5918 return -1;
5921 memset(mapcache_entry, 0, nr_buckets * sizeof(struct map_cache));
5923 /*
5924 * To avoid ENOMEM from xc_map_foreign_batch() at runtime, we
5925 * pre-fill all the map caches in advance.
5926 */
5927 for (i = 0; i < nr_buckets; i++)
5928 (void)qemu_map_cache(((target_phys_addr_t)i) << MCACHE_BUCKET_SHIFT);
5930 return 0;
5933 uint8_t *qemu_map_cache(target_phys_addr_t phys_addr)
5935 struct map_cache *entry;
5936 unsigned long address_index = phys_addr >> MCACHE_BUCKET_SHIFT;
5937 unsigned long address_offset = phys_addr & (MCACHE_BUCKET_SIZE-1);
5939 if (address_index == last_address_index)
5940 return last_address_vaddr + address_offset;
5942 entry = &mapcache_entry[address_index % nr_buckets];
5944 if (entry->vaddr_base == NULL || entry->paddr_index != address_index) {
5945 /* We need to remap a bucket. */
5946 uint8_t *vaddr_base;
5947 unsigned long pfns[MCACHE_BUCKET_SIZE >> PAGE_SHIFT];
5948 unsigned int i;
5950 if (entry->vaddr_base != NULL) {
5951 errno = munmap(entry->vaddr_base, MCACHE_BUCKET_SIZE);
5952 if (errno) {
5953 fprintf(logfile, "unmap fails %d\n", errno);
5954 exit(-1);
5958 for (i = 0; i < MCACHE_BUCKET_SIZE >> PAGE_SHIFT; i++)
5959 pfns[i] = (address_index << (MCACHE_BUCKET_SHIFT-PAGE_SHIFT)) + i;
5961 vaddr_base = xc_map_foreign_batch(
5962 xc_handle, domid, PROT_READ|PROT_WRITE,
5963 pfns, MCACHE_BUCKET_SIZE >> PAGE_SHIFT);
5964 if (vaddr_base == NULL) {
5965 fprintf(logfile, "xc_map_foreign_batch error %d\n", errno);
5966 exit(-1);
5969 entry->vaddr_base = vaddr_base;
5970 entry->paddr_index = address_index;;
5973 last_address_index = address_index;
5974 last_address_vaddr = entry->vaddr_base;
5976 return last_address_vaddr + address_offset;
5979 void qemu_invalidate_map_cache(void)
5981 unsigned long i;
5983 mapcache_lock();
5985 for (i = 0; i < nr_buckets; i++) {
5986 struct map_cache *entry = &mapcache_entry[i];
5988 if (entry->vaddr_base == NULL)
5989 continue;
5991 errno = munmap(entry->vaddr_base, MCACHE_BUCKET_SIZE);
5992 if (errno) {
5993 fprintf(logfile, "unmap fails %d\n", errno);
5994 exit(-1);
5997 entry->paddr_index = 0;
5998 entry->vaddr_base = NULL;
6001 last_address_index = ~0UL;
6002 last_address_vaddr = NULL;
6004 mapcache_unlock();
6006 #endif
6008 int main(int argc, char **argv)
6010 #ifdef CONFIG_GDBSTUB
6011 int use_gdbstub, gdbstub_port;
6012 #endif
6013 int i;
6014 #ifndef CONFIG_DM
6015 int cdrom_index;
6016 #endif /* !CONFIG_DM */
6017 int snapshot, linux_boot;
6018 const char *initrd_filename;
6019 #ifndef CONFIG_DM
6020 const char *hd_filename[MAX_DISKS];
6021 #endif /* !CONFIG_DM */
6022 const char *fd_filename[MAX_FD];
6023 const char *kernel_filename, *kernel_cmdline;
6024 DisplayState *ds = &display_state;
6025 int cyls, heads, secs, translation;
6026 int start_emulation = 1;
6027 char net_clients[MAX_NET_CLIENTS][256];
6028 int nb_net_clients;
6029 int optind;
6030 const char *r, *optarg;
6031 CharDriverState *monitor_hd;
6032 char monitor_device[128];
6033 char serial_devices[MAX_SERIAL_PORTS][128];
6034 int serial_device_index;
6035 char parallel_devices[MAX_PARALLEL_PORTS][128];
6036 int parallel_device_index;
6037 const char *loadvm = NULL;
6038 QEMUMachine *machine;
6039 char usb_devices[MAX_USB_CMDLINE][128];
6040 int usb_devices_index;
6041 unsigned long nr_pages, tmp_nr_pages, shared_page_nr;
6042 xen_pfn_t *page_array;
6043 extern void *shared_page;
6044 extern void *buffered_io_page;
6045 extern void *buffered_pio_page;
6047 char qemu_dm_logfilename[64];
6049 LIST_INIT (&vm_change_state_head);
6050 #ifndef _WIN32
6052 struct sigaction act;
6053 sigfillset(&act.sa_mask);
6054 act.sa_flags = 0;
6055 act.sa_handler = SIG_IGN;
6056 sigaction(SIGPIPE, &act, NULL);
6058 #else
6059 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6060 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6061 QEMU to run on a single CPU */
6063 HANDLE h;
6064 DWORD mask, smask;
6065 int i;
6066 h = GetCurrentProcess();
6067 if (GetProcessAffinityMask(h, &mask, &smask)) {
6068 for(i = 0; i < 32; i++) {
6069 if (mask & (1 << i))
6070 break;
6072 if (i != 32) {
6073 mask = 1 << i;
6074 SetProcessAffinityMask(h, mask);
6078 #endif
6080 register_machines();
6081 machine = first_machine;
6082 initrd_filename = NULL;
6083 for(i = 0; i < MAX_FD; i++)
6084 fd_filename[i] = NULL;
6085 #ifndef CONFIG_DM
6086 for(i = 0; i < MAX_DISKS; i++)
6087 hd_filename[i] = NULL;
6088 #endif /* !CONFIG_DM */
6089 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6090 vga_ram_size = VGA_RAM_SIZE;
6091 bios_size = BIOS_SIZE;
6092 #ifdef CONFIG_GDBSTUB
6093 use_gdbstub = 0;
6094 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6095 #endif
6096 snapshot = 0;
6097 nographic = 0;
6098 vncviewer = 0;
6099 vncunused = 0;
6100 kernel_filename = NULL;
6101 kernel_cmdline = "";
6102 *vncpasswd = '\0';
6103 #ifndef CONFIG_DM
6104 #ifdef TARGET_PPC
6105 cdrom_index = 1;
6106 #else
6107 cdrom_index = 2;
6108 #endif
6109 #endif /* !CONFIG_DM */
6110 cyls = heads = secs = 0;
6111 translation = BIOS_ATA_TRANSLATION_AUTO;
6112 pstrcpy(monitor_device, sizeof(monitor_device), "null");
6114 for(i = 0; i < MAX_SERIAL_PORTS; i++)
6115 serial_devices[i][0] = '\0';
6116 serial_device_index = 0;
6118 #ifndef CONFIG_DM
6119 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6120 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6121 #else
6122 /* Xen steals IRQ7 for PCI. Disable LPT1 by default. */
6123 for(i = 0; i < MAX_PARALLEL_PORTS; i++)
6124 #endif
6125 parallel_devices[i][0] = '\0';
6126 parallel_device_index = 0;
6128 usb_devices_index = 0;
6130 nb_net_clients = 0;
6132 nb_nics = 0;
6133 /* default mac address of the first network interface */
6135 memset(&vnclisten_addr.sin_addr, 0, sizeof(vnclisten_addr.sin_addr));
6137 /* init debug */
6138 sprintf(qemu_dm_logfilename, "/var/log/xen/qemu-dm.%ld.log", (long)getpid());
6139 cpu_set_log_filename(qemu_dm_logfilename);
6140 cpu_set_log(0);
6142 optind = 1;
6143 for(;;) {
6144 if (optind >= argc)
6145 break;
6146 r = argv[optind];
6147 if (r[0] != '-') {
6148 #ifndef CONFIG_DM
6149 hd_filename[0] = argv[optind++];
6150 #else
6151 help();
6152 #endif /* !CONFIG_DM */
6153 } else {
6154 const QEMUOption *popt;
6156 optind++;
6157 popt = qemu_options;
6158 for(;;) {
6159 if (!popt->name) {
6160 fprintf(stderr, "%s: invalid option -- '%s'\n",
6161 argv[0], r);
6162 exit(1);
6164 if (!strcmp(popt->name, r + 1))
6165 break;
6166 popt++;
6168 if (popt->flags & HAS_ARG) {
6169 if (optind >= argc) {
6170 fprintf(stderr, "%s: option '%s' requires an argument\n",
6171 argv[0], r);
6172 exit(1);
6174 optarg = argv[optind++];
6175 } else {
6176 optarg = NULL;
6179 switch(popt->index) {
6180 case QEMU_OPTION_M:
6181 machine = find_machine(optarg);
6182 if (!machine) {
6183 QEMUMachine *m;
6184 printf("Supported machines are:\n");
6185 for(m = first_machine; m != NULL; m = m->next) {
6186 printf("%-10s %s%s\n",
6187 m->name, m->desc,
6188 m == first_machine ? " (default)" : "");
6190 exit(1);
6192 break;
6193 case QEMU_OPTION_initrd:
6194 initrd_filename = optarg;
6195 break;
6196 #ifndef CONFIG_DM
6197 case QEMU_OPTION_hda:
6198 case QEMU_OPTION_hdb:
6199 case QEMU_OPTION_hdc:
6200 case QEMU_OPTION_hdd:
6202 int hd_index;
6203 hd_index = popt->index - QEMU_OPTION_hda;
6204 hd_filename[hd_index] = optarg;
6205 if (hd_index == cdrom_index)
6206 cdrom_index = -1;
6208 break;
6209 #endif /* !CONFIG_DM */
6210 case QEMU_OPTION_snapshot:
6211 snapshot = 1;
6212 break;
6213 case QEMU_OPTION_hdachs:
6215 const char *p;
6216 p = optarg;
6217 cyls = strtol(p, (char **)&p, 0);
6218 if (cyls < 1 || cyls > 16383)
6219 goto chs_fail;
6220 if (*p != ',')
6221 goto chs_fail;
6222 p++;
6223 heads = strtol(p, (char **)&p, 0);
6224 if (heads < 1 || heads > 16)
6225 goto chs_fail;
6226 if (*p != ',')
6227 goto chs_fail;
6228 p++;
6229 secs = strtol(p, (char **)&p, 0);
6230 if (secs < 1 || secs > 63)
6231 goto chs_fail;
6232 if (*p == ',') {
6233 p++;
6234 if (!strcmp(p, "none"))
6235 translation = BIOS_ATA_TRANSLATION_NONE;
6236 else if (!strcmp(p, "lba"))
6237 translation = BIOS_ATA_TRANSLATION_LBA;
6238 else if (!strcmp(p, "auto"))
6239 translation = BIOS_ATA_TRANSLATION_AUTO;
6240 else
6241 goto chs_fail;
6242 } else if (*p != '\0') {
6243 chs_fail:
6244 fprintf(stderr, "qemu: invalid physical CHS format\n");
6245 exit(1);
6248 break;
6249 case QEMU_OPTION_nographic:
6250 if(!strcmp(monitor_device, "vc"))
6251 pstrcpy(monitor_device, sizeof(monitor_device), "null");
6252 if(!strcmp(serial_devices[0], "vc"))
6253 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
6254 "null");
6255 nographic = 1;
6256 break;
6257 case QEMU_OPTION_kernel:
6258 kernel_filename = optarg;
6259 break;
6260 case QEMU_OPTION_append:
6261 kernel_cmdline = optarg;
6262 break;
6263 #ifndef CONFIG_DM
6264 case QEMU_OPTION_cdrom:
6265 if (cdrom_index >= 0) {
6266 hd_filename[cdrom_index] = optarg;
6268 break;
6269 #endif /* !CONFIG_DM */
6270 case QEMU_OPTION_boot:
6271 boot_device = strdup(optarg);
6272 if (strspn(boot_device, "acd"
6273 #if defined(TARGET_SPARC) || defined(TARGET_I386)
6274 "n"
6275 #endif
6276 ) != strlen(boot_device)) {
6277 fprintf(stderr, "qemu: invalid boot device in '%s'\n",
6278 boot_device);
6279 exit(1);
6281 break;
6282 case QEMU_OPTION_fda:
6283 fd_filename[0] = optarg;
6284 break;
6285 case QEMU_OPTION_fdb:
6286 fd_filename[1] = optarg;
6287 break;
6288 #ifdef TARGET_I386
6289 case QEMU_OPTION_no_fd_bootchk:
6290 fd_bootchk = 0;
6291 break;
6292 #endif
6293 #ifdef USE_CODE_COPY
6294 case QEMU_OPTION_no_code_copy:
6295 code_copy_enabled = 0;
6296 break;
6297 #endif
6298 case QEMU_OPTION_net:
6299 if (nb_net_clients >= MAX_NET_CLIENTS) {
6300 fprintf(stderr, "qemu: too many network clients\n");
6301 exit(1);
6303 pstrcpy(net_clients[nb_net_clients],
6304 sizeof(net_clients[0]),
6305 optarg);
6306 nb_net_clients++;
6307 break;
6308 #ifdef CONFIG_SLIRP
6309 case QEMU_OPTION_tftp:
6310 tftp_prefix = optarg;
6311 break;
6312 #ifndef _WIN32
6313 case QEMU_OPTION_smb:
6314 net_slirp_smb(optarg);
6315 break;
6316 #endif
6317 case QEMU_OPTION_redir:
6318 net_slirp_redir(optarg);
6319 break;
6320 #endif
6321 #ifdef HAS_AUDIO
6322 case QEMU_OPTION_audio_help:
6323 AUD_help ();
6324 exit (0);
6325 break;
6326 case QEMU_OPTION_soundhw:
6327 select_soundhw (optarg);
6328 break;
6329 #endif
6330 case QEMU_OPTION_h:
6331 help();
6332 break;
6333 case QEMU_OPTION_m:
6334 ram_size = atol(optarg) * 1024 * 1024;
6335 ram_size = (uint64_t)atol(optarg) * 1024 * 1024;
6336 if (ram_size <= 0)
6337 help();
6338 #ifndef CONFIG_DM
6339 if (ram_size > PHYS_RAM_MAX_SIZE) {
6340 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6341 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6342 exit(1);
6344 #endif /* !CONFIG_DM */
6345 break;
6346 case QEMU_OPTION_l:
6348 int mask;
6349 CPULogItem *item;
6351 mask = cpu_str_to_log_mask(optarg);
6352 if (!mask) {
6353 printf("Log items (comma separated):\n");
6354 for(item = cpu_log_items; item->mask != 0; item++) {
6355 printf("%-10s %s\n", item->name, item->help);
6357 exit(1);
6359 cpu_set_log(mask);
6361 break;
6362 #ifdef CONFIG_GDBSTUB
6363 case QEMU_OPTION_s:
6364 use_gdbstub = 1;
6365 break;
6366 case QEMU_OPTION_p:
6367 gdbstub_port = atoi(optarg);
6368 break;
6369 #endif
6370 case QEMU_OPTION_L:
6371 bios_dir = optarg;
6372 break;
6373 case QEMU_OPTION_S:
6374 start_emulation = 0;
6375 break;
6376 case QEMU_OPTION_k:
6377 keyboard_layout = optarg;
6378 break;
6379 case QEMU_OPTION_localtime:
6380 rtc_utc = 0;
6381 break;
6382 case QEMU_OPTION_cirrusvga:
6383 cirrus_vga_enabled = 1;
6384 break;
6385 case QEMU_OPTION_std_vga:
6386 cirrus_vga_enabled = 0;
6387 break;
6388 case QEMU_OPTION_g:
6390 const char *p;
6391 int w, h, depth;
6392 p = optarg;
6393 w = strtol(p, (char **)&p, 10);
6394 if (w <= 0) {
6395 graphic_error:
6396 fprintf(stderr, "qemu: invalid resolution or depth\n");
6397 exit(1);
6399 if (*p != 'x')
6400 goto graphic_error;
6401 p++;
6402 h = strtol(p, (char **)&p, 10);
6403 if (h <= 0)
6404 goto graphic_error;
6405 if (*p == 'x') {
6406 p++;
6407 depth = strtol(p, (char **)&p, 10);
6408 if (depth != 8 && depth != 15 && depth != 16 &&
6409 depth != 24 && depth != 32)
6410 goto graphic_error;
6411 } else if (*p == '\0') {
6412 depth = graphic_depth;
6413 } else {
6414 goto graphic_error;
6417 graphic_width = w;
6418 graphic_height = h;
6419 graphic_depth = depth;
6421 break;
6422 case QEMU_OPTION_monitor:
6423 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6424 break;
6425 case QEMU_OPTION_serial:
6426 if (serial_device_index >= MAX_SERIAL_PORTS) {
6427 fprintf(stderr, "qemu: too many serial ports\n");
6428 exit(1);
6430 pstrcpy(serial_devices[serial_device_index],
6431 sizeof(serial_devices[0]), optarg);
6432 serial_device_index++;
6433 break;
6434 case QEMU_OPTION_parallel:
6435 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6436 fprintf(stderr, "qemu: too many parallel ports\n");
6437 exit(1);
6439 pstrcpy(parallel_devices[parallel_device_index],
6440 sizeof(parallel_devices[0]), optarg);
6441 parallel_device_index++;
6442 break;
6443 case QEMU_OPTION_loadvm:
6444 loadvm = optarg;
6445 break;
6446 case QEMU_OPTION_full_screen:
6447 full_screen = 1;
6448 break;
6449 case QEMU_OPTION_pidfile:
6450 create_pidfile(optarg);
6451 break;
6452 #ifdef TARGET_I386
6453 case QEMU_OPTION_win2k_hack:
6454 win2k_install_hack = 1;
6455 break;
6456 #endif
6457 #ifdef USE_KQEMU
6458 case QEMU_OPTION_no_kqemu:
6459 kqemu_allowed = 0;
6460 break;
6461 case QEMU_OPTION_kernel_kqemu:
6462 kqemu_allowed = 2;
6463 break;
6464 #endif
6465 case QEMU_OPTION_usb:
6466 usb_enabled = 1;
6467 break;
6468 case QEMU_OPTION_usbdevice:
6469 usb_enabled = 1;
6470 if (usb_devices_index >= MAX_USB_CMDLINE) {
6471 fprintf(stderr, "Too many USB devices\n");
6472 exit(1);
6474 pstrcpy(usb_devices[usb_devices_index],
6475 sizeof(usb_devices[usb_devices_index]),
6476 optarg);
6477 usb_devices_index++;
6478 break;
6479 case QEMU_OPTION_smp:
6480 smp_cpus = atoi(optarg);
6481 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6482 fprintf(stderr, "Invalid number of CPUs\n");
6483 exit(1);
6485 break;
6486 case QEMU_OPTION_vnc:
6487 vnc_display = atoi(optarg);
6488 if (vnc_display < 0) {
6489 fprintf(stderr, "Invalid VNC display\n");
6490 exit(1);
6492 break;
6493 case QEMU_OPTION_no_acpi:
6494 acpi_enabled = 0;
6495 break;
6496 case QEMU_OPTION_domainname:
6497 strncat(domain_name, optarg, sizeof(domain_name) - 20);
6498 break;
6499 case QEMU_OPTION_d:
6500 domid = atoi(optarg);
6501 fprintf(logfile, "domid: %d\n", domid);
6502 break;
6503 case QEMU_OPTION_vcpus:
6504 vcpus = atoi(optarg);
6505 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
6506 break;
6507 case QEMU_OPTION_timeoffset:
6508 timeoffset = strtol(optarg, NULL, 0);
6509 break;
6510 case QEMU_OPTION_acpi:
6511 acpi_enabled = 1;
6512 break;
6513 case QEMU_OPTION_vncviewer:
6514 vncviewer++;
6515 break;
6516 case QEMU_OPTION_vncunused:
6517 vncunused++;
6518 if (vnc_display == -1)
6519 vnc_display = 0;
6520 break;
6521 case QEMU_OPTION_vnclisten:
6522 parse_host(&vnclisten_addr, optarg);
6523 break;
6528 #ifdef CONFIG_DM
6529 bdrv_init();
6530 xenstore_parse_domain_config(domid);
6531 #endif /* CONFIG_DM */
6533 #ifdef USE_KQEMU
6534 if (smp_cpus > 1)
6535 kqemu_allowed = 0;
6536 #endif
6537 linux_boot = (kernel_filename != NULL);
6539 #ifndef CONFIG_DM
6540 if (!linux_boot &&
6541 hd_filename[0] == '\0' &&
6542 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6543 fd_filename[0] == '\0')
6544 help();
6546 #if 0
6547 /* boot to cd by default if no hard disk */
6548 if (hd_filename[0] == '\0' && boot_device == 'c') {
6549 if (fd_filename[0] != '\0')
6550 boot_device = 'a';
6551 else
6552 boot_device = 'd';
6554 #endif
6555 #endif /* !CONFIG_DM */
6557 setvbuf(stdout, NULL, _IOLBF, 0);
6559 init_timers();
6560 init_timer_alarm();
6562 #ifdef _WIN32
6563 socket_init();
6564 #endif
6566 #ifndef CONFIG_DM
6567 /* init network clients */
6568 if (nb_net_clients == 0) {
6569 /* if no clients, we use a default config */
6570 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6571 "nic");
6572 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6573 "user");
6574 nb_net_clients = 2;
6576 #endif /* !CONFIG_DM */
6578 for(i = 0;i < nb_net_clients; i++) {
6579 if (net_client_init(net_clients[i]) < 0)
6580 exit(1);
6583 #if defined (__ia64__)
6584 if (ram_size > MMIO_START)
6585 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
6586 #endif
6588 /* init the memory */
6589 phys_ram_size = ram_size + vga_ram_size + bios_size;
6591 #ifdef CONFIG_DM
6593 xc_handle = xc_interface_open();
6595 nr_pages = ram_size/PAGE_SIZE;
6596 tmp_nr_pages = nr_pages;
6598 #if defined(__i386__) || defined(__x86_64__)
6599 if (ram_size > HVM_BELOW_4G_RAM_END) {
6600 tmp_nr_pages += HVM_BELOW_4G_MMIO_LENGTH >> PAGE_SHIFT;
6601 shared_page_nr = (HVM_BELOW_4G_RAM_END >> PAGE_SHIFT) - 1;
6602 } else
6603 shared_page_nr = nr_pages - 1;
6604 #endif
6606 #if defined(__i386__) || defined(__x86_64__)
6608 if ( qemu_map_cache_init(tmp_nr_pages) )
6610 fprintf(logfile, "qemu_map_cache_init returned: error %d\n", errno);
6611 exit(-1);
6614 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6615 PROT_READ|PROT_WRITE, shared_page_nr);
6616 if (shared_page == NULL) {
6617 fprintf(logfile, "map shared IO page returned error %d\n", errno);
6618 exit(-1);
6621 fprintf(logfile, "shared page at pfn:%lx\n", shared_page_nr);
6623 buffered_io_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6624 PROT_READ|PROT_WRITE,
6625 shared_page_nr - 2);
6626 if (buffered_io_page == NULL) {
6627 fprintf(logfile, "map buffered IO page returned error %d\n", errno);
6628 exit(-1);
6631 fprintf(logfile, "buffered io page at pfn:%lx\n", shared_page_nr - 2);
6633 #elif defined(__ia64__)
6635 page_array = (xen_pfn_t *)malloc(tmp_nr_pages * sizeof(xen_pfn_t));
6636 if (page_array == NULL) {
6637 fprintf(logfile, "malloc returned error %d\n", errno);
6638 exit(-1);
6641 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6642 PROT_READ|PROT_WRITE,
6643 IO_PAGE_START >> PAGE_SHIFT);
6645 buffered_io_page =xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6646 PROT_READ|PROT_WRITE,
6647 BUFFER_IO_PAGE_START >> PAGE_SHIFT);
6649 buffered_pio_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6650 PROT_READ|PROT_WRITE,
6651 BUFFER_PIO_PAGE_START >> PAGE_SHIFT);
6653 for (i = 0; i < tmp_nr_pages; i++)
6654 page_array[i] = i;
6656 /* VTI will not use memory between 3G~4G, so we just pass a legal pfn
6657 to make QEMU map continuous virtual memory space */
6658 if (ram_size > MMIO_START) {
6659 for (i = 0 ; i < (MEM_G >> PAGE_SHIFT); i++)
6660 page_array[(MMIO_START >> PAGE_SHIFT) + i] =
6661 (STORE_PAGE_START >> PAGE_SHIFT);
6664 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
6665 PROT_READ|PROT_WRITE,
6666 page_array, nr_pages);
6667 if (phys_ram_base == 0) {
6668 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
6669 exit(-1);
6671 free(page_array);
6672 #endif
6673 #else /* !CONFIG_DM */
6675 phys_ram_base = qemu_vmalloc(phys_ram_size);
6676 if (!phys_ram_base) {
6677 fprintf(stderr, "Could not allocate physical memory\n");
6678 exit(1);
6681 #endif /* !CONFIG_DM */
6683 #ifndef CONFIG_DM
6684 /* we always create the cdrom drive, even if no disk is there */
6685 bdrv_init();
6686 if (cdrom_index >= 0) {
6687 bs_table[cdrom_index] = bdrv_new("cdrom");
6688 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6691 /* open the virtual block devices */
6692 for(i = 0; i < MAX_DISKS; i++) {
6693 if (hd_filename[i]) {
6694 if (!bs_table[i]) {
6695 char buf[64];
6696 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6697 bs_table[i] = bdrv_new(buf);
6699 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6700 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6701 hd_filename[i]);
6702 exit(1);
6704 if (i == 0 && cyls != 0) {
6705 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6706 bdrv_set_translation_hint(bs_table[i], translation);
6710 #endif /* !CONFIG_DM */
6712 /* we always create at least one floppy disk */
6713 fd_table[0] = bdrv_new("fda");
6714 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6716 for(i = 0; i < MAX_FD; i++) {
6717 if (fd_filename[i]) {
6718 if (!fd_table[i]) {
6719 char buf[64];
6720 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6721 fd_table[i] = bdrv_new(buf);
6722 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6724 if (fd_filename[i] != '\0') {
6725 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6726 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6727 fd_filename[i]);
6728 exit(1);
6734 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6735 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6737 init_ioports();
6739 /* read vncpasswd from xenstore */
6740 if (0 > xenstore_read_vncpasswd(domid))
6741 exit(1);
6743 /* terminal init */
6744 if (nographic) {
6745 dumb_display_init(ds);
6746 } else if (vnc_display != -1) {
6747 vnc_display = vnc_display_init(ds, vnc_display, vncunused, &vnclisten_addr);
6748 if (vncviewer)
6749 vnc_start_viewer(vnc_display);
6750 xenstore_write_vncport(vnc_display);
6751 } else {
6752 #if defined(CONFIG_SDL)
6753 sdl_display_init(ds, full_screen);
6754 #elif defined(CONFIG_COCOA)
6755 cocoa_display_init(ds, full_screen);
6756 #else
6757 dumb_display_init(ds);
6758 #endif
6761 monitor_hd = qemu_chr_open(monitor_device);
6762 if (!monitor_hd) {
6763 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6764 exit(1);
6766 store_dev_info(monitor_device, domid, monitor_hd, "/monitor");
6767 monitor_init(monitor_hd, !nographic);
6769 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6770 if (serial_devices[i][0] != '\0') {
6771 char buf[16];
6772 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6773 if (!serial_hds[i]) {
6774 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6775 serial_devices[i]);
6776 exit(1);
6778 snprintf(buf, sizeof(buf), "/serial/%d", i);
6779 store_dev_info(serial_devices[i], domid, serial_hds[i], buf);
6780 if (i == 0) /* serial 0 is also called the console */
6781 store_dev_info(serial_devices[i], domid,
6782 serial_hds[i], "/console");
6783 if (!strcmp(serial_devices[i], "vc"))
6784 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6788 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6789 if (parallel_devices[i][0] != '\0') {
6790 char buf[16];
6791 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6792 if (!parallel_hds[i]) {
6793 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6794 parallel_devices[i]);
6795 exit(1);
6797 snprintf(buf, sizeof(buf), "/parallel/%d", i);
6798 store_dev_info(parallel_devices[i], domid, parallel_hds[i], buf);
6799 if (!strcmp(parallel_devices[i], "vc"))
6800 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6804 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
6806 machine->init(ram_size, vga_ram_size, boot_device,
6807 ds, fd_filename, snapshot,
6808 kernel_filename, kernel_cmdline, initrd_filename,
6809 timeoffset);
6810 free(boot_device);
6812 /* init USB devices */
6813 if (usb_enabled) {
6814 for(i = 0; i < usb_devices_index; i++) {
6815 if (usb_device_add(usb_devices[i]) < 0) {
6816 fprintf(stderr, "Warning: could not add USB device %s\n",
6817 usb_devices[i]);
6822 if (vnc_display == -1) {
6823 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6824 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6827 #ifdef CONFIG_GDBSTUB
6828 if (use_gdbstub) {
6829 if (gdbserver_start(gdbstub_port) < 0) {
6830 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6831 gdbstub_port);
6832 exit(1);
6833 } else {
6834 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6836 } else
6837 #endif
6838 if (loadvm)
6839 qemu_loadvm(loadvm);
6842 /* XXX: simplify init */
6843 read_passwords();
6844 if (start_emulation) {
6845 vm_start();
6849 /* register signal for the suspend request when save */
6851 struct sigaction act;
6852 sigset_t set;
6853 act.sa_handler = suspend;
6854 act.sa_flags = SA_RESTART;
6855 sigemptyset(&act.sa_mask);
6857 sigaction(SIGUSR1, &act, NULL);
6859 /* control panel mask some signals when spawn qemu, need unmask here*/
6860 sigemptyset(&set);
6861 sigaddset(&set, SIGUSR1);
6862 sigaddset(&set, SIGTERM);
6863 if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
6864 fprintf(stderr, "unblock signal fail, possible issue for HVM save!\n");
6868 main_loop();
6869 quit_timers();
6870 return 0;