ia64/xen-unstable

view tools/ioemu/vl.c @ 14202:42aa0100574b

hvm: Clean up console-information passing via xenstore.

Each serial, parallel and monitor device in qemu that is connected to
a pty creates a xenstore node of the form:
<domain-path>/monitor/tty
<domain-path>/serial/<n>/tty
<domain-path>/parallel/<n>/tty

In addition, serial/0 (com1) also registers its information at:
<domain-path>/console/tty

Also fix a realloc() failure memory leak.

Signed-off-by: Ben Thomas <ben@virtualiron.com>
author kfraser@localhost.localdomain
date Thu Mar 01 13:57:25 2007 +0000 (2007-03-01)
parents b0f663e668d9
children 095a476a96b1
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 }
846 static int timer_load(QEMUFile *f, void *opaque, int version_id)
847 {
848 return 0;
849 }
850 #else /* !CONFIG_DM */
851 static void timer_save(QEMUFile *f, void *opaque)
852 {
853 if (cpu_ticks_enabled) {
854 hw_error("cannot save state if virtual timers are running");
855 }
856 qemu_put_be64s(f, &cpu_ticks_offset);
857 qemu_put_be64s(f, &ticks_per_sec);
858 }
860 static int timer_load(QEMUFile *f, void *opaque, int version_id)
861 {
862 if (version_id != 1)
863 return -EINVAL;
864 if (cpu_ticks_enabled) {
865 return -EINVAL;
866 }
867 qemu_get_be64s(f, &cpu_ticks_offset);
868 qemu_get_be64s(f, &ticks_per_sec);
869 return 0;
870 }
872 #ifdef _WIN32
873 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
874 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
875 #else
876 static void host_alarm_handler(int host_signum)
877 #endif
878 {
879 #if 0
880 #define DISP_FREQ 1000
881 {
882 static int64_t delta_min = INT64_MAX;
883 static int64_t delta_max, delta_cum, last_clock, delta, ti;
884 static int count;
885 ti = qemu_get_clock(vm_clock);
886 if (last_clock != 0) {
887 delta = ti - last_clock;
888 if (delta < delta_min)
889 delta_min = delta;
890 if (delta > delta_max)
891 delta_max = delta;
892 delta_cum += delta;
893 if (++count == DISP_FREQ) {
894 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
895 muldiv64(delta_min, 1000000, ticks_per_sec),
896 muldiv64(delta_max, 1000000, ticks_per_sec),
897 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
898 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
899 count = 0;
900 delta_min = INT64_MAX;
901 delta_max = 0;
902 delta_cum = 0;
903 }
904 }
905 last_clock = ti;
906 }
907 #endif
908 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
909 qemu_get_clock(vm_clock)) ||
910 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
911 qemu_get_clock(rt_clock))) {
912 #ifdef _WIN32
913 SetEvent(host_alarm);
914 #endif
915 CPUState *env = cpu_single_env;
916 if (env) {
917 /* stop the currently executing cpu because a timer occured */
918 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
919 #ifdef USE_KQEMU
920 if (env->kqemu_enabled) {
921 kqemu_cpu_interrupt(env);
922 }
923 #endif
924 }
925 }
926 }
928 #ifndef _WIN32
930 #if defined(__linux__)
932 #define RTC_FREQ 1024
934 static int rtc_fd;
936 static int start_rtc_timer(void)
937 {
938 rtc_fd = open("/dev/rtc", O_RDONLY);
939 if (rtc_fd < 0)
940 return -1;
941 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
942 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
943 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
944 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
945 goto fail;
946 }
947 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
948 fail:
949 close(rtc_fd);
950 return -1;
951 }
952 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
953 return 0;
954 }
956 #else
958 static int start_rtc_timer(void)
959 {
960 return -1;
961 }
963 #endif /* !defined(__linux__) */
965 #endif /* !defined(_WIN32) */
967 #endif /* !CONFIG_DM */
969 static void init_timer_alarm(void)
970 {
971 #ifdef _WIN32
972 {
973 int count=0;
974 TIMECAPS tc;
976 ZeroMemory(&tc, sizeof(TIMECAPS));
977 timeGetDevCaps(&tc, sizeof(TIMECAPS));
978 if (period < tc.wPeriodMin)
979 period = tc.wPeriodMin;
980 timeBeginPeriod(period);
981 timerID = timeSetEvent(1, // interval (ms)
982 period, // resolution
983 host_alarm_handler, // function
984 (DWORD)&count, // user parameter
985 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
986 if( !timerID ) {
987 perror("failed timer alarm");
988 exit(1);
989 }
990 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
991 if (!host_alarm) {
992 perror("failed CreateEvent");
993 exit(1);
994 }
995 qemu_add_wait_object(host_alarm, NULL, NULL);
996 }
997 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
998 #else
999 {
1000 #ifndef CONFIG_DM
1001 struct sigaction act;
1002 struct itimerval itv;
1003 #endif
1005 /* get times() syscall frequency */
1006 timer_freq = sysconf(_SC_CLK_TCK);
1008 #ifndef CONFIG_DM
1009 /* timer signal */
1010 sigfillset(&act.sa_mask);
1011 act.sa_flags = 0;
1012 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1013 act.sa_flags |= SA_ONSTACK;
1014 #endif
1015 act.sa_handler = host_alarm_handler;
1016 sigaction(SIGALRM, &act, NULL);
1018 itv.it_interval.tv_sec = 0;
1019 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1020 itv.it_value.tv_sec = 0;
1021 itv.it_value.tv_usec = 10 * 1000;
1022 setitimer(ITIMER_REAL, &itv, NULL);
1023 /* we probe the tick duration of the kernel to inform the user if
1024 the emulated kernel requested a too high timer frequency */
1025 getitimer(ITIMER_REAL, &itv);
1027 #if defined(__linux__)
1028 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1029 have timers with 1 ms resolution. The correct solution will
1030 be to use the POSIX real time timers available in recent
1031 2.6 kernels */
1032 if (itv.it_interval.tv_usec > 1000 || 1) {
1033 /* try to use /dev/rtc to have a faster timer */
1034 if (start_rtc_timer() < 0)
1035 goto use_itimer;
1036 /* disable itimer */
1037 itv.it_interval.tv_sec = 0;
1038 itv.it_interval.tv_usec = 0;
1039 itv.it_value.tv_sec = 0;
1040 itv.it_value.tv_usec = 0;
1041 setitimer(ITIMER_REAL, &itv, NULL);
1043 /* use the RTC */
1044 sigaction(SIGIO, &act, NULL);
1045 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1046 fcntl(rtc_fd, F_SETOWN, getpid());
1047 } else
1048 #endif /* defined(__linux__) */
1050 use_itimer:
1051 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1052 PIT_FREQ) / 1000000;
1054 #endif /* CONFIG_DM */
1056 #endif
1059 void quit_timers(void)
1061 #ifdef _WIN32
1062 timeKillEvent(timerID);
1063 timeEndPeriod(period);
1064 if (host_alarm) {
1065 CloseHandle(host_alarm);
1066 host_alarm = NULL;
1068 #endif
1071 /***********************************************************/
1072 /* character device */
1074 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1076 return s->chr_write(s, buf, len);
1079 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1081 if (!s->chr_ioctl)
1082 return -ENOTSUP;
1083 return s->chr_ioctl(s, cmd, arg);
1086 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1088 char buf[4096];
1089 va_list ap;
1090 va_start(ap, fmt);
1091 vsnprintf(buf, sizeof(buf), fmt, ap);
1092 qemu_chr_write(s, buf, strlen(buf));
1093 va_end(ap);
1096 void qemu_chr_send_event(CharDriverState *s, int event)
1098 if (s->chr_send_event)
1099 s->chr_send_event(s, event);
1102 void qemu_chr_add_read_handler(CharDriverState *s,
1103 IOCanRWHandler *fd_can_read,
1104 IOReadHandler *fd_read, void *opaque)
1106 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1109 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1111 s->chr_event = chr_event;
1114 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1116 return len;
1119 static void null_chr_add_read_handler(CharDriverState *chr,
1120 IOCanRWHandler *fd_can_read,
1121 IOReadHandler *fd_read, void *opaque)
1125 CharDriverState *qemu_chr_open_null(void)
1127 CharDriverState *chr;
1129 chr = qemu_mallocz(sizeof(CharDriverState));
1130 if (!chr)
1131 return NULL;
1132 chr->chr_write = null_chr_write;
1133 chr->chr_add_read_handler = null_chr_add_read_handler;
1134 return chr;
1137 #ifdef _WIN32
1139 static void socket_cleanup(void)
1141 WSACleanup();
1144 static int socket_init(void)
1146 WSADATA Data;
1147 int ret, err;
1149 ret = WSAStartup(MAKEWORD(2,2), &Data);
1150 if (ret != 0) {
1151 err = WSAGetLastError();
1152 fprintf(stderr, "WSAStartup: %d\n", err);
1153 return -1;
1155 atexit(socket_cleanup);
1156 return 0;
1159 static int send_all(int fd, const uint8_t *buf, int len1)
1161 int ret, len;
1163 len = len1;
1164 while (len > 0) {
1165 ret = send(fd, buf, len, 0);
1166 if (ret < 0) {
1167 int errno;
1168 errno = WSAGetLastError();
1169 if (errno != WSAEWOULDBLOCK) {
1170 return -1;
1172 } else if (ret == 0) {
1173 break;
1174 } else {
1175 buf += ret;
1176 len -= ret;
1179 return len1 - len;
1182 void socket_set_nonblock(int fd)
1184 unsigned long opt = 1;
1185 ioctlsocket(fd, FIONBIO, &opt);
1188 #else
1190 static int unix_write(int fd, const uint8_t *buf, int len1)
1192 int ret, sel_ret, len;
1193 int max_fd;
1194 fd_set writefds;
1195 struct timeval timeout;
1197 max_fd = fd;
1199 len = len1;
1200 while (len > 0) {
1201 FD_ZERO(&writefds);
1202 FD_SET(fd, &writefds);
1203 timeout.tv_sec = 0;
1204 timeout.tv_usec = 0;
1205 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1206 if (sel_ret <= 0) {
1207 /* Timeout or select error */
1208 return -1;
1209 } else {
1210 ret = write(fd, buf, len);
1211 if (ret < 0) {
1212 if (errno != EINTR && errno != EAGAIN)
1213 return -1;
1214 } else if (ret == 0) {
1215 break;
1216 } else {
1217 buf += ret;
1218 len -= ret;
1222 return len1 - len;
1225 static inline int send_all(int fd, const uint8_t *buf, int len1)
1227 return unix_write(fd, buf, len1);
1230 void socket_set_nonblock(int fd)
1232 fcntl(fd, F_SETFL, O_NONBLOCK);
1234 #endif /* !_WIN32 */
1236 #ifndef _WIN32
1238 typedef struct {
1239 int fd_in, fd_out;
1240 IOCanRWHandler *fd_can_read;
1241 IOReadHandler *fd_read;
1242 void *fd_opaque;
1243 int max_size;
1244 } FDCharDriver;
1246 #define STDIO_MAX_CLIENTS 2
1248 static int stdio_nb_clients;
1249 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1251 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1253 FDCharDriver *s = chr->opaque;
1254 return unix_write(s->fd_out, buf, len);
1257 static int fd_chr_read_poll(void *opaque)
1259 CharDriverState *chr = opaque;
1260 FDCharDriver *s = chr->opaque;
1262 s->max_size = s->fd_can_read(s->fd_opaque);
1263 return s->max_size;
1266 static void fd_chr_read(void *opaque)
1268 CharDriverState *chr = opaque;
1269 FDCharDriver *s = chr->opaque;
1270 int size, len;
1271 uint8_t buf[1024];
1273 len = sizeof(buf);
1274 if (len > s->max_size)
1275 len = s->max_size;
1276 if (len == 0)
1277 return;
1278 size = read(s->fd_in, buf, len);
1279 if (size > 0) {
1280 s->fd_read(s->fd_opaque, buf, size);
1284 static void fd_chr_add_read_handler(CharDriverState *chr,
1285 IOCanRWHandler *fd_can_read,
1286 IOReadHandler *fd_read, void *opaque)
1288 FDCharDriver *s = chr->opaque;
1290 if (s->fd_in >= 0) {
1291 s->fd_can_read = fd_can_read;
1292 s->fd_read = fd_read;
1293 s->fd_opaque = opaque;
1294 if (nographic && s->fd_in == 0) {
1295 } else {
1296 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1297 fd_chr_read, NULL, chr);
1302 /* open a character device to a unix fd */
1303 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1305 CharDriverState *chr;
1306 FDCharDriver *s;
1308 chr = qemu_mallocz(sizeof(CharDriverState));
1309 if (!chr)
1310 return NULL;
1311 s = qemu_mallocz(sizeof(FDCharDriver));
1312 if (!s) {
1313 free(chr);
1314 return NULL;
1316 s->fd_in = fd_in;
1317 s->fd_out = fd_out;
1318 chr->opaque = s;
1319 chr->chr_write = fd_chr_write;
1320 chr->chr_add_read_handler = fd_chr_add_read_handler;
1321 return chr;
1324 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1326 int fd_out;
1328 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1329 if (fd_out < 0)
1330 return NULL;
1331 return qemu_chr_open_fd(-1, fd_out);
1334 CharDriverState *qemu_chr_open_pipe(const char *filename)
1336 int fd;
1338 fd = open(filename, O_RDWR | O_BINARY);
1339 if (fd < 0)
1340 return NULL;
1341 return qemu_chr_open_fd(fd, fd);
1345 /* for STDIO, we handle the case where several clients use it
1346 (nographic mode) */
1348 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1350 #define TERM_FIFO_MAX_SIZE 1
1352 static int term_got_escape, client_index;
1353 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1354 static int term_fifo_size;
1355 static int term_timestamps;
1356 static int64_t term_timestamps_start;
1358 void term_print_help(void)
1360 printf("\n"
1361 "C-a h print this help\n"
1362 "C-a x exit emulator\n"
1363 "C-a s save disk data back to file (if -snapshot)\n"
1364 "C-a b send break (magic sysrq)\n"
1365 "C-a t toggle console timestamps\n"
1366 "C-a c switch between console and monitor\n"
1367 "C-a C-a send C-a\n"
1368 );
1371 /* called when a char is received */
1372 static void stdio_received_byte(int ch)
1374 if (term_got_escape) {
1375 term_got_escape = 0;
1376 switch(ch) {
1377 case 'h':
1378 term_print_help();
1379 break;
1380 case 'x':
1381 exit(0);
1382 break;
1383 case 's':
1385 int i;
1386 for (i = 0; i < MAX_DISKS; i++) {
1387 if (bs_table[i])
1388 bdrv_commit(bs_table[i]);
1391 break;
1392 case 'b':
1393 if (client_index < stdio_nb_clients) {
1394 CharDriverState *chr;
1395 FDCharDriver *s;
1397 chr = stdio_clients[client_index];
1398 s = chr->opaque;
1399 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1401 break;
1402 case 'c':
1403 client_index++;
1404 if (client_index >= stdio_nb_clients)
1405 client_index = 0;
1406 if (client_index == 0) {
1407 /* send a new line in the monitor to get the prompt */
1408 ch = '\r';
1409 goto send_char;
1411 break;
1412 case 't':
1413 term_timestamps = !term_timestamps;
1414 term_timestamps_start = -1;
1415 break;
1416 case TERM_ESCAPE:
1417 goto send_char;
1419 } else if (ch == TERM_ESCAPE) {
1420 term_got_escape = 1;
1421 } else {
1422 send_char:
1423 if (client_index < stdio_nb_clients) {
1424 uint8_t buf[1];
1425 CharDriverState *chr;
1426 FDCharDriver *s;
1428 chr = stdio_clients[client_index];
1429 s = chr->opaque;
1430 if (s->fd_can_read(s->fd_opaque) > 0) {
1431 buf[0] = ch;
1432 s->fd_read(s->fd_opaque, buf, 1);
1433 } else if (term_fifo_size == 0) {
1434 term_fifo[term_fifo_size++] = ch;
1440 static int stdio_read_poll(void *opaque)
1442 CharDriverState *chr;
1443 FDCharDriver *s;
1445 if (client_index < stdio_nb_clients) {
1446 chr = stdio_clients[client_index];
1447 s = chr->opaque;
1448 /* try to flush the queue if needed */
1449 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1450 s->fd_read(s->fd_opaque, term_fifo, 1);
1451 term_fifo_size = 0;
1453 /* see if we can absorb more chars */
1454 if (term_fifo_size == 0)
1455 return 1;
1456 else
1457 return 0;
1458 } else {
1459 return 1;
1463 static void stdio_read(void *opaque)
1465 int size;
1466 uint8_t buf[1];
1468 size = read(0, buf, 1);
1469 if (size > 0)
1470 stdio_received_byte(buf[0]);
1473 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1475 FDCharDriver *s = chr->opaque;
1476 if (!term_timestamps) {
1477 return unix_write(s->fd_out, buf, len);
1478 } else {
1479 int i;
1480 char buf1[64];
1482 for(i = 0; i < len; i++) {
1483 unix_write(s->fd_out, buf + i, 1);
1484 if (buf[i] == '\n') {
1485 int64_t ti;
1486 int secs;
1488 ti = get_clock();
1489 if (term_timestamps_start == -1)
1490 term_timestamps_start = ti;
1491 ti -= term_timestamps_start;
1492 secs = ti / 1000000000;
1493 snprintf(buf1, sizeof(buf1),
1494 "[%02d:%02d:%02d.%03d] ",
1495 secs / 3600,
1496 (secs / 60) % 60,
1497 secs % 60,
1498 (int)((ti / 1000000) % 1000));
1499 unix_write(s->fd_out, buf1, strlen(buf1));
1502 return len;
1506 /* init terminal so that we can grab keys */
1507 static struct termios oldtty;
1508 static int old_fd0_flags;
1510 static void term_exit(void)
1512 tcsetattr (0, TCSANOW, &oldtty);
1513 fcntl(0, F_SETFL, old_fd0_flags);
1516 static void term_init(void)
1518 struct termios tty;
1520 tcgetattr (0, &tty);
1521 oldtty = tty;
1522 old_fd0_flags = fcntl(0, F_GETFL);
1524 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1525 |INLCR|IGNCR|ICRNL|IXON);
1526 tty.c_oflag |= OPOST;
1527 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1528 /* if graphical mode, we allow Ctrl-C handling */
1529 if (nographic)
1530 tty.c_lflag &= ~ISIG;
1531 tty.c_cflag &= ~(CSIZE|PARENB);
1532 tty.c_cflag |= CS8;
1533 tty.c_cc[VMIN] = 1;
1534 tty.c_cc[VTIME] = 0;
1536 tcsetattr (0, TCSANOW, &tty);
1538 atexit(term_exit);
1540 fcntl(0, F_SETFL, O_NONBLOCK);
1543 CharDriverState *qemu_chr_open_stdio(void)
1545 CharDriverState *chr;
1547 if (nographic) {
1548 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1549 return NULL;
1550 chr = qemu_chr_open_fd(0, 1);
1551 chr->chr_write = stdio_write;
1552 if (stdio_nb_clients == 0)
1553 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1554 client_index = stdio_nb_clients;
1555 } else {
1556 if (stdio_nb_clients != 0)
1557 return NULL;
1558 chr = qemu_chr_open_fd(0, 1);
1560 stdio_clients[stdio_nb_clients++] = chr;
1561 if (stdio_nb_clients == 1) {
1562 /* set the terminal in raw mode */
1563 term_init();
1565 return chr;
1568 /*
1569 * Create a store entry for a device (e.g., monitor, serial/parallel lines).
1570 * The entry is <domain-path><storeString>/tty and the value is the name
1571 * of the pty associated with the device.
1572 */
1573 static int store_dev_info(char *devName, int domid,
1574 CharDriverState *cState, char *storeString)
1576 int xc_handle;
1577 struct xs_handle *xs;
1578 char *path;
1579 char *newpath;
1580 FDCharDriver *s;
1581 char *pts;
1583 /* Check for valid arguments (at least, prevent segfaults). */
1584 if ((devName == NULL) || (cState == NULL) || (storeString == NULL)) {
1585 fprintf(logfile, "%s - invalid arguments\n", __FUNCTION__);
1586 return EINVAL;
1589 /*
1590 * Only continue if we're talking to a pty
1591 * Actually, the following code works for any CharDriverState using
1592 * FDCharDriver, but we really only care about pty's here
1593 */
1594 if (strcmp(devName, "pty"))
1595 return 0;
1597 s = cState->opaque;
1598 if (s == NULL) {
1599 fprintf(logfile, "%s - unable to retrieve fd for '%s'/'%s'\n",
1600 __FUNCTION__, storeString, devName);
1601 return EBADF;
1604 pts = ptsname(s->fd_in);
1605 if (pts == NULL) {
1606 fprintf(logfile, "%s - unable to determine ptsname '%s'/'%s', "
1607 "error %d (%s)\n",
1608 __FUNCTION__, storeString, devName, errno, strerror(errno));
1609 return errno;
1612 /* We now have everything we need to set the xenstore entry. */
1613 xs = xs_daemon_open();
1614 if (xs == NULL) {
1615 fprintf(logfile, "Could not contact XenStore\n");
1616 return -1;
1619 xc_handle = xc_interface_open();
1620 if (xc_handle == -1) {
1621 fprintf(logfile, "xc_interface_open() error\n");
1622 return -1;
1625 path = xs_get_domain_path(xs, domid);
1626 if (path == NULL) {
1627 fprintf(logfile, "xs_get_domain_path() error\n");
1628 return -1;
1630 newpath = realloc(path, (strlen(path) + strlen(storeString) +
1631 strlen("/tty") + 1));
1632 if (newpath == NULL) {
1633 free(path); /* realloc errors leave old block */
1634 fprintf(logfile, "realloc error\n");
1635 return -1;
1637 path = newpath;
1639 strcat(path, storeString);
1640 strcat(path, "/tty");
1641 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1642 fprintf(logfile, "xs_write for '%s' fail", storeString);
1643 return -1;
1646 free(path);
1647 xs_daemon_close(xs);
1648 close(xc_handle);
1650 return 0;
1653 #if defined(__linux__)
1654 CharDriverState *qemu_chr_open_pty(void)
1656 struct termios tty;
1657 int master_fd, slave_fd;
1659 /* Not satisfying */
1660 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1661 return NULL;
1664 /* Set raw attributes on the pty. */
1665 cfmakeraw(&tty);
1666 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1668 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1670 return qemu_chr_open_fd(master_fd, master_fd);
1673 static void tty_serial_init(int fd, int speed,
1674 int parity, int data_bits, int stop_bits)
1676 struct termios tty;
1677 speed_t spd;
1679 #if 0
1680 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1681 speed, parity, data_bits, stop_bits);
1682 #endif
1683 tcgetattr (fd, &tty);
1685 switch(speed) {
1686 case 50:
1687 spd = B50;
1688 break;
1689 case 75:
1690 spd = B75;
1691 break;
1692 case 300:
1693 spd = B300;
1694 break;
1695 case 600:
1696 spd = B600;
1697 break;
1698 case 1200:
1699 spd = B1200;
1700 break;
1701 case 2400:
1702 spd = B2400;
1703 break;
1704 case 4800:
1705 spd = B4800;
1706 break;
1707 case 9600:
1708 spd = B9600;
1709 break;
1710 case 19200:
1711 spd = B19200;
1712 break;
1713 case 38400:
1714 spd = B38400;
1715 break;
1716 case 57600:
1717 spd = B57600;
1718 break;
1719 default:
1720 case 115200:
1721 spd = B115200;
1722 break;
1725 cfsetispeed(&tty, spd);
1726 cfsetospeed(&tty, spd);
1728 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1729 |INLCR|IGNCR|ICRNL|IXON);
1730 tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1731 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1732 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1733 switch(data_bits) {
1734 default:
1735 case 8:
1736 tty.c_cflag |= CS8;
1737 break;
1738 case 7:
1739 tty.c_cflag |= CS7;
1740 break;
1741 case 6:
1742 tty.c_cflag |= CS6;
1743 break;
1744 case 5:
1745 tty.c_cflag |= CS5;
1746 break;
1748 switch(parity) {
1749 default:
1750 case 'N':
1751 break;
1752 case 'E':
1753 tty.c_cflag |= PARENB;
1754 break;
1755 case 'O':
1756 tty.c_cflag |= PARENB | PARODD;
1757 break;
1760 tcsetattr (fd, TCSANOW, &tty);
1763 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1765 FDCharDriver *s = chr->opaque;
1767 switch(cmd) {
1768 case CHR_IOCTL_SERIAL_SET_PARAMS:
1770 QEMUSerialSetParams *ssp = arg;
1771 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1772 ssp->data_bits, ssp->stop_bits);
1774 break;
1775 case CHR_IOCTL_SERIAL_SET_BREAK:
1777 int enable = *(int *)arg;
1778 if (enable)
1779 tcsendbreak(s->fd_in, 1);
1781 break;
1782 default:
1783 return -ENOTSUP;
1785 return 0;
1788 CharDriverState *qemu_chr_open_tty(const char *filename)
1790 CharDriverState *chr;
1791 int fd;
1793 fd = open(filename, O_RDWR | O_NONBLOCK);
1794 if (fd < 0)
1795 return NULL;
1796 fcntl(fd, F_SETFL, O_NONBLOCK);
1797 tty_serial_init(fd, 115200, 'N', 8, 1);
1798 chr = qemu_chr_open_fd(fd, fd);
1799 if (!chr)
1800 return NULL;
1801 chr->chr_ioctl = tty_serial_ioctl;
1802 return chr;
1805 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1807 int fd = (int)chr->opaque;
1808 uint8_t b;
1810 switch(cmd) {
1811 case CHR_IOCTL_PP_READ_DATA:
1812 if (ioctl(fd, PPRDATA, &b) < 0)
1813 return -ENOTSUP;
1814 *(uint8_t *)arg = b;
1815 break;
1816 case CHR_IOCTL_PP_WRITE_DATA:
1817 b = *(uint8_t *)arg;
1818 if (ioctl(fd, PPWDATA, &b) < 0)
1819 return -ENOTSUP;
1820 break;
1821 case CHR_IOCTL_PP_READ_CONTROL:
1822 if (ioctl(fd, PPRCONTROL, &b) < 0)
1823 return -ENOTSUP;
1824 *(uint8_t *)arg = b;
1825 break;
1826 case CHR_IOCTL_PP_WRITE_CONTROL:
1827 b = *(uint8_t *)arg;
1828 if (ioctl(fd, PPWCONTROL, &b) < 0)
1829 return -ENOTSUP;
1830 break;
1831 case CHR_IOCTL_PP_READ_STATUS:
1832 if (ioctl(fd, PPRSTATUS, &b) < 0)
1833 return -ENOTSUP;
1834 *(uint8_t *)arg = b;
1835 break;
1836 default:
1837 return -ENOTSUP;
1839 return 0;
1842 CharDriverState *qemu_chr_open_pp(const char *filename)
1844 CharDriverState *chr;
1845 int fd;
1847 fd = open(filename, O_RDWR);
1848 if (fd < 0)
1849 return NULL;
1851 if (ioctl(fd, PPCLAIM) < 0) {
1852 close(fd);
1853 return NULL;
1856 chr = qemu_mallocz(sizeof(CharDriverState));
1857 if (!chr) {
1858 close(fd);
1859 return NULL;
1861 chr->opaque = (void *)fd;
1862 chr->chr_write = null_chr_write;
1863 chr->chr_add_read_handler = null_chr_add_read_handler;
1864 chr->chr_ioctl = pp_ioctl;
1865 return chr;
1868 #else
1869 CharDriverState *qemu_chr_open_pty(void)
1871 return NULL;
1873 #endif
1875 #endif /* !defined(_WIN32) */
1877 #ifdef _WIN32
1878 typedef struct {
1879 IOCanRWHandler *fd_can_read;
1880 IOReadHandler *fd_read;
1881 void *win_opaque;
1882 int max_size;
1883 HANDLE hcom, hrecv, hsend;
1884 OVERLAPPED orecv, osend;
1885 BOOL fpipe;
1886 DWORD len;
1887 } WinCharState;
1889 #define NSENDBUF 2048
1890 #define NRECVBUF 2048
1891 #define MAXCONNECT 1
1892 #define NTIMEOUT 5000
1894 static int win_chr_poll(void *opaque);
1895 static int win_chr_pipe_poll(void *opaque);
1897 static void win_chr_close2(WinCharState *s)
1899 if (s->hsend) {
1900 CloseHandle(s->hsend);
1901 s->hsend = NULL;
1903 if (s->hrecv) {
1904 CloseHandle(s->hrecv);
1905 s->hrecv = NULL;
1907 if (s->hcom) {
1908 CloseHandle(s->hcom);
1909 s->hcom = NULL;
1911 if (s->fpipe)
1912 qemu_del_polling_cb(win_chr_pipe_poll, s);
1913 else
1914 qemu_del_polling_cb(win_chr_poll, s);
1917 static void win_chr_close(CharDriverState *chr)
1919 WinCharState *s = chr->opaque;
1920 win_chr_close2(s);
1923 static int win_chr_init(WinCharState *s, const char *filename)
1925 COMMCONFIG comcfg;
1926 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1927 COMSTAT comstat;
1928 DWORD size;
1929 DWORD err;
1931 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1932 if (!s->hsend) {
1933 fprintf(stderr, "Failed CreateEvent\n");
1934 goto fail;
1936 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1937 if (!s->hrecv) {
1938 fprintf(stderr, "Failed CreateEvent\n");
1939 goto fail;
1942 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1943 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1944 if (s->hcom == INVALID_HANDLE_VALUE) {
1945 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1946 s->hcom = NULL;
1947 goto fail;
1950 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1951 fprintf(stderr, "Failed SetupComm\n");
1952 goto fail;
1955 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1956 size = sizeof(COMMCONFIG);
1957 GetDefaultCommConfig(filename, &comcfg, &size);
1958 comcfg.dcb.DCBlength = sizeof(DCB);
1959 CommConfigDialog(filename, NULL, &comcfg);
1961 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1962 fprintf(stderr, "Failed SetCommState\n");
1963 goto fail;
1966 if (!SetCommMask(s->hcom, EV_ERR)) {
1967 fprintf(stderr, "Failed SetCommMask\n");
1968 goto fail;
1971 cto.ReadIntervalTimeout = MAXDWORD;
1972 if (!SetCommTimeouts(s->hcom, &cto)) {
1973 fprintf(stderr, "Failed SetCommTimeouts\n");
1974 goto fail;
1977 if (!ClearCommError(s->hcom, &err, &comstat)) {
1978 fprintf(stderr, "Failed ClearCommError\n");
1979 goto fail;
1981 qemu_add_polling_cb(win_chr_poll, s);
1982 return 0;
1984 fail:
1985 win_chr_close2(s);
1986 return -1;
1989 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1991 WinCharState *s = chr->opaque;
1992 DWORD len, ret, size, err;
1994 len = len1;
1995 ZeroMemory(&s->osend, sizeof(s->osend));
1996 s->osend.hEvent = s->hsend;
1997 while (len > 0) {
1998 if (s->hsend)
1999 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2000 else
2001 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2002 if (!ret) {
2003 err = GetLastError();
2004 if (err == ERROR_IO_PENDING) {
2005 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2006 if (ret) {
2007 buf += size;
2008 len -= size;
2009 } else {
2010 break;
2012 } else {
2013 break;
2015 } else {
2016 buf += size;
2017 len -= size;
2020 return len1 - len;
2023 static int win_chr_read_poll(WinCharState *s)
2025 s->max_size = s->fd_can_read(s->win_opaque);
2026 return s->max_size;
2029 static void win_chr_readfile(WinCharState *s)
2031 int ret, err;
2032 uint8_t buf[1024];
2033 DWORD size;
2035 ZeroMemory(&s->orecv, sizeof(s->orecv));
2036 s->orecv.hEvent = s->hrecv;
2037 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2038 if (!ret) {
2039 err = GetLastError();
2040 if (err == ERROR_IO_PENDING) {
2041 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2045 if (size > 0) {
2046 s->fd_read(s->win_opaque, buf, size);
2050 static void win_chr_read(WinCharState *s)
2052 if (s->len > s->max_size)
2053 s->len = s->max_size;
2054 if (s->len == 0)
2055 return;
2057 win_chr_readfile(s);
2060 static int win_chr_poll(void *opaque)
2062 WinCharState *s = opaque;
2063 COMSTAT status;
2064 DWORD comerr;
2066 ClearCommError(s->hcom, &comerr, &status);
2067 if (status.cbInQue > 0) {
2068 s->len = status.cbInQue;
2069 win_chr_read_poll(s);
2070 win_chr_read(s);
2071 return 1;
2073 return 0;
2076 static void win_chr_add_read_handler(CharDriverState *chr,
2077 IOCanRWHandler *fd_can_read,
2078 IOReadHandler *fd_read, void *opaque)
2080 WinCharState *s = chr->opaque;
2082 s->fd_can_read = fd_can_read;
2083 s->fd_read = fd_read;
2084 s->win_opaque = opaque;
2087 CharDriverState *qemu_chr_open_win(const char *filename)
2089 CharDriverState *chr;
2090 WinCharState *s;
2092 chr = qemu_mallocz(sizeof(CharDriverState));
2093 if (!chr)
2094 return NULL;
2095 s = qemu_mallocz(sizeof(WinCharState));
2096 if (!s) {
2097 free(chr);
2098 return NULL;
2100 chr->opaque = s;
2101 chr->chr_write = win_chr_write;
2102 chr->chr_add_read_handler = win_chr_add_read_handler;
2103 chr->chr_close = win_chr_close;
2105 if (win_chr_init(s, filename) < 0) {
2106 free(s);
2107 free(chr);
2108 return NULL;
2110 return chr;
2113 static int win_chr_pipe_poll(void *opaque)
2115 WinCharState *s = opaque;
2116 DWORD size;
2118 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2119 if (size > 0) {
2120 s->len = size;
2121 win_chr_read_poll(s);
2122 win_chr_read(s);
2123 return 1;
2125 return 0;
2128 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2130 OVERLAPPED ov;
2131 int ret;
2132 DWORD size;
2133 char openname[256];
2135 s->fpipe = TRUE;
2137 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2138 if (!s->hsend) {
2139 fprintf(stderr, "Failed CreateEvent\n");
2140 goto fail;
2142 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2143 if (!s->hrecv) {
2144 fprintf(stderr, "Failed CreateEvent\n");
2145 goto fail;
2148 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2149 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2150 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2151 PIPE_WAIT,
2152 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2153 if (s->hcom == INVALID_HANDLE_VALUE) {
2154 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2155 s->hcom = NULL;
2156 goto fail;
2159 ZeroMemory(&ov, sizeof(ov));
2160 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2161 ret = ConnectNamedPipe(s->hcom, &ov);
2162 if (ret) {
2163 fprintf(stderr, "Failed ConnectNamedPipe\n");
2164 goto fail;
2167 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2168 if (!ret) {
2169 fprintf(stderr, "Failed GetOverlappedResult\n");
2170 if (ov.hEvent) {
2171 CloseHandle(ov.hEvent);
2172 ov.hEvent = NULL;
2174 goto fail;
2177 if (ov.hEvent) {
2178 CloseHandle(ov.hEvent);
2179 ov.hEvent = NULL;
2181 qemu_add_polling_cb(win_chr_pipe_poll, s);
2182 return 0;
2184 fail:
2185 win_chr_close2(s);
2186 return -1;
2190 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2192 CharDriverState *chr;
2193 WinCharState *s;
2195 chr = qemu_mallocz(sizeof(CharDriverState));
2196 if (!chr)
2197 return NULL;
2198 s = qemu_mallocz(sizeof(WinCharState));
2199 if (!s) {
2200 free(chr);
2201 return NULL;
2203 chr->opaque = s;
2204 chr->chr_write = win_chr_write;
2205 chr->chr_add_read_handler = win_chr_add_read_handler;
2206 chr->chr_close = win_chr_close;
2208 if (win_chr_pipe_init(s, filename) < 0) {
2209 free(s);
2210 free(chr);
2211 return NULL;
2213 return chr;
2216 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2218 CharDriverState *chr;
2219 WinCharState *s;
2221 chr = qemu_mallocz(sizeof(CharDriverState));
2222 if (!chr)
2223 return NULL;
2224 s = qemu_mallocz(sizeof(WinCharState));
2225 if (!s) {
2226 free(chr);
2227 return NULL;
2229 s->hcom = fd_out;
2230 chr->opaque = s;
2231 chr->chr_write = win_chr_write;
2232 chr->chr_add_read_handler = win_chr_add_read_handler;
2233 return chr;
2236 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2238 HANDLE fd_out;
2240 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2241 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2242 if (fd_out == INVALID_HANDLE_VALUE)
2243 return NULL;
2245 return qemu_chr_open_win_file(fd_out);
2247 #endif
2249 /***********************************************************/
2250 /* UDP Net console */
2252 typedef struct {
2253 IOCanRWHandler *fd_can_read;
2254 IOReadHandler *fd_read;
2255 void *fd_opaque;
2256 int fd;
2257 struct sockaddr_in daddr;
2258 char buf[1024];
2259 int bufcnt;
2260 int bufptr;
2261 int max_size;
2262 } NetCharDriver;
2264 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2266 NetCharDriver *s = chr->opaque;
2268 return sendto(s->fd, buf, len, 0,
2269 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2272 static int udp_chr_read_poll(void *opaque)
2274 CharDriverState *chr = opaque;
2275 NetCharDriver *s = chr->opaque;
2277 s->max_size = s->fd_can_read(s->fd_opaque);
2279 /* If there were any stray characters in the queue process them
2280 * first
2281 */
2282 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2283 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2284 s->bufptr++;
2285 s->max_size = s->fd_can_read(s->fd_opaque);
2287 return s->max_size;
2290 static void udp_chr_read(void *opaque)
2292 CharDriverState *chr = opaque;
2293 NetCharDriver *s = chr->opaque;
2295 if (s->max_size == 0)
2296 return;
2297 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2298 s->bufptr = s->bufcnt;
2299 if (s->bufcnt <= 0)
2300 return;
2302 s->bufptr = 0;
2303 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2304 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2305 s->bufptr++;
2306 s->max_size = s->fd_can_read(s->fd_opaque);
2310 static void udp_chr_add_read_handler(CharDriverState *chr,
2311 IOCanRWHandler *fd_can_read,
2312 IOReadHandler *fd_read, void *opaque)
2314 NetCharDriver *s = chr->opaque;
2316 if (s->fd >= 0) {
2317 s->fd_can_read = fd_can_read;
2318 s->fd_read = fd_read;
2319 s->fd_opaque = opaque;
2320 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2321 udp_chr_read, NULL, chr);
2325 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2326 int parse_host_src_port(struct sockaddr_in *haddr,
2327 struct sockaddr_in *saddr,
2328 const char *str);
2330 CharDriverState *qemu_chr_open_udp(const char *def)
2332 CharDriverState *chr = NULL;
2333 NetCharDriver *s = NULL;
2334 int fd = -1;
2335 struct sockaddr_in saddr;
2337 chr = qemu_mallocz(sizeof(CharDriverState));
2338 if (!chr)
2339 goto return_err;
2340 s = qemu_mallocz(sizeof(NetCharDriver));
2341 if (!s)
2342 goto return_err;
2344 fd = socket(PF_INET, SOCK_DGRAM, 0);
2345 if (fd < 0) {
2346 perror("socket(PF_INET, SOCK_DGRAM)");
2347 goto return_err;
2350 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2351 printf("Could not parse: %s\n", def);
2352 goto return_err;
2355 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2357 perror("bind");
2358 goto return_err;
2361 s->fd = fd;
2362 s->bufcnt = 0;
2363 s->bufptr = 0;
2364 chr->opaque = s;
2365 chr->chr_write = udp_chr_write;
2366 chr->chr_add_read_handler = udp_chr_add_read_handler;
2367 return chr;
2369 return_err:
2370 if (chr)
2371 free(chr);
2372 if (s)
2373 free(s);
2374 if (fd >= 0)
2375 closesocket(fd);
2376 return NULL;
2379 /***********************************************************/
2380 /* TCP Net console */
2382 typedef struct {
2383 IOCanRWHandler *fd_can_read;
2384 IOReadHandler *fd_read;
2385 void *fd_opaque;
2386 int fd, listen_fd;
2387 int connected;
2388 int max_size;
2389 int do_telnetopt;
2390 } TCPCharDriver;
2392 static void tcp_chr_accept(void *opaque);
2394 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2396 TCPCharDriver *s = chr->opaque;
2397 if (s->connected) {
2398 return send_all(s->fd, buf, len);
2399 } else {
2400 /* XXX: indicate an error ? */
2401 return len;
2405 static int tcp_chr_read_poll(void *opaque)
2407 CharDriverState *chr = opaque;
2408 TCPCharDriver *s = chr->opaque;
2409 if (!s->connected)
2410 return 0;
2411 s->max_size = s->fd_can_read(s->fd_opaque);
2412 return s->max_size;
2415 #define IAC 255
2416 #define IAC_BREAK 243
2417 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2418 TCPCharDriver *s,
2419 char *buf, int *size)
2421 /* Handle any telnet client's basic IAC options to satisfy char by
2422 * char mode with no echo. All IAC options will be removed from
2423 * the buf and the do_telnetopt variable will be used to track the
2424 * state of the width of the IAC information.
2426 * IAC commands come in sets of 3 bytes with the exception of the
2427 * "IAC BREAK" command and the double IAC.
2428 */
2430 int i;
2431 int j = 0;
2433 for (i = 0; i < *size; i++) {
2434 if (s->do_telnetopt > 1) {
2435 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2436 /* Double IAC means send an IAC */
2437 if (j != i)
2438 buf[j] = buf[i];
2439 j++;
2440 s->do_telnetopt = 1;
2441 } else {
2442 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2443 /* Handle IAC break commands by sending a serial break */
2444 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2445 s->do_telnetopt++;
2447 s->do_telnetopt++;
2449 if (s->do_telnetopt >= 4) {
2450 s->do_telnetopt = 1;
2452 } else {
2453 if ((unsigned char)buf[i] == IAC) {
2454 s->do_telnetopt = 2;
2455 } else {
2456 if (j != i)
2457 buf[j] = buf[i];
2458 j++;
2462 *size = j;
2465 static void tcp_chr_read(void *opaque)
2467 CharDriverState *chr = opaque;
2468 TCPCharDriver *s = chr->opaque;
2469 uint8_t buf[1024];
2470 int len, size;
2472 if (!s->connected || s->max_size <= 0)
2473 return;
2474 len = sizeof(buf);
2475 if (len > s->max_size)
2476 len = s->max_size;
2477 size = recv(s->fd, buf, len, 0);
2478 if (size == 0) {
2479 /* connection closed */
2480 s->connected = 0;
2481 if (s->listen_fd >= 0) {
2482 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2484 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2485 closesocket(s->fd);
2486 s->fd = -1;
2487 } else if (size > 0) {
2488 if (s->do_telnetopt)
2489 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2490 if (size > 0)
2491 s->fd_read(s->fd_opaque, buf, size);
2495 static void tcp_chr_add_read_handler(CharDriverState *chr,
2496 IOCanRWHandler *fd_can_read,
2497 IOReadHandler *fd_read, void *opaque)
2499 TCPCharDriver *s = chr->opaque;
2501 s->fd_can_read = fd_can_read;
2502 s->fd_read = fd_read;
2503 s->fd_opaque = opaque;
2506 static void tcp_chr_connect(void *opaque)
2508 CharDriverState *chr = opaque;
2509 TCPCharDriver *s = chr->opaque;
2511 s->connected = 1;
2512 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2513 tcp_chr_read, NULL, chr);
2516 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2517 static void tcp_chr_telnet_init(int fd)
2519 char buf[3];
2520 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2521 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2522 send(fd, (char *)buf, 3, 0);
2523 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2524 send(fd, (char *)buf, 3, 0);
2525 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2526 send(fd, (char *)buf, 3, 0);
2527 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2528 send(fd, (char *)buf, 3, 0);
2531 static void tcp_chr_accept(void *opaque)
2533 CharDriverState *chr = opaque;
2534 TCPCharDriver *s = chr->opaque;
2535 struct sockaddr_in saddr;
2536 socklen_t len;
2537 int fd;
2539 for(;;) {
2540 len = sizeof(saddr);
2541 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2542 if (fd < 0 && errno != EINTR) {
2543 return;
2544 } else if (fd >= 0) {
2545 if (s->do_telnetopt)
2546 tcp_chr_telnet_init(fd);
2547 break;
2550 socket_set_nonblock(fd);
2551 s->fd = fd;
2552 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2553 tcp_chr_connect(chr);
2556 static void tcp_chr_close(CharDriverState *chr)
2558 TCPCharDriver *s = chr->opaque;
2559 if (s->fd >= 0)
2560 closesocket(s->fd);
2561 if (s->listen_fd >= 0)
2562 closesocket(s->listen_fd);
2563 qemu_free(s);
2566 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2567 int is_telnet)
2569 CharDriverState *chr = NULL;
2570 TCPCharDriver *s = NULL;
2571 int fd = -1, ret, err, val;
2572 int is_listen = 0;
2573 int is_waitconnect = 1;
2574 const char *ptr;
2575 struct sockaddr_in saddr;
2576 int opt;
2578 if (parse_host_port(&saddr, host_str) < 0)
2579 goto fail;
2581 ptr = host_str;
2582 while((ptr = strchr(ptr,','))) {
2583 ptr++;
2584 if (!strncmp(ptr,"server",6)) {
2585 is_listen = 1;
2586 } else if (!strncmp(ptr,"nowait",6)) {
2587 is_waitconnect = 0;
2588 } else {
2589 printf("Unknown option: %s\n", ptr);
2590 goto fail;
2593 if (!is_listen)
2594 is_waitconnect = 0;
2596 chr = qemu_mallocz(sizeof(CharDriverState));
2597 if (!chr)
2598 goto fail;
2599 s = qemu_mallocz(sizeof(TCPCharDriver));
2600 if (!s)
2601 goto fail;
2603 fd = socket(PF_INET, SOCK_STREAM, 0);
2604 if (fd < 0)
2605 goto fail;
2607 if (!is_waitconnect)
2608 socket_set_nonblock(fd);
2610 s->connected = 0;
2611 s->fd = -1;
2612 s->listen_fd = -1;
2613 if (is_listen) {
2614 /* allow fast reuse */
2615 val = 1;
2616 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2618 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2619 if (ret < 0)
2620 goto fail;
2621 ret = listen(fd, 0);
2622 if (ret < 0)
2623 goto fail;
2624 s->listen_fd = fd;
2625 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2626 if (is_telnet)
2627 s->do_telnetopt = 1;
2628 } else {
2629 for(;;) {
2630 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2631 if (ret < 0) {
2632 err = socket_error();
2633 if (err == EINTR || err == EWOULDBLOCK) {
2634 } else if (err == EINPROGRESS) {
2635 break;
2636 } else {
2637 goto fail;
2639 } else {
2640 s->connected = 1;
2641 break;
2644 s->fd = fd;
2645 opt = 1;
2646 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
2647 if (s->connected)
2648 tcp_chr_connect(chr);
2649 else
2650 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2653 chr->opaque = s;
2654 chr->chr_write = tcp_chr_write;
2655 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2656 chr->chr_close = tcp_chr_close;
2657 if (is_listen && is_waitconnect) {
2658 printf("QEMU waiting for connection on: %s\n", host_str);
2659 tcp_chr_accept(chr);
2660 socket_set_nonblock(s->listen_fd);
2663 return chr;
2664 fail:
2665 if (fd >= 0)
2666 closesocket(fd);
2667 qemu_free(s);
2668 qemu_free(chr);
2669 return NULL;
2672 CharDriverState *qemu_chr_open(const char *filename)
2674 const char *p;
2676 if (!strcmp(filename, "vc")) {
2677 return text_console_init(&display_state);
2678 } else if (!strcmp(filename, "null")) {
2679 return qemu_chr_open_null();
2680 } else
2681 if (strstart(filename, "tcp:", &p)) {
2682 return qemu_chr_open_tcp(p, 0);
2683 } else
2684 if (strstart(filename, "telnet:", &p)) {
2685 return qemu_chr_open_tcp(p, 1);
2686 } else
2687 if (strstart(filename, "udp:", &p)) {
2688 return qemu_chr_open_udp(p);
2689 } else
2690 #ifndef _WIN32
2691 if (strstart(filename, "file:", &p)) {
2692 return qemu_chr_open_file_out(p);
2693 } else if (strstart(filename, "pipe:", &p)) {
2694 return qemu_chr_open_pipe(p);
2695 } else if (!strcmp(filename, "pty")) {
2696 return qemu_chr_open_pty();
2697 } else if (!strcmp(filename, "stdio")) {
2698 return qemu_chr_open_stdio();
2699 } else
2700 #endif
2701 #if defined(__linux__)
2702 if (strstart(filename, "/dev/parport", NULL)) {
2703 return qemu_chr_open_pp(filename);
2704 } else
2705 if (strstart(filename, "/dev/", NULL)) {
2706 return qemu_chr_open_tty(filename);
2707 } else
2708 #endif
2709 #ifdef _WIN32
2710 if (strstart(filename, "COM", NULL)) {
2711 return qemu_chr_open_win(filename);
2712 } else
2713 if (strstart(filename, "pipe:", &p)) {
2714 return qemu_chr_open_win_pipe(p);
2715 } else
2716 if (strstart(filename, "file:", &p)) {
2717 return qemu_chr_open_win_file_out(p);
2719 #endif
2721 return NULL;
2725 void qemu_chr_close(CharDriverState *chr)
2727 if (chr->chr_close)
2728 chr->chr_close(chr);
2731 /***********************************************************/
2732 /* network device redirectors */
2734 void hex_dump(FILE *f, const uint8_t *buf, int size)
2736 int len, i, j, c;
2738 for(i=0;i<size;i+=16) {
2739 len = size - i;
2740 if (len > 16)
2741 len = 16;
2742 fprintf(f, "%08x ", i);
2743 for(j=0;j<16;j++) {
2744 if (j < len)
2745 fprintf(f, " %02x", buf[i+j]);
2746 else
2747 fprintf(f, " ");
2749 fprintf(f, " ");
2750 for(j=0;j<len;j++) {
2751 c = buf[i+j];
2752 if (c < ' ' || c > '~')
2753 c = '.';
2754 fprintf(f, "%c", c);
2756 fprintf(f, "\n");
2760 static int parse_macaddr(uint8_t *macaddr, const char *p)
2762 int i;
2763 for(i = 0; i < 6; i++) {
2764 macaddr[i] = strtol(p, (char **)&p, 16);
2765 if (i == 5) {
2766 if (*p != '\0')
2767 return -1;
2768 } else {
2769 if (*p != ':')
2770 return -1;
2771 p++;
2774 return 0;
2777 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2779 const char *p, *p1;
2780 int len;
2781 p = *pp;
2782 p1 = strchr(p, sep);
2783 if (!p1)
2784 return -1;
2785 len = p1 - p;
2786 p1++;
2787 if (buf_size > 0) {
2788 if (len > buf_size - 1)
2789 len = buf_size - 1;
2790 memcpy(buf, p, len);
2791 buf[len] = '\0';
2793 *pp = p1;
2794 return 0;
2797 int parse_host_src_port(struct sockaddr_in *haddr,
2798 struct sockaddr_in *saddr,
2799 const char *input_str)
2801 char *str = strdup(input_str);
2802 char *host_str = str;
2803 char *src_str;
2804 char *ptr;
2806 /*
2807 * Chop off any extra arguments at the end of the string which
2808 * would start with a comma, then fill in the src port information
2809 * if it was provided else use the "any address" and "any port".
2810 */
2811 if ((ptr = strchr(str,',')))
2812 *ptr = '\0';
2814 if ((src_str = strchr(input_str,'@'))) {
2815 *src_str = '\0';
2816 src_str++;
2819 if (parse_host_port(haddr, host_str) < 0)
2820 goto fail;
2822 if (!src_str || *src_str == '\0')
2823 src_str = ":0";
2825 if (parse_host_port(saddr, src_str) < 0)
2826 goto fail;
2828 free(str);
2829 return(0);
2831 fail:
2832 free(str);
2833 return -1;
2836 int parse_host(struct sockaddr_in *saddr, const char *buf)
2838 struct hostent *he;
2840 if ((he = gethostbyname(buf)) != NULL) {
2841 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2842 } else {
2843 if (!inet_aton(buf, &saddr->sin_addr))
2844 return -1;
2846 return 0;
2849 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2851 char buf[512];
2852 const char *p, *r;
2853 int port;
2855 p = str;
2856 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2857 return -1;
2858 saddr->sin_family = AF_INET;
2859 if (buf[0] == '\0') {
2860 saddr->sin_addr.s_addr = 0;
2861 } else {
2862 if (parse_host(saddr, buf) == -1)
2863 return -1;
2865 port = strtol(p, (char **)&r, 0);
2866 if (r == p)
2867 return -1;
2868 saddr->sin_port = htons(port);
2869 return 0;
2872 /* find or alloc a new VLAN */
2873 VLANState *qemu_find_vlan(int id)
2875 VLANState **pvlan, *vlan;
2876 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2877 if (vlan->id == id)
2878 return vlan;
2880 vlan = qemu_mallocz(sizeof(VLANState));
2881 if (!vlan)
2882 return NULL;
2883 vlan->id = id;
2884 vlan->next = NULL;
2885 pvlan = &first_vlan;
2886 while (*pvlan != NULL)
2887 pvlan = &(*pvlan)->next;
2888 *pvlan = vlan;
2889 return vlan;
2892 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2893 IOReadHandler *fd_read,
2894 IOCanRWHandler *fd_can_read,
2895 void *opaque)
2897 VLANClientState *vc, **pvc;
2898 vc = qemu_mallocz(sizeof(VLANClientState));
2899 if (!vc)
2900 return NULL;
2901 vc->fd_read = fd_read;
2902 vc->fd_can_read = fd_can_read;
2903 vc->opaque = opaque;
2904 vc->vlan = vlan;
2906 vc->next = NULL;
2907 pvc = &vlan->first_client;
2908 while (*pvc != NULL)
2909 pvc = &(*pvc)->next;
2910 *pvc = vc;
2911 return vc;
2914 int qemu_can_send_packet(VLANClientState *vc1)
2916 VLANState *vlan = vc1->vlan;
2917 VLANClientState *vc;
2919 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2920 if (vc != vc1) {
2921 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2922 return 0;
2925 return 1;
2928 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2930 VLANState *vlan = vc1->vlan;
2931 VLANClientState *vc;
2933 #if 0
2934 printf("vlan %d send:\n", vlan->id);
2935 hex_dump(stdout, buf, size);
2936 #endif
2937 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2938 if (vc != vc1) {
2939 vc->fd_read(vc->opaque, buf, size);
2944 #if defined(CONFIG_SLIRP)
2946 /* slirp network adapter */
2948 static int slirp_inited;
2949 static VLANClientState *slirp_vc;
2951 int slirp_can_output(void)
2953 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2956 void slirp_output(const uint8_t *pkt, int pkt_len)
2958 #if 0
2959 printf("slirp output:\n");
2960 hex_dump(stdout, pkt, pkt_len);
2961 #endif
2962 if (!slirp_vc)
2963 return;
2964 qemu_send_packet(slirp_vc, pkt, pkt_len);
2967 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2969 #if 0
2970 printf("slirp input:\n");
2971 hex_dump(stdout, buf, size);
2972 #endif
2973 slirp_input(buf, size);
2976 static int net_slirp_init(VLANState *vlan)
2978 if (!slirp_inited) {
2979 slirp_inited = 1;
2980 slirp_init();
2982 slirp_vc = qemu_new_vlan_client(vlan,
2983 slirp_receive, NULL, NULL);
2984 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2985 return 0;
2988 static void net_slirp_redir(const char *redir_str)
2990 int is_udp;
2991 char buf[256], *r;
2992 const char *p;
2993 struct in_addr guest_addr;
2994 int host_port, guest_port;
2996 if (!slirp_inited) {
2997 slirp_inited = 1;
2998 slirp_init();
3001 p = redir_str;
3002 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3003 goto fail;
3004 if (!strcmp(buf, "tcp")) {
3005 is_udp = 0;
3006 } else if (!strcmp(buf, "udp")) {
3007 is_udp = 1;
3008 } else {
3009 goto fail;
3012 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3013 goto fail;
3014 host_port = strtol(buf, &r, 0);
3015 if (r == buf)
3016 goto fail;
3018 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3019 goto fail;
3020 if (buf[0] == '\0') {
3021 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3023 if (!inet_aton(buf, &guest_addr))
3024 goto fail;
3026 guest_port = strtol(p, &r, 0);
3027 if (r == p)
3028 goto fail;
3030 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3031 fprintf(stderr, "qemu: could not set up redirection\n");
3032 exit(1);
3034 return;
3035 fail:
3036 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3037 exit(1);
3040 #ifndef _WIN32
3042 char smb_dir[1024];
3044 static void smb_exit(void)
3046 DIR *d;
3047 struct dirent *de;
3048 char filename[1024];
3050 /* erase all the files in the directory */
3051 d = opendir(smb_dir);
3052 for(;;) {
3053 de = readdir(d);
3054 if (!de)
3055 break;
3056 if (strcmp(de->d_name, ".") != 0 &&
3057 strcmp(de->d_name, "..") != 0) {
3058 snprintf(filename, sizeof(filename), "%s/%s",
3059 smb_dir, de->d_name);
3060 unlink(filename);
3063 closedir(d);
3064 rmdir(smb_dir);
3067 /* automatic user mode samba server configuration */
3068 void net_slirp_smb(const char *exported_dir)
3070 char smb_conf[1024];
3071 char smb_cmdline[1024];
3072 FILE *f;
3074 if (!slirp_inited) {
3075 slirp_inited = 1;
3076 slirp_init();
3079 /* XXX: better tmp dir construction */
3080 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3081 if (mkdir(smb_dir, 0700) < 0) {
3082 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3083 exit(1);
3085 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3087 f = fopen(smb_conf, "w");
3088 if (!f) {
3089 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3090 exit(1);
3092 fprintf(f,
3093 "[global]\n"
3094 "private dir=%s\n"
3095 "smb ports=0\n"
3096 "socket address=127.0.0.1\n"
3097 "pid directory=%s\n"
3098 "lock directory=%s\n"
3099 "log file=%s/log.smbd\n"
3100 "smb passwd file=%s/smbpasswd\n"
3101 "security = share\n"
3102 "[qemu]\n"
3103 "path=%s\n"
3104 "read only=no\n"
3105 "guest ok=yes\n",
3106 smb_dir,
3107 smb_dir,
3108 smb_dir,
3109 smb_dir,
3110 smb_dir,
3111 exported_dir
3112 );
3113 fclose(f);
3114 atexit(smb_exit);
3116 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3117 smb_conf);
3119 slirp_add_exec(0, smb_cmdline, 4, 139);
3122 #endif /* !defined(_WIN32) */
3124 #endif /* CONFIG_SLIRP */
3126 #if !defined(_WIN32)
3128 typedef struct TAPState {
3129 VLANClientState *vc;
3130 int fd;
3131 } TAPState;
3133 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3135 TAPState *s = opaque;
3136 int ret;
3137 for(;;) {
3138 ret = write(s->fd, buf, size);
3139 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3140 } else {
3141 break;
3146 static void tap_send(void *opaque)
3148 TAPState *s = opaque;
3149 uint8_t buf[4096];
3150 int size;
3152 size = read(s->fd, buf, sizeof(buf));
3153 if (size > 0) {
3154 qemu_send_packet(s->vc, buf, size);
3158 /* fd support */
3160 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3162 TAPState *s;
3164 s = qemu_mallocz(sizeof(TAPState));
3165 if (!s)
3166 return NULL;
3167 s->fd = fd;
3168 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3169 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3170 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3171 return s;
3174 #ifdef _BSD
3175 static int tap_open(char *ifname, int ifname_size)
3177 int fd;
3178 char *dev;
3179 struct stat s;
3181 fd = open("/dev/tap", O_RDWR);
3182 if (fd < 0) {
3183 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3184 return -1;
3187 fstat(fd, &s);
3188 dev = devname(s.st_rdev, S_IFCHR);
3189 pstrcpy(ifname, ifname_size, dev);
3191 fcntl(fd, F_SETFL, O_NONBLOCK);
3192 return fd;
3194 #elif defined(__sun__)
3195 static int tap_open(char *ifname, int ifname_size)
3197 fprintf(stderr, "warning: tap_open not yet implemented\n");
3198 return -1;
3200 #else
3201 static int tap_open(char *ifname, int ifname_size)
3203 struct ifreq ifr;
3204 int fd, ret;
3206 fd = open("/dev/net/tun", O_RDWR);
3207 if (fd < 0) {
3208 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3209 return -1;
3211 memset(&ifr, 0, sizeof(ifr));
3212 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3213 if (ifname[0] != '\0')
3214 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3215 else
3216 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3217 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3218 if (ret != 0) {
3219 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3220 close(fd);
3221 return -1;
3223 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3224 fcntl(fd, F_SETFL, O_NONBLOCK);
3225 return fd;
3227 #endif
3229 static int net_tap_init(VLANState *vlan, const char *ifname1,
3230 const char *setup_script, const char *bridge)
3232 TAPState *s;
3233 int pid, status, fd;
3234 char *args[4];
3235 char **parg;
3236 char ifname[128];
3238 if (ifname1 != NULL)
3239 pstrcpy(ifname, sizeof(ifname), ifname1);
3240 else
3241 ifname[0] = '\0';
3242 fd = tap_open(ifname, sizeof(ifname));
3243 if (fd < 0)
3244 return -1;
3246 if (!setup_script)
3247 setup_script = "";
3248 if (setup_script[0] != '\0') {
3249 /* try to launch network init script */
3250 pid = fork();
3251 if (pid >= 0) {
3252 if (pid == 0) {
3253 parg = args;
3254 *parg++ = (char *)setup_script;
3255 *parg++ = ifname;
3256 *parg++ = (char *)bridge;
3257 *parg++ = NULL;
3258 execv(setup_script, args);
3259 _exit(1);
3261 while (waitpid(pid, &status, 0) != pid);
3262 if (!WIFEXITED(status) ||
3263 WEXITSTATUS(status) != 0) {
3264 fprintf(stderr, "%s: could not launch network script\n",
3265 setup_script);
3266 return -1;
3270 s = net_tap_fd_init(vlan, fd);
3271 if (!s)
3272 return -1;
3273 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3274 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3275 return 0;
3278 #endif /* !_WIN32 */
3280 /* network connection */
3281 typedef struct NetSocketState {
3282 VLANClientState *vc;
3283 int fd;
3284 int state; /* 0 = getting length, 1 = getting data */
3285 int index;
3286 int packet_len;
3287 uint8_t buf[4096];
3288 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3289 } NetSocketState;
3291 typedef struct NetSocketListenState {
3292 VLANState *vlan;
3293 int fd;
3294 } NetSocketListenState;
3296 /* XXX: we consider we can send the whole packet without blocking */
3297 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3299 NetSocketState *s = opaque;
3300 uint32_t len;
3301 len = htonl(size);
3303 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3304 send_all(s->fd, buf, size);
3307 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3309 NetSocketState *s = opaque;
3310 sendto(s->fd, buf, size, 0,
3311 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3314 static void net_socket_send(void *opaque)
3316 NetSocketState *s = opaque;
3317 int l, size, err;
3318 uint8_t buf1[4096];
3319 const uint8_t *buf;
3321 size = recv(s->fd, buf1, sizeof(buf1), 0);
3322 if (size < 0) {
3323 err = socket_error();
3324 if (err != EWOULDBLOCK)
3325 goto eoc;
3326 } else if (size == 0) {
3327 /* end of connection */
3328 eoc:
3329 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3330 closesocket(s->fd);
3331 return;
3333 buf = buf1;
3334 while (size > 0) {
3335 /* reassemble a packet from the network */
3336 switch(s->state) {
3337 case 0:
3338 l = 4 - s->index;
3339 if (l > size)
3340 l = size;
3341 memcpy(s->buf + s->index, buf, l);
3342 buf += l;
3343 size -= l;
3344 s->index += l;
3345 if (s->index == 4) {
3346 /* got length */
3347 s->packet_len = ntohl(*(uint32_t *)s->buf);
3348 s->index = 0;
3349 s->state = 1;
3351 break;
3352 case 1:
3353 l = s->packet_len - s->index;
3354 if (l > size)
3355 l = size;
3356 memcpy(s->buf + s->index, buf, l);
3357 s->index += l;
3358 buf += l;
3359 size -= l;
3360 if (s->index >= s->packet_len) {
3361 qemu_send_packet(s->vc, s->buf, s->packet_len);
3362 s->index = 0;
3363 s->state = 0;
3365 break;
3370 static void net_socket_send_dgram(void *opaque)
3372 NetSocketState *s = opaque;
3373 int size;
3375 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3376 if (size < 0)
3377 return;
3378 if (size == 0) {
3379 /* end of connection */
3380 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3381 return;
3383 qemu_send_packet(s->vc, s->buf, size);
3386 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3388 struct ip_mreq imr;
3389 int fd;
3390 int val, ret;
3391 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3392 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3393 inet_ntoa(mcastaddr->sin_addr),
3394 (int)ntohl(mcastaddr->sin_addr.s_addr));
3395 return -1;
3398 fd = socket(PF_INET, SOCK_DGRAM, 0);
3399 if (fd < 0) {
3400 perror("socket(PF_INET, SOCK_DGRAM)");
3401 return -1;
3404 val = 1;
3405 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3406 (const char *)&val, sizeof(val));
3407 if (ret < 0) {
3408 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3409 goto fail;
3412 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3413 if (ret < 0) {
3414 perror("bind");
3415 goto fail;
3418 /* Add host to multicast group */
3419 imr.imr_multiaddr = mcastaddr->sin_addr;
3420 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3422 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3423 (const char *)&imr, sizeof(struct ip_mreq));
3424 if (ret < 0) {
3425 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3426 goto fail;
3429 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3430 val = 1;
3431 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3432 (const char *)&val, sizeof(val));
3433 if (ret < 0) {
3434 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3435 goto fail;
3438 socket_set_nonblock(fd);
3439 return fd;
3440 fail:
3441 if (fd >= 0)
3442 closesocket(fd);
3443 return -1;
3446 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3447 int is_connected)
3449 struct sockaddr_in saddr;
3450 int newfd;
3451 socklen_t saddr_len;
3452 NetSocketState *s;
3454 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3455 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3456 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3457 */
3459 if (is_connected) {
3460 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3461 /* must be bound */
3462 if (saddr.sin_addr.s_addr==0) {
3463 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3464 fd);
3465 return NULL;
3467 /* clone dgram socket */
3468 newfd = net_socket_mcast_create(&saddr);
3469 if (newfd < 0) {
3470 /* error already reported by net_socket_mcast_create() */
3471 close(fd);
3472 return NULL;
3474 /* clone newfd to fd, close newfd */
3475 dup2(newfd, fd);
3476 close(newfd);
3478 } else {
3479 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3480 fd, strerror(errno));
3481 return NULL;
3485 s = qemu_mallocz(sizeof(NetSocketState));
3486 if (!s)
3487 return NULL;
3488 s->fd = fd;
3490 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3491 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3493 /* mcast: save bound address as dst */
3494 if (is_connected) s->dgram_dst=saddr;
3496 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3497 "socket: fd=%d (%s mcast=%s:%d)",
3498 fd, is_connected? "cloned" : "",
3499 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3500 return s;
3503 static void net_socket_connect(void *opaque)
3505 NetSocketState *s = opaque;
3506 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3509 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3510 int is_connected)
3512 NetSocketState *s;
3513 s = qemu_mallocz(sizeof(NetSocketState));
3514 if (!s)
3515 return NULL;
3516 s->fd = fd;
3517 s->vc = qemu_new_vlan_client(vlan,
3518 net_socket_receive, NULL, s);
3519 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3520 "socket: fd=%d", fd);
3521 if (is_connected) {
3522 net_socket_connect(s);
3523 } else {
3524 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3526 return s;
3529 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3530 int is_connected)
3532 int so_type=-1, optlen=sizeof(so_type);
3534 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3535 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3536 return NULL;
3538 switch(so_type) {
3539 case SOCK_DGRAM:
3540 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3541 case SOCK_STREAM:
3542 return net_socket_fd_init_stream(vlan, fd, is_connected);
3543 default:
3544 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3545 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3546 return net_socket_fd_init_stream(vlan, fd, is_connected);
3548 return NULL;
3551 static void net_socket_accept(void *opaque)
3553 NetSocketListenState *s = opaque;
3554 NetSocketState *s1;
3555 struct sockaddr_in saddr;
3556 socklen_t len;
3557 int fd;
3559 for(;;) {
3560 len = sizeof(saddr);
3561 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3562 if (fd < 0 && errno != EINTR) {
3563 return;
3564 } else if (fd >= 0) {
3565 break;
3568 s1 = net_socket_fd_init(s->vlan, fd, 1);
3569 if (!s1) {
3570 closesocket(fd);
3571 } else {
3572 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3573 "socket: connection from %s:%d",
3574 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3578 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3580 NetSocketListenState *s;
3581 int fd, val, ret;
3582 struct sockaddr_in saddr;
3584 if (parse_host_port(&saddr, host_str) < 0)
3585 return -1;
3587 s = qemu_mallocz(sizeof(NetSocketListenState));
3588 if (!s)
3589 return -1;
3591 fd = socket(PF_INET, SOCK_STREAM, 0);
3592 if (fd < 0) {
3593 perror("socket");
3594 return -1;
3596 socket_set_nonblock(fd);
3598 /* allow fast reuse */
3599 val = 1;
3600 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3602 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3603 if (ret < 0) {
3604 perror("bind");
3605 return -1;
3607 ret = listen(fd, 0);
3608 if (ret < 0) {
3609 perror("listen");
3610 return -1;
3612 s->vlan = vlan;
3613 s->fd = fd;
3614 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3615 return 0;
3618 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3620 NetSocketState *s;
3621 int fd, connected, ret, err;
3622 struct sockaddr_in saddr;
3624 if (parse_host_port(&saddr, host_str) < 0)
3625 return -1;
3627 fd = socket(PF_INET, SOCK_STREAM, 0);
3628 if (fd < 0) {
3629 perror("socket");
3630 return -1;
3632 socket_set_nonblock(fd);
3634 connected = 0;
3635 for(;;) {
3636 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3637 if (ret < 0) {
3638 err = socket_error();
3639 if (err == EINTR || err == EWOULDBLOCK) {
3640 } else if (err == EINPROGRESS) {
3641 break;
3642 } else {
3643 perror("connect");
3644 closesocket(fd);
3645 return -1;
3647 } else {
3648 connected = 1;
3649 break;
3652 s = net_socket_fd_init(vlan, fd, connected);
3653 if (!s)
3654 return -1;
3655 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3656 "socket: connect to %s:%d",
3657 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3658 return 0;
3661 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3663 NetSocketState *s;
3664 int fd;
3665 struct sockaddr_in saddr;
3667 if (parse_host_port(&saddr, host_str) < 0)
3668 return -1;
3671 fd = net_socket_mcast_create(&saddr);
3672 if (fd < 0)
3673 return -1;
3675 s = net_socket_fd_init(vlan, fd, 0);
3676 if (!s)
3677 return -1;
3679 s->dgram_dst = saddr;
3681 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3682 "socket: mcast=%s:%d",
3683 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3684 return 0;
3688 static int get_param_value(char *buf, int buf_size,
3689 const char *tag, const char *str)
3691 const char *p;
3692 char *q;
3693 char option[128];
3695 p = str;
3696 for(;;) {
3697 q = option;
3698 while (*p != '\0' && *p != '=') {
3699 if ((q - option) < sizeof(option) - 1)
3700 *q++ = *p;
3701 p++;
3703 *q = '\0';
3704 if (*p != '=')
3705 break;
3706 p++;
3707 if (!strcmp(tag, option)) {
3708 q = buf;
3709 while (*p != '\0' && *p != ',') {
3710 if ((q - buf) < buf_size - 1)
3711 *q++ = *p;
3712 p++;
3714 *q = '\0';
3715 return q - buf;
3716 } else {
3717 while (*p != '\0' && *p != ',') {
3718 p++;
3721 if (*p != ',')
3722 break;
3723 p++;
3725 return 0;
3728 int net_client_init(const char *str)
3730 const char *p;
3731 char *q;
3732 char device[64];
3733 char buf[1024];
3734 int vlan_id, ret;
3735 VLANState *vlan;
3737 p = str;
3738 q = device;
3739 while (*p != '\0' && *p != ',') {
3740 if ((q - device) < sizeof(device) - 1)
3741 *q++ = *p;
3742 p++;
3744 *q = '\0';
3745 if (*p == ',')
3746 p++;
3747 vlan_id = 0;
3748 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3749 vlan_id = strtol(buf, NULL, 0);
3751 vlan = qemu_find_vlan(vlan_id);
3752 if (!vlan) {
3753 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3754 return -1;
3756 if (!strcmp(device, "nic")) {
3757 NICInfo *nd;
3758 uint8_t *macaddr;
3760 if (nb_nics >= MAX_NICS) {
3761 fprintf(stderr, "Too Many NICs\n");
3762 return -1;
3764 nd = &nd_table[nb_nics];
3765 macaddr = nd->macaddr;
3766 macaddr[0] = 0x52;
3767 macaddr[1] = 0x54;
3768 macaddr[2] = 0x00;
3769 macaddr[3] = 0x12;
3770 macaddr[4] = 0x34;
3771 macaddr[5] = 0x56 + nb_nics;
3773 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3774 if (parse_macaddr(macaddr, buf) < 0) {
3775 fprintf(stderr, "invalid syntax for ethernet address\n");
3776 return -1;
3779 if (get_param_value(buf, sizeof(buf), "model", p)) {
3780 nd->model = strdup(buf);
3782 nd->vlan = vlan;
3783 nb_nics++;
3784 ret = 0;
3785 } else
3786 if (!strcmp(device, "none")) {
3787 /* does nothing. It is needed to signal that no network cards
3788 are wanted */
3789 ret = 0;
3790 } else
3791 #ifdef CONFIG_SLIRP
3792 if (!strcmp(device, "user")) {
3793 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3794 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3796 ret = net_slirp_init(vlan);
3797 } else
3798 #endif
3799 #ifdef _WIN32
3800 if (!strcmp(device, "tap")) {
3801 char ifname[64];
3802 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3803 fprintf(stderr, "tap: no interface name\n");
3804 return -1;
3806 ret = tap_win32_init(vlan, ifname);
3807 } else
3808 #else
3809 if (!strcmp(device, "tap")) {
3810 char ifname[64];
3811 char setup_script[1024];
3812 char bridge[16];
3813 int fd;
3814 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3815 fd = strtol(buf, NULL, 0);
3816 ret = -1;
3817 if (net_tap_fd_init(vlan, fd))
3818 ret = 0;
3819 } else {
3820 ifname[0] = '\0';
3821 get_param_value(ifname, sizeof(ifname), "ifname", p);
3822 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3823 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3825 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
3826 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
3828 ret = net_tap_init(vlan, ifname, setup_script, bridge);
3830 } else
3831 #endif
3832 if (!strcmp(device, "socket")) {
3833 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3834 int fd;
3835 fd = strtol(buf, NULL, 0);
3836 ret = -1;
3837 if (net_socket_fd_init(vlan, fd, 1))
3838 ret = 0;
3839 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3840 ret = net_socket_listen_init(vlan, buf);
3841 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3842 ret = net_socket_connect_init(vlan, buf);
3843 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3844 ret = net_socket_mcast_init(vlan, buf);
3845 } else {
3846 fprintf(stderr, "Unknown socket options: %s\n", p);
3847 return -1;
3849 } else
3851 fprintf(stderr, "Unknown network device: %s\n", device);
3852 return -1;
3854 if (ret < 0) {
3855 fprintf(stderr, "Could not initialize device '%s'\n", device);
3858 return ret;
3861 void do_info_network(void)
3863 VLANState *vlan;
3864 VLANClientState *vc;
3866 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3867 term_printf("VLAN %d devices:\n", vlan->id);
3868 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3869 term_printf(" %s\n", vc->info_str);
3873 /***********************************************************/
3874 /* USB devices */
3876 static USBPort *used_usb_ports;
3877 static USBPort *free_usb_ports;
3879 /* ??? Maybe change this to register a hub to keep track of the topology. */
3880 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3881 usb_attachfn attach)
3883 port->opaque = opaque;
3884 port->index = index;
3885 port->attach = attach;
3886 port->next = free_usb_ports;
3887 free_usb_ports = port;
3890 static int usb_device_add(const char *devname)
3892 const char *p;
3893 USBDevice *dev;
3894 USBPort *port;
3896 if (!free_usb_ports)
3897 return -1;
3899 if (strstart(devname, "host:", &p)) {
3900 dev = usb_host_device_open(p);
3901 } else if (!strcmp(devname, "mouse")) {
3902 dev = usb_mouse_init();
3903 } else if (!strcmp(devname, "tablet")) {
3904 dev = usb_tablet_init();
3905 } else if (strstart(devname, "disk:", &p)) {
3906 dev = usb_msd_init(p);
3907 } else {
3908 return -1;
3910 if (!dev)
3911 return -1;
3913 /* Find a USB port to add the device to. */
3914 port = free_usb_ports;
3915 if (!port->next) {
3916 USBDevice *hub;
3918 /* Create a new hub and chain it on. */
3919 free_usb_ports = NULL;
3920 port->next = used_usb_ports;
3921 used_usb_ports = port;
3923 hub = usb_hub_init(VM_USB_HUB_SIZE);
3924 usb_attach(port, hub);
3925 port = free_usb_ports;
3928 free_usb_ports = port->next;
3929 port->next = used_usb_ports;
3930 used_usb_ports = port;
3931 usb_attach(port, dev);
3932 return 0;
3935 static int usb_device_del(const char *devname)
3937 USBPort *port;
3938 USBPort **lastp;
3939 USBDevice *dev;
3940 int bus_num, addr;
3941 const char *p;
3943 if (!used_usb_ports)
3944 return -1;
3946 p = strchr(devname, '.');
3947 if (!p)
3948 return -1;
3949 bus_num = strtoul(devname, NULL, 0);
3950 addr = strtoul(p + 1, NULL, 0);
3951 if (bus_num != 0)
3952 return -1;
3954 lastp = &used_usb_ports;
3955 port = used_usb_ports;
3956 while (port && port->dev->addr != addr) {
3957 lastp = &port->next;
3958 port = port->next;
3961 if (!port)
3962 return -1;
3964 dev = port->dev;
3965 *lastp = port->next;
3966 usb_attach(port, NULL);
3967 dev->handle_destroy(dev);
3968 port->next = free_usb_ports;
3969 free_usb_ports = port;
3970 return 0;
3973 void do_usb_add(const char *devname)
3975 int ret;
3976 ret = usb_device_add(devname);
3977 if (ret < 0)
3978 term_printf("Could not add USB device '%s'\n", devname);
3981 void do_usb_del(const char *devname)
3983 int ret;
3984 ret = usb_device_del(devname);
3985 if (ret < 0)
3986 term_printf("Could not remove USB device '%s'\n", devname);
3989 void usb_info(void)
3991 USBDevice *dev;
3992 USBPort *port;
3993 const char *speed_str;
3995 if (!usb_enabled) {
3996 term_printf("USB support not enabled\n");
3997 return;
4000 for (port = used_usb_ports; port; port = port->next) {
4001 dev = port->dev;
4002 if (!dev)
4003 continue;
4004 switch(dev->speed) {
4005 case USB_SPEED_LOW:
4006 speed_str = "1.5";
4007 break;
4008 case USB_SPEED_FULL:
4009 speed_str = "12";
4010 break;
4011 case USB_SPEED_HIGH:
4012 speed_str = "480";
4013 break;
4014 default:
4015 speed_str = "?";
4016 break;
4018 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4019 0, dev->addr, speed_str, dev->devname);
4023 /***********************************************************/
4024 /* pid file */
4026 static char *pid_filename;
4028 /* Remove PID file. Called on normal exit */
4030 static void remove_pidfile(void)
4032 unlink (pid_filename);
4035 static void create_pidfile(const char *filename)
4037 struct stat pidstat;
4038 FILE *f;
4040 /* Try to write our PID to the named file */
4041 if (stat(filename, &pidstat) < 0) {
4042 if (errno == ENOENT) {
4043 if ((f = fopen (filename, "w")) == NULL) {
4044 perror("Opening pidfile");
4045 exit(1);
4047 fprintf(f, "%ld\n", (long)getpid());
4048 fclose(f);
4049 pid_filename = qemu_strdup(filename);
4050 if (!pid_filename) {
4051 fprintf(stderr, "Could not save PID filename");
4052 exit(1);
4054 atexit(remove_pidfile);
4056 } else {
4057 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4058 filename);
4059 exit(1);
4063 /***********************************************************/
4064 /* dumb display */
4066 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4070 static void dumb_resize(DisplayState *ds, int w, int h)
4074 static void dumb_refresh(DisplayState *ds)
4076 vga_hw_update();
4079 void dumb_display_init(DisplayState *ds)
4081 ds->data = NULL;
4082 ds->linesize = 0;
4083 ds->depth = 0;
4084 ds->dpy_update = dumb_update;
4085 ds->dpy_resize = dumb_resize;
4086 ds->dpy_refresh = dumb_refresh;
4089 /***********************************************************/
4090 /* I/O handling */
4092 #define MAX_IO_HANDLERS 64
4094 typedef struct IOHandlerRecord {
4095 int fd;
4096 IOCanRWHandler *fd_read_poll;
4097 IOHandler *fd_read;
4098 IOHandler *fd_write;
4099 void *opaque;
4100 /* temporary data */
4101 struct pollfd *ufd;
4102 struct IOHandlerRecord *next;
4103 } IOHandlerRecord;
4105 static IOHandlerRecord *first_io_handler;
4107 /* XXX: fd_read_poll should be suppressed, but an API change is
4108 necessary in the character devices to suppress fd_can_read(). */
4109 int qemu_set_fd_handler2(int fd,
4110 IOCanRWHandler *fd_read_poll,
4111 IOHandler *fd_read,
4112 IOHandler *fd_write,
4113 void *opaque)
4115 IOHandlerRecord **pioh, *ioh;
4117 if (!fd_read && !fd_write) {
4118 pioh = &first_io_handler;
4119 for(;;) {
4120 ioh = *pioh;
4121 if (ioh == NULL)
4122 break;
4123 if (ioh->fd == fd) {
4124 *pioh = ioh->next;
4125 qemu_free(ioh);
4126 break;
4128 pioh = &ioh->next;
4130 } else {
4131 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4132 if (ioh->fd == fd)
4133 goto found;
4135 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4136 if (!ioh)
4137 return -1;
4138 ioh->next = first_io_handler;
4139 first_io_handler = ioh;
4140 found:
4141 ioh->fd = fd;
4142 ioh->fd_read_poll = fd_read_poll;
4143 ioh->fd_read = fd_read;
4144 ioh->fd_write = fd_write;
4145 ioh->opaque = opaque;
4147 return 0;
4150 int qemu_set_fd_handler(int fd,
4151 IOHandler *fd_read,
4152 IOHandler *fd_write,
4153 void *opaque)
4155 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4158 /***********************************************************/
4159 /* Polling handling */
4161 typedef struct PollingEntry {
4162 PollingFunc *func;
4163 void *opaque;
4164 struct PollingEntry *next;
4165 } PollingEntry;
4167 static PollingEntry *first_polling_entry;
4169 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4171 PollingEntry **ppe, *pe;
4172 pe = qemu_mallocz(sizeof(PollingEntry));
4173 if (!pe)
4174 return -1;
4175 pe->func = func;
4176 pe->opaque = opaque;
4177 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4178 *ppe = pe;
4179 return 0;
4182 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4184 PollingEntry **ppe, *pe;
4185 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4186 pe = *ppe;
4187 if (pe->func == func && pe->opaque == opaque) {
4188 *ppe = pe->next;
4189 qemu_free(pe);
4190 break;
4195 #ifdef _WIN32
4196 /***********************************************************/
4197 /* Wait objects support */
4198 typedef struct WaitObjects {
4199 int num;
4200 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4201 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4202 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4203 } WaitObjects;
4205 static WaitObjects wait_objects = {0};
4207 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4209 WaitObjects *w = &wait_objects;
4211 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4212 return -1;
4213 w->events[w->num] = handle;
4214 w->func[w->num] = func;
4215 w->opaque[w->num] = opaque;
4216 w->num++;
4217 return 0;
4220 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4222 int i, found;
4223 WaitObjects *w = &wait_objects;
4225 found = 0;
4226 for (i = 0; i < w->num; i++) {
4227 if (w->events[i] == handle)
4228 found = 1;
4229 if (found) {
4230 w->events[i] = w->events[i + 1];
4231 w->func[i] = w->func[i + 1];
4232 w->opaque[i] = w->opaque[i + 1];
4235 if (found)
4236 w->num--;
4238 #endif
4240 /***********************************************************/
4241 /* savevm/loadvm support */
4243 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4245 fwrite(buf, 1, size, f);
4248 void qemu_put_byte(QEMUFile *f, int v)
4250 fputc(v, f);
4253 void qemu_put_be16(QEMUFile *f, unsigned int v)
4255 qemu_put_byte(f, v >> 8);
4256 qemu_put_byte(f, v);
4259 void qemu_put_be32(QEMUFile *f, unsigned int v)
4261 qemu_put_byte(f, v >> 24);
4262 qemu_put_byte(f, v >> 16);
4263 qemu_put_byte(f, v >> 8);
4264 qemu_put_byte(f, v);
4267 void qemu_put_be64(QEMUFile *f, uint64_t v)
4269 qemu_put_be32(f, v >> 32);
4270 qemu_put_be32(f, v);
4273 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4275 return fread(buf, 1, size, f);
4278 int qemu_get_byte(QEMUFile *f)
4280 int v;
4281 v = fgetc(f);
4282 if (v == EOF)
4283 return 0;
4284 else
4285 return v;
4288 unsigned int qemu_get_be16(QEMUFile *f)
4290 unsigned int v;
4291 v = qemu_get_byte(f) << 8;
4292 v |= qemu_get_byte(f);
4293 return v;
4296 unsigned int qemu_get_be32(QEMUFile *f)
4298 unsigned int v;
4299 v = qemu_get_byte(f) << 24;
4300 v |= qemu_get_byte(f) << 16;
4301 v |= qemu_get_byte(f) << 8;
4302 v |= qemu_get_byte(f);
4303 return v;
4306 uint64_t qemu_get_be64(QEMUFile *f)
4308 uint64_t v;
4309 v = (uint64_t)qemu_get_be32(f) << 32;
4310 v |= qemu_get_be32(f);
4311 return v;
4314 int64_t qemu_ftell(QEMUFile *f)
4316 return ftell(f);
4319 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4321 if (fseek(f, pos, whence) < 0)
4322 return -1;
4323 return ftell(f);
4326 typedef struct SaveStateEntry {
4327 char idstr[256];
4328 int instance_id;
4329 int version_id;
4330 SaveStateHandler *save_state;
4331 LoadStateHandler *load_state;
4332 void *opaque;
4333 struct SaveStateEntry *next;
4334 } SaveStateEntry;
4336 static SaveStateEntry *first_se;
4338 int register_savevm(const char *idstr,
4339 int instance_id,
4340 int version_id,
4341 SaveStateHandler *save_state,
4342 LoadStateHandler *load_state,
4343 void *opaque)
4345 SaveStateEntry *se, **pse;
4347 se = qemu_malloc(sizeof(SaveStateEntry));
4348 if (!se)
4349 return -1;
4350 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4351 se->instance_id = instance_id;
4352 se->version_id = version_id;
4353 se->save_state = save_state;
4354 se->load_state = load_state;
4355 se->opaque = opaque;
4356 se->next = NULL;
4358 /* add at the end of list */
4359 pse = &first_se;
4360 while (*pse != NULL)
4361 pse = &(*pse)->next;
4362 *pse = se;
4363 return 0;
4366 #define QEMU_VM_FILE_MAGIC 0x5145564d
4367 #define QEMU_VM_FILE_VERSION 0x00000001
4369 int qemu_savevm(const char *filename)
4371 SaveStateEntry *se;
4372 QEMUFile *f;
4373 int len, len_pos, cur_pos, saved_vm_running, ret;
4375 saved_vm_running = vm_running;
4376 vm_stop(0);
4378 f = fopen(filename, "wb");
4379 if (!f) {
4380 ret = -1;
4381 goto the_end;
4384 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4385 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4387 for(se = first_se; se != NULL; se = se->next) {
4388 /* ID string */
4389 len = strlen(se->idstr);
4390 qemu_put_byte(f, len);
4391 qemu_put_buffer(f, se->idstr, len);
4393 qemu_put_be32(f, se->instance_id);
4394 qemu_put_be32(f, se->version_id);
4396 /* record size: filled later */
4397 len_pos = ftell(f);
4398 qemu_put_be32(f, 0);
4400 se->save_state(f, se->opaque);
4402 /* fill record size */
4403 cur_pos = ftell(f);
4404 len = ftell(f) - len_pos - 4;
4405 fseek(f, len_pos, SEEK_SET);
4406 qemu_put_be32(f, len);
4407 fseek(f, cur_pos, SEEK_SET);
4410 fclose(f);
4411 ret = 0;
4412 the_end:
4413 if (saved_vm_running)
4414 vm_start();
4415 return ret;
4418 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4420 SaveStateEntry *se;
4422 for(se = first_se; se != NULL; se = se->next) {
4423 if (!strcmp(se->idstr, idstr) &&
4424 instance_id == se->instance_id)
4425 return se;
4427 return NULL;
4430 int qemu_loadvm(const char *filename)
4432 SaveStateEntry *se;
4433 QEMUFile *f;
4434 int len, cur_pos, ret, instance_id, record_len, version_id;
4435 int saved_vm_running;
4436 unsigned int v;
4437 char idstr[256];
4439 saved_vm_running = vm_running;
4440 vm_stop(0);
4442 f = fopen(filename, "rb");
4443 if (!f) {
4444 ret = -1;
4445 goto the_end;
4448 v = qemu_get_be32(f);
4449 if (v != QEMU_VM_FILE_MAGIC)
4450 goto fail;
4451 v = qemu_get_be32(f);
4452 if (v != QEMU_VM_FILE_VERSION) {
4453 fail:
4454 fclose(f);
4455 ret = -1;
4456 goto the_end;
4458 for(;;) {
4459 len = qemu_get_byte(f);
4460 if (feof(f))
4461 break;
4462 qemu_get_buffer(f, idstr, len);
4463 idstr[len] = '\0';
4464 instance_id = qemu_get_be32(f);
4465 version_id = qemu_get_be32(f);
4466 record_len = qemu_get_be32(f);
4467 #if 0
4468 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4469 idstr, instance_id, version_id, record_len);
4470 #endif
4471 cur_pos = ftell(f);
4472 se = find_se(idstr, instance_id);
4473 if (!se) {
4474 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4475 instance_id, idstr);
4476 } else {
4477 ret = se->load_state(f, se->opaque, version_id);
4478 if (ret < 0) {
4479 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4480 instance_id, idstr);
4483 /* always seek to exact end of record */
4484 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4486 fclose(f);
4488 /* del tmp file */
4489 if (unlink(filename) == -1)
4490 fprintf(stderr, "delete tmp qemu state file failed.\n");
4492 ret = 0;
4493 the_end:
4494 if (saved_vm_running)
4495 vm_start();
4496 return ret;
4499 #ifndef CONFIG_DM
4500 /***********************************************************/
4501 /* cpu save/restore */
4503 #if defined(TARGET_I386)
4505 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4507 qemu_put_be32(f, dt->selector);
4508 qemu_put_betl(f, dt->base);
4509 qemu_put_be32(f, dt->limit);
4510 qemu_put_be32(f, dt->flags);
4513 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4515 dt->selector = qemu_get_be32(f);
4516 dt->base = qemu_get_betl(f);
4517 dt->limit = qemu_get_be32(f);
4518 dt->flags = qemu_get_be32(f);
4521 void cpu_save(QEMUFile *f, void *opaque)
4523 CPUState *env = opaque;
4524 uint16_t fptag, fpus, fpuc, fpregs_format;
4525 uint32_t hflags;
4526 int i;
4528 for(i = 0; i < CPU_NB_REGS; i++)
4529 qemu_put_betls(f, &env->regs[i]);
4530 qemu_put_betls(f, &env->eip);
4531 qemu_put_betls(f, &env->eflags);
4532 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4533 qemu_put_be32s(f, &hflags);
4535 /* FPU */
4536 fpuc = env->fpuc;
4537 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4538 fptag = 0;
4539 for(i = 0; i < 8; i++) {
4540 fptag |= ((!env->fptags[i]) << i);
4543 qemu_put_be16s(f, &fpuc);
4544 qemu_put_be16s(f, &fpus);
4545 qemu_put_be16s(f, &fptag);
4547 #ifdef USE_X86LDOUBLE
4548 fpregs_format = 0;
4549 #else
4550 fpregs_format = 1;
4551 #endif
4552 qemu_put_be16s(f, &fpregs_format);
4554 for(i = 0; i < 8; i++) {
4555 #ifdef USE_X86LDOUBLE
4557 uint64_t mant;
4558 uint16_t exp;
4559 /* we save the real CPU data (in case of MMX usage only 'mant'
4560 contains the MMX register */
4561 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4562 qemu_put_be64(f, mant);
4563 qemu_put_be16(f, exp);
4565 #else
4566 /* if we use doubles for float emulation, we save the doubles to
4567 avoid losing information in case of MMX usage. It can give
4568 problems if the image is restored on a CPU where long
4569 doubles are used instead. */
4570 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4571 #endif
4574 for(i = 0; i < 6; i++)
4575 cpu_put_seg(f, &env->segs[i]);
4576 cpu_put_seg(f, &env->ldt);
4577 cpu_put_seg(f, &env->tr);
4578 cpu_put_seg(f, &env->gdt);
4579 cpu_put_seg(f, &env->idt);
4581 qemu_put_be32s(f, &env->sysenter_cs);
4582 qemu_put_be32s(f, &env->sysenter_esp);
4583 qemu_put_be32s(f, &env->sysenter_eip);
4585 qemu_put_betls(f, &env->cr[0]);
4586 qemu_put_betls(f, &env->cr[2]);
4587 qemu_put_betls(f, &env->cr[3]);
4588 qemu_put_betls(f, &env->cr[4]);
4590 for(i = 0; i < 8; i++)
4591 qemu_put_betls(f, &env->dr[i]);
4593 /* MMU */
4594 qemu_put_be32s(f, &env->a20_mask);
4596 /* XMM */
4597 qemu_put_be32s(f, &env->mxcsr);
4598 for(i = 0; i < CPU_NB_REGS; i++) {
4599 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4600 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4603 #ifdef TARGET_X86_64
4604 qemu_put_be64s(f, &env->efer);
4605 qemu_put_be64s(f, &env->star);
4606 qemu_put_be64s(f, &env->lstar);
4607 qemu_put_be64s(f, &env->cstar);
4608 qemu_put_be64s(f, &env->fmask);
4609 qemu_put_be64s(f, &env->kernelgsbase);
4610 #endif
4613 #ifdef USE_X86LDOUBLE
4614 /* XXX: add that in a FPU generic layer */
4615 union x86_longdouble {
4616 uint64_t mant;
4617 uint16_t exp;
4618 };
4620 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4621 #define EXPBIAS1 1023
4622 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4623 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4625 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4627 int e;
4628 /* mantissa */
4629 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4630 /* exponent + sign */
4631 e = EXPD1(temp) - EXPBIAS1 + 16383;
4632 e |= SIGND1(temp) >> 16;
4633 p->exp = e;
4635 #endif
4637 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4639 CPUState *env = opaque;
4640 int i, guess_mmx;
4641 uint32_t hflags;
4642 uint16_t fpus, fpuc, fptag, fpregs_format;
4644 if (version_id != 3)
4645 return -EINVAL;
4646 for(i = 0; i < CPU_NB_REGS; i++)
4647 qemu_get_betls(f, &env->regs[i]);
4648 qemu_get_betls(f, &env->eip);
4649 qemu_get_betls(f, &env->eflags);
4650 qemu_get_be32s(f, &hflags);
4652 qemu_get_be16s(f, &fpuc);
4653 qemu_get_be16s(f, &fpus);
4654 qemu_get_be16s(f, &fptag);
4655 qemu_get_be16s(f, &fpregs_format);
4657 /* NOTE: we cannot always restore the FPU state if the image come
4658 from a host with a different 'USE_X86LDOUBLE' define. We guess
4659 if we are in an MMX state to restore correctly in that case. */
4660 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4661 for(i = 0; i < 8; i++) {
4662 uint64_t mant;
4663 uint16_t exp;
4665 switch(fpregs_format) {
4666 case 0:
4667 mant = qemu_get_be64(f);
4668 exp = qemu_get_be16(f);
4669 #ifdef USE_X86LDOUBLE
4670 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4671 #else
4672 /* difficult case */
4673 if (guess_mmx)
4674 env->fpregs[i].mmx.MMX_Q(0) = mant;
4675 else
4676 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4677 #endif
4678 break;
4679 case 1:
4680 mant = qemu_get_be64(f);
4681 #ifdef USE_X86LDOUBLE
4683 union x86_longdouble *p;
4684 /* difficult case */
4685 p = (void *)&env->fpregs[i];
4686 if (guess_mmx) {
4687 p->mant = mant;
4688 p->exp = 0xffff;
4689 } else {
4690 fp64_to_fp80(p, mant);
4693 #else
4694 env->fpregs[i].mmx.MMX_Q(0) = mant;
4695 #endif
4696 break;
4697 default:
4698 return -EINVAL;
4702 env->fpuc = fpuc;
4703 /* XXX: restore FPU round state */
4704 env->fpstt = (fpus >> 11) & 7;
4705 env->fpus = fpus & ~0x3800;
4706 fptag ^= 0xff;
4707 for(i = 0; i < 8; i++) {
4708 env->fptags[i] = (fptag >> i) & 1;
4711 for(i = 0; i < 6; i++)
4712 cpu_get_seg(f, &env->segs[i]);
4713 cpu_get_seg(f, &env->ldt);
4714 cpu_get_seg(f, &env->tr);
4715 cpu_get_seg(f, &env->gdt);
4716 cpu_get_seg(f, &env->idt);
4718 qemu_get_be32s(f, &env->sysenter_cs);
4719 qemu_get_be32s(f, &env->sysenter_esp);
4720 qemu_get_be32s(f, &env->sysenter_eip);
4722 qemu_get_betls(f, &env->cr[0]);
4723 qemu_get_betls(f, &env->cr[2]);
4724 qemu_get_betls(f, &env->cr[3]);
4725 qemu_get_betls(f, &env->cr[4]);
4727 for(i = 0; i < 8; i++)
4728 qemu_get_betls(f, &env->dr[i]);
4730 /* MMU */
4731 qemu_get_be32s(f, &env->a20_mask);
4733 qemu_get_be32s(f, &env->mxcsr);
4734 for(i = 0; i < CPU_NB_REGS; i++) {
4735 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4736 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4739 #ifdef TARGET_X86_64
4740 qemu_get_be64s(f, &env->efer);
4741 qemu_get_be64s(f, &env->star);
4742 qemu_get_be64s(f, &env->lstar);
4743 qemu_get_be64s(f, &env->cstar);
4744 qemu_get_be64s(f, &env->fmask);
4745 qemu_get_be64s(f, &env->kernelgsbase);
4746 #endif
4748 /* XXX: compute hflags from scratch, except for CPL and IIF */
4749 env->hflags = hflags;
4750 tlb_flush(env, 1);
4751 return 0;
4754 #elif defined(TARGET_PPC)
4755 void cpu_save(QEMUFile *f, void *opaque)
4759 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4761 return 0;
4764 #elif defined(TARGET_MIPS)
4765 void cpu_save(QEMUFile *f, void *opaque)
4769 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4771 return 0;
4774 #elif defined(TARGET_SPARC)
4775 void cpu_save(QEMUFile *f, void *opaque)
4777 CPUState *env = opaque;
4778 int i;
4779 uint32_t tmp;
4781 for(i = 0; i < 8; i++)
4782 qemu_put_betls(f, &env->gregs[i]);
4783 for(i = 0; i < NWINDOWS * 16; i++)
4784 qemu_put_betls(f, &env->regbase[i]);
4786 /* FPU */
4787 for(i = 0; i < TARGET_FPREGS; i++) {
4788 union {
4789 float32 f;
4790 uint32_t i;
4791 } u;
4792 u.f = env->fpr[i];
4793 qemu_put_be32(f, u.i);
4796 qemu_put_betls(f, &env->pc);
4797 qemu_put_betls(f, &env->npc);
4798 qemu_put_betls(f, &env->y);
4799 tmp = GET_PSR(env);
4800 qemu_put_be32(f, tmp);
4801 qemu_put_betls(f, &env->fsr);
4802 qemu_put_betls(f, &env->tbr);
4803 #ifndef TARGET_SPARC64
4804 qemu_put_be32s(f, &env->wim);
4805 /* MMU */
4806 for(i = 0; i < 16; i++)
4807 qemu_put_be32s(f, &env->mmuregs[i]);
4808 #endif
4811 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4813 CPUState *env = opaque;
4814 int i;
4815 uint32_t tmp;
4817 for(i = 0; i < 8; i++)
4818 qemu_get_betls(f, &env->gregs[i]);
4819 for(i = 0; i < NWINDOWS * 16; i++)
4820 qemu_get_betls(f, &env->regbase[i]);
4822 /* FPU */
4823 for(i = 0; i < TARGET_FPREGS; i++) {
4824 union {
4825 float32 f;
4826 uint32_t i;
4827 } u;
4828 u.i = qemu_get_be32(f);
4829 env->fpr[i] = u.f;
4832 qemu_get_betls(f, &env->pc);
4833 qemu_get_betls(f, &env->npc);
4834 qemu_get_betls(f, &env->y);
4835 tmp = qemu_get_be32(f);
4836 env->cwp = 0; /* needed to ensure that the wrapping registers are
4837 correctly updated */
4838 PUT_PSR(env, tmp);
4839 qemu_get_betls(f, &env->fsr);
4840 qemu_get_betls(f, &env->tbr);
4841 #ifndef TARGET_SPARC64
4842 qemu_get_be32s(f, &env->wim);
4843 /* MMU */
4844 for(i = 0; i < 16; i++)
4845 qemu_get_be32s(f, &env->mmuregs[i]);
4846 #endif
4847 tlb_flush(env, 1);
4848 return 0;
4851 #elif defined(TARGET_ARM)
4853 /* ??? Need to implement these. */
4854 void cpu_save(QEMUFile *f, void *opaque)
4858 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4860 return 0;
4863 #else
4865 #warning No CPU save/restore functions
4867 #endif
4869 /***********************************************************/
4870 /* ram save/restore */
4872 /* we just avoid storing empty pages */
4873 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4875 int i, v;
4877 v = buf[0];
4878 for(i = 1; i < len; i++) {
4879 if (buf[i] != v)
4880 goto normal_save;
4882 qemu_put_byte(f, 1);
4883 qemu_put_byte(f, v);
4884 return;
4885 normal_save:
4886 qemu_put_byte(f, 0);
4887 qemu_put_buffer(f, buf, len);
4890 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4892 int v;
4894 v = qemu_get_byte(f);
4895 switch(v) {
4896 case 0:
4897 if (qemu_get_buffer(f, buf, len) != len)
4898 return -EIO;
4899 break;
4900 case 1:
4901 v = qemu_get_byte(f);
4902 memset(buf, v, len);
4903 break;
4904 default:
4905 return -EINVAL;
4907 return 0;
4910 static void ram_save(QEMUFile *f, void *opaque)
4912 int i;
4913 qemu_put_be32(f, phys_ram_size);
4914 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4915 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4919 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4921 int i, ret;
4923 if (version_id != 1)
4924 return -EINVAL;
4925 if (qemu_get_be32(f) != phys_ram_size)
4926 return -EINVAL;
4927 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4928 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4929 if (ret)
4930 return ret;
4932 return 0;
4934 #else /* CONFIG_DM */
4935 void cpu_save(QEMUFile *f, void *opaque)
4939 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4941 return 0;
4944 static void ram_save(QEMUFile *f, void *opaque)
4948 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4950 return 0;
4952 #endif /* CONFIG_DM */
4954 /***********************************************************/
4955 /* machine registration */
4957 QEMUMachine *first_machine = NULL;
4959 int qemu_register_machine(QEMUMachine *m)
4961 QEMUMachine **pm;
4962 pm = &first_machine;
4963 while (*pm != NULL)
4964 pm = &(*pm)->next;
4965 m->next = NULL;
4966 *pm = m;
4967 return 0;
4970 QEMUMachine *find_machine(const char *name)
4972 QEMUMachine *m;
4974 for(m = first_machine; m != NULL; m = m->next) {
4975 if (!strcmp(m->name, name))
4976 return m;
4978 return NULL;
4981 /***********************************************************/
4982 /* main execution loop */
4984 void gui_update(void *opaque)
4986 display_state.dpy_refresh(&display_state);
4987 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4990 struct vm_change_state_entry {
4991 VMChangeStateHandler *cb;
4992 void *opaque;
4993 LIST_ENTRY (vm_change_state_entry) entries;
4994 };
4996 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4998 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4999 void *opaque)
5001 VMChangeStateEntry *e;
5003 e = qemu_mallocz(sizeof (*e));
5004 if (!e)
5005 return NULL;
5007 e->cb = cb;
5008 e->opaque = opaque;
5009 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5010 return e;
5013 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5015 LIST_REMOVE (e, entries);
5016 qemu_free (e);
5019 static void vm_state_notify(int running)
5021 VMChangeStateEntry *e;
5023 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5024 e->cb(e->opaque, running);
5028 /* XXX: support several handlers */
5029 static VMStopHandler *vm_stop_cb;
5030 static void *vm_stop_opaque;
5032 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5034 vm_stop_cb = cb;
5035 vm_stop_opaque = opaque;
5036 return 0;
5039 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5041 vm_stop_cb = NULL;
5044 void vm_start(void)
5046 if (!vm_running) {
5047 cpu_enable_ticks();
5048 vm_running = 1;
5049 vm_state_notify(1);
5053 void vm_stop(int reason)
5055 if (vm_running) {
5056 cpu_disable_ticks();
5057 vm_running = 0;
5058 if (reason != 0) {
5059 if (vm_stop_cb) {
5060 vm_stop_cb(vm_stop_opaque, reason);
5063 vm_state_notify(0);
5067 /* reset/shutdown handler */
5069 typedef struct QEMUResetEntry {
5070 QEMUResetHandler *func;
5071 void *opaque;
5072 struct QEMUResetEntry *next;
5073 } QEMUResetEntry;
5075 static QEMUResetEntry *first_reset_entry;
5076 int reset_requested;
5077 int shutdown_requested;
5078 int suspend_requested;
5079 static int powerdown_requested;
5081 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5083 QEMUResetEntry **pre, *re;
5085 pre = &first_reset_entry;
5086 while (*pre != NULL)
5087 pre = &(*pre)->next;
5088 re = qemu_mallocz(sizeof(QEMUResetEntry));
5089 re->func = func;
5090 re->opaque = opaque;
5091 re->next = NULL;
5092 *pre = re;
5095 void qemu_system_reset(void)
5097 QEMUResetEntry *re;
5099 /* reset all devices */
5100 for(re = first_reset_entry; re != NULL; re = re->next) {
5101 re->func(re->opaque);
5105 void qemu_system_reset_request(void)
5107 reset_requested = 1;
5108 if (cpu_single_env)
5109 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5112 void qemu_system_shutdown_request(void)
5114 shutdown_requested = 1;
5115 if (cpu_single_env)
5116 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5119 void qemu_system_powerdown_request(void)
5121 powerdown_requested = 1;
5122 if (cpu_single_env)
5123 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5126 void main_loop_wait(int timeout)
5128 IOHandlerRecord *ioh, *ioh_next;
5129 fd_set rfds, wfds, xfds;
5130 int ret, nfds;
5131 struct timeval tv;
5132 PollingEntry *pe;
5135 /* XXX: need to suppress polling by better using win32 events */
5136 ret = 0;
5137 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5138 ret |= pe->func(pe->opaque);
5140 #ifdef _WIN32
5141 if (ret == 0 && timeout > 0) {
5142 int err;
5143 WaitObjects *w = &wait_objects;
5145 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5146 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5147 if (w->func[ret - WAIT_OBJECT_0])
5148 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5149 } else if (ret == WAIT_TIMEOUT) {
5150 } else {
5151 err = GetLastError();
5152 fprintf(stderr, "Wait error %d %d\n", ret, err);
5155 #endif
5156 /* poll any events */
5157 /* XXX: separate device handlers from system ones */
5158 nfds = -1;
5159 FD_ZERO(&rfds);
5160 FD_ZERO(&wfds);
5161 FD_ZERO(&xfds);
5162 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5163 if (ioh->fd_read &&
5164 (!ioh->fd_read_poll ||
5165 ioh->fd_read_poll(ioh->opaque) != 0)) {
5166 FD_SET(ioh->fd, &rfds);
5167 if (ioh->fd > nfds)
5168 nfds = ioh->fd;
5170 if (ioh->fd_write) {
5171 FD_SET(ioh->fd, &wfds);
5172 if (ioh->fd > nfds)
5173 nfds = ioh->fd;
5177 tv.tv_sec = 0;
5178 #ifdef _WIN32
5179 tv.tv_usec = 0;
5180 #else
5181 tv.tv_usec = timeout * 1000;
5182 #endif
5183 #if defined(CONFIG_SLIRP)
5184 if (slirp_inited) {
5185 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5187 #endif
5188 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5189 if (ret > 0) {
5190 /* XXX: better handling of removal */
5191 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5192 ioh_next = ioh->next;
5193 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
5194 ioh->fd_read(ioh->opaque);
5196 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
5197 ioh->fd_write(ioh->opaque);
5201 #if defined(CONFIG_SLIRP)
5202 if (slirp_inited) {
5203 if (ret < 0) {
5204 FD_ZERO(&rfds);
5205 FD_ZERO(&wfds);
5206 FD_ZERO(&xfds);
5208 slirp_select_poll(&rfds, &wfds, &xfds);
5210 #endif
5211 #ifdef _WIN32
5212 tap_win32_poll();
5213 #endif
5215 if (vm_running) {
5216 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5217 qemu_get_clock(vm_clock));
5218 /* run dma transfers, if any */
5219 DMA_run();
5222 /* real time timers */
5223 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5224 qemu_get_clock(rt_clock));
5227 #ifndef CONFIG_DM
5228 static CPUState *cur_cpu;
5230 int main_loop(void)
5232 int ret, timeout;
5233 #ifdef CONFIG_PROFILER
5234 int64_t ti;
5235 #endif
5236 CPUState *env;
5238 cur_cpu = first_cpu;
5239 for(;;) {
5240 if (vm_running) {
5242 env = cur_cpu;
5243 for(;;) {
5244 /* get next cpu */
5245 env = env->next_cpu;
5246 if (!env)
5247 env = first_cpu;
5248 #ifdef CONFIG_PROFILER
5249 ti = profile_getclock();
5250 #endif
5251 ret = cpu_exec(env);
5252 #ifdef CONFIG_PROFILER
5253 qemu_time += profile_getclock() - ti;
5254 #endif
5255 if (ret != EXCP_HALTED)
5256 break;
5257 /* all CPUs are halted ? */
5258 if (env == cur_cpu) {
5259 ret = EXCP_HLT;
5260 break;
5263 cur_cpu = env;
5265 if (shutdown_requested) {
5266 ret = EXCP_INTERRUPT;
5267 break;
5269 if (reset_requested) {
5270 reset_requested = 0;
5271 qemu_system_reset();
5272 ret = EXCP_INTERRUPT;
5274 if (powerdown_requested) {
5275 powerdown_requested = 0;
5276 qemu_system_powerdown();
5277 ret = EXCP_INTERRUPT;
5279 if (ret == EXCP_DEBUG) {
5280 vm_stop(EXCP_DEBUG);
5282 /* if hlt instruction, we wait until the next IRQ */
5283 /* XXX: use timeout computed from timers */
5284 if (ret == EXCP_HLT)
5285 timeout = 10;
5286 else
5287 timeout = 0;
5288 } else {
5289 timeout = 10;
5291 #ifdef CONFIG_PROFILER
5292 ti = profile_getclock();
5293 #endif
5294 main_loop_wait(timeout);
5295 #ifdef CONFIG_PROFILER
5296 dev_time += profile_getclock() - ti;
5297 #endif
5299 cpu_disable_ticks();
5300 return ret;
5302 #endif /* !CONFIG_DM */
5304 void help(void)
5306 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5307 "usage: %s [options] [disk_image]\n"
5308 "\n"
5309 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5310 "\n"
5311 "Standard options:\n"
5312 "-M machine select emulated machine (-M ? for list)\n"
5313 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5314 #ifndef CONFIG_DM
5315 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5316 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5317 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5318 #endif /* !CONFIG_DM */
5319 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5320 "-snapshot write to temporary files instead of disk image files\n"
5321 #ifdef TARGET_I386
5322 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5323 #endif
5324 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5325 "-smp n set the number of CPUs to 'n' [default=1]\n"
5326 "-nographic disable graphical output and redirect serial I/Os to console\n"
5327 "-vcpus set CPU number of guest platform\n"
5328 #ifndef _WIN32
5329 "-k language use keyboard layout (for example \"fr\" for French)\n"
5330 #endif
5331 #ifdef HAS_AUDIO
5332 "-audio-help print list of audio drivers and their options\n"
5333 "-soundhw c1,... enable audio support\n"
5334 " and only specified sound cards (comma separated list)\n"
5335 " use -soundhw ? to get the list of supported cards\n"
5336 " use -soundhw all to enable all of them\n"
5337 #endif
5338 "-localtime set the real time clock to local time [default=utc]\n"
5339 "-full-screen start in full screen\n"
5340 #ifdef TARGET_I386
5341 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5342 #endif
5343 "-usb enable the USB driver (will be the default soon)\n"
5344 "-usbdevice name add the host or guest USB device 'name'\n"
5345 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5346 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5347 #endif
5348 "\n"
5349 "Network options:\n"
5350 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5351 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5352 #ifdef CONFIG_SLIRP
5353 "-net user[,vlan=n][,hostname=host]\n"
5354 " connect the user mode network stack to VLAN 'n' and send\n"
5355 " hostname 'host' to DHCP clients\n"
5356 #endif
5357 #ifdef _WIN32
5358 "-net tap[,vlan=n],ifname=name\n"
5359 " connect the host TAP network interface to VLAN 'n'\n"
5360 #else
5361 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
5362 " connect the host TAP network interface to VLAN 'n' and use\n"
5363 " the network script 'file' (default=%s);\n"
5364 " use 'fd=h' to connect to an already opened TAP interface\n"
5365 #endif
5366 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5367 " connect the vlan 'n' to another VLAN using a socket connection\n"
5368 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5369 " connect the vlan 'n' to multicast maddr and port\n"
5370 "-net none use it alone to have zero network devices; if no -net option\n"
5371 " is provided, the default is '-net nic -net user'\n"
5372 "\n"
5373 #ifdef CONFIG_SLIRP
5374 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5375 #ifndef _WIN32
5376 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5377 #endif
5378 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5379 " redirect TCP or UDP connections from host to guest [-net user]\n"
5380 #endif
5381 "\n"
5382 "Linux boot specific:\n"
5383 "-kernel bzImage use 'bzImage' as kernel image\n"
5384 "-append cmdline use 'cmdline' as kernel command line\n"
5385 "-initrd file use 'file' as initial ram disk\n"
5386 "\n"
5387 "Debug/Expert options:\n"
5388 "-monitor dev redirect the monitor to char device 'dev'\n"
5389 "-serial dev redirect the serial port to char device 'dev'\n"
5390 "-parallel dev redirect the parallel port to char device 'dev'\n"
5391 "-pidfile file Write PID to 'file'\n"
5392 "-S freeze CPU at startup (use 'c' to start execution)\n"
5393 "-s wait gdb connection to port %d\n"
5394 "-p port change gdb connection port\n"
5395 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
5396 "-d domain domain that we're serving\n"
5397 "-domain-name domain name that we're serving\n"
5398 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5399 " translation (t=none or lba) (usually qemu can guess them)\n"
5400 "-L path set the directory for the BIOS and VGA BIOS\n"
5401 #ifdef USE_KQEMU
5402 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5403 "-no-kqemu disable KQEMU kernel module usage\n"
5404 #endif
5405 #ifdef USE_CODE_COPY
5406 "-no-code-copy disable code copy acceleration\n"
5407 #endif
5408 #ifdef TARGET_I386
5409 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5410 " (default is CL-GD5446 PCI VGA)\n"
5411 "-no-acpi disable ACPI\n"
5412 #endif
5413 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5414 "-vnc display start a VNC server on display\n"
5415 "-vncviewer start a vncviewer process for this domain\n"
5416 "-vncunused bind the VNC server to an unused port\n"
5417 "-vnclisten bind the VNC server to this address\n"
5418 "-timeoffset time offset (in seconds) from local time\n"
5419 "-acpi disable or enable ACPI of HVM domain \n"
5420 "\n"
5421 "During emulation, the following keys are useful:\n"
5422 "ctrl-alt-f toggle full screen\n"
5423 "ctrl-alt-n switch to virtual console 'n'\n"
5424 "ctrl-alt toggle mouse and keyboard grab\n"
5425 "\n"
5426 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5428 "qemu",
5429 DEFAULT_RAM_SIZE,
5430 #ifndef _WIN32
5431 DEFAULT_NETWORK_SCRIPT,
5432 #endif
5433 DEFAULT_GDBSTUB_PORT,
5434 "/tmp/qemu.log");
5435 exit(1);
5438 #define HAS_ARG 0x0001
5440 enum {
5441 QEMU_OPTION_h,
5443 QEMU_OPTION_M,
5444 QEMU_OPTION_fda,
5445 QEMU_OPTION_fdb,
5446 #ifndef CONFIG_DM
5447 QEMU_OPTION_hda,
5448 QEMU_OPTION_hdb,
5449 QEMU_OPTION_hdc,
5450 QEMU_OPTION_hdd,
5451 QEMU_OPTION_cdrom,
5452 #endif /* !CONFIG_DM */
5453 QEMU_OPTION_boot,
5454 QEMU_OPTION_snapshot,
5455 #ifdef TARGET_I386
5456 QEMU_OPTION_no_fd_bootchk,
5457 #endif
5458 QEMU_OPTION_m,
5459 QEMU_OPTION_nographic,
5460 #ifdef HAS_AUDIO
5461 QEMU_OPTION_audio_help,
5462 QEMU_OPTION_soundhw,
5463 #endif
5465 QEMU_OPTION_net,
5466 QEMU_OPTION_tftp,
5467 QEMU_OPTION_smb,
5468 QEMU_OPTION_redir,
5470 QEMU_OPTION_kernel,
5471 QEMU_OPTION_append,
5472 QEMU_OPTION_initrd,
5474 QEMU_OPTION_S,
5475 QEMU_OPTION_s,
5476 QEMU_OPTION_p,
5477 QEMU_OPTION_l,
5478 QEMU_OPTION_hdachs,
5479 QEMU_OPTION_L,
5480 #ifdef USE_CODE_COPY
5481 QEMU_OPTION_no_code_copy,
5482 #endif
5483 QEMU_OPTION_k,
5484 QEMU_OPTION_localtime,
5485 QEMU_OPTION_cirrusvga,
5486 QEMU_OPTION_g,
5487 QEMU_OPTION_std_vga,
5488 QEMU_OPTION_monitor,
5489 QEMU_OPTION_domainname,
5490 QEMU_OPTION_serial,
5491 QEMU_OPTION_parallel,
5492 QEMU_OPTION_loadvm,
5493 QEMU_OPTION_full_screen,
5494 QEMU_OPTION_pidfile,
5495 QEMU_OPTION_no_kqemu,
5496 QEMU_OPTION_kernel_kqemu,
5497 QEMU_OPTION_win2k_hack,
5498 QEMU_OPTION_usb,
5499 QEMU_OPTION_usbdevice,
5500 QEMU_OPTION_smp,
5501 QEMU_OPTION_vnc,
5502 QEMU_OPTION_no_acpi,
5504 QEMU_OPTION_d,
5505 QEMU_OPTION_vcpus,
5506 QEMU_OPTION_timeoffset,
5507 QEMU_OPTION_acpi,
5508 QEMU_OPTION_vncviewer,
5509 QEMU_OPTION_vncunused,
5510 QEMU_OPTION_vnclisten,
5511 };
5513 typedef struct QEMUOption {
5514 const char *name;
5515 int flags;
5516 int index;
5517 } QEMUOption;
5519 const QEMUOption qemu_options[] = {
5520 { "h", 0, QEMU_OPTION_h },
5522 { "M", HAS_ARG, QEMU_OPTION_M },
5523 { "fda", HAS_ARG, QEMU_OPTION_fda },
5524 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5525 #ifndef CONFIG_DM
5526 { "hda", HAS_ARG, QEMU_OPTION_hda },
5527 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5528 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5529 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5530 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5531 #endif /* !CONFIG_DM */
5532 { "boot", HAS_ARG, QEMU_OPTION_boot },
5533 { "snapshot", 0, QEMU_OPTION_snapshot },
5534 #ifdef TARGET_I386
5535 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5536 #endif
5537 { "m", HAS_ARG, QEMU_OPTION_m },
5538 { "nographic", 0, QEMU_OPTION_nographic },
5539 { "k", HAS_ARG, QEMU_OPTION_k },
5540 #ifdef HAS_AUDIO
5541 { "audio-help", 0, QEMU_OPTION_audio_help },
5542 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5543 #endif
5545 { "net", HAS_ARG, QEMU_OPTION_net},
5546 #ifdef CONFIG_SLIRP
5547 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5548 #ifndef _WIN32
5549 { "smb", HAS_ARG, QEMU_OPTION_smb },
5550 #endif
5551 { "redir", HAS_ARG, QEMU_OPTION_redir },
5552 #endif
5554 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5555 { "append", HAS_ARG, QEMU_OPTION_append },
5556 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5558 { "S", 0, QEMU_OPTION_S },
5559 { "s", 0, QEMU_OPTION_s },
5560 { "p", HAS_ARG, QEMU_OPTION_p },
5561 { "l", HAS_ARG, QEMU_OPTION_l },
5562 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5563 { "L", HAS_ARG, QEMU_OPTION_L },
5564 #ifdef USE_CODE_COPY
5565 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5566 #endif
5567 #ifdef USE_KQEMU
5568 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5569 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5570 #endif
5571 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5572 { "g", 1, QEMU_OPTION_g },
5573 #endif
5574 { "localtime", 0, QEMU_OPTION_localtime },
5575 { "std-vga", 0, QEMU_OPTION_std_vga },
5576 { "monitor", 1, QEMU_OPTION_monitor },
5577 { "domain-name", 1, QEMU_OPTION_domainname },
5578 { "serial", 1, QEMU_OPTION_serial },
5579 { "parallel", 1, QEMU_OPTION_parallel },
5580 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5581 { "full-screen", 0, QEMU_OPTION_full_screen },
5582 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5583 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5584 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5585 { "smp", HAS_ARG, QEMU_OPTION_smp },
5586 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5587 { "vncviewer", 0, QEMU_OPTION_vncviewer },
5588 { "vncunused", 0, QEMU_OPTION_vncunused },
5589 { "vnclisten", HAS_ARG, QEMU_OPTION_vnclisten },
5591 /* temporary options */
5592 { "usb", 0, QEMU_OPTION_usb },
5593 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5594 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5596 { "d", HAS_ARG, QEMU_OPTION_d },
5597 { "vcpus", 1, QEMU_OPTION_vcpus },
5598 { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
5599 { "acpi", 0, QEMU_OPTION_acpi },
5600 { NULL },
5601 };
5603 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5605 /* this stack is only used during signal handling */
5606 #define SIGNAL_STACK_SIZE 32768
5608 static uint8_t *signal_stack;
5610 #endif
5612 /* password input */
5614 static BlockDriverState *get_bdrv(int index)
5616 BlockDriverState *bs;
5618 if (index < 4) {
5619 bs = bs_table[index];
5620 } else if (index < 6) {
5621 bs = fd_table[index - 4];
5622 } else {
5623 bs = NULL;
5625 return bs;
5628 static void read_passwords(void)
5630 BlockDriverState *bs;
5631 int i, j;
5632 char password[256];
5634 for(i = 0; i < 6; i++) {
5635 bs = get_bdrv(i);
5636 if (bs && bdrv_is_encrypted(bs)) {
5637 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5638 for(j = 0; j < 3; j++) {
5639 monitor_readline("Password: ",
5640 1, password, sizeof(password));
5641 if (bdrv_set_key(bs, password) == 0)
5642 break;
5643 term_printf("invalid password\n");
5649 /* XXX: currently we cannot use simultaneously different CPUs */
5650 void register_machines(void)
5652 #if defined(TARGET_I386)
5653 qemu_register_machine(&pc_machine);
5654 qemu_register_machine(&isapc_machine);
5655 #elif defined(TARGET_PPC)
5656 qemu_register_machine(&heathrow_machine);
5657 qemu_register_machine(&core99_machine);
5658 qemu_register_machine(&prep_machine);
5659 #elif defined(TARGET_MIPS)
5660 qemu_register_machine(&mips_machine);
5661 #elif defined(TARGET_SPARC)
5662 #ifdef TARGET_SPARC64
5663 qemu_register_machine(&sun4u_machine);
5664 #else
5665 qemu_register_machine(&sun4m_machine);
5666 #endif
5667 #elif defined(TARGET_ARM)
5668 qemu_register_machine(&integratorcp926_machine);
5669 qemu_register_machine(&integratorcp1026_machine);
5670 qemu_register_machine(&versatilepb_machine);
5671 qemu_register_machine(&versatileab_machine);
5672 #elif defined(TARGET_SH4)
5673 qemu_register_machine(&shix_machine);
5674 #else
5675 #error unsupported CPU
5676 #endif
5679 #ifdef HAS_AUDIO
5680 struct soundhw soundhw[] = {
5681 #ifndef CONFIG_DM
5682 #ifdef TARGET_I386
5684 "pcspk",
5685 "PC speaker",
5686 0,
5687 1,
5688 { .init_isa = pcspk_audio_init }
5689 },
5690 #endif
5691 #endif /* !CONFIG_DM */
5693 "sb16",
5694 "Creative Sound Blaster 16",
5695 0,
5696 1,
5697 { .init_isa = SB16_init }
5698 },
5700 #ifdef CONFIG_ADLIB
5702 "adlib",
5703 #ifdef HAS_YMF262
5704 "Yamaha YMF262 (OPL3)",
5705 #else
5706 "Yamaha YM3812 (OPL2)",
5707 #endif
5708 0,
5709 1,
5710 { .init_isa = Adlib_init }
5711 },
5712 #endif
5714 #ifdef CONFIG_GUS
5716 "gus",
5717 "Gravis Ultrasound GF1",
5718 0,
5719 1,
5720 { .init_isa = GUS_init }
5721 },
5722 #endif
5725 "es1370",
5726 "ENSONIQ AudioPCI ES1370",
5727 0,
5728 0,
5729 { .init_pci = es1370_init }
5730 },
5732 { NULL, NULL, 0, 0, { NULL } }
5733 };
5735 static void select_soundhw (const char *optarg)
5737 struct soundhw *c;
5739 if (*optarg == '?') {
5740 show_valid_cards:
5742 printf ("Valid sound card names (comma separated):\n");
5743 for (c = soundhw; c->name; ++c) {
5744 printf ("%-11s %s\n", c->name, c->descr);
5746 printf ("\n-soundhw all will enable all of the above\n");
5747 exit (*optarg != '?');
5749 else {
5750 size_t l;
5751 const char *p;
5752 char *e;
5753 int bad_card = 0;
5755 if (!strcmp (optarg, "all")) {
5756 for (c = soundhw; c->name; ++c) {
5757 c->enabled = 1;
5759 return;
5762 p = optarg;
5763 while (*p) {
5764 e = strchr (p, ',');
5765 l = !e ? strlen (p) : (size_t) (e - p);
5767 for (c = soundhw; c->name; ++c) {
5768 if (!strncmp (c->name, p, l)) {
5769 c->enabled = 1;
5770 break;
5774 if (!c->name) {
5775 if (l > 80) {
5776 fprintf (stderr,
5777 "Unknown sound card name (too big to show)\n");
5779 else {
5780 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5781 (int) l, p);
5783 bad_card = 1;
5785 p += l + (e != NULL);
5788 if (bad_card)
5789 goto show_valid_cards;
5792 #endif
5794 #ifdef _WIN32
5795 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5797 exit(STATUS_CONTROL_C_EXIT);
5798 return TRUE;
5800 #endif
5802 #define MAX_NET_CLIENTS 32
5804 #include <xg_private.h>
5806 /* FIXME Flush the shadow page */
5807 int unset_mm_mapping(int xc_handle, uint32_t domid,
5808 unsigned long nr_pages, unsigned int address_bits,
5809 xen_pfn_t *extent_start)
5811 int err = 0;
5812 xc_dominfo_t info;
5814 xc_domain_getinfo(xc_handle, domid, 1, &info);
5815 if ((info.nr_pages - nr_pages) <= 0) {
5816 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
5817 err = -1;
5820 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
5821 nr_pages, 0, extent_start);
5822 if (err)
5823 fprintf(stderr, "Failed to decrease physmap\n");
5826 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
5827 PAGE_SIZE/1024) != 0) {
5828 fprintf(logfile, "set maxmem returned error %d\n", errno);
5829 err = -1;
5832 return err;
5835 int set_mm_mapping(int xc_handle, uint32_t domid,
5836 unsigned long nr_pages, unsigned int address_bits,
5837 xen_pfn_t *extent_start)
5839 xc_dominfo_t info;
5840 int err = 0;
5842 xc_domain_getinfo(xc_handle, domid, 1, &info);
5844 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
5845 nr_pages * PAGE_SIZE/1024) != 0) {
5846 fprintf(logfile, "set maxmem returned error %d\n", errno);
5847 return -1;
5850 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
5851 address_bits, extent_start);
5852 if (err) {
5853 fprintf(stderr, "Failed to populate physmap\n");
5854 return -1;
5857 return 0;
5860 void suspend(int sig)
5862 fprintf(logfile, "suspend sig handler called with requested=%d!\n", suspend_requested);
5863 if (sig != SIGUSR1)
5864 fprintf(logfile, "suspend signal dismatch, get sig=%d!\n", sig);
5865 suspend_requested = 1;
5868 #if defined(__i386__) || defined(__x86_64__)
5869 static struct map_cache *mapcache_entry;
5870 static unsigned long nr_buckets;
5872 /* For most cases (>99.9%), the page address is the same. */
5873 static unsigned long last_address_index = ~0UL;
5874 static uint8_t *last_address_vaddr;
5876 static int qemu_map_cache_init(unsigned long nr_pages)
5878 unsigned long max_pages = MAX_MCACHE_SIZE >> PAGE_SHIFT;
5879 int i;
5881 if (nr_pages < max_pages)
5882 max_pages = nr_pages;
5884 nr_buckets = max_pages + (1UL << (MCACHE_BUCKET_SHIFT - PAGE_SHIFT)) - 1;
5885 nr_buckets >>= (MCACHE_BUCKET_SHIFT - PAGE_SHIFT);
5886 fprintf(logfile, "qemu_map_cache_init nr_buckets = %lx\n", nr_buckets);
5888 mapcache_entry = malloc(nr_buckets * sizeof(struct map_cache));
5889 if (mapcache_entry == NULL) {
5890 errno = ENOMEM;
5891 return -1;
5894 memset(mapcache_entry, 0, nr_buckets * sizeof(struct map_cache));
5896 /*
5897 * To avoid ENOMEM from xc_map_foreign_batch() at runtime, we
5898 * pre-fill all the map caches in advance.
5899 */
5900 for (i = 0; i < nr_buckets; i++)
5901 (void)qemu_map_cache(((target_phys_addr_t)i) << MCACHE_BUCKET_SHIFT);
5903 return 0;
5906 uint8_t *qemu_map_cache(target_phys_addr_t phys_addr)
5908 struct map_cache *entry;
5909 unsigned long address_index = phys_addr >> MCACHE_BUCKET_SHIFT;
5910 unsigned long address_offset = phys_addr & (MCACHE_BUCKET_SIZE-1);
5912 if (address_index == last_address_index)
5913 return last_address_vaddr + address_offset;
5915 entry = &mapcache_entry[address_index % nr_buckets];
5917 if (entry->vaddr_base == NULL || entry->paddr_index != address_index) {
5918 /* We need to remap a bucket. */
5919 uint8_t *vaddr_base;
5920 unsigned long pfns[MCACHE_BUCKET_SIZE >> PAGE_SHIFT];
5921 unsigned int i;
5923 if (entry->vaddr_base != NULL) {
5924 errno = munmap(entry->vaddr_base, MCACHE_BUCKET_SIZE);
5925 if (errno) {
5926 fprintf(logfile, "unmap fails %d\n", errno);
5927 exit(-1);
5931 for (i = 0; i < MCACHE_BUCKET_SIZE >> PAGE_SHIFT; i++)
5932 pfns[i] = (address_index << (MCACHE_BUCKET_SHIFT-PAGE_SHIFT)) + i;
5934 vaddr_base = xc_map_foreign_batch(
5935 xc_handle, domid, PROT_READ|PROT_WRITE,
5936 pfns, MCACHE_BUCKET_SIZE >> PAGE_SHIFT);
5937 if (vaddr_base == NULL) {
5938 fprintf(logfile, "xc_map_foreign_batch error %d\n", errno);
5939 exit(-1);
5942 entry->vaddr_base = vaddr_base;
5943 entry->paddr_index = address_index;;
5946 last_address_index = address_index;
5947 last_address_vaddr = entry->vaddr_base;
5949 return last_address_vaddr + address_offset;
5952 void qemu_invalidate_map_cache(void)
5954 unsigned long i;
5956 mapcache_lock();
5958 for (i = 0; i < nr_buckets; i++) {
5959 struct map_cache *entry = &mapcache_entry[i];
5961 if (entry->vaddr_base == NULL)
5962 continue;
5964 errno = munmap(entry->vaddr_base, MCACHE_BUCKET_SIZE);
5965 if (errno) {
5966 fprintf(logfile, "unmap fails %d\n", errno);
5967 exit(-1);
5970 entry->paddr_index = 0;
5971 entry->vaddr_base = NULL;
5974 last_address_index = ~0UL;
5975 last_address_vaddr = NULL;
5977 mapcache_unlock();
5979 #endif
5981 int main(int argc, char **argv)
5983 #ifdef CONFIG_GDBSTUB
5984 int use_gdbstub, gdbstub_port;
5985 #endif
5986 int i;
5987 #ifndef CONFIG_DM
5988 int cdrom_index;
5989 #endif /* !CONFIG_DM */
5990 int snapshot, linux_boot;
5991 const char *initrd_filename;
5992 #ifndef CONFIG_DM
5993 const char *hd_filename[MAX_DISKS];
5994 #endif /* !CONFIG_DM */
5995 const char *fd_filename[MAX_FD];
5996 const char *kernel_filename, *kernel_cmdline;
5997 DisplayState *ds = &display_state;
5998 int cyls, heads, secs, translation;
5999 int start_emulation = 1;
6000 char net_clients[MAX_NET_CLIENTS][256];
6001 int nb_net_clients;
6002 int optind;
6003 const char *r, *optarg;
6004 CharDriverState *monitor_hd;
6005 char monitor_device[128];
6006 char serial_devices[MAX_SERIAL_PORTS][128];
6007 int serial_device_index;
6008 char parallel_devices[MAX_PARALLEL_PORTS][128];
6009 int parallel_device_index;
6010 const char *loadvm = NULL;
6011 QEMUMachine *machine;
6012 char usb_devices[MAX_USB_CMDLINE][128];
6013 int usb_devices_index;
6014 unsigned long nr_pages, tmp_nr_pages, shared_page_nr;
6015 xen_pfn_t *page_array;
6016 extern void *shared_page;
6017 extern void *buffered_io_page;
6018 extern void *buffered_pio_page;
6020 char qemu_dm_logfilename[64];
6022 LIST_INIT (&vm_change_state_head);
6023 #ifndef _WIN32
6025 struct sigaction act;
6026 sigfillset(&act.sa_mask);
6027 act.sa_flags = 0;
6028 act.sa_handler = SIG_IGN;
6029 sigaction(SIGPIPE, &act, NULL);
6031 #else
6032 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6033 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6034 QEMU to run on a single CPU */
6036 HANDLE h;
6037 DWORD mask, smask;
6038 int i;
6039 h = GetCurrentProcess();
6040 if (GetProcessAffinityMask(h, &mask, &smask)) {
6041 for(i = 0; i < 32; i++) {
6042 if (mask & (1 << i))
6043 break;
6045 if (i != 32) {
6046 mask = 1 << i;
6047 SetProcessAffinityMask(h, mask);
6051 #endif
6053 register_machines();
6054 machine = first_machine;
6055 initrd_filename = NULL;
6056 for(i = 0; i < MAX_FD; i++)
6057 fd_filename[i] = NULL;
6058 #ifndef CONFIG_DM
6059 for(i = 0; i < MAX_DISKS; i++)
6060 hd_filename[i] = NULL;
6061 #endif /* !CONFIG_DM */
6062 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6063 vga_ram_size = VGA_RAM_SIZE;
6064 bios_size = BIOS_SIZE;
6065 #ifdef CONFIG_GDBSTUB
6066 use_gdbstub = 0;
6067 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6068 #endif
6069 snapshot = 0;
6070 nographic = 0;
6071 vncviewer = 0;
6072 vncunused = 0;
6073 kernel_filename = NULL;
6074 kernel_cmdline = "";
6075 *vncpasswd = '\0';
6076 #ifndef CONFIG_DM
6077 #ifdef TARGET_PPC
6078 cdrom_index = 1;
6079 #else
6080 cdrom_index = 2;
6081 #endif
6082 #endif /* !CONFIG_DM */
6083 cyls = heads = secs = 0;
6084 translation = BIOS_ATA_TRANSLATION_AUTO;
6085 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6087 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6088 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6089 serial_devices[i][0] = '\0';
6090 serial_device_index = 0;
6092 #ifndef CONFIG_DM
6093 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6094 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6095 #else
6096 /* Xen steals IRQ7 for PCI. Disable LPT1 by default. */
6097 for(i = 0; i < MAX_PARALLEL_PORTS; i++)
6098 #endif
6099 parallel_devices[i][0] = '\0';
6100 parallel_device_index = 0;
6102 usb_devices_index = 0;
6104 nb_net_clients = 0;
6106 nb_nics = 0;
6107 /* default mac address of the first network interface */
6109 memset(&vnclisten_addr.sin_addr, 0, sizeof(vnclisten_addr.sin_addr));
6111 /* init debug */
6112 sprintf(qemu_dm_logfilename, "/var/log/xen/qemu-dm.%ld.log", (long)getpid());
6113 cpu_set_log_filename(qemu_dm_logfilename);
6114 cpu_set_log(0);
6116 optind = 1;
6117 for(;;) {
6118 if (optind >= argc)
6119 break;
6120 r = argv[optind];
6121 if (r[0] != '-') {
6122 #ifndef CONFIG_DM
6123 hd_filename[0] = argv[optind++];
6124 #else
6125 help();
6126 #endif /* !CONFIG_DM */
6127 } else {
6128 const QEMUOption *popt;
6130 optind++;
6131 popt = qemu_options;
6132 for(;;) {
6133 if (!popt->name) {
6134 fprintf(stderr, "%s: invalid option -- '%s'\n",
6135 argv[0], r);
6136 exit(1);
6138 if (!strcmp(popt->name, r + 1))
6139 break;
6140 popt++;
6142 if (popt->flags & HAS_ARG) {
6143 if (optind >= argc) {
6144 fprintf(stderr, "%s: option '%s' requires an argument\n",
6145 argv[0], r);
6146 exit(1);
6148 optarg = argv[optind++];
6149 } else {
6150 optarg = NULL;
6153 switch(popt->index) {
6154 case QEMU_OPTION_M:
6155 machine = find_machine(optarg);
6156 if (!machine) {
6157 QEMUMachine *m;
6158 printf("Supported machines are:\n");
6159 for(m = first_machine; m != NULL; m = m->next) {
6160 printf("%-10s %s%s\n",
6161 m->name, m->desc,
6162 m == first_machine ? " (default)" : "");
6164 exit(1);
6166 break;
6167 case QEMU_OPTION_initrd:
6168 initrd_filename = optarg;
6169 break;
6170 #ifndef CONFIG_DM
6171 case QEMU_OPTION_hda:
6172 case QEMU_OPTION_hdb:
6173 case QEMU_OPTION_hdc:
6174 case QEMU_OPTION_hdd:
6176 int hd_index;
6177 hd_index = popt->index - QEMU_OPTION_hda;
6178 hd_filename[hd_index] = optarg;
6179 if (hd_index == cdrom_index)
6180 cdrom_index = -1;
6182 break;
6183 #endif /* !CONFIG_DM */
6184 case QEMU_OPTION_snapshot:
6185 snapshot = 1;
6186 break;
6187 case QEMU_OPTION_hdachs:
6189 const char *p;
6190 p = optarg;
6191 cyls = strtol(p, (char **)&p, 0);
6192 if (cyls < 1 || cyls > 16383)
6193 goto chs_fail;
6194 if (*p != ',')
6195 goto chs_fail;
6196 p++;
6197 heads = strtol(p, (char **)&p, 0);
6198 if (heads < 1 || heads > 16)
6199 goto chs_fail;
6200 if (*p != ',')
6201 goto chs_fail;
6202 p++;
6203 secs = strtol(p, (char **)&p, 0);
6204 if (secs < 1 || secs > 63)
6205 goto chs_fail;
6206 if (*p == ',') {
6207 p++;
6208 if (!strcmp(p, "none"))
6209 translation = BIOS_ATA_TRANSLATION_NONE;
6210 else if (!strcmp(p, "lba"))
6211 translation = BIOS_ATA_TRANSLATION_LBA;
6212 else if (!strcmp(p, "auto"))
6213 translation = BIOS_ATA_TRANSLATION_AUTO;
6214 else
6215 goto chs_fail;
6216 } else if (*p != '\0') {
6217 chs_fail:
6218 fprintf(stderr, "qemu: invalid physical CHS format\n");
6219 exit(1);
6222 break;
6223 case QEMU_OPTION_nographic:
6224 if(!strcmp(monitor_device, "vc"))
6225 pstrcpy(monitor_device, sizeof(monitor_device), "null");
6226 if(!strcmp(serial_devices[0], "vc"))
6227 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
6228 "null");
6229 nographic = 1;
6230 break;
6231 case QEMU_OPTION_kernel:
6232 kernel_filename = optarg;
6233 break;
6234 case QEMU_OPTION_append:
6235 kernel_cmdline = optarg;
6236 break;
6237 #ifndef CONFIG_DM
6238 case QEMU_OPTION_cdrom:
6239 if (cdrom_index >= 0) {
6240 hd_filename[cdrom_index] = optarg;
6242 break;
6243 #endif /* !CONFIG_DM */
6244 case QEMU_OPTION_boot:
6245 boot_device = strdup(optarg);
6246 if (strspn(boot_device, "acd"
6247 #if defined(TARGET_SPARC) || defined(TARGET_I386)
6248 "n"
6249 #endif
6250 ) != strlen(boot_device)) {
6251 fprintf(stderr, "qemu: invalid boot device in '%s'\n",
6252 boot_device);
6253 exit(1);
6255 break;
6256 case QEMU_OPTION_fda:
6257 fd_filename[0] = optarg;
6258 break;
6259 case QEMU_OPTION_fdb:
6260 fd_filename[1] = optarg;
6261 break;
6262 #ifdef TARGET_I386
6263 case QEMU_OPTION_no_fd_bootchk:
6264 fd_bootchk = 0;
6265 break;
6266 #endif
6267 #ifdef USE_CODE_COPY
6268 case QEMU_OPTION_no_code_copy:
6269 code_copy_enabled = 0;
6270 break;
6271 #endif
6272 case QEMU_OPTION_net:
6273 if (nb_net_clients >= MAX_NET_CLIENTS) {
6274 fprintf(stderr, "qemu: too many network clients\n");
6275 exit(1);
6277 pstrcpy(net_clients[nb_net_clients],
6278 sizeof(net_clients[0]),
6279 optarg);
6280 nb_net_clients++;
6281 break;
6282 #ifdef CONFIG_SLIRP
6283 case QEMU_OPTION_tftp:
6284 tftp_prefix = optarg;
6285 break;
6286 #ifndef _WIN32
6287 case QEMU_OPTION_smb:
6288 net_slirp_smb(optarg);
6289 break;
6290 #endif
6291 case QEMU_OPTION_redir:
6292 net_slirp_redir(optarg);
6293 break;
6294 #endif
6295 #ifdef HAS_AUDIO
6296 case QEMU_OPTION_audio_help:
6297 AUD_help ();
6298 exit (0);
6299 break;
6300 case QEMU_OPTION_soundhw:
6301 select_soundhw (optarg);
6302 break;
6303 #endif
6304 case QEMU_OPTION_h:
6305 help();
6306 break;
6307 case QEMU_OPTION_m:
6308 ram_size = atol(optarg) * 1024 * 1024;
6309 ram_size = (uint64_t)atol(optarg) * 1024 * 1024;
6310 if (ram_size <= 0)
6311 help();
6312 #ifndef CONFIG_DM
6313 if (ram_size > PHYS_RAM_MAX_SIZE) {
6314 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6315 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6316 exit(1);
6318 #endif /* !CONFIG_DM */
6319 break;
6320 case QEMU_OPTION_l:
6322 int mask;
6323 CPULogItem *item;
6325 mask = cpu_str_to_log_mask(optarg);
6326 if (!mask) {
6327 printf("Log items (comma separated):\n");
6328 for(item = cpu_log_items; item->mask != 0; item++) {
6329 printf("%-10s %s\n", item->name, item->help);
6331 exit(1);
6333 cpu_set_log(mask);
6335 break;
6336 #ifdef CONFIG_GDBSTUB
6337 case QEMU_OPTION_s:
6338 use_gdbstub = 1;
6339 break;
6340 case QEMU_OPTION_p:
6341 gdbstub_port = atoi(optarg);
6342 break;
6343 #endif
6344 case QEMU_OPTION_L:
6345 bios_dir = optarg;
6346 break;
6347 case QEMU_OPTION_S:
6348 start_emulation = 0;
6349 break;
6350 case QEMU_OPTION_k:
6351 keyboard_layout = optarg;
6352 break;
6353 case QEMU_OPTION_localtime:
6354 rtc_utc = 0;
6355 break;
6356 case QEMU_OPTION_cirrusvga:
6357 cirrus_vga_enabled = 1;
6358 break;
6359 case QEMU_OPTION_std_vga:
6360 cirrus_vga_enabled = 0;
6361 break;
6362 case QEMU_OPTION_g:
6364 const char *p;
6365 int w, h, depth;
6366 p = optarg;
6367 w = strtol(p, (char **)&p, 10);
6368 if (w <= 0) {
6369 graphic_error:
6370 fprintf(stderr, "qemu: invalid resolution or depth\n");
6371 exit(1);
6373 if (*p != 'x')
6374 goto graphic_error;
6375 p++;
6376 h = strtol(p, (char **)&p, 10);
6377 if (h <= 0)
6378 goto graphic_error;
6379 if (*p == 'x') {
6380 p++;
6381 depth = strtol(p, (char **)&p, 10);
6382 if (depth != 8 && depth != 15 && depth != 16 &&
6383 depth != 24 && depth != 32)
6384 goto graphic_error;
6385 } else if (*p == '\0') {
6386 depth = graphic_depth;
6387 } else {
6388 goto graphic_error;
6391 graphic_width = w;
6392 graphic_height = h;
6393 graphic_depth = depth;
6395 break;
6396 case QEMU_OPTION_monitor:
6397 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6398 break;
6399 case QEMU_OPTION_serial:
6400 if (serial_device_index >= MAX_SERIAL_PORTS) {
6401 fprintf(stderr, "qemu: too many serial ports\n");
6402 exit(1);
6404 pstrcpy(serial_devices[serial_device_index],
6405 sizeof(serial_devices[0]), optarg);
6406 serial_device_index++;
6407 break;
6408 case QEMU_OPTION_parallel:
6409 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6410 fprintf(stderr, "qemu: too many parallel ports\n");
6411 exit(1);
6413 pstrcpy(parallel_devices[parallel_device_index],
6414 sizeof(parallel_devices[0]), optarg);
6415 parallel_device_index++;
6416 break;
6417 case QEMU_OPTION_loadvm:
6418 loadvm = optarg;
6419 break;
6420 case QEMU_OPTION_full_screen:
6421 full_screen = 1;
6422 break;
6423 case QEMU_OPTION_pidfile:
6424 create_pidfile(optarg);
6425 break;
6426 #ifdef TARGET_I386
6427 case QEMU_OPTION_win2k_hack:
6428 win2k_install_hack = 1;
6429 break;
6430 #endif
6431 #ifdef USE_KQEMU
6432 case QEMU_OPTION_no_kqemu:
6433 kqemu_allowed = 0;
6434 break;
6435 case QEMU_OPTION_kernel_kqemu:
6436 kqemu_allowed = 2;
6437 break;
6438 #endif
6439 case QEMU_OPTION_usb:
6440 usb_enabled = 1;
6441 break;
6442 case QEMU_OPTION_usbdevice:
6443 usb_enabled = 1;
6444 if (usb_devices_index >= MAX_USB_CMDLINE) {
6445 fprintf(stderr, "Too many USB devices\n");
6446 exit(1);
6448 pstrcpy(usb_devices[usb_devices_index],
6449 sizeof(usb_devices[usb_devices_index]),
6450 optarg);
6451 usb_devices_index++;
6452 break;
6453 case QEMU_OPTION_smp:
6454 smp_cpus = atoi(optarg);
6455 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6456 fprintf(stderr, "Invalid number of CPUs\n");
6457 exit(1);
6459 break;
6460 case QEMU_OPTION_vnc:
6461 vnc_display = atoi(optarg);
6462 if (vnc_display < 0) {
6463 fprintf(stderr, "Invalid VNC display\n");
6464 exit(1);
6466 break;
6467 case QEMU_OPTION_no_acpi:
6468 acpi_enabled = 0;
6469 break;
6470 case QEMU_OPTION_domainname:
6471 strncat(domain_name, optarg, sizeof(domain_name) - 20);
6472 break;
6473 case QEMU_OPTION_d:
6474 domid = atoi(optarg);
6475 fprintf(logfile, "domid: %d\n", domid);
6476 break;
6477 case QEMU_OPTION_vcpus:
6478 vcpus = atoi(optarg);
6479 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
6480 break;
6481 case QEMU_OPTION_timeoffset:
6482 timeoffset = strtol(optarg, NULL, 0);
6483 break;
6484 case QEMU_OPTION_acpi:
6485 acpi_enabled = 1;
6486 break;
6487 case QEMU_OPTION_vncviewer:
6488 vncviewer++;
6489 break;
6490 case QEMU_OPTION_vncunused:
6491 vncunused++;
6492 if (vnc_display == -1)
6493 vnc_display = 0;
6494 break;
6495 case QEMU_OPTION_vnclisten:
6496 parse_host(&vnclisten_addr, optarg);
6497 break;
6502 #ifdef CONFIG_DM
6503 bdrv_init();
6504 xenstore_parse_domain_config(domid);
6505 #endif /* CONFIG_DM */
6507 #ifdef USE_KQEMU
6508 if (smp_cpus > 1)
6509 kqemu_allowed = 0;
6510 #endif
6511 linux_boot = (kernel_filename != NULL);
6513 #ifndef CONFIG_DM
6514 if (!linux_boot &&
6515 hd_filename[0] == '\0' &&
6516 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6517 fd_filename[0] == '\0')
6518 help();
6520 #if 0
6521 /* boot to cd by default if no hard disk */
6522 if (hd_filename[0] == '\0' && boot_device == 'c') {
6523 if (fd_filename[0] != '\0')
6524 boot_device = 'a';
6525 else
6526 boot_device = 'd';
6528 #endif
6529 #endif /* !CONFIG_DM */
6531 setvbuf(stdout, NULL, _IOLBF, 0);
6533 init_timers();
6534 init_timer_alarm();
6536 #ifdef _WIN32
6537 socket_init();
6538 #endif
6540 #ifndef CONFIG_DM
6541 /* init network clients */
6542 if (nb_net_clients == 0) {
6543 /* if no clients, we use a default config */
6544 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6545 "nic");
6546 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6547 "user");
6548 nb_net_clients = 2;
6550 #endif /* !CONFIG_DM */
6552 for(i = 0;i < nb_net_clients; i++) {
6553 if (net_client_init(net_clients[i]) < 0)
6554 exit(1);
6557 #if defined (__ia64__)
6558 if (ram_size > MMIO_START)
6559 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
6560 #endif
6562 /* init the memory */
6563 phys_ram_size = ram_size + vga_ram_size + bios_size;
6565 #ifdef CONFIG_DM
6567 xc_handle = xc_interface_open();
6569 nr_pages = ram_size/PAGE_SIZE;
6570 tmp_nr_pages = nr_pages;
6572 #if defined(__i386__) || defined(__x86_64__)
6573 if (ram_size > HVM_BELOW_4G_RAM_END) {
6574 tmp_nr_pages += HVM_BELOW_4G_MMIO_LENGTH >> PAGE_SHIFT;
6575 shared_page_nr = (HVM_BELOW_4G_RAM_END >> PAGE_SHIFT) - 1;
6576 } else
6577 shared_page_nr = nr_pages - 1;
6578 #endif
6580 #if defined(__i386__) || defined(__x86_64__)
6582 if ( qemu_map_cache_init(tmp_nr_pages) )
6584 fprintf(logfile, "qemu_map_cache_init returned: error %d\n", errno);
6585 exit(-1);
6588 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6589 PROT_READ|PROT_WRITE, shared_page_nr);
6590 if (shared_page == NULL) {
6591 fprintf(logfile, "map shared IO page returned error %d\n", errno);
6592 exit(-1);
6595 fprintf(logfile, "shared page at pfn:%lx\n", shared_page_nr);
6597 buffered_io_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6598 PROT_READ|PROT_WRITE,
6599 shared_page_nr - 2);
6600 if (buffered_io_page == NULL) {
6601 fprintf(logfile, "map buffered IO page returned error %d\n", errno);
6602 exit(-1);
6605 fprintf(logfile, "buffered io page at pfn:%lx\n", shared_page_nr - 2);
6607 #elif defined(__ia64__)
6609 page_array = (xen_pfn_t *)malloc(tmp_nr_pages * sizeof(xen_pfn_t));
6610 if (page_array == NULL) {
6611 fprintf(logfile, "malloc returned error %d\n", errno);
6612 exit(-1);
6615 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6616 PROT_READ|PROT_WRITE,
6617 IO_PAGE_START >> PAGE_SHIFT);
6619 buffered_io_page =xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6620 PROT_READ|PROT_WRITE,
6621 BUFFER_IO_PAGE_START >> PAGE_SHIFT);
6623 buffered_pio_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
6624 PROT_READ|PROT_WRITE,
6625 BUFFER_PIO_PAGE_START >> PAGE_SHIFT);
6627 for (i = 0; i < tmp_nr_pages; i++)
6628 page_array[i] = i;
6630 /* VTI will not use memory between 3G~4G, so we just pass a legal pfn
6631 to make QEMU map continuous virtual memory space */
6632 if (ram_size > MMIO_START) {
6633 for (i = 0 ; i < (MEM_G >> PAGE_SHIFT); i++)
6634 page_array[(MMIO_START >> PAGE_SHIFT) + i] =
6635 (STORE_PAGE_START >> PAGE_SHIFT);
6638 phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
6639 PROT_READ|PROT_WRITE,
6640 page_array, nr_pages);
6641 if (phys_ram_base == 0) {
6642 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
6643 exit(-1);
6645 free(page_array);
6646 #endif
6647 #else /* !CONFIG_DM */
6649 phys_ram_base = qemu_vmalloc(phys_ram_size);
6650 if (!phys_ram_base) {
6651 fprintf(stderr, "Could not allocate physical memory\n");
6652 exit(1);
6655 #endif /* !CONFIG_DM */
6657 #ifndef CONFIG_DM
6658 /* we always create the cdrom drive, even if no disk is there */
6659 bdrv_init();
6660 if (cdrom_index >= 0) {
6661 bs_table[cdrom_index] = bdrv_new("cdrom");
6662 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6665 /* open the virtual block devices */
6666 for(i = 0; i < MAX_DISKS; i++) {
6667 if (hd_filename[i]) {
6668 if (!bs_table[i]) {
6669 char buf[64];
6670 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6671 bs_table[i] = bdrv_new(buf);
6673 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6674 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6675 hd_filename[i]);
6676 exit(1);
6678 if (i == 0 && cyls != 0) {
6679 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6680 bdrv_set_translation_hint(bs_table[i], translation);
6684 #endif /* !CONFIG_DM */
6686 /* we always create at least one floppy disk */
6687 fd_table[0] = bdrv_new("fda");
6688 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6690 for(i = 0; i < MAX_FD; i++) {
6691 if (fd_filename[i]) {
6692 if (!fd_table[i]) {
6693 char buf[64];
6694 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6695 fd_table[i] = bdrv_new(buf);
6696 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6698 if (fd_filename[i] != '\0') {
6699 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6700 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6701 fd_filename[i]);
6702 exit(1);
6708 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6709 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6711 init_ioports();
6713 /* read vncpasswd from xenstore */
6714 if (0 > xenstore_read_vncpasswd(domid))
6715 exit(1);
6717 /* terminal init */
6718 if (nographic) {
6719 dumb_display_init(ds);
6720 } else if (vnc_display != -1) {
6721 vnc_display = vnc_display_init(ds, vnc_display, vncunused, &vnclisten_addr);
6722 if (vncviewer)
6723 vnc_start_viewer(vnc_display);
6724 xenstore_write_vncport(vnc_display);
6725 } else {
6726 #if defined(CONFIG_SDL)
6727 sdl_display_init(ds, full_screen);
6728 #elif defined(CONFIG_COCOA)
6729 cocoa_display_init(ds, full_screen);
6730 #else
6731 dumb_display_init(ds);
6732 #endif
6735 monitor_hd = qemu_chr_open(monitor_device);
6736 if (!monitor_hd) {
6737 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6738 exit(1);
6740 store_dev_info(monitor_device, domid, monitor_hd, "/monitor");
6741 monitor_init(monitor_hd, !nographic);
6743 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6744 if (serial_devices[i][0] != '\0') {
6745 char buf[16];
6746 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6747 if (!serial_hds[i]) {
6748 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6749 serial_devices[i]);
6750 exit(1);
6752 snprintf(buf, sizeof(buf), "/serial/%d", i);
6753 store_dev_info(serial_devices[i], domid, serial_hds[i], buf);
6754 if (i == 0) /* serial 0 is also called the console */
6755 store_dev_info(serial_devices[i], domid,
6756 serial_hds[i], "/console");
6757 if (!strcmp(serial_devices[i], "vc"))
6758 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6762 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6763 if (parallel_devices[i][0] != '\0') {
6764 char buf[16];
6765 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6766 if (!parallel_hds[i]) {
6767 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6768 parallel_devices[i]);
6769 exit(1);
6771 snprintf(buf, sizeof(buf), "/parallel/%d", i);
6772 store_dev_info(parallel_devices[i], domid, parallel_hds[i], buf);
6773 if (!strcmp(parallel_devices[i], "vc"))
6774 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6778 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
6780 machine->init(ram_size, vga_ram_size, boot_device,
6781 ds, fd_filename, snapshot,
6782 kernel_filename, kernel_cmdline, initrd_filename,
6783 timeoffset);
6784 free(boot_device);
6786 /* init USB devices */
6787 if (usb_enabled) {
6788 for(i = 0; i < usb_devices_index; i++) {
6789 if (usb_device_add(usb_devices[i]) < 0) {
6790 fprintf(stderr, "Warning: could not add USB device %s\n",
6791 usb_devices[i]);
6796 if (vnc_display == -1) {
6797 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6798 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6801 #ifdef CONFIG_GDBSTUB
6802 if (use_gdbstub) {
6803 if (gdbserver_start(gdbstub_port) < 0) {
6804 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6805 gdbstub_port);
6806 exit(1);
6807 } else {
6808 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6810 } else
6811 #endif
6812 if (loadvm)
6813 qemu_loadvm(loadvm);
6816 /* XXX: simplify init */
6817 read_passwords();
6818 if (start_emulation) {
6819 vm_start();
6823 /* register signal for the suspend request when save */
6825 struct sigaction act;
6826 sigset_t set;
6827 act.sa_handler = suspend;
6828 act.sa_flags = SA_RESTART;
6829 sigemptyset(&act.sa_mask);
6831 sigaction(SIGUSR1, &act, NULL);
6833 /* control panel mask some signals when spawn qemu, need unmask here*/
6834 sigemptyset(&set);
6835 sigaddset(&set, SIGUSR1);
6836 sigaddset(&set, SIGTERM);
6837 if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
6838 fprintf(stderr, "unblock signal fail, possible issue for HVM save!\n");
6842 main_loop();
6843 quit_timers();
6844 return 0;