ia64/xen-unstable

view tools/ioemu/vl.c @ 16647:d0052f37363c

ioemu: Do not close slave half of a pty.
Signed-off-by: Keir Fraser <keir.fraser@citrix.com>
author Keir Fraser <keir.fraser@citrix.com>
date Thu Dec 20 10:35:22 2007 +0000 (2007-12-20)
parents 28921e83000b
children 05e36e506c09
line source
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2007 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 <stdlib.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <time.h>
31 #include <errno.h>
32 #include <sys/time.h>
33 #include <zlib.h>
35 #ifndef _WIN32
36 #include <sys/times.h>
37 #include <sys/wait.h>
38 #include <termios.h>
39 #include <sys/poll.h>
40 #include <sys/mman.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <net/if.h>
46 #if defined(__NetBSD__)
47 #include <net/if_tap.h>
48 #endif
49 #if defined(__linux__) || defined(__Linux__)
50 #include <linux/if_tun.h>
51 #endif
52 #include <arpa/inet.h>
53 #include <dirent.h>
54 #include <netdb.h>
55 #ifdef _BSD
56 #include <sys/stat.h>
57 #ifndef _BSD
58 #include <libutil.h>
59 #else
60 #include <util.h>
61 #endif
62 #else
63 #ifndef __sun__
64 #include <pty.h>
65 #include <linux/rtc.h>
66 #include <linux/ppdev.h>
67 #endif
68 #endif
69 #if defined(__sun__)
70 #include <stropts.h>
71 #endif
72 #endif
74 #if defined(CONFIG_SLIRP)
75 #include "libslirp.h"
76 #endif
78 #ifdef _WIN32
79 #include <sys/timeb.h>
80 #include <windows.h>
81 #define getopt_long_only getopt_long
82 #define memalign(align, size) malloc(size)
83 #endif
85 #include "qemu_socket.h"
87 #ifdef CONFIG_SDL
88 #ifdef __APPLE__
89 #include <SDL/SDL.h>
90 #endif
91 #endif /* CONFIG_SDL */
93 #ifdef CONFIG_COCOA
94 #undef main
95 #define main qemu_main
96 #endif /* CONFIG_COCOA */
98 #include "disas.h"
100 #include "exec-all.h"
102 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
103 #ifdef _BSD
104 #define DEFAULT_BRIDGE "bridge0"
105 #else
106 #define DEFAULT_BRIDGE "xenbr0"
107 #endif
108 #ifdef __sun__
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110 #else
111 #define SMBD_COMMAND "/usr/sbin/smbd"
112 #endif
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
119 #ifdef TARGET_PPC
120 #define DEFAULT_RAM_SIZE 144
121 #else
122 #define DEFAULT_RAM_SIZE 128
123 #endif
124 /* in ms */
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134 char phys_ram_file[1024];
135 void *ioport_opaque[MAX_IOPORTS];
136 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState *bs_table[MAX_DISKS + MAX_SCSI_DISKS + 1], *fd_table[MAX_FD];
141 /* point to the block driver where the snapshots are managed */
142 BlockDriverState *bs_snapshots;
143 int vga_ram_size;
144 int bios_size;
145 static DisplayState display_state;
146 int nographic;
147 int vncviewer;
148 int vncunused;
149 const char* keyboard_layout = NULL;
150 int64_t ticks_per_sec;
151 char *boot_device = NULL;
152 uint64_t ram_size;
153 int pit_min_timer_count = 0;
154 int nb_nics;
155 NICInfo nd_table[MAX_NICS];
156 QEMUTimer *gui_timer;
157 int vm_running;
158 int rtc_utc = 1;
159 int cirrus_vga_enabled = 1;
160 #ifdef TARGET_SPARC
161 int graphic_width = 1024;
162 int graphic_height = 768;
163 #else
164 int graphic_width = 800;
165 int graphic_height = 600;
166 #endif
167 int graphic_depth = 15;
168 int full_screen = 0;
169 int no_quit = 0;
170 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
171 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
172 #ifdef TARGET_I386
173 int win2k_install_hack = 0;
174 #endif
175 int usb_enabled = 0;
176 static VLANState *first_vlan;
177 int smp_cpus = 1;
178 const char *vnc_display;
179 #if defined(TARGET_SPARC)
180 #define MAX_CPUS 16
181 #elif defined(TARGET_I386)
182 #define MAX_CPUS 255
183 #else
184 #define MAX_CPUS 1
185 #endif
186 int acpi_enabled = 0;
187 int fd_bootchk = 1;
188 int no_reboot = 0;
189 int daemonize = 0;
190 const char *option_rom[MAX_OPTION_ROMS];
191 int nb_option_roms;
192 int semihosting_enabled = 0;
193 int autostart = 1;
195 extern int vcpus;
197 int xc_handle;
199 char domain_name[64] = "Xen-no-name";
200 extern int domid;
202 /***********************************************************/
203 /* x86 ISA bus support */
205 target_phys_addr_t isa_mem_base = 0;
206 PicState2 *isa_pic;
208 uint32_t default_ioport_readb(void *opaque, uint32_t address)
209 {
210 #ifdef DEBUG_UNUSED_IOPORT
211 fprintf(stderr, "inb: port=0x%04x\n", address);
212 #endif
213 return 0xff;
214 }
216 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
217 {
218 #ifdef DEBUG_UNUSED_IOPORT
219 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
220 #endif
221 }
223 /* default is to make two byte accesses */
224 uint32_t default_ioport_readw(void *opaque, uint32_t address)
225 {
226 uint32_t data;
227 data = ioport_read_table[0][address](ioport_opaque[address], address);
228 address = (address + 1) & (MAX_IOPORTS - 1);
229 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
230 return data;
231 }
233 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
234 {
235 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
236 address = (address + 1) & (MAX_IOPORTS - 1);
237 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
238 }
240 uint32_t default_ioport_readl(void *opaque, uint32_t address)
241 {
242 #ifdef DEBUG_UNUSED_IOPORT
243 fprintf(stderr, "inl: port=0x%04x\n", address);
244 #endif
245 return 0xffffffff;
246 }
248 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
249 {
250 #ifdef DEBUG_UNUSED_IOPORT
251 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
252 #endif
253 }
255 void init_ioports(void)
256 {
257 int i;
259 for(i = 0; i < MAX_IOPORTS; i++) {
260 ioport_read_table[0][i] = default_ioport_readb;
261 ioport_write_table[0][i] = default_ioport_writeb;
262 ioport_read_table[1][i] = default_ioport_readw;
263 ioport_write_table[1][i] = default_ioport_writew;
264 ioport_read_table[2][i] = default_ioport_readl;
265 ioport_write_table[2][i] = default_ioport_writel;
266 }
267 }
269 /* size is the word size in byte */
270 int register_ioport_read(int start, int length, int size,
271 IOPortReadFunc *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_read: invalid size");
283 return -1;
284 }
285 for(i = start; i < start + length; i += size) {
286 ioport_read_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 /* size is the word size in byte */
295 int register_ioport_write(int start, int length, int size,
296 IOPortWriteFunc *func, void *opaque)
297 {
298 int i, bsize;
300 if (size == 1) {
301 bsize = 0;
302 } else if (size == 2) {
303 bsize = 1;
304 } else if (size == 4) {
305 bsize = 2;
306 } else {
307 hw_error("register_ioport_write: invalid size");
308 return -1;
309 }
310 for(i = start; i < start + length; i += size) {
311 ioport_write_table[bsize][i] = func;
312 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
313 hw_error("register_ioport_write: invalid opaque");
314 ioport_opaque[i] = opaque;
315 }
316 return 0;
317 }
319 void isa_unassign_ioport(int start, int length)
320 {
321 int i;
323 for(i = start; i < start + length; i++) {
324 ioport_read_table[0][i] = default_ioport_readb;
325 ioport_read_table[1][i] = default_ioport_readw;
326 ioport_read_table[2][i] = default_ioport_readl;
328 ioport_write_table[0][i] = default_ioport_writeb;
329 ioport_write_table[1][i] = default_ioport_writew;
330 ioport_write_table[2][i] = default_ioport_writel;
331 }
332 }
334 /***********************************************************/
336 void cpu_outb(CPUState *env, int addr, int val)
337 {
338 #ifdef DEBUG_IOPORT
339 if (loglevel & CPU_LOG_IOPORT)
340 fprintf(logfile, "outb: %04x %02x\n", addr, val);
341 #endif
342 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
343 #ifdef USE_KQEMU
344 if (env)
345 env->last_io_time = cpu_get_time_fast();
346 #endif
347 }
349 void cpu_outw(CPUState *env, int addr, int val)
350 {
351 #ifdef DEBUG_IOPORT
352 if (loglevel & CPU_LOG_IOPORT)
353 fprintf(logfile, "outw: %04x %04x\n", addr, val);
354 #endif
355 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
356 #ifdef USE_KQEMU
357 if (env)
358 env->last_io_time = cpu_get_time_fast();
359 #endif
360 }
362 void cpu_outl(CPUState *env, int addr, int val)
363 {
364 #ifdef DEBUG_IOPORT
365 if (loglevel & CPU_LOG_IOPORT)
366 fprintf(logfile, "outl: %04x %08x\n", addr, val);
367 #endif
368 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
369 #ifdef USE_KQEMU
370 if (env)
371 env->last_io_time = cpu_get_time_fast();
372 #endif
373 }
375 int cpu_inb(CPUState *env, int addr)
376 {
377 int val;
378 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
379 #ifdef DEBUG_IOPORT
380 if (loglevel & CPU_LOG_IOPORT)
381 fprintf(logfile, "inb : %04x %02x\n", addr, val);
382 #endif
383 #ifdef USE_KQEMU
384 if (env)
385 env->last_io_time = cpu_get_time_fast();
386 #endif
387 return val;
388 }
390 int cpu_inw(CPUState *env, int addr)
391 {
392 int val;
393 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
394 #ifdef DEBUG_IOPORT
395 if (loglevel & CPU_LOG_IOPORT)
396 fprintf(logfile, "inw : %04x %04x\n", addr, val);
397 #endif
398 #ifdef USE_KQEMU
399 if (env)
400 env->last_io_time = cpu_get_time_fast();
401 #endif
402 return val;
403 }
405 int cpu_inl(CPUState *env, int addr)
406 {
407 int val;
408 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
409 #ifdef DEBUG_IOPORT
410 if (loglevel & CPU_LOG_IOPORT)
411 fprintf(logfile, "inl : %04x %08x\n", addr, val);
412 #endif
413 #ifdef USE_KQEMU
414 if (env)
415 env->last_io_time = cpu_get_time_fast();
416 #endif
417 return val;
418 }
420 /***********************************************************/
421 void hw_error(const char *fmt, ...)
422 {
423 va_list ap;
424 #ifndef CONFIG_DM
425 CPUState *env;
426 #endif /* !CONFIG_DM */
428 va_start(ap, fmt);
429 fprintf(stderr, "qemu: hardware error: ");
430 vfprintf(stderr, fmt, ap);
431 fprintf(stderr, "\n");
432 #ifndef CONFIG_DM
433 for(env = first_cpu; env != NULL; env = env->next_cpu) {
434 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
435 #ifdef TARGET_I386
436 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
437 #else
438 cpu_dump_state(env, stderr, fprintf, 0);
439 #endif
440 }
441 #endif /* !CONFIG_DM */
442 va_end(ap);
443 abort();
444 }
446 /***********************************************************/
447 /* keyboard/mouse */
449 static QEMUPutKBDEvent *qemu_put_kbd_event;
450 static void *qemu_put_kbd_event_opaque;
451 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
452 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
454 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
455 {
456 qemu_put_kbd_event_opaque = opaque;
457 qemu_put_kbd_event = func;
458 }
460 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
461 void *opaque, int absolute,
462 const char *name)
463 {
464 QEMUPutMouseEntry *s, *cursor;
466 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
467 if (!s)
468 return NULL;
470 s->qemu_put_mouse_event = func;
471 s->qemu_put_mouse_event_opaque = opaque;
472 s->qemu_put_mouse_event_absolute = absolute;
473 s->qemu_put_mouse_event_name = qemu_strdup(name);
474 s->next = NULL;
476 if (!qemu_put_mouse_event_head) {
477 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
478 return s;
479 }
481 cursor = qemu_put_mouse_event_head;
482 while (cursor->next != NULL)
483 cursor = cursor->next;
485 cursor->next = s;
486 qemu_put_mouse_event_current = s;
488 return s;
489 }
491 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
492 {
493 QEMUPutMouseEntry *prev = NULL, *cursor;
495 if (!qemu_put_mouse_event_head || entry == NULL)
496 return;
498 cursor = qemu_put_mouse_event_head;
499 while (cursor != NULL && cursor != entry) {
500 prev = cursor;
501 cursor = cursor->next;
502 }
504 if (cursor == NULL) // does not exist or list empty
505 return;
506 else if (prev == NULL) { // entry is head
507 qemu_put_mouse_event_head = cursor->next;
508 if (qemu_put_mouse_event_current == entry)
509 qemu_put_mouse_event_current = cursor->next;
510 qemu_free(entry->qemu_put_mouse_event_name);
511 qemu_free(entry);
512 return;
513 }
515 prev->next = entry->next;
517 if (qemu_put_mouse_event_current == entry)
518 qemu_put_mouse_event_current = prev;
520 qemu_free(entry->qemu_put_mouse_event_name);
521 qemu_free(entry);
522 }
524 void kbd_put_keycode(int keycode)
525 {
526 if (qemu_put_kbd_event) {
527 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
528 }
529 }
531 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
532 {
533 QEMUPutMouseEvent *mouse_event;
534 void *mouse_event_opaque;
536 if (!qemu_put_mouse_event_current) {
537 return;
538 }
540 mouse_event =
541 qemu_put_mouse_event_current->qemu_put_mouse_event;
542 mouse_event_opaque =
543 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
545 if (mouse_event) {
546 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
547 }
548 }
550 int kbd_mouse_is_absolute(void)
551 {
552 if (!qemu_put_mouse_event_current)
553 return 0;
555 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
556 }
558 void do_info_mice(void)
559 {
560 QEMUPutMouseEntry *cursor;
561 int index = 0;
563 if (!qemu_put_mouse_event_head) {
564 term_printf("No mouse devices connected\n");
565 return;
566 }
568 term_printf("Mouse devices available:\n");
569 cursor = qemu_put_mouse_event_head;
570 while (cursor != NULL) {
571 term_printf("%c Mouse #%d: %s\n",
572 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
573 index, cursor->qemu_put_mouse_event_name);
574 index++;
575 cursor = cursor->next;
576 }
577 }
579 void do_mouse_set(int index)
580 {
581 QEMUPutMouseEntry *cursor;
582 int i = 0;
584 if (!qemu_put_mouse_event_head) {
585 term_printf("No mouse devices connected\n");
586 return;
587 }
589 cursor = qemu_put_mouse_event_head;
590 while (cursor != NULL && index != i) {
591 i++;
592 cursor = cursor->next;
593 }
595 if (cursor != NULL)
596 qemu_put_mouse_event_current = cursor;
597 else
598 term_printf("Mouse at given index not found\n");
599 }
601 /* compute with 96 bit intermediate result: (a*b)/c */
602 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
603 {
604 union {
605 uint64_t ll;
606 struct {
607 #ifdef WORDS_BIGENDIAN
608 uint32_t high, low;
609 #else
610 uint32_t low, high;
611 #endif
612 } l;
613 } u, res;
614 uint64_t rl, rh;
616 u.ll = a;
617 rl = (uint64_t)u.l.low * (uint64_t)b;
618 rh = (uint64_t)u.l.high * (uint64_t)b;
619 rh += (rl >> 32);
620 res.l.high = rh / c;
621 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
622 return res.ll;
623 }
625 /***********************************************************/
626 /* real time host monotonic timer */
628 #define QEMU_TIMER_BASE 1000000000LL
630 #ifdef WIN32
632 static int64_t clock_freq;
634 static void init_get_clock(void)
635 {
636 LARGE_INTEGER freq;
637 int ret;
638 ret = QueryPerformanceFrequency(&freq);
639 if (ret == 0) {
640 fprintf(stderr, "Could not calibrate ticks\n");
641 exit(1);
642 }
643 clock_freq = freq.QuadPart;
644 }
646 static int64_t get_clock(void)
647 {
648 LARGE_INTEGER ti;
649 QueryPerformanceCounter(&ti);
650 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
651 }
653 #else
655 static int use_rt_clock;
657 static void init_get_clock(void)
658 {
659 use_rt_clock = 0;
660 #if defined(__linux__)
661 {
662 struct timespec ts;
663 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
664 use_rt_clock = 1;
665 }
666 }
667 #endif
668 }
670 static int64_t get_clock(void)
671 {
672 #if defined(__linux__)
673 if (use_rt_clock) {
674 struct timespec ts;
675 clock_gettime(CLOCK_MONOTONIC, &ts);
676 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
677 } else
678 #endif
679 {
680 /* XXX: using gettimeofday leads to problems if the date
681 changes, so it should be avoided. */
682 struct timeval tv;
683 gettimeofday(&tv, NULL);
684 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
685 }
686 }
688 #endif
690 /***********************************************************/
691 /* guest cycle counter */
693 static int64_t cpu_ticks_prev;
694 static int64_t cpu_ticks_offset;
695 static int64_t cpu_clock_offset;
696 static int cpu_ticks_enabled;
698 /* return the host CPU cycle counter and handle stop/restart */
699 int64_t cpu_get_ticks(void)
700 {
701 if (!cpu_ticks_enabled) {
702 return cpu_ticks_offset;
703 } else {
704 int64_t ticks;
705 ticks = cpu_get_real_ticks();
706 if (cpu_ticks_prev > ticks) {
707 /* Note: non increasing ticks may happen if the host uses
708 software suspend */
709 cpu_ticks_offset += cpu_ticks_prev - ticks;
710 }
711 cpu_ticks_prev = ticks;
712 return ticks + cpu_ticks_offset;
713 }
714 }
716 /* return the host CPU monotonic timer and handle stop/restart */
717 static int64_t cpu_get_clock(void)
718 {
719 int64_t ti;
720 if (!cpu_ticks_enabled) {
721 return cpu_clock_offset;
722 } else {
723 ti = get_clock();
724 return ti + cpu_clock_offset;
725 }
726 }
728 /* enable cpu_get_ticks() */
729 void cpu_enable_ticks(void)
730 {
731 if (!cpu_ticks_enabled) {
732 cpu_ticks_offset -= cpu_get_real_ticks();
733 cpu_clock_offset -= get_clock();
734 cpu_ticks_enabled = 1;
735 }
736 }
738 /* disable cpu_get_ticks() : the clock is stopped. You must not call
739 cpu_get_ticks() after that. */
740 void cpu_disable_ticks(void)
741 {
742 if (cpu_ticks_enabled) {
743 cpu_ticks_offset = cpu_get_ticks();
744 cpu_clock_offset = cpu_get_clock();
745 cpu_ticks_enabled = 0;
746 }
747 }
749 /***********************************************************/
750 /* timers */
752 #define QEMU_TIMER_REALTIME 0
753 #define QEMU_TIMER_VIRTUAL 1
755 struct QEMUClock {
756 int type;
757 /* XXX: add frequency */
758 };
760 struct QEMUTimer {
761 QEMUClock *clock;
762 int64_t expire_time;
763 QEMUTimerCB *cb;
764 void *opaque;
765 struct QEMUTimer *next;
766 };
768 QEMUClock *rt_clock;
769 QEMUClock *vm_clock;
771 static QEMUTimer *active_timers[2];
772 #ifdef _WIN32
773 static MMRESULT timerID;
774 static HANDLE host_alarm = NULL;
775 static unsigned int period = 1;
776 #else
777 /* frequency of the times() clock tick */
778 static int timer_freq;
779 #endif
781 QEMUClock *qemu_new_clock(int type)
782 {
783 QEMUClock *clock;
784 clock = qemu_mallocz(sizeof(QEMUClock));
785 if (!clock)
786 return NULL;
787 clock->type = type;
788 return clock;
789 }
791 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
792 {
793 QEMUTimer *ts;
795 ts = qemu_mallocz(sizeof(QEMUTimer));
796 ts->clock = clock;
797 ts->cb = cb;
798 ts->opaque = opaque;
799 return ts;
800 }
802 void qemu_free_timer(QEMUTimer *ts)
803 {
804 qemu_free(ts);
805 }
807 /* stop a timer, but do not dealloc it */
808 void qemu_del_timer(QEMUTimer *ts)
809 {
810 QEMUTimer **pt, *t;
812 /* NOTE: this code must be signal safe because
813 qemu_timer_expired() can be called from a signal. */
814 pt = &active_timers[ts->clock->type];
815 for(;;) {
816 t = *pt;
817 if (!t)
818 break;
819 if (t == ts) {
820 *pt = t->next;
821 break;
822 }
823 pt = &t->next;
824 }
825 }
827 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
828 {
829 if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
830 qemu_mod_timer(ts, expire_time);
831 }
833 /* modify the current timer so that it will be fired when current_time
834 >= expire_time. The corresponding callback will be called. */
835 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
836 {
837 QEMUTimer **pt, *t;
839 qemu_del_timer(ts);
841 /* add the timer in the sorted list */
842 /* NOTE: this code must be signal safe because
843 qemu_timer_expired() can be called from a signal. */
844 pt = &active_timers[ts->clock->type];
845 for(;;) {
846 t = *pt;
847 if (!t)
848 break;
849 if (t->expire_time > expire_time)
850 break;
851 pt = &t->next;
852 }
853 ts->expire_time = expire_time;
854 ts->next = *pt;
855 *pt = ts;
856 }
858 int qemu_timer_pending(QEMUTimer *ts)
859 {
860 QEMUTimer *t;
861 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
862 if (t == ts)
863 return 1;
864 }
865 return 0;
866 }
868 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
869 {
870 if (!timer_head)
871 return 0;
872 return (timer_head->expire_time <= current_time);
873 }
875 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
876 {
877 QEMUTimer *ts;
879 for(;;) {
880 ts = *ptimer_head;
881 if (!ts || ts->expire_time > current_time)
882 break;
883 /* remove timer from the list before calling the callback */
884 *ptimer_head = ts->next;
885 ts->next = NULL;
887 /* run the callback (the timer list can be modified) */
888 ts->cb(ts->opaque);
889 }
890 }
892 int64_t qemu_get_clock(QEMUClock *clock)
893 {
894 switch(clock->type) {
895 case QEMU_TIMER_REALTIME:
896 return get_clock() / 1000000;
897 default:
898 case QEMU_TIMER_VIRTUAL:
899 return cpu_get_clock();
900 }
901 }
903 static void init_timers(void)
904 {
905 init_get_clock();
906 ticks_per_sec = QEMU_TIMER_BASE;
907 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
908 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
909 }
911 /* save a timer */
912 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
913 {
914 uint64_t expire_time;
916 if (qemu_timer_pending(ts)) {
917 expire_time = ts->expire_time;
918 } else {
919 expire_time = -1;
920 }
921 qemu_put_be64(f, expire_time);
922 }
924 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
925 {
926 uint64_t expire_time;
928 expire_time = qemu_get_be64(f);
929 if (expire_time != -1) {
930 qemu_mod_timer(ts, expire_time);
931 } else {
932 qemu_del_timer(ts);
933 }
934 }
936 #ifdef CONFIG_DM
937 static void timer_save(QEMUFile *f, void *opaque)
938 {
939 /* need timer for save/restoe qemu_timer in usb_uhci */
940 if (cpu_ticks_enabled) {
941 hw_error("cannot save state if virtual timers are running");
942 }
943 qemu_put_be64s(f, &cpu_clock_offset);
944 }
946 static int timer_load(QEMUFile *f, void *opaque, int version_id)
947 {
948 if (version_id != 1 && version_id != 2)
949 return -EINVAL;
950 if (cpu_ticks_enabled) {
951 return -EINVAL;
952 }
954 qemu_get_be64s(f, &cpu_clock_offset);
955 return 0;
956 }
957 #else /* !CONFIG_DM */
958 static void timer_save(QEMUFile *f, void *opaque)
959 {
960 if (cpu_ticks_enabled) {
961 hw_error("cannot save state if virtual timers are running");
962 }
963 qemu_put_be64s(f, &cpu_ticks_offset);
964 qemu_put_be64s(f, &ticks_per_sec);
965 qemu_put_be64s(f, &cpu_clock_offset);
966 }
968 static int timer_load(QEMUFile *f, void *opaque, int version_id)
969 {
970 if (version_id != 1 && version_id != 2)
971 return -EINVAL;
972 if (cpu_ticks_enabled) {
973 return -EINVAL;
974 }
975 qemu_get_be64s(f, &cpu_ticks_offset);
976 qemu_get_be64s(f, &ticks_per_sec);
977 if (version_id == 2) {
978 qemu_get_be64s(f, &cpu_clock_offset);
979 }
980 return 0;
981 }
983 #ifdef _WIN32
984 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
985 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
986 #else
987 static void host_alarm_handler(int host_signum)
988 #endif
989 {
990 #if 0
991 #define DISP_FREQ 1000
992 {
993 static int64_t delta_min = INT64_MAX;
994 static int64_t delta_max, delta_cum, last_clock, delta, ti;
995 static int count;
996 ti = qemu_get_clock(vm_clock);
997 if (last_clock != 0) {
998 delta = ti - last_clock;
999 if (delta < delta_min)
1000 delta_min = delta;
1001 if (delta > delta_max)
1002 delta_max = delta;
1003 delta_cum += delta;
1004 if (++count == DISP_FREQ) {
1005 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1006 muldiv64(delta_min, 1000000, ticks_per_sec),
1007 muldiv64(delta_max, 1000000, ticks_per_sec),
1008 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1009 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1010 count = 0;
1011 delta_min = INT64_MAX;
1012 delta_max = 0;
1013 delta_cum = 0;
1016 last_clock = ti;
1018 #endif
1019 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1020 qemu_get_clock(vm_clock)) ||
1021 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1022 qemu_get_clock(rt_clock))) {
1023 #ifdef _WIN32
1024 SetEvent(host_alarm);
1025 #endif
1026 CPUState *env = cpu_single_env;
1027 if (env) {
1028 /* stop the currently executing cpu because a timer occured */
1029 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1030 #ifdef USE_KQEMU
1031 if (env->kqemu_enabled) {
1032 kqemu_cpu_interrupt(env);
1034 #endif
1039 #ifndef _WIN32
1041 #if defined(__linux__)
1043 #define RTC_FREQ 1024
1045 static int rtc_fd;
1047 static int start_rtc_timer(void)
1049 rtc_fd = open("/dev/rtc", O_RDONLY);
1050 if (rtc_fd < 0)
1051 return -1;
1052 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1053 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1054 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1055 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1056 goto fail;
1058 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1059 fail:
1060 close(rtc_fd);
1061 return -1;
1063 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1064 return 0;
1067 #else
1069 static int start_rtc_timer(void)
1071 return -1;
1074 #endif /* !defined(__linux__) */
1076 #endif /* !defined(_WIN32) */
1078 #endif /* !CONFIG_DM */
1080 static void init_timer_alarm(void)
1082 #ifdef _WIN32
1084 int count=0;
1085 TIMECAPS tc;
1087 ZeroMemory(&tc, sizeof(TIMECAPS));
1088 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1089 if (period < tc.wPeriodMin)
1090 period = tc.wPeriodMin;
1091 timeBeginPeriod(period);
1092 timerID = timeSetEvent(1, // interval (ms)
1093 period, // resolution
1094 host_alarm_handler, // function
1095 (DWORD)&count, // user parameter
1096 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1097 if( !timerID ) {
1098 perror("failed timer alarm");
1099 exit(1);
1101 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1102 if (!host_alarm) {
1103 perror("failed CreateEvent");
1104 exit(1);
1106 qemu_add_wait_object(host_alarm, NULL, NULL);
1108 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1109 #else
1111 #ifndef CONFIG_DM
1112 struct sigaction act;
1113 struct itimerval itv;
1114 #endif
1116 /* get times() syscall frequency */
1117 timer_freq = sysconf(_SC_CLK_TCK);
1119 #ifndef CONFIG_DM
1120 /* timer signal */
1121 sigfillset(&act.sa_mask);
1122 act.sa_flags = 0;
1123 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1124 act.sa_flags |= SA_ONSTACK;
1125 #endif
1126 act.sa_handler = host_alarm_handler;
1127 sigaction(SIGALRM, &act, NULL);
1129 itv.it_interval.tv_sec = 0;
1130 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1131 itv.it_value.tv_sec = 0;
1132 itv.it_value.tv_usec = 10 * 1000;
1133 setitimer(ITIMER_REAL, &itv, NULL);
1134 /* we probe the tick duration of the kernel to inform the user if
1135 the emulated kernel requested a too high timer frequency */
1136 getitimer(ITIMER_REAL, &itv);
1138 #if defined(__linux__)
1139 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1140 have timers with 1 ms resolution. The correct solution will
1141 be to use the POSIX real time timers available in recent
1142 2.6 kernels */
1143 if (itv.it_interval.tv_usec > 1000 || 1) {
1144 /* try to use /dev/rtc to have a faster timer */
1145 if (start_rtc_timer() < 0)
1146 goto use_itimer;
1147 /* disable itimer */
1148 itv.it_interval.tv_sec = 0;
1149 itv.it_interval.tv_usec = 0;
1150 itv.it_value.tv_sec = 0;
1151 itv.it_value.tv_usec = 0;
1152 setitimer(ITIMER_REAL, &itv, NULL);
1154 /* use the RTC */
1155 sigaction(SIGIO, &act, NULL);
1156 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1157 fcntl(rtc_fd, F_SETOWN, getpid());
1158 } else
1159 #endif /* defined(__linux__) */
1161 use_itimer:
1162 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1163 PIT_FREQ) / 1000000;
1165 #endif /* CONFIG_DM */
1167 #endif
1170 void quit_timers(void)
1172 #ifdef _WIN32
1173 timeKillEvent(timerID);
1174 timeEndPeriod(period);
1175 if (host_alarm) {
1176 CloseHandle(host_alarm);
1177 host_alarm = NULL;
1179 #endif
1182 /***********************************************************/
1183 /* character device */
1185 static void qemu_chr_event(CharDriverState *s, int event)
1187 if (!s->chr_event)
1188 return;
1189 s->chr_event(s->handler_opaque, event);
1192 static void qemu_chr_reset_bh(void *opaque)
1194 CharDriverState *s = opaque;
1195 qemu_chr_event(s, CHR_EVENT_RESET);
1196 qemu_bh_delete(s->bh);
1197 s->bh = NULL;
1200 void qemu_chr_reset(CharDriverState *s)
1202 if (s->bh == NULL) {
1203 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1204 qemu_bh_schedule(s->bh);
1208 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1210 return s->chr_write(s, buf, len);
1213 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1215 if (!s->chr_ioctl)
1216 return -ENOTSUP;
1217 return s->chr_ioctl(s, cmd, arg);
1220 int qemu_chr_can_read(CharDriverState *s)
1222 if (!s->chr_can_read)
1223 return 0;
1224 return s->chr_can_read(s->handler_opaque);
1227 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1229 s->chr_read(s->handler_opaque, buf, len);
1233 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1235 char buf[4096];
1236 va_list ap;
1237 va_start(ap, fmt);
1238 vsnprintf(buf, sizeof(buf), fmt, ap);
1239 qemu_chr_write(s, buf, strlen(buf));
1240 va_end(ap);
1243 void qemu_chr_send_event(CharDriverState *s, int event)
1245 if (s->chr_send_event)
1246 s->chr_send_event(s, event);
1249 void qemu_chr_add_handlers(CharDriverState *s,
1250 IOCanRWHandler *fd_can_read,
1251 IOReadHandler *fd_read,
1252 IOEventHandler *fd_event,
1253 void *opaque)
1255 s->chr_can_read = fd_can_read;
1256 s->chr_read = fd_read;
1257 s->chr_event = fd_event;
1258 s->handler_opaque = opaque;
1259 if (s->chr_update_read_handler)
1260 s->chr_update_read_handler(s);
1263 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1265 return len;
1268 static CharDriverState *qemu_chr_open_null(void)
1270 CharDriverState *chr;
1272 chr = qemu_mallocz(sizeof(CharDriverState));
1273 if (!chr)
1274 return NULL;
1275 chr->chr_write = null_chr_write;
1276 return chr;
1279 #ifdef _WIN32
1281 static void socket_cleanup(void)
1283 WSACleanup();
1286 static int socket_init(void)
1288 WSADATA Data;
1289 int ret, err;
1291 ret = WSAStartup(MAKEWORD(2,2), &Data);
1292 if (ret != 0) {
1293 err = WSAGetLastError();
1294 fprintf(stderr, "WSAStartup: %d\n", err);
1295 return -1;
1297 atexit(socket_cleanup);
1298 return 0;
1301 static int send_all(int fd, const uint8_t *buf, int len1)
1303 int ret, len;
1305 len = len1;
1306 while (len > 0) {
1307 ret = send(fd, buf, len, 0);
1308 if (ret < 0) {
1309 int errno;
1310 errno = WSAGetLastError();
1311 if (errno != WSAEWOULDBLOCK) {
1312 return -1;
1314 } else if (ret == 0) {
1315 break;
1316 } else {
1317 buf += ret;
1318 len -= ret;
1321 return len1 - len;
1324 void socket_set_nonblock(int fd)
1326 unsigned long opt = 1;
1327 ioctlsocket(fd, FIONBIO, &opt);
1330 #else
1332 static int unix_write(int fd, const uint8_t *buf, int len1)
1334 int ret, sel_ret, len;
1335 int max_fd;
1336 fd_set writefds;
1337 struct timeval timeout;
1339 max_fd = fd;
1341 len = len1;
1342 while (len > 0) {
1343 FD_ZERO(&writefds);
1344 FD_SET(fd, &writefds);
1345 timeout.tv_sec = 0;
1346 timeout.tv_usec = 0;
1347 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1348 if (sel_ret <= 0) {
1349 /* Timeout or select error */
1350 return -1;
1351 } else {
1352 ret = write(fd, buf, len);
1353 if (ret < 0) {
1354 if (errno != EINTR && errno != EAGAIN)
1355 return -1;
1356 } else if (ret == 0) {
1357 break;
1358 } else {
1359 buf += ret;
1360 len -= ret;
1364 return len1 - len;
1367 static inline int send_all(int fd, const uint8_t *buf, int len1)
1369 return unix_write(fd, buf, len1);
1372 void socket_set_nonblock(int fd)
1374 fcntl(fd, F_SETFL, O_NONBLOCK);
1376 #endif /* !_WIN32 */
1378 #ifndef _WIN32
1380 typedef struct {
1381 int fd_in, fd_out;
1382 int max_size;
1383 } FDCharDriver;
1385 #define STDIO_MAX_CLIENTS 2
1387 static int stdio_nb_clients;
1388 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1390 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1392 FDCharDriver *s = chr->opaque;
1393 return unix_write(s->fd_out, buf, len);
1396 static int fd_chr_read_poll(void *opaque)
1398 CharDriverState *chr = opaque;
1399 FDCharDriver *s = chr->opaque;
1401 s->max_size = qemu_chr_can_read(chr);
1402 return s->max_size;
1405 static void fd_chr_read(void *opaque)
1407 CharDriverState *chr = opaque;
1408 FDCharDriver *s = chr->opaque;
1409 int size, len;
1410 uint8_t buf[1024];
1412 len = sizeof(buf);
1413 if (len > s->max_size)
1414 len = s->max_size;
1415 if (len == 0)
1416 return;
1417 size = read(s->fd_in, buf, len);
1418 if (size == 0) {
1419 /* FD has been closed. Remove it from the active list. */
1420 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1421 return;
1423 if (size > 0) {
1424 qemu_chr_read(chr, buf, size);
1428 static void fd_chr_update_read_handler(CharDriverState *chr)
1430 FDCharDriver *s = chr->opaque;
1432 if (s->fd_in >= 0) {
1433 if (nographic && s->fd_in == 0) {
1434 } else {
1435 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1436 fd_chr_read, NULL, chr);
1441 /* open a character device to a unix fd */
1442 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1444 CharDriverState *chr;
1445 FDCharDriver *s;
1447 chr = qemu_mallocz(sizeof(CharDriverState));
1448 if (!chr)
1449 return NULL;
1450 s = qemu_mallocz(sizeof(FDCharDriver));
1451 if (!s) {
1452 free(chr);
1453 return NULL;
1455 s->fd_in = fd_in;
1456 s->fd_out = fd_out;
1457 chr->opaque = s;
1458 chr->chr_write = fd_chr_write;
1459 chr->chr_update_read_handler = fd_chr_update_read_handler;
1461 qemu_chr_reset(chr);
1463 return chr;
1466 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1468 int fd_out;
1470 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1471 if (fd_out < 0)
1472 return NULL;
1473 return qemu_chr_open_fd(-1, fd_out);
1476 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1478 int fd_in, fd_out;
1479 char filename_in[256], filename_out[256];
1481 snprintf(filename_in, 256, "%s.in", filename);
1482 snprintf(filename_out, 256, "%s.out", filename);
1483 fd_in = open(filename_in, O_RDWR | O_BINARY);
1484 fd_out = open(filename_out, O_RDWR | O_BINARY);
1485 if (fd_in < 0 || fd_out < 0) {
1486 if (fd_in >= 0)
1487 close(fd_in);
1488 if (fd_out >= 0)
1489 close(fd_out);
1490 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1491 if (fd_in < 0)
1492 return NULL;
1494 return qemu_chr_open_fd(fd_in, fd_out);
1498 /* for STDIO, we handle the case where several clients use it
1499 (nographic mode) */
1501 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1503 #define TERM_FIFO_MAX_SIZE 1
1505 static int term_got_escape, client_index;
1506 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1507 static int term_fifo_size;
1508 static int term_timestamps;
1509 static int64_t term_timestamps_start;
1511 void term_print_help(void)
1513 printf("\n"
1514 "C-a h print this help\n"
1515 "C-a x exit emulator\n"
1516 "C-a s save disk data back to file (if -snapshot)\n"
1517 "C-a b send break (magic sysrq)\n"
1518 "C-a t toggle console timestamps\n"
1519 "C-a c switch between console and monitor\n"
1520 "C-a C-a send C-a\n"
1521 );
1524 /* called when a char is received */
1525 static void stdio_received_byte(int ch)
1527 if (term_got_escape) {
1528 term_got_escape = 0;
1529 switch(ch) {
1530 case 'h':
1531 term_print_help();
1532 break;
1533 case 'x':
1534 exit(0);
1535 break;
1536 case 's':
1538 int i;
1539 for (i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
1540 if (bs_table[i])
1541 bdrv_commit(bs_table[i]);
1544 break;
1545 case 'b':
1546 if (client_index < stdio_nb_clients) {
1547 CharDriverState *chr;
1548 FDCharDriver *s;
1550 chr = stdio_clients[client_index];
1551 s = chr->opaque;
1552 qemu_chr_event(chr, CHR_EVENT_BREAK);
1554 break;
1555 case 'c':
1556 client_index++;
1557 if (client_index >= stdio_nb_clients)
1558 client_index = 0;
1559 if (client_index == 0) {
1560 /* send a new line in the monitor to get the prompt */
1561 ch = '\r';
1562 goto send_char;
1564 break;
1565 case 't':
1566 term_timestamps = !term_timestamps;
1567 term_timestamps_start = -1;
1568 break;
1569 case TERM_ESCAPE:
1570 goto send_char;
1572 } else if (ch == TERM_ESCAPE) {
1573 term_got_escape = 1;
1574 } else {
1575 send_char:
1576 if (client_index < stdio_nb_clients) {
1577 uint8_t buf[1];
1578 CharDriverState *chr;
1580 chr = stdio_clients[client_index];
1581 if (qemu_chr_can_read(chr) > 0) {
1582 buf[0] = ch;
1583 qemu_chr_read(chr, buf, 1);
1584 } else if (term_fifo_size == 0) {
1585 term_fifo[term_fifo_size++] = ch;
1591 static int stdio_read_poll(void *opaque)
1593 CharDriverState *chr;
1595 if (client_index < stdio_nb_clients) {
1596 chr = stdio_clients[client_index];
1597 /* try to flush the queue if needed */
1598 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1599 qemu_chr_read(chr, term_fifo, 1);
1600 term_fifo_size = 0;
1602 /* see if we can absorb more chars */
1603 if (term_fifo_size == 0)
1604 return 1;
1605 else
1606 return 0;
1607 } else {
1608 return 1;
1612 static void stdio_read(void *opaque)
1614 int size;
1615 uint8_t buf[1];
1617 size = read(0, buf, 1);
1618 if (size == 0) {
1619 /* stdin has been closed. Remove it from the active list. */
1620 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1621 return;
1623 if (size > 0)
1624 stdio_received_byte(buf[0]);
1627 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1629 FDCharDriver *s = chr->opaque;
1630 if (!term_timestamps) {
1631 return unix_write(s->fd_out, buf, len);
1632 } else {
1633 int i;
1634 char buf1[64];
1636 for(i = 0; i < len; i++) {
1637 unix_write(s->fd_out, buf + i, 1);
1638 if (buf[i] == '\n') {
1639 int64_t ti;
1640 int secs;
1642 ti = get_clock();
1643 if (term_timestamps_start == -1)
1644 term_timestamps_start = ti;
1645 ti -= term_timestamps_start;
1646 secs = ti / 1000000000;
1647 snprintf(buf1, sizeof(buf1),
1648 "[%02d:%02d:%02d.%03d] ",
1649 secs / 3600,
1650 (secs / 60) % 60,
1651 secs % 60,
1652 (int)((ti / 1000000) % 1000));
1653 unix_write(s->fd_out, buf1, strlen(buf1));
1656 return len;
1660 /* init terminal so that we can grab keys */
1661 static struct termios oldtty;
1662 static int old_fd0_flags;
1664 static void term_exit(void)
1666 tcsetattr (0, TCSANOW, &oldtty);
1667 fcntl(0, F_SETFL, old_fd0_flags);
1670 static void term_init(void)
1672 struct termios tty;
1674 tcgetattr (0, &tty);
1675 oldtty = tty;
1676 old_fd0_flags = fcntl(0, F_GETFL);
1678 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1679 |INLCR|IGNCR|ICRNL|IXON);
1680 tty.c_oflag |= OPOST;
1681 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1682 /* if graphical mode, we allow Ctrl-C handling */
1683 if (nographic)
1684 tty.c_lflag &= ~ISIG;
1685 tty.c_cflag &= ~(CSIZE|PARENB);
1686 tty.c_cflag |= CS8;
1687 tty.c_cc[VMIN] = 1;
1688 tty.c_cc[VTIME] = 0;
1690 tcsetattr (0, TCSANOW, &tty);
1692 atexit(term_exit);
1694 fcntl(0, F_SETFL, O_NONBLOCK);
1697 static CharDriverState *qemu_chr_open_stdio(void)
1699 CharDriverState *chr;
1701 if (nographic) {
1702 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1703 return NULL;
1704 chr = qemu_chr_open_fd(0, 1);
1705 chr->chr_write = stdio_write;
1706 if (stdio_nb_clients == 0)
1707 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1708 client_index = stdio_nb_clients;
1709 } else {
1710 if (stdio_nb_clients != 0)
1711 return NULL;
1712 chr = qemu_chr_open_fd(0, 1);
1714 stdio_clients[stdio_nb_clients++] = chr;
1715 if (stdio_nb_clients == 1) {
1716 /* set the terminal in raw mode */
1717 term_init();
1719 return chr;
1722 /*
1723 * Create a store entry for a device (e.g., monitor, serial/parallel lines).
1724 * The entry is <domain-path><storeString>/tty and the value is the name
1725 * of the pty associated with the device.
1726 */
1727 static int store_dev_info(char *devName, int domid,
1728 CharDriverState *cState, char *storeString)
1730 int xc_handle;
1731 struct xs_handle *xs;
1732 char *path;
1733 char *newpath;
1734 FDCharDriver *s;
1735 char *pts;
1737 /* Check for valid arguments (at least, prevent segfaults). */
1738 if ((devName == NULL) || (cState == NULL) || (storeString == NULL)) {
1739 fprintf(logfile, "%s - invalid arguments\n", __FUNCTION__);
1740 return EINVAL;
1743 /*
1744 * Only continue if we're talking to a pty
1745 * Actually, the following code works for any CharDriverState using
1746 * FDCharDriver, but we really only care about pty's here
1747 */
1748 if (strcmp(devName, "pty"))
1749 return 0;
1751 s = cState->opaque;
1752 if (s == NULL) {
1753 fprintf(logfile, "%s - unable to retrieve fd for '%s'/'%s'\n",
1754 __FUNCTION__, storeString, devName);
1755 return EBADF;
1758 pts = ptsname(s->fd_in);
1759 if (pts == NULL) {
1760 fprintf(logfile, "%s - unable to determine ptsname '%s'/'%s', "
1761 "error %d (%s)\n",
1762 __FUNCTION__, storeString, devName, errno, strerror(errno));
1763 return errno;
1766 /* We now have everything we need to set the xenstore entry. */
1767 xs = xs_daemon_open();
1768 if (xs == NULL) {
1769 fprintf(logfile, "Could not contact XenStore\n");
1770 return -1;
1773 xc_handle = xc_interface_open();
1774 if (xc_handle == -1) {
1775 fprintf(logfile, "xc_interface_open() error\n");
1776 return -1;
1779 path = xs_get_domain_path(xs, domid);
1780 if (path == NULL) {
1781 fprintf(logfile, "xs_get_domain_path() error\n");
1782 return -1;
1784 newpath = realloc(path, (strlen(path) + strlen(storeString) +
1785 strlen("/tty") + 1));
1786 if (newpath == NULL) {
1787 free(path); /* realloc errors leave old block */
1788 fprintf(logfile, "realloc error\n");
1789 return -1;
1791 path = newpath;
1793 strcat(path, storeString);
1794 strcat(path, "/tty");
1795 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1796 fprintf(logfile, "xs_write for '%s' fail", storeString);
1797 return -1;
1800 free(path);
1801 xs_daemon_close(xs);
1802 close(xc_handle);
1804 return 0;
1807 #ifdef __sun__
1808 /* Once Solaris has openpty(), this is going to be removed. */
1809 int openpty(int *amaster, int *aslave, char *name,
1810 struct termios *termp, struct winsize *winp)
1812 const char *slave;
1813 int mfd = -1, sfd = -1;
1815 *amaster = *aslave = -1;
1817 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
1818 if (mfd < 0)
1819 goto err;
1821 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
1822 goto err;
1824 if ((slave = ptsname(mfd)) == NULL)
1825 goto err;
1827 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
1828 goto err;
1830 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
1831 (termp != NULL && tcgetattr(sfd, termp) < 0))
1832 goto err;
1834 if (amaster)
1835 *amaster = mfd;
1836 if (aslave)
1837 *aslave = sfd;
1838 if (winp)
1839 ioctl(sfd, TIOCSWINSZ, winp);
1841 return 0;
1843 err:
1844 if (sfd != -1)
1845 close(sfd);
1846 close(mfd);
1847 return -1;
1850 void cfmakeraw (struct termios *termios_p)
1852 termios_p->c_iflag &=
1853 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
1854 termios_p->c_oflag &= ~OPOST;
1855 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1856 termios_p->c_cflag &= ~(CSIZE|PARENB);
1857 termios_p->c_cflag |= CS8;
1859 termios_p->c_cc[VMIN] = 0;
1860 termios_p->c_cc[VTIME] = 0;
1863 #endif
1865 #if defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__sun__)
1866 static CharDriverState *qemu_chr_open_pty(void)
1868 struct termios tty;
1869 int master_fd, slave_fd;
1871 /* Not satisfying */
1872 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1873 return NULL;
1876 /* Set raw attributes on the pty. */
1877 cfmakeraw(&tty);
1878 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1880 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1882 return qemu_chr_open_fd(master_fd, master_fd);
1885 static void tty_serial_init(int fd, int speed,
1886 int parity, int data_bits, int stop_bits)
1888 struct termios tty;
1889 speed_t spd;
1891 #if 0
1892 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1893 speed, parity, data_bits, stop_bits);
1894 #endif
1895 tcgetattr (fd, &tty);
1897 switch(speed) {
1898 case 50:
1899 spd = B50;
1900 break;
1901 case 75:
1902 spd = B75;
1903 break;
1904 case 300:
1905 spd = B300;
1906 break;
1907 case 600:
1908 spd = B600;
1909 break;
1910 case 1200:
1911 spd = B1200;
1912 break;
1913 case 2400:
1914 spd = B2400;
1915 break;
1916 case 4800:
1917 spd = B4800;
1918 break;
1919 case 9600:
1920 spd = B9600;
1921 break;
1922 case 19200:
1923 spd = B19200;
1924 break;
1925 case 38400:
1926 spd = B38400;
1927 break;
1928 case 57600:
1929 spd = B57600;
1930 break;
1931 default:
1932 case 115200:
1933 spd = B115200;
1934 break;
1937 cfsetispeed(&tty, spd);
1938 cfsetospeed(&tty, spd);
1940 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1941 |INLCR|IGNCR|ICRNL|IXON);
1942 tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1943 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1944 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1945 switch(data_bits) {
1946 default:
1947 case 8:
1948 tty.c_cflag |= CS8;
1949 break;
1950 case 7:
1951 tty.c_cflag |= CS7;
1952 break;
1953 case 6:
1954 tty.c_cflag |= CS6;
1955 break;
1956 case 5:
1957 tty.c_cflag |= CS5;
1958 break;
1960 switch(parity) {
1961 default:
1962 case 'N':
1963 break;
1964 case 'E':
1965 tty.c_cflag |= PARENB;
1966 break;
1967 case 'O':
1968 tty.c_cflag |= PARENB | PARODD;
1969 break;
1971 if (stop_bits == 2)
1972 tty.c_cflag |= CSTOPB;
1974 tcsetattr (fd, TCSANOW, &tty);
1977 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1979 FDCharDriver *s = chr->opaque;
1981 switch(cmd) {
1982 case CHR_IOCTL_SERIAL_SET_PARAMS:
1984 QEMUSerialSetParams *ssp = arg;
1985 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1986 ssp->data_bits, ssp->stop_bits);
1988 break;
1989 case CHR_IOCTL_SERIAL_SET_BREAK:
1991 int enable = *(int *)arg;
1992 if (enable)
1993 tcsendbreak(s->fd_in, 1);
1995 break;
1996 case CHR_IOCTL_SERIAL_GET_TIOCM:
1998 ioctl(s->fd_in, TIOCMGET, arg);
2000 break;
2001 case CHR_IOCTL_SERIAL_SET_TIOCM:
2003 ioctl(s->fd_in, TIOCMSET, arg);
2005 break;
2006 default:
2007 return -ENOTSUP;
2009 return 0;
2012 static CharDriverState *qemu_chr_open_tty(const char *filename)
2014 CharDriverState *chr;
2015 int fd;
2017 fd = open(filename, O_RDWR | O_NONBLOCK);
2018 if (fd < 0)
2019 return NULL;
2020 fcntl(fd, F_SETFL, O_NONBLOCK);
2021 tty_serial_init(fd, 115200, 'N', 8, 1);
2022 chr = qemu_chr_open_fd(fd, fd);
2023 if (!chr)
2024 return NULL;
2025 chr->chr_ioctl = tty_serial_ioctl;
2026 qemu_chr_reset(chr);
2027 return chr;
2030 #if defined(__linux__)
2031 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2033 int fd = (int)chr->opaque;
2034 uint8_t b;
2036 switch(cmd) {
2037 case CHR_IOCTL_PP_READ_DATA:
2038 if (ioctl(fd, PPRDATA, &b) < 0)
2039 return -ENOTSUP;
2040 *(uint8_t *)arg = b;
2041 break;
2042 case CHR_IOCTL_PP_WRITE_DATA:
2043 b = *(uint8_t *)arg;
2044 if (ioctl(fd, PPWDATA, &b) < 0)
2045 return -ENOTSUP;
2046 break;
2047 case CHR_IOCTL_PP_READ_CONTROL:
2048 if (ioctl(fd, PPRCONTROL, &b) < 0)
2049 return -ENOTSUP;
2050 *(uint8_t *)arg = b;
2051 break;
2052 case CHR_IOCTL_PP_WRITE_CONTROL:
2053 b = *(uint8_t *)arg;
2054 if (ioctl(fd, PPWCONTROL, &b) < 0)
2055 return -ENOTSUP;
2056 break;
2057 case CHR_IOCTL_PP_READ_STATUS:
2058 if (ioctl(fd, PPRSTATUS, &b) < 0)
2059 return -ENOTSUP;
2060 *(uint8_t *)arg = b;
2061 break;
2062 default:
2063 return -ENOTSUP;
2065 return 0;
2068 static CharDriverState *qemu_chr_open_pp(const char *filename)
2070 CharDriverState *chr;
2071 int fd;
2073 fd = open(filename, O_RDWR);
2074 if (fd < 0)
2075 return NULL;
2077 if (ioctl(fd, PPCLAIM) < 0) {
2078 close(fd);
2079 return NULL;
2082 chr = qemu_mallocz(sizeof(CharDriverState));
2083 if (!chr) {
2084 close(fd);
2085 return NULL;
2087 chr->opaque = (void *)fd;
2088 chr->chr_write = null_chr_write;
2089 chr->chr_ioctl = pp_ioctl;
2091 qemu_chr_reset(chr);
2093 return chr;
2095 #endif /* __linux__ */
2097 #else
2098 static CharDriverState *qemu_chr_open_pty(void)
2100 return NULL;
2102 #endif /* __linux__ || __NetBSD__ || __OpenBSD__ || __sun__ */
2104 #endif /* !defined(_WIN32) */
2106 #ifdef _WIN32
2107 typedef struct {
2108 CharDriverState *chr;
2109 int max_size;
2110 HANDLE hcom, hrecv, hsend;
2111 OVERLAPPED orecv, osend;
2112 BOOL fpipe;
2113 DWORD len;
2114 } WinCharState;
2116 #define NSENDBUF 2048
2117 #define NRECVBUF 2048
2118 #define MAXCONNECT 1
2119 #define NTIMEOUT 5000
2121 static int win_chr_poll(void *opaque);
2122 static int win_chr_pipe_poll(void *opaque);
2124 static void win_chr_close2(WinCharState *s)
2126 if (s->hsend) {
2127 CloseHandle(s->hsend);
2128 s->hsend = NULL;
2130 if (s->hrecv) {
2131 CloseHandle(s->hrecv);
2132 s->hrecv = NULL;
2134 if (s->hcom) {
2135 CloseHandle(s->hcom);
2136 s->hcom = NULL;
2138 if (s->fpipe)
2139 qemu_del_polling_cb(win_chr_pipe_poll, s);
2140 else
2141 qemu_del_polling_cb(win_chr_poll, s);
2144 static void win_chr_close(CharDriverState *chr)
2146 WinCharState *s = chr->opaque;
2147 win_chr_close2(s);
2150 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
2152 COMMCONFIG comcfg;
2153 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2154 COMSTAT comstat;
2155 DWORD size;
2156 DWORD err;
2158 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2159 if (!s->hsend) {
2160 fprintf(stderr, "Failed CreateEvent\n");
2161 goto fail;
2163 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2164 if (!s->hrecv) {
2165 fprintf(stderr, "Failed CreateEvent\n");
2166 goto fail;
2169 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2170 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2171 if (s->hcom == INVALID_HANDLE_VALUE) {
2172 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2173 s->hcom = NULL;
2174 goto fail;
2177 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2178 fprintf(stderr, "Failed SetupComm\n");
2179 goto fail;
2182 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2183 size = sizeof(COMMCONFIG);
2184 GetDefaultCommConfig(filename, &comcfg, &size);
2185 comcfg.dcb.DCBlength = sizeof(DCB);
2186 CommConfigDialog(filename, NULL, &comcfg);
2188 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2189 fprintf(stderr, "Failed SetCommState\n");
2190 goto fail;
2193 if (!SetCommMask(s->hcom, EV_ERR)) {
2194 fprintf(stderr, "Failed SetCommMask\n");
2195 goto fail;
2198 cto.ReadIntervalTimeout = MAXDWORD;
2199 if (!SetCommTimeouts(s->hcom, &cto)) {
2200 fprintf(stderr, "Failed SetCommTimeouts\n");
2201 goto fail;
2204 if (!ClearCommError(s->hcom, &err, &comstat)) {
2205 fprintf(stderr, "Failed ClearCommError\n");
2206 goto fail;
2208 s->chr = chr;
2209 qemu_add_polling_cb(win_chr_poll, s);
2210 return 0;
2212 fail:
2213 win_chr_close2(s);
2214 return -1;
2217 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2219 WinCharState *s = chr->opaque;
2220 DWORD len, ret, size, err;
2222 len = len1;
2223 ZeroMemory(&s->osend, sizeof(s->osend));
2224 s->osend.hEvent = s->hsend;
2225 while (len > 0) {
2226 if (s->hsend)
2227 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2228 else
2229 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2230 if (!ret) {
2231 err = GetLastError();
2232 if (err == ERROR_IO_PENDING) {
2233 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2234 if (ret) {
2235 buf += size;
2236 len -= size;
2237 } else {
2238 break;
2240 } else {
2241 break;
2243 } else {
2244 buf += size;
2245 len -= size;
2248 return len1 - len;
2251 static int win_chr_read_poll(WinCharState *s)
2253 s->max_size = qemu_chr_can_read(s->chr);
2254 return s->max_size;
2257 static void win_chr_readfile(WinCharState *s)
2259 int ret, err;
2260 uint8_t buf[1024];
2261 DWORD size;
2263 ZeroMemory(&s->orecv, sizeof(s->orecv));
2264 s->orecv.hEvent = s->hrecv;
2265 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2266 if (!ret) {
2267 err = GetLastError();
2268 if (err == ERROR_IO_PENDING) {
2269 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2273 if (size > 0) {
2274 qemu_chr_read(s->chr, buf, size);
2278 static void win_chr_read(WinCharState *s)
2280 if (s->len > s->max_size)
2281 s->len = s->max_size;
2282 if (s->len == 0)
2283 return;
2285 win_chr_readfile(s);
2288 static int win_chr_poll(void *opaque)
2290 WinCharState *s = opaque;
2291 COMSTAT status;
2292 DWORD comerr;
2294 ClearCommError(s->hcom, &comerr, &status);
2295 if (status.cbInQue > 0) {
2296 s->len = status.cbInQue;
2297 win_chr_read_poll(s);
2298 win_chr_read(s);
2299 return 1;
2301 return 0;
2304 static CharDriverState *qemu_chr_open_win(const char *filename)
2306 CharDriverState *chr;
2307 WinCharState *s;
2309 chr = qemu_mallocz(sizeof(CharDriverState));
2310 if (!chr)
2311 return NULL;
2312 s = qemu_mallocz(sizeof(WinCharState));
2313 if (!s) {
2314 free(chr);
2315 return NULL;
2317 chr->opaque = s;
2318 chr->chr_write = win_chr_write;
2319 chr->chr_close = win_chr_close;
2321 if (win_chr_init(s, chr, filename) < 0) {
2322 free(s);
2323 free(chr);
2324 return NULL;
2326 qemu_chr_reset(chr);
2327 return chr;
2330 static int win_chr_pipe_poll(void *opaque)
2332 WinCharState *s = opaque;
2333 DWORD size;
2335 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2336 if (size > 0) {
2337 s->len = size;
2338 win_chr_read_poll(s);
2339 win_chr_read(s);
2340 return 1;
2342 return 0;
2345 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2347 OVERLAPPED ov;
2348 int ret;
2349 DWORD size;
2350 char openname[256];
2352 s->fpipe = TRUE;
2354 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2355 if (!s->hsend) {
2356 fprintf(stderr, "Failed CreateEvent\n");
2357 goto fail;
2359 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2360 if (!s->hrecv) {
2361 fprintf(stderr, "Failed CreateEvent\n");
2362 goto fail;
2365 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2366 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2367 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2368 PIPE_WAIT,
2369 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2370 if (s->hcom == INVALID_HANDLE_VALUE) {
2371 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2372 s->hcom = NULL;
2373 goto fail;
2376 ZeroMemory(&ov, sizeof(ov));
2377 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2378 ret = ConnectNamedPipe(s->hcom, &ov);
2379 if (ret) {
2380 fprintf(stderr, "Failed ConnectNamedPipe\n");
2381 goto fail;
2384 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2385 if (!ret) {
2386 fprintf(stderr, "Failed GetOverlappedResult\n");
2387 if (ov.hEvent) {
2388 CloseHandle(ov.hEvent);
2389 ov.hEvent = NULL;
2391 goto fail;
2394 if (ov.hEvent) {
2395 CloseHandle(ov.hEvent);
2396 ov.hEvent = NULL;
2398 qemu_add_polling_cb(win_chr_pipe_poll, s);
2399 return 0;
2401 fail:
2402 win_chr_close2(s);
2403 return -1;
2407 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2409 CharDriverState *chr;
2410 WinCharState *s;
2412 chr = qemu_mallocz(sizeof(CharDriverState));
2413 if (!chr)
2414 return NULL;
2415 s = qemu_mallocz(sizeof(WinCharState));
2416 if (!s) {
2417 free(chr);
2418 return NULL;
2420 chr->opaque = s;
2421 chr->chr_write = win_chr_write;
2422 chr->chr_close = win_chr_close;
2424 if (win_chr_pipe_init(s, filename) < 0) {
2425 free(s);
2426 free(chr);
2427 return NULL;
2429 qemu_chr_reset(chr);
2430 return chr;
2433 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2435 CharDriverState *chr;
2436 WinCharState *s;
2438 chr = qemu_mallocz(sizeof(CharDriverState));
2439 if (!chr)
2440 return NULL;
2441 s = qemu_mallocz(sizeof(WinCharState));
2442 if (!s) {
2443 free(chr);
2444 return NULL;
2446 s->hcom = fd_out;
2447 chr->opaque = s;
2448 chr->chr_write = win_chr_write;
2449 qemu_chr_reset(chr);
2450 return chr;
2453 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2455 HANDLE fd_out;
2457 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2458 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2459 if (fd_out == INVALID_HANDLE_VALUE)
2460 return NULL;
2462 return qemu_chr_open_win_file(fd_out);
2464 #endif
2466 /***********************************************************/
2467 /* UDP Net console */
2469 typedef struct {
2470 int fd;
2471 struct sockaddr_in daddr;
2472 char buf[1024];
2473 int bufcnt;
2474 int bufptr;
2475 int max_size;
2476 } NetCharDriver;
2478 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2480 NetCharDriver *s = chr->opaque;
2482 return sendto(s->fd, buf, len, 0,
2483 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2486 static int udp_chr_read_poll(void *opaque)
2488 CharDriverState *chr = opaque;
2489 NetCharDriver *s = chr->opaque;
2491 s->max_size = qemu_chr_can_read(chr);
2493 /* If there were any stray characters in the queue process them
2494 * first
2495 */
2496 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2497 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2498 s->bufptr++;
2499 s->max_size = qemu_chr_can_read(chr);
2501 return s->max_size;
2504 static void udp_chr_read(void *opaque)
2506 CharDriverState *chr = opaque;
2507 NetCharDriver *s = chr->opaque;
2509 if (s->max_size == 0)
2510 return;
2511 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2512 s->bufptr = s->bufcnt;
2513 if (s->bufcnt <= 0)
2514 return;
2516 s->bufptr = 0;
2517 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2518 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2519 s->bufptr++;
2520 s->max_size = qemu_chr_can_read(chr);
2524 static void udp_chr_update_read_handler(CharDriverState *chr)
2526 NetCharDriver *s = chr->opaque;
2528 if (s->fd >= 0) {
2529 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2530 udp_chr_read, NULL, chr);
2534 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2535 #ifndef _WIN32
2536 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2537 #endif
2538 int parse_host_src_port(struct sockaddr_in *haddr,
2539 struct sockaddr_in *saddr,
2540 const char *str);
2542 static CharDriverState *qemu_chr_open_udp(const char *def)
2544 CharDriverState *chr = NULL;
2545 NetCharDriver *s = NULL;
2546 int fd = -1;
2547 struct sockaddr_in saddr;
2549 chr = qemu_mallocz(sizeof(CharDriverState));
2550 if (!chr)
2551 goto return_err;
2552 s = qemu_mallocz(sizeof(NetCharDriver));
2553 if (!s)
2554 goto return_err;
2556 fd = socket(PF_INET, SOCK_DGRAM, 0);
2557 if (fd < 0) {
2558 perror("socket(PF_INET, SOCK_DGRAM)");
2559 goto return_err;
2562 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2563 printf("Could not parse: %s\n", def);
2564 goto return_err;
2567 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2569 perror("bind");
2570 goto return_err;
2573 s->fd = fd;
2574 s->bufcnt = 0;
2575 s->bufptr = 0;
2576 chr->opaque = s;
2577 chr->chr_write = udp_chr_write;
2578 chr->chr_update_read_handler = udp_chr_update_read_handler;
2579 return chr;
2581 return_err:
2582 if (chr)
2583 free(chr);
2584 if (s)
2585 free(s);
2586 if (fd >= 0)
2587 closesocket(fd);
2588 return NULL;
2591 /***********************************************************/
2592 /* TCP Net console */
2594 typedef struct {
2595 int fd, listen_fd;
2596 int connected;
2597 int max_size;
2598 int do_telnetopt;
2599 int do_nodelay;
2600 int is_unix;
2601 } TCPCharDriver;
2603 static void tcp_chr_accept(void *opaque);
2605 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2607 TCPCharDriver *s = chr->opaque;
2608 if (s->connected) {
2609 return send_all(s->fd, buf, len);
2610 } else {
2611 /* XXX: indicate an error ? */
2612 return len;
2616 static int tcp_chr_read_poll(void *opaque)
2618 CharDriverState *chr = opaque;
2619 TCPCharDriver *s = chr->opaque;
2620 if (!s->connected)
2621 return 0;
2622 s->max_size = qemu_chr_can_read(chr);
2623 return s->max_size;
2626 #define IAC 255
2627 #define IAC_BREAK 243
2628 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2629 TCPCharDriver *s,
2630 char *buf, int *size)
2632 /* Handle any telnet client's basic IAC options to satisfy char by
2633 * char mode with no echo. All IAC options will be removed from
2634 * the buf and the do_telnetopt variable will be used to track the
2635 * state of the width of the IAC information.
2637 * IAC commands come in sets of 3 bytes with the exception of the
2638 * "IAC BREAK" command and the double IAC.
2639 */
2641 int i;
2642 int j = 0;
2644 for (i = 0; i < *size; i++) {
2645 if (s->do_telnetopt > 1) {
2646 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2647 /* Double IAC means send an IAC */
2648 if (j != i)
2649 buf[j] = buf[i];
2650 j++;
2651 s->do_telnetopt = 1;
2652 } else {
2653 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2654 /* Handle IAC break commands by sending a serial break */
2655 qemu_chr_event(chr, CHR_EVENT_BREAK);
2656 s->do_telnetopt++;
2658 s->do_telnetopt++;
2660 if (s->do_telnetopt >= 4) {
2661 s->do_telnetopt = 1;
2663 } else {
2664 if ((unsigned char)buf[i] == IAC) {
2665 s->do_telnetopt = 2;
2666 } else {
2667 if (j != i)
2668 buf[j] = buf[i];
2669 j++;
2673 *size = j;
2676 static void tcp_chr_read(void *opaque)
2678 CharDriverState *chr = opaque;
2679 TCPCharDriver *s = chr->opaque;
2680 uint8_t buf[1024];
2681 int len, size;
2683 if (!s->connected || s->max_size <= 0)
2684 return;
2685 len = sizeof(buf);
2686 if (len > s->max_size)
2687 len = s->max_size;
2688 size = recv(s->fd, buf, len, 0);
2689 if (size == 0) {
2690 /* connection closed */
2691 s->connected = 0;
2692 if (s->listen_fd >= 0) {
2693 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2695 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2696 closesocket(s->fd);
2697 s->fd = -1;
2698 } else if (size > 0) {
2699 if (s->do_telnetopt)
2700 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2701 if (size > 0)
2702 qemu_chr_read(chr, buf, size);
2706 static void tcp_chr_connect(void *opaque)
2708 CharDriverState *chr = opaque;
2709 TCPCharDriver *s = chr->opaque;
2711 s->connected = 1;
2712 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2713 tcp_chr_read, NULL, chr);
2714 qemu_chr_reset(chr);
2717 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2718 static void tcp_chr_telnet_init(int fd)
2720 char buf[3];
2721 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2722 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2723 send(fd, (char *)buf, 3, 0);
2724 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2725 send(fd, (char *)buf, 3, 0);
2726 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2727 send(fd, (char *)buf, 3, 0);
2728 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2729 send(fd, (char *)buf, 3, 0);
2732 static void socket_set_nodelay(int fd)
2734 int val = 1;
2735 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2738 static void tcp_chr_accept(void *opaque)
2740 CharDriverState *chr = opaque;
2741 TCPCharDriver *s = chr->opaque;
2742 struct sockaddr_in saddr;
2743 #ifndef _WIN32
2744 struct sockaddr_un uaddr;
2745 #endif
2746 struct sockaddr *addr;
2747 socklen_t len;
2748 int fd;
2750 for(;;) {
2751 #ifndef _WIN32
2752 if (s->is_unix) {
2753 len = sizeof(uaddr);
2754 addr = (struct sockaddr *)&uaddr;
2755 } else
2756 #endif
2758 len = sizeof(saddr);
2759 addr = (struct sockaddr *)&saddr;
2761 fd = accept(s->listen_fd, addr, &len);
2762 if (fd < 0 && errno != EINTR) {
2763 return;
2764 } else if (fd >= 0) {
2765 if (s->do_telnetopt)
2766 tcp_chr_telnet_init(fd);
2767 break;
2770 socket_set_nonblock(fd);
2771 if (s->do_nodelay)
2772 socket_set_nodelay(fd);
2773 s->fd = fd;
2774 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2775 tcp_chr_connect(chr);
2778 static void tcp_chr_close(CharDriverState *chr)
2780 TCPCharDriver *s = chr->opaque;
2781 if (s->fd >= 0)
2782 closesocket(s->fd);
2783 if (s->listen_fd >= 0)
2784 closesocket(s->listen_fd);
2785 qemu_free(s);
2788 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2789 int is_telnet,
2790 int is_unix)
2792 CharDriverState *chr = NULL;
2793 TCPCharDriver *s = NULL;
2794 int fd = -1, ret, err, val;
2795 int is_listen = 0;
2796 int is_waitconnect = 1;
2797 int do_nodelay = 0;
2798 const char *ptr;
2799 struct sockaddr_in saddr;
2800 #ifndef _WIN32
2801 struct sockaddr_un uaddr;
2802 #endif
2803 struct sockaddr *addr;
2804 socklen_t addrlen;
2806 #ifndef _WIN32
2807 if (is_unix) {
2808 addr = (struct sockaddr *)&uaddr;
2809 addrlen = sizeof(uaddr);
2810 if (parse_unix_path(&uaddr, host_str) < 0)
2811 goto fail;
2812 } else
2813 #endif
2815 addr = (struct sockaddr *)&saddr;
2816 addrlen = sizeof(saddr);
2817 if (parse_host_port(&saddr, host_str) < 0)
2818 goto fail;
2821 ptr = host_str;
2822 while((ptr = strchr(ptr,','))) {
2823 ptr++;
2824 if (!strncmp(ptr,"server",6)) {
2825 is_listen = 1;
2826 } else if (!strncmp(ptr,"nowait",6)) {
2827 is_waitconnect = 0;
2828 } else if (!strncmp(ptr,"nodelay",6)) {
2829 do_nodelay = 1;
2830 } else {
2831 printf("Unknown option: %s\n", ptr);
2832 goto fail;
2835 if (!is_listen)
2836 is_waitconnect = 0;
2838 chr = qemu_mallocz(sizeof(CharDriverState));
2839 if (!chr)
2840 goto fail;
2841 s = qemu_mallocz(sizeof(TCPCharDriver));
2842 if (!s)
2843 goto fail;
2845 #ifndef _WIN32
2846 if (is_unix)
2847 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2848 else
2849 #endif
2850 fd = socket(PF_INET, SOCK_STREAM, 0);
2852 if (fd < 0)
2853 goto fail;
2855 if (!is_waitconnect)
2856 socket_set_nonblock(fd);
2858 s->connected = 0;
2859 s->fd = -1;
2860 s->listen_fd = -1;
2861 s->is_unix = is_unix;
2862 s->do_nodelay = do_nodelay && !is_unix;
2864 chr->opaque = s;
2865 chr->chr_write = tcp_chr_write;
2866 chr->chr_close = tcp_chr_close;
2868 if (is_listen) {
2869 /* allow fast reuse */
2870 #ifndef _WIN32
2871 if (is_unix) {
2872 char path[109];
2873 strncpy(path, uaddr.sun_path, 108);
2874 path[108] = 0;
2875 unlink(path);
2876 } else
2877 #endif
2879 val = 1;
2880 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2883 ret = bind(fd, addr, addrlen);
2884 if (ret < 0)
2885 goto fail;
2887 ret = listen(fd, 0);
2888 if (ret < 0)
2889 goto fail;
2891 s->listen_fd = fd;
2892 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2893 if (is_telnet)
2894 s->do_telnetopt = 1;
2895 } else {
2896 for(;;) {
2897 ret = connect(fd, addr, addrlen);
2898 if (ret < 0) {
2899 err = socket_error();
2900 if (err == EINTR || err == EWOULDBLOCK) {
2901 } else if (err == EINPROGRESS) {
2902 break;
2903 } else {
2904 goto fail;
2906 } else {
2907 s->connected = 1;
2908 break;
2911 s->fd = fd;
2912 socket_set_nodelay(fd);
2913 if (s->connected)
2914 tcp_chr_connect(chr);
2915 else
2916 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2919 if (is_listen && is_waitconnect) {
2920 printf("QEMU waiting for connection on: %s\n", host_str);
2921 tcp_chr_accept(chr);
2922 socket_set_nonblock(s->listen_fd);
2925 return chr;
2926 fail:
2927 if (fd >= 0)
2928 closesocket(fd);
2929 qemu_free(s);
2930 qemu_free(chr);
2931 return NULL;
2934 CharDriverState *qemu_chr_open(const char *filename)
2936 const char *p;
2938 if (!strcmp(filename, "vc")) {
2939 return text_console_init(&display_state);
2940 } else if (!strcmp(filename, "null")) {
2941 return qemu_chr_open_null();
2942 } else
2943 if (strstart(filename, "tcp:", &p)) {
2944 return qemu_chr_open_tcp(p, 0, 0);
2945 } else
2946 if (strstart(filename, "telnet:", &p)) {
2947 return qemu_chr_open_tcp(p, 1, 0);
2948 } else
2949 if (strstart(filename, "udp:", &p)) {
2950 return qemu_chr_open_udp(p);
2951 } else
2952 #ifndef _WIN32
2953 if (strstart(filename, "unix:", &p)) {
2954 return qemu_chr_open_tcp(p, 0, 1);
2955 } else if (strstart(filename, "file:", &p)) {
2956 return qemu_chr_open_file_out(p);
2957 } else if (strstart(filename, "pipe:", &p)) {
2958 return qemu_chr_open_pipe(p);
2959 } else if (!strcmp(filename, "pty")) {
2960 return qemu_chr_open_pty();
2961 } else if (!strcmp(filename, "stdio")) {
2962 return qemu_chr_open_stdio();
2963 } else
2964 #endif
2965 #if defined(__linux__)
2966 if (strstart(filename, "/dev/parport", NULL)) {
2967 return qemu_chr_open_pp(filename);
2968 } else
2969 if (strstart(filename, "/dev/", NULL)) {
2970 return qemu_chr_open_tty(filename);
2971 } else
2972 #endif
2973 #ifdef _WIN32
2974 if (strstart(filename, "COM", NULL)) {
2975 return qemu_chr_open_win(filename);
2976 } else
2977 if (strstart(filename, "pipe:", &p)) {
2978 return qemu_chr_open_win_pipe(p);
2979 } else
2980 if (strstart(filename, "file:", &p)) {
2981 return qemu_chr_open_win_file_out(p);
2983 #endif
2985 return NULL;
2989 void qemu_chr_close(CharDriverState *chr)
2991 if (chr->chr_close)
2992 chr->chr_close(chr);
2995 /***********************************************************/
2996 /* network device redirectors */
2998 void hex_dump(FILE *f, const uint8_t *buf, int size)
3000 int len, i, j, c;
3002 for(i=0;i<size;i+=16) {
3003 len = size - i;
3004 if (len > 16)
3005 len = 16;
3006 fprintf(f, "%08x ", i);
3007 for(j=0;j<16;j++) {
3008 if (j < len)
3009 fprintf(f, " %02x", buf[i+j]);
3010 else
3011 fprintf(f, " ");
3013 fprintf(f, " ");
3014 for(j=0;j<len;j++) {
3015 c = buf[i+j];
3016 if (c < ' ' || c > '~')
3017 c = '.';
3018 fprintf(f, "%c", c);
3020 fprintf(f, "\n");
3024 static int parse_macaddr(uint8_t *macaddr, const char *p)
3026 int i;
3027 for(i = 0; i < 6; i++) {
3028 macaddr[i] = strtol(p, (char **)&p, 16);
3029 if (i == 5) {
3030 if (*p != '\0')
3031 return -1;
3032 } else {
3033 if (*p != ':')
3034 return -1;
3035 p++;
3038 return 0;
3041 static int get_str_sep(char *buf, size_t buf_size, const char **pp, int sep)
3043 const char *p, *p1;
3044 int len;
3045 p = *pp;
3046 p1 = strchr(p, sep);
3047 if (!p1)
3048 return -1;
3049 len = p1 - p;
3050 p1++;
3051 if (buf_size > 0) {
3052 if (len > buf_size - 1)
3053 len = buf_size - 1;
3054 memcpy(buf, p, len);
3055 buf[len] = '\0';
3057 *pp = p1;
3058 return 0;
3061 int parse_host_src_port(struct sockaddr_in *haddr,
3062 struct sockaddr_in *saddr,
3063 const char *input_str)
3065 char *str = strdup(input_str);
3066 char *host_str = str;
3067 char *src_str;
3068 char *ptr;
3070 /*
3071 * Chop off any extra arguments at the end of the string which
3072 * would start with a comma, then fill in the src port information
3073 * if it was provided else use the "any address" and "any port".
3074 */
3075 if ((ptr = strchr(str,',')))
3076 *ptr = '\0';
3078 if ((src_str = strchr(input_str,'@'))) {
3079 *src_str = '\0';
3080 src_str++;
3083 if (parse_host_port(haddr, host_str) < 0)
3084 goto fail;
3086 if (!src_str || *src_str == '\0')
3087 src_str = ":0";
3089 if (parse_host_port(saddr, src_str) < 0)
3090 goto fail;
3092 free(str);
3093 return(0);
3095 fail:
3096 free(str);
3097 return -1;
3100 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3102 char buf[512];
3103 struct hostent *he;
3104 const char *p, *r;
3105 int port;
3107 p = str;
3108 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3109 return -1;
3110 saddr->sin_family = AF_INET;
3111 if (buf[0] == '\0') {
3112 saddr->sin_addr.s_addr = 0;
3113 } else {
3114 if (isdigit((uint8_t)buf[0])) {
3115 if (!inet_aton(buf, &saddr->sin_addr))
3116 return -1;
3117 } else {
3118 if ((he = gethostbyname(buf)) == NULL)
3119 return - 1;
3120 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3123 port = strtol(p, (char **)&r, 0);
3124 if (r == p)
3125 return -1;
3126 saddr->sin_port = htons(port);
3127 return 0;
3130 #ifndef _WIN32
3131 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3133 const char *p;
3134 int len;
3136 len = MIN(108, strlen(str));
3137 p = strchr(str, ',');
3138 if (p)
3139 len = MIN(len, p - str);
3141 memset(uaddr, 0, sizeof(*uaddr));
3143 uaddr->sun_family = AF_UNIX;
3144 memcpy(uaddr->sun_path, str, len);
3146 return 0;
3148 #endif
3150 /* find or alloc a new VLAN */
3151 VLANState *qemu_find_vlan(int id)
3153 VLANState **pvlan, *vlan;
3154 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3155 if (vlan->id == id)
3156 return vlan;
3158 vlan = qemu_mallocz(sizeof(VLANState));
3159 if (!vlan)
3160 return NULL;
3161 vlan->id = id;
3162 vlan->next = NULL;
3163 pvlan = &first_vlan;
3164 while (*pvlan != NULL)
3165 pvlan = &(*pvlan)->next;
3166 *pvlan = vlan;
3167 return vlan;
3170 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3171 IOReadHandler *fd_read,
3172 IOCanRWHandler *fd_can_read,
3173 void *opaque)
3175 VLANClientState *vc, **pvc;
3176 vc = qemu_mallocz(sizeof(VLANClientState));
3177 if (!vc)
3178 return NULL;
3179 vc->fd_read = fd_read;
3180 vc->fd_can_read = fd_can_read;
3181 vc->opaque = opaque;
3182 vc->vlan = vlan;
3184 vc->next = NULL;
3185 pvc = &vlan->first_client;
3186 while (*pvc != NULL)
3187 pvc = &(*pvc)->next;
3188 *pvc = vc;
3189 return vc;
3192 int qemu_can_send_packet(VLANClientState *vc1)
3194 VLANState *vlan = vc1->vlan;
3195 VLANClientState *vc;
3197 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3198 if (vc != vc1) {
3199 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3200 return 0;
3203 return 1;
3206 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3208 VLANState *vlan = vc1->vlan;
3209 VLANClientState *vc;
3211 #if 0
3212 printf("vlan %d send:\n", vlan->id);
3213 hex_dump(stdout, buf, size);
3214 #endif
3215 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3216 if (vc != vc1) {
3217 vc->fd_read(vc->opaque, buf, size);
3222 #if defined(CONFIG_SLIRP)
3224 /* slirp network adapter */
3226 static int slirp_inited;
3227 static VLANClientState *slirp_vc;
3229 int slirp_can_output(void)
3231 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3234 void slirp_output(const uint8_t *pkt, int pkt_len)
3236 #if 0
3237 printf("slirp output:\n");
3238 hex_dump(stdout, pkt, pkt_len);
3239 #endif
3240 if (!slirp_vc)
3241 return;
3242 qemu_send_packet(slirp_vc, pkt, pkt_len);
3245 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3247 #if 0
3248 printf("slirp input:\n");
3249 hex_dump(stdout, buf, size);
3250 #endif
3251 slirp_input(buf, size);
3254 static int net_slirp_init(VLANState *vlan)
3256 if (!slirp_inited) {
3257 slirp_inited = 1;
3258 slirp_init();
3260 slirp_vc = qemu_new_vlan_client(vlan,
3261 slirp_receive, NULL, NULL);
3262 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3263 return 0;
3266 static void net_slirp_redir(const char *redir_str)
3268 int is_udp;
3269 char buf[256], *r;
3270 const char *p;
3271 struct in_addr guest_addr;
3272 int host_port, guest_port;
3274 if (!slirp_inited) {
3275 slirp_inited = 1;
3276 slirp_init();
3279 p = redir_str;
3280 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3281 goto fail;
3282 if (!strcmp(buf, "tcp")) {
3283 is_udp = 0;
3284 } else if (!strcmp(buf, "udp")) {
3285 is_udp = 1;
3286 } else {
3287 goto fail;
3290 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3291 goto fail;
3292 host_port = strtol(buf, &r, 0);
3293 if (r == buf)
3294 goto fail;
3296 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3297 goto fail;
3298 if (buf[0] == '\0') {
3299 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3301 if (!inet_aton(buf, &guest_addr))
3302 goto fail;
3304 guest_port = strtol(p, &r, 0);
3305 if (r == p)
3306 goto fail;
3308 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3309 fprintf(stderr, "qemu: could not set up redirection\n");
3310 exit(1);
3312 return;
3313 fail:
3314 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3315 exit(1);
3318 #ifndef _WIN32
3320 char smb_dir[1024];
3322 static void smb_exit(void)
3324 DIR *d;
3325 struct dirent *de;
3326 char filename[1024];
3328 /* erase all the files in the directory */
3329 d = opendir(smb_dir);
3330 for(;;) {
3331 de = readdir(d);
3332 if (!de)
3333 break;
3334 if (strcmp(de->d_name, ".") != 0 &&
3335 strcmp(de->d_name, "..") != 0) {
3336 snprintf(filename, sizeof(filename), "%s/%s",
3337 smb_dir, de->d_name);
3338 unlink(filename);
3341 closedir(d);
3342 rmdir(smb_dir);
3345 /* automatic user mode samba server configuration */
3346 void net_slirp_smb(const char *exported_dir)
3348 char smb_conf[1024];
3349 char smb_cmdline[1024];
3350 FILE *f;
3352 if (!slirp_inited) {
3353 slirp_inited = 1;
3354 slirp_init();
3357 /* XXX: better tmp dir construction */
3358 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3359 if (mkdir(smb_dir, 0700) < 0) {
3360 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3361 exit(1);
3363 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3365 f = fopen(smb_conf, "w");
3366 if (!f) {
3367 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3368 exit(1);
3370 fprintf(f,
3371 "[global]\n"
3372 "private dir=%s\n"
3373 "smb ports=0\n"
3374 "socket address=127.0.0.1\n"
3375 "pid directory=%s\n"
3376 "lock directory=%s\n"
3377 "log file=%s/log.smbd\n"
3378 "smb passwd file=%s/smbpasswd\n"
3379 "security = share\n"
3380 "[qemu]\n"
3381 "path=%s\n"
3382 "read only=no\n"
3383 "guest ok=yes\n",
3384 smb_dir,
3385 smb_dir,
3386 smb_dir,
3387 smb_dir,
3388 smb_dir,
3389 exported_dir
3390 );
3391 fclose(f);
3392 atexit(smb_exit);
3394 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3395 SMBD_COMMAND, smb_conf);
3397 slirp_add_exec(0, smb_cmdline, 4, 139);
3400 #endif /* !defined(_WIN32) */
3402 #endif /* CONFIG_SLIRP */
3404 #if !defined(_WIN32)
3406 typedef struct TAPState {
3407 VLANClientState *vc;
3408 int fd;
3409 } TAPState;
3411 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3413 TAPState *s = opaque;
3414 int ret;
3415 for(;;) {
3416 ret = write(s->fd, buf, size);
3417 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3418 } else {
3419 break;
3424 static void tap_send(void *opaque)
3426 TAPState *s = opaque;
3427 uint8_t buf[4096];
3428 int size;
3430 size = read(s->fd, buf, sizeof(buf));
3431 if (size > 0) {
3432 qemu_send_packet(s->vc, buf, size);
3436 /* fd support */
3438 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3440 TAPState *s;
3442 s = qemu_mallocz(sizeof(TAPState));
3443 if (!s)
3444 return NULL;
3445 s->fd = fd;
3446 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3447 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3448 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3449 return s;
3452 #ifdef _BSD
3453 static int tap_open(char *ifname, int ifname_size)
3455 int fd;
3456 #ifndef TAPGIFNAME
3457 char *dev;
3458 struct stat s;
3459 #endif
3460 struct ifreq ifr;
3462 fd = open("/dev/tap", O_RDWR);
3463 if (fd < 0) {
3464 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation %s\n", strerror(errno));
3465 return -1;
3468 #ifdef TAPGIFNAME
3469 if (ioctl (fd, TAPGIFNAME, (void*)&ifr) < 0) {
3470 fprintf(stderr, "warning: could not open get tap name: %s\n",
3471 strerror(errno));
3472 return -1;
3474 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3475 #else
3476 fstat(fd, &s);
3477 dev = devname(s.st_rdev, S_IFCHR);
3478 pstrcpy(ifname, ifname_size, dev);
3479 #endif
3481 fcntl(fd, F_SETFL, O_NONBLOCK);
3482 return fd;
3484 #elif defined(__sun__)
3485 static int tap_open(char *ifname, int ifname_size)
3487 fprintf(stderr, "warning: tap_open not yet implemented\n");
3488 return -1;
3490 #else
3491 static int tap_open(char *ifname, int ifname_size)
3493 struct ifreq ifr;
3494 int fd, ret, retries = 0;
3496 fd = open("/dev/net/tun", O_RDWR);
3497 if (fd < 0) {
3498 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3499 return -1;
3501 memset(&ifr, 0, sizeof(ifr));
3502 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3503 if (ifname[0] != '\0')
3504 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3505 else
3506 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3507 do {
3508 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3509 } while ((ret != 0) && (retries++ < 3));
3510 if (ret != 0) {
3511 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3512 close(fd);
3513 return -1;
3515 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3516 fcntl(fd, F_SETFL, O_NONBLOCK);
3517 return fd;
3519 #endif
3521 static int net_tap_init(VLANState *vlan, const char *ifname1,
3522 const char *setup_script, const char *bridge)
3524 TAPState *s;
3525 int pid, status, fd;
3526 char *args[4];
3527 char **parg;
3528 char ifname[128];
3530 memset(ifname, 0, sizeof(ifname));
3532 if (ifname1 != NULL)
3533 pstrcpy(ifname, sizeof(ifname), ifname1);
3534 else
3535 ifname[0] = '\0';
3536 fd = tap_open(ifname, sizeof(ifname));
3537 if (fd < 0)
3538 return -1;
3540 if (!setup_script || !strcmp(setup_script, "no"))
3541 setup_script = "";
3542 if (setup_script[0] != '\0') {
3543 /* try to launch network init script */
3544 pid = fork();
3545 if (pid >= 0) {
3546 if (pid == 0) {
3547 int open_max = sysconf(_SC_OPEN_MAX), i;
3548 for (i = 0; i < open_max; i++)
3549 if (i != STDIN_FILENO &&
3550 i != STDOUT_FILENO &&
3551 i != STDERR_FILENO &&
3552 i != fd)
3553 close(i);
3555 parg = args;
3556 *parg++ = (char *)setup_script;
3557 *parg++ = ifname;
3558 *parg++ = (char *)bridge;
3559 *parg++ = NULL;
3560 execv(setup_script, args);
3561 _exit(1);
3563 while (waitpid(pid, &status, 0) != pid);
3564 if (!WIFEXITED(status) ||
3565 WEXITSTATUS(status) != 0) {
3566 fprintf(stderr, "%s: could not launch network script\n",
3567 setup_script);
3568 return -1;
3572 s = net_tap_fd_init(vlan, fd);
3573 if (!s)
3574 return -1;
3575 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3576 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3577 return 0;
3580 #endif /* !_WIN32 */
3582 /* network connection */
3583 typedef struct NetSocketState {
3584 VLANClientState *vc;
3585 int fd;
3586 int state; /* 0 = getting length, 1 = getting data */
3587 int index;
3588 int packet_len;
3589 uint8_t buf[4096];
3590 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3591 } NetSocketState;
3593 typedef struct NetSocketListenState {
3594 VLANState *vlan;
3595 int fd;
3596 } NetSocketListenState;
3598 /* XXX: we consider we can send the whole packet without blocking */
3599 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3601 NetSocketState *s = opaque;
3602 uint32_t len;
3603 len = htonl(size);
3605 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3606 send_all(s->fd, buf, size);
3609 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3611 NetSocketState *s = opaque;
3612 sendto(s->fd, buf, size, 0,
3613 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3616 static void net_socket_send(void *opaque)
3618 NetSocketState *s = opaque;
3619 int l, size, err;
3620 uint8_t buf1[4096];
3621 const uint8_t *buf;
3623 size = recv(s->fd, buf1, sizeof(buf1), 0);
3624 if (size < 0) {
3625 err = socket_error();
3626 if (err != EWOULDBLOCK)
3627 goto eoc;
3628 } else if (size == 0) {
3629 /* end of connection */
3630 eoc:
3631 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3632 closesocket(s->fd);
3633 return;
3635 buf = buf1;
3636 while (size > 0) {
3637 /* reassemble a packet from the network */
3638 switch(s->state) {
3639 case 0:
3640 l = 4 - s->index;
3641 if (l > size)
3642 l = size;
3643 memcpy(s->buf + s->index, buf, l);
3644 buf += l;
3645 size -= l;
3646 s->index += l;
3647 if (s->index == 4) {
3648 /* got length */
3649 s->packet_len = ntohl(*(uint32_t *)s->buf);
3650 s->index = 0;
3651 s->state = 1;
3653 break;
3654 case 1:
3655 l = s->packet_len - s->index;
3656 if (l > size)
3657 l = size;
3658 memcpy(s->buf + s->index, buf, l);
3659 s->index += l;
3660 buf += l;
3661 size -= l;
3662 if (s->index >= s->packet_len) {
3663 qemu_send_packet(s->vc, s->buf, s->packet_len);
3664 s->index = 0;
3665 s->state = 0;
3667 break;
3672 static void net_socket_send_dgram(void *opaque)
3674 NetSocketState *s = opaque;
3675 int size;
3677 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3678 if (size < 0)
3679 return;
3680 if (size == 0) {
3681 /* end of connection */
3682 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3683 return;
3685 qemu_send_packet(s->vc, s->buf, size);
3688 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3690 struct ip_mreq imr;
3691 int fd;
3692 int val, ret;
3693 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3694 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3695 inet_ntoa(mcastaddr->sin_addr),
3696 (int)ntohl(mcastaddr->sin_addr.s_addr));
3697 return -1;
3700 fd = socket(PF_INET, SOCK_DGRAM, 0);
3701 if (fd < 0) {
3702 perror("socket(PF_INET, SOCK_DGRAM)");
3703 return -1;
3706 val = 1;
3707 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3708 (const char *)&val, sizeof(char));
3709 if (ret < 0) {
3710 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3711 goto fail;
3714 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3715 if (ret < 0) {
3716 perror("bind");
3717 goto fail;
3720 /* Add host to multicast group */
3721 imr.imr_multiaddr = mcastaddr->sin_addr;
3722 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3724 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3725 (const char *)&imr, sizeof(struct ip_mreq));
3726 if (ret < 0) {
3727 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3728 goto fail;
3731 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3732 val = 1;
3733 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3734 (const char *)&val, sizeof(val));
3735 if (ret < 0) {
3736 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3737 goto fail;
3740 socket_set_nonblock(fd);
3741 return fd;
3742 fail:
3743 if (fd >= 0)
3744 closesocket(fd);
3745 return -1;
3748 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3749 int is_connected)
3751 struct sockaddr_in saddr;
3752 int newfd;
3753 socklen_t saddr_len;
3754 NetSocketState *s;
3756 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3757 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3758 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3759 */
3761 if (is_connected) {
3762 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3763 /* must be bound */
3764 if (saddr.sin_addr.s_addr==0) {
3765 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3766 fd);
3767 return NULL;
3769 /* clone dgram socket */
3770 newfd = net_socket_mcast_create(&saddr);
3771 if (newfd < 0) {
3772 /* error already reported by net_socket_mcast_create() */
3773 close(fd);
3774 return NULL;
3776 /* clone newfd to fd, close newfd */
3777 dup2(newfd, fd);
3778 close(newfd);
3780 } else {
3781 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3782 fd, strerror(errno));
3783 return NULL;
3787 s = qemu_mallocz(sizeof(NetSocketState));
3788 if (!s)
3789 return NULL;
3790 s->fd = fd;
3792 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3793 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3795 /* mcast: save bound address as dst */
3796 if (is_connected) s->dgram_dst=saddr;
3798 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3799 "socket: fd=%d (%s mcast=%s:%d)",
3800 fd, is_connected? "cloned" : "",
3801 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3802 return s;
3805 static void net_socket_connect(void *opaque)
3807 NetSocketState *s = opaque;
3808 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3811 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3812 int is_connected)
3814 NetSocketState *s;
3815 s = qemu_mallocz(sizeof(NetSocketState));
3816 if (!s)
3817 return NULL;
3818 s->fd = fd;
3819 s->vc = qemu_new_vlan_client(vlan,
3820 net_socket_receive, NULL, s);
3821 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3822 "socket: fd=%d", fd);
3823 if (is_connected) {
3824 net_socket_connect(s);
3825 } else {
3826 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3828 return s;
3831 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3832 int is_connected)
3834 int so_type=-1, optlen=sizeof(so_type);
3836 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3837 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3838 return NULL;
3840 switch(so_type) {
3841 case SOCK_DGRAM:
3842 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3843 case SOCK_STREAM:
3844 return net_socket_fd_init_stream(vlan, fd, is_connected);
3845 default:
3846 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3847 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3848 return net_socket_fd_init_stream(vlan, fd, is_connected);
3850 return NULL;
3853 static void net_socket_accept(void *opaque)
3855 NetSocketListenState *s = opaque;
3856 NetSocketState *s1;
3857 struct sockaddr_in saddr;
3858 socklen_t len;
3859 int fd;
3861 for(;;) {
3862 len = sizeof(saddr);
3863 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3864 if (fd < 0 && errno != EINTR) {
3865 return;
3866 } else if (fd >= 0) {
3867 break;
3870 s1 = net_socket_fd_init(s->vlan, fd, 1);
3871 if (!s1) {
3872 closesocket(fd);
3873 } else {
3874 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3875 "socket: connection from %s:%d",
3876 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3880 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3882 NetSocketListenState *s;
3883 int fd, val, ret;
3884 struct sockaddr_in saddr;
3886 if (parse_host_port(&saddr, host_str) < 0)
3887 return -1;
3889 s = qemu_mallocz(sizeof(NetSocketListenState));
3890 if (!s)
3891 return -1;
3893 fd = socket(PF_INET, SOCK_STREAM, 0);
3894 if (fd < 0) {
3895 perror("socket");
3896 return -1;
3898 socket_set_nonblock(fd);
3900 /* allow fast reuse */
3901 val = 1;
3902 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3904 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3905 if (ret < 0) {
3906 perror("bind");
3907 return -1;
3909 ret = listen(fd, 0);
3910 if (ret < 0) {
3911 perror("listen");
3912 return -1;
3914 s->vlan = vlan;
3915 s->fd = fd;
3916 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3917 return 0;
3920 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3922 NetSocketState *s;
3923 int fd, connected, ret, err;
3924 struct sockaddr_in saddr;
3926 if (parse_host_port(&saddr, host_str) < 0)
3927 return -1;
3929 fd = socket(PF_INET, SOCK_STREAM, 0);
3930 if (fd < 0) {
3931 perror("socket");
3932 return -1;
3934 socket_set_nonblock(fd);
3936 connected = 0;
3937 for(;;) {
3938 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3939 if (ret < 0) {
3940 err = socket_error();
3941 if (err == EINTR || err == EWOULDBLOCK) {
3942 } else if (err == EINPROGRESS) {
3943 break;
3944 } else {
3945 perror("connect");
3946 closesocket(fd);
3947 return -1;
3949 } else {
3950 connected = 1;
3951 break;
3954 s = net_socket_fd_init(vlan, fd, connected);
3955 if (!s)
3956 return -1;
3957 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3958 "socket: connect to %s:%d",
3959 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3960 return 0;
3963 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3965 NetSocketState *s;
3966 int fd;
3967 struct sockaddr_in saddr;
3969 if (parse_host_port(&saddr, host_str) < 0)
3970 return -1;
3973 fd = net_socket_mcast_create(&saddr);
3974 if (fd < 0)
3975 return -1;
3977 s = net_socket_fd_init(vlan, fd, 0);
3978 if (!s)
3979 return -1;
3981 s->dgram_dst = saddr;
3983 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3984 "socket: mcast=%s:%d",
3985 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3986 return 0;
3990 static int get_param_value(char *buf, size_t buf_size,
3991 const char *tag, const char *str)
3993 const char *p;
3994 char *q;
3995 char option[128];
3997 p = str;
3998 for(;;) {
3999 q = option;
4000 while (*p != '\0' && *p != '=') {
4001 if ((q - option) < sizeof(option) - 1)
4002 *q++ = *p;
4003 p++;
4005 *q = '\0';
4006 if (*p != '=')
4007 break;
4008 p++;
4009 if (!strcmp(tag, option)) {
4010 q = buf;
4011 while (*p != '\0' && *p != ',') {
4012 if ((q - buf) < buf_size - 1)
4013 *q++ = *p;
4014 p++;
4016 *q = '\0';
4017 return q - buf;
4018 } else {
4019 while (*p != '\0' && *p != ',') {
4020 p++;
4023 if (*p != ',')
4024 break;
4025 p++;
4027 return 0;
4030 static int net_client_init(const char *str)
4032 const char *p;
4033 char *q;
4034 char device[64];
4035 char buf[1024];
4036 int vlan_id, ret;
4037 VLANState *vlan;
4039 p = str;
4040 q = device;
4041 while (*p != '\0' && *p != ',') {
4042 if ((q - device) < sizeof(device) - 1)
4043 *q++ = *p;
4044 p++;
4046 *q = '\0';
4047 if (*p == ',')
4048 p++;
4049 vlan_id = 0;
4050 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4051 vlan_id = strtol(buf, NULL, 0);
4053 vlan = qemu_find_vlan(vlan_id);
4054 if (!vlan) {
4055 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4056 return -1;
4058 if (!strcmp(device, "nic")) {
4059 NICInfo *nd;
4060 uint8_t *macaddr;
4062 if (nb_nics < MAX_NICS) {
4063 nd = &nd_table[nb_nics];
4064 macaddr = nd->macaddr;
4065 macaddr[0] = 0x52;
4066 macaddr[1] = 0x54;
4067 macaddr[2] = 0x00;
4068 macaddr[3] = 0x12;
4069 macaddr[4] = 0x34;
4070 macaddr[5] = 0x56 + nb_nics;
4072 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4073 if (parse_macaddr(macaddr, buf) < 0) {
4074 fprintf(stderr, "invalid syntax for ethernet address\n");
4075 return -1;
4078 if (get_param_value(buf, sizeof(buf), "model", p)) {
4079 nd->model = strdup(buf);
4081 nd->vlan = vlan;
4082 nb_nics++;
4083 } else {
4084 fprintf(stderr, "Too Many NICs\n");
4086 ret = 0;
4087 } else
4088 if (!strcmp(device, "none")) {
4089 /* does nothing. It is needed to signal that no network cards
4090 are wanted */
4091 ret = 0;
4092 } else
4093 #ifdef CONFIG_SLIRP
4094 if (!strcmp(device, "user")) {
4095 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4096 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4098 ret = net_slirp_init(vlan);
4099 } else
4100 #endif
4101 #ifdef _WIN32
4102 if (!strcmp(device, "tap")) {
4103 char ifname[64];
4104 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4105 fprintf(stderr, "tap: no interface name\n");
4106 return -1;
4108 ret = tap_win32_init(vlan, ifname);
4109 } else
4110 #else
4111 if (!strcmp(device, "tap")) {
4112 char ifname[64];
4113 char setup_script[1024];
4114 char bridge[16];
4115 int fd;
4117 memset(ifname, 0, sizeof(ifname));
4118 memset(setup_script, 0, sizeof(setup_script));
4120 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4121 fd = strtol(buf, NULL, 0);
4122 ret = -1;
4123 if (net_tap_fd_init(vlan, fd))
4124 ret = 0;
4125 } else {
4126 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4127 ifname[0] = '\0';
4129 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4130 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4132 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
4133 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
4135 ret = net_tap_init(vlan, ifname, setup_script, bridge);
4137 } else
4138 #endif
4139 if (!strcmp(device, "socket")) {
4140 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4141 int fd;
4142 fd = strtol(buf, NULL, 0);
4143 ret = -1;
4144 if (net_socket_fd_init(vlan, fd, 1))
4145 ret = 0;
4146 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4147 ret = net_socket_listen_init(vlan, buf);
4148 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4149 ret = net_socket_connect_init(vlan, buf);
4150 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4151 ret = net_socket_mcast_init(vlan, buf);
4152 } else {
4153 fprintf(stderr, "Unknown socket options: %s\n", p);
4154 return -1;
4156 } else
4158 fprintf(stderr, "Unknown network device: %s\n", device);
4159 return -1;
4161 if (ret < 0) {
4162 fprintf(stderr, "Could not initialize device '%s'\n", device);
4165 return ret;
4168 void do_info_network(void)
4170 VLANState *vlan;
4171 VLANClientState *vc;
4173 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4174 term_printf("VLAN %d devices:\n", vlan->id);
4175 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4176 term_printf(" %s\n", vc->info_str);
4180 /***********************************************************/
4181 /* USB devices */
4183 static USBPort *used_usb_ports;
4184 static USBPort *free_usb_ports;
4186 /* ??? Maybe change this to register a hub to keep track of the topology. */
4187 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4188 usb_attachfn attach)
4190 port->opaque = opaque;
4191 port->index = index;
4192 port->attach = attach;
4193 port->next = free_usb_ports;
4194 free_usb_ports = port;
4197 static int usb_device_add(const char *devname)
4199 const char *p;
4200 USBDevice *dev;
4201 USBPort *port;
4202 char usb_name[256] = "USB ";
4204 if (!free_usb_ports)
4205 return -1;
4207 if (strstart(devname, "host:", &p)) {
4208 dev = usb_host_device_open(p);
4209 } else if (!strcmp(devname, "mouse")) {
4210 dev = usb_mouse_init();
4211 } else if (!strcmp(devname, "tablet")) {
4212 dev = usb_tablet_init();
4213 } else if (strstart(devname, "disk:", &p)) {
4214 dev = usb_msd_init(p);
4215 } else {
4216 return -1;
4218 if (!dev)
4219 return -1;
4221 /* Find a USB port to add the device to. */
4222 port = free_usb_ports;
4223 if (!port->next) {
4224 USBDevice *hub;
4226 /* Create a new hub and chain it on. */
4227 free_usb_ports = NULL;
4228 port->next = used_usb_ports;
4229 used_usb_ports = port;
4231 hub = usb_hub_init(VM_USB_HUB_SIZE);
4232 usb_attach(port, hub);
4233 port = free_usb_ports;
4236 free_usb_ports = port->next;
4237 port->next = used_usb_ports;
4238 used_usb_ports = port;
4240 pstrcpy(usb_name + strlen(usb_name),
4241 sizeof(usb_name) - strlen(usb_name),
4242 devname);
4243 register_savevm(usb_name, 0, 1, generic_usb_save, generic_usb_load, dev);
4245 usb_attach(port, dev);
4246 return 0;
4249 static int usb_device_del(const char *devname)
4251 USBPort *port;
4252 USBPort **lastp;
4253 USBDevice *dev;
4254 int bus_num, addr;
4255 const char *p;
4257 if (!used_usb_ports)
4258 return -1;
4260 p = strchr(devname, '.');
4261 if (!p)
4262 return -1;
4263 bus_num = strtoul(devname, NULL, 0);
4264 addr = strtoul(p + 1, NULL, 0);
4265 if (bus_num != 0)
4266 return -1;
4268 lastp = &used_usb_ports;
4269 port = used_usb_ports;
4270 while (port && port->dev->addr != addr) {
4271 lastp = &port->next;
4272 port = port->next;
4275 if (!port)
4276 return -1;
4278 dev = port->dev;
4279 *lastp = port->next;
4280 usb_attach(port, NULL);
4281 dev->handle_destroy(dev);
4282 port->next = free_usb_ports;
4283 free_usb_ports = port;
4284 return 0;
4287 void do_usb_add(const char *devname)
4289 int ret;
4290 ret = usb_device_add(devname);
4291 if (ret < 0)
4292 term_printf("Could not add USB device '%s'\n", devname);
4295 void do_usb_del(const char *devname)
4297 int ret;
4298 ret = usb_device_del(devname);
4299 if (ret < 0)
4300 term_printf("Could not remove USB device '%s'\n", devname);
4303 void usb_info(void)
4305 USBDevice *dev;
4306 USBPort *port;
4307 const char *speed_str;
4309 if (!usb_enabled) {
4310 term_printf("USB support not enabled\n");
4311 return;
4314 for (port = used_usb_ports; port; port = port->next) {
4315 dev = port->dev;
4316 if (!dev)
4317 continue;
4318 switch(dev->speed) {
4319 case USB_SPEED_LOW:
4320 speed_str = "1.5";
4321 break;
4322 case USB_SPEED_FULL:
4323 speed_str = "12";
4324 break;
4325 case USB_SPEED_HIGH:
4326 speed_str = "480";
4327 break;
4328 default:
4329 speed_str = "?";
4330 break;
4332 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4333 0, dev->addr, speed_str, dev->devname);
4337 /***********************************************************/
4338 /* pid file */
4340 static char *pid_filename;
4342 /* Remove PID file. Called on normal exit */
4344 static void remove_pidfile(void)
4346 unlink (pid_filename);
4349 static void create_pidfile(const char *filename)
4351 struct stat pidstat;
4352 FILE *f;
4354 /* Try to write our PID to the named file */
4355 if (stat(filename, &pidstat) < 0) {
4356 if (errno == ENOENT) {
4357 if ((f = fopen (filename, "w")) == NULL) {
4358 perror("Opening pidfile");
4359 exit(1);
4361 fprintf(f, "%ld\n", (long)getpid());
4362 fclose(f);
4363 pid_filename = qemu_strdup(filename);
4364 if (!pid_filename) {
4365 fprintf(stderr, "Could not save PID filename");
4366 exit(1);
4368 atexit(remove_pidfile);
4370 } else {
4371 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4372 filename);
4373 exit(1);
4377 /***********************************************************/
4378 /* dumb display */
4380 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4384 static void dumb_resize(DisplayState *ds, int w, int h)
4388 static void dumb_refresh(DisplayState *ds)
4390 vga_hw_update();
4393 void dumb_display_init(DisplayState *ds)
4395 ds->data = NULL;
4396 ds->linesize = 0;
4397 ds->depth = 0;
4398 ds->dpy_update = dumb_update;
4399 ds->dpy_resize = dumb_resize;
4400 ds->dpy_refresh = dumb_refresh;
4403 /***********************************************************/
4404 /* I/O handling */
4406 #define MAX_IO_HANDLERS 64
4408 typedef struct IOHandlerRecord {
4409 int fd;
4410 IOCanRWHandler *fd_read_poll;
4411 IOHandler *fd_read;
4412 IOHandler *fd_write;
4413 int deleted;
4414 void *opaque;
4415 /* temporary data */
4416 struct pollfd *ufd;
4417 struct IOHandlerRecord *next;
4418 } IOHandlerRecord;
4420 static IOHandlerRecord *first_io_handler;
4422 /* XXX: fd_read_poll should be suppressed, but an API change is
4423 necessary in the character devices to suppress fd_can_read(). */
4424 int qemu_set_fd_handler2(int fd,
4425 IOCanRWHandler *fd_read_poll,
4426 IOHandler *fd_read,
4427 IOHandler *fd_write,
4428 void *opaque)
4430 IOHandlerRecord **pioh, *ioh;
4432 if (!fd_read && !fd_write) {
4433 pioh = &first_io_handler;
4434 for(;;) {
4435 ioh = *pioh;
4436 if (ioh == NULL)
4437 break;
4438 if (ioh->fd == fd) {
4439 ioh->deleted = 1;
4440 break;
4442 pioh = &ioh->next;
4444 } else {
4445 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4446 if (ioh->fd == fd)
4447 goto found;
4449 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4450 if (!ioh)
4451 return -1;
4452 ioh->next = first_io_handler;
4453 first_io_handler = ioh;
4454 found:
4455 ioh->fd = fd;
4456 ioh->fd_read_poll = fd_read_poll;
4457 ioh->fd_read = fd_read;
4458 ioh->fd_write = fd_write;
4459 ioh->opaque = opaque;
4460 ioh->deleted = 0;
4462 return 0;
4465 int qemu_set_fd_handler(int fd,
4466 IOHandler *fd_read,
4467 IOHandler *fd_write,
4468 void *opaque)
4470 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4473 /***********************************************************/
4474 /* Polling handling */
4476 typedef struct PollingEntry {
4477 PollingFunc *func;
4478 void *opaque;
4479 struct PollingEntry *next;
4480 } PollingEntry;
4482 static PollingEntry *first_polling_entry;
4484 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4486 PollingEntry **ppe, *pe;
4487 pe = qemu_mallocz(sizeof(PollingEntry));
4488 if (!pe)
4489 return -1;
4490 pe->func = func;
4491 pe->opaque = opaque;
4492 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4493 *ppe = pe;
4494 return 0;
4497 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4499 PollingEntry **ppe, *pe;
4500 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4501 pe = *ppe;
4502 if (pe->func == func && pe->opaque == opaque) {
4503 *ppe = pe->next;
4504 qemu_free(pe);
4505 break;
4510 #ifdef _WIN32
4511 /***********************************************************/
4512 /* Wait objects support */
4513 typedef struct WaitObjects {
4514 int num;
4515 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4516 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4517 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4518 } WaitObjects;
4520 static WaitObjects wait_objects = {0};
4522 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4524 WaitObjects *w = &wait_objects;
4526 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4527 return -1;
4528 w->events[w->num] = handle;
4529 w->func[w->num] = func;
4530 w->opaque[w->num] = opaque;
4531 w->num++;
4532 return 0;
4535 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4537 int i, found;
4538 WaitObjects *w = &wait_objects;
4540 found = 0;
4541 for (i = 0; i < w->num; i++) {
4542 if (w->events[i] == handle)
4543 found = 1;
4544 if (found) {
4545 w->events[i] = w->events[i + 1];
4546 w->func[i] = w->func[i + 1];
4547 w->opaque[i] = w->opaque[i + 1];
4550 if (found)
4551 w->num--;
4553 #endif
4555 /***********************************************************/
4556 /* savevm/loadvm support */
4558 #define IO_BUF_SIZE 32768
4560 struct QEMUFile {
4561 FILE *outfile;
4562 BlockDriverState *bs;
4563 int is_file;
4564 int is_writable;
4565 int64_t base_offset;
4566 int64_t buf_offset; /* start of buffer when writing, end of buffer
4567 when reading */
4568 int buf_index;
4569 int buf_size; /* 0 when writing */
4570 uint8_t buf[IO_BUF_SIZE];
4571 };
4573 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4575 QEMUFile *f;
4577 f = qemu_mallocz(sizeof(QEMUFile));
4578 if (!f)
4579 return NULL;
4580 if (!strcmp(mode, "wb")) {
4581 f->is_writable = 1;
4582 } else if (!strcmp(mode, "rb")) {
4583 f->is_writable = 0;
4584 } else {
4585 goto fail;
4587 f->outfile = fopen(filename, mode);
4588 if (!f->outfile)
4589 goto fail;
4590 f->is_file = 1;
4591 return f;
4592 fail:
4593 if (f->outfile)
4594 fclose(f->outfile);
4595 qemu_free(f);
4596 return NULL;
4599 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4601 QEMUFile *f;
4603 f = qemu_mallocz(sizeof(QEMUFile));
4604 if (!f)
4605 return NULL;
4606 f->is_file = 0;
4607 f->bs = bs;
4608 f->is_writable = is_writable;
4609 f->base_offset = offset;
4610 return f;
4613 void qemu_fflush(QEMUFile *f)
4615 if (!f->is_writable)
4616 return;
4617 if (f->buf_index > 0) {
4618 if (f->is_file) {
4619 fseek(f->outfile, f->buf_offset, SEEK_SET);
4620 fwrite(f->buf, 1, f->buf_index, f->outfile);
4621 } else {
4622 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4623 f->buf, f->buf_index);
4625 f->buf_offset += f->buf_index;
4626 f->buf_index = 0;
4630 static void qemu_fill_buffer(QEMUFile *f)
4632 int len;
4634 if (f->is_writable)
4635 return;
4636 if (f->is_file) {
4637 fseek(f->outfile, f->buf_offset, SEEK_SET);
4638 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4639 if (len < 0)
4640 len = 0;
4641 } else {
4642 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4643 f->buf, IO_BUF_SIZE);
4644 if (len < 0)
4645 len = 0;
4647 f->buf_index = 0;
4648 f->buf_size = len;
4649 f->buf_offset += len;
4652 void qemu_fclose(QEMUFile *f)
4654 if (f->is_writable)
4655 qemu_fflush(f);
4656 if (f->is_file) {
4657 fclose(f->outfile);
4659 qemu_free(f);
4662 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4664 int l;
4665 while (size > 0) {
4666 l = IO_BUF_SIZE - f->buf_index;
4667 if (l > size)
4668 l = size;
4669 memcpy(f->buf + f->buf_index, buf, l);
4670 f->buf_index += l;
4671 buf += l;
4672 size -= l;
4673 if (f->buf_index >= IO_BUF_SIZE)
4674 qemu_fflush(f);
4678 void qemu_put_byte(QEMUFile *f, int v)
4680 f->buf[f->buf_index++] = v;
4681 if (f->buf_index >= IO_BUF_SIZE)
4682 qemu_fflush(f);
4685 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4687 int size, l;
4689 size = size1;
4690 while (size > 0) {
4691 l = f->buf_size - f->buf_index;
4692 if (l == 0) {
4693 qemu_fill_buffer(f);
4694 l = f->buf_size - f->buf_index;
4695 if (l == 0)
4696 break;
4698 if (l > size)
4699 l = size;
4700 memcpy(buf, f->buf + f->buf_index, l);
4701 f->buf_index += l;
4702 buf += l;
4703 size -= l;
4705 return size1 - size;
4708 int qemu_get_byte(QEMUFile *f)
4710 if (f->buf_index >= f->buf_size) {
4711 qemu_fill_buffer(f);
4712 if (f->buf_index >= f->buf_size)
4713 return 0;
4715 return f->buf[f->buf_index++];
4718 int64_t qemu_ftell(QEMUFile *f)
4720 return f->buf_offset - f->buf_size + f->buf_index;
4723 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4725 if (whence == SEEK_SET) {
4726 /* nothing to do */
4727 } else if (whence == SEEK_CUR) {
4728 pos += qemu_ftell(f);
4729 } else {
4730 /* SEEK_END not supported */
4731 return -1;
4733 if (f->is_writable) {
4734 qemu_fflush(f);
4735 f->buf_offset = pos;
4736 } else {
4737 f->buf_offset = pos;
4738 f->buf_index = 0;
4739 f->buf_size = 0;
4741 return pos;
4744 void qemu_put_be16(QEMUFile *f, unsigned int v)
4746 qemu_put_byte(f, v >> 8);
4747 qemu_put_byte(f, v);
4750 void qemu_put_be32(QEMUFile *f, unsigned int v)
4752 qemu_put_byte(f, v >> 24);
4753 qemu_put_byte(f, v >> 16);
4754 qemu_put_byte(f, v >> 8);
4755 qemu_put_byte(f, v);
4758 void qemu_put_be64(QEMUFile *f, uint64_t v)
4760 qemu_put_be32(f, v >> 32);
4761 qemu_put_be32(f, v);
4764 unsigned int qemu_get_be16(QEMUFile *f)
4766 unsigned int v;
4767 v = qemu_get_byte(f) << 8;
4768 v |= qemu_get_byte(f);
4769 return v;
4772 unsigned int qemu_get_be32(QEMUFile *f)
4774 unsigned int v;
4775 v = qemu_get_byte(f) << 24;
4776 v |= qemu_get_byte(f) << 16;
4777 v |= qemu_get_byte(f) << 8;
4778 v |= qemu_get_byte(f);
4779 return v;
4782 uint64_t qemu_get_be64(QEMUFile *f)
4784 uint64_t v;
4785 v = (uint64_t)qemu_get_be32(f) << 32;
4786 v |= qemu_get_be32(f);
4787 return v;
4790 typedef struct SaveStateEntry {
4791 char idstr[256];
4792 int instance_id;
4793 int version_id;
4794 SaveStateHandler *save_state;
4795 LoadStateHandler *load_state;
4796 void *opaque;
4797 struct SaveStateEntry *next;
4798 } SaveStateEntry;
4800 static SaveStateEntry *first_se;
4802 int register_savevm(const char *idstr,
4803 int instance_id,
4804 int version_id,
4805 SaveStateHandler *save_state,
4806 LoadStateHandler *load_state,
4807 void *opaque)
4809 SaveStateEntry *se, **pse;
4811 se = qemu_malloc(sizeof(SaveStateEntry));
4812 if (!se)
4813 return -1;
4814 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4815 se->instance_id = instance_id;
4816 se->version_id = version_id;
4817 se->save_state = save_state;
4818 se->load_state = load_state;
4819 se->opaque = opaque;
4820 se->next = NULL;
4822 /* add at the end of list */
4823 pse = &first_se;
4824 while (*pse != NULL)
4825 pse = &(*pse)->next;
4826 *pse = se;
4827 return 0;
4830 #define QEMU_VM_FILE_MAGIC 0x5145564d
4831 #define QEMU_VM_FILE_VERSION 0x00000002
4833 int qemu_savevm_state(QEMUFile *f)
4835 SaveStateEntry *se;
4836 int len, ret;
4837 int64_t cur_pos, len_pos, total_len_pos;
4839 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4840 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4841 total_len_pos = qemu_ftell(f);
4842 qemu_put_be64(f, 0); /* total size */
4844 for(se = first_se; se != NULL; se = se->next) {
4845 /* ID string */
4846 len = strlen(se->idstr);
4847 qemu_put_byte(f, len);
4848 qemu_put_buffer(f, se->idstr, len);
4850 qemu_put_be32(f, se->instance_id);
4851 qemu_put_be32(f, se->version_id);
4853 /* record size: filled later */
4854 len_pos = qemu_ftell(f);
4855 qemu_put_be32(f, 0);
4857 se->save_state(f, se->opaque);
4859 /* fill record size */
4860 cur_pos = qemu_ftell(f);
4861 len = cur_pos - len_pos - 4;
4862 qemu_fseek(f, len_pos, SEEK_SET);
4863 qemu_put_be32(f, len);
4864 qemu_fseek(f, cur_pos, SEEK_SET);
4866 cur_pos = qemu_ftell(f);
4867 qemu_fseek(f, total_len_pos, SEEK_SET);
4868 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4869 qemu_fseek(f, cur_pos, SEEK_SET);
4871 ret = 0;
4872 return ret;
4875 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4877 SaveStateEntry *se;
4879 for(se = first_se; se != NULL; se = se->next) {
4880 if (!strcmp(se->idstr, idstr) &&
4881 instance_id == se->instance_id)
4882 return se;
4884 return NULL;
4887 int qemu_loadvm_state(QEMUFile *f)
4889 SaveStateEntry *se;
4890 int len, ret, instance_id, record_len, version_id;
4891 int64_t total_len, end_pos, cur_pos;
4892 unsigned int v;
4893 char idstr[256];
4895 v = qemu_get_be32(f);
4896 if (v != QEMU_VM_FILE_MAGIC)
4897 goto fail;
4898 v = qemu_get_be32(f);
4899 if (v != QEMU_VM_FILE_VERSION) {
4900 fail:
4901 ret = -1;
4902 goto the_end;
4904 total_len = qemu_get_be64(f);
4905 end_pos = total_len + qemu_ftell(f);
4906 for(;;) {
4907 if (qemu_ftell(f) >= end_pos)
4908 break;
4909 len = qemu_get_byte(f);
4910 qemu_get_buffer(f, idstr, len);
4911 idstr[len] = '\0';
4912 instance_id = qemu_get_be32(f);
4913 version_id = qemu_get_be32(f);
4914 record_len = qemu_get_be32(f);
4915 #if 0
4916 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4917 idstr, instance_id, version_id, record_len);
4918 #endif
4919 cur_pos = qemu_ftell(f);
4920 se = find_se(idstr, instance_id);
4921 if (!se) {
4922 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4923 instance_id, idstr);
4924 } else {
4925 ret = se->load_state(f, se->opaque, version_id);
4926 if (ret < 0) {
4927 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4928 instance_id, idstr);
4931 /* always seek to exact end of record */
4932 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4934 ret = 0;
4935 the_end:
4936 return ret;
4939 /* device can contain snapshots */
4940 static int bdrv_can_snapshot(BlockDriverState *bs)
4942 return (bs &&
4943 !bdrv_is_removable(bs) &&
4944 !bdrv_is_read_only(bs));
4947 /* device must be snapshots in order to have a reliable snapshot */
4948 static int bdrv_has_snapshot(BlockDriverState *bs)
4950 return (bs &&
4951 !bdrv_is_removable(bs) &&
4952 !bdrv_is_read_only(bs));
4955 static BlockDriverState *get_bs_snapshots(void)
4957 BlockDriverState *bs;
4958 int i;
4960 if (bs_snapshots)
4961 return bs_snapshots;
4962 for(i = 0; i <= MAX_DISKS; i++) {
4963 bs = bs_table[i];
4964 if (bdrv_can_snapshot(bs))
4965 goto ok;
4967 return NULL;
4968 ok:
4969 bs_snapshots = bs;
4970 return bs;
4973 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4974 const char *name)
4976 QEMUSnapshotInfo *sn_tab, *sn;
4977 int nb_sns, i, ret;
4979 ret = -ENOENT;
4980 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4981 if (nb_sns < 0)
4982 return ret;
4983 for(i = 0; i < nb_sns; i++) {
4984 sn = &sn_tab[i];
4985 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4986 *sn_info = *sn;
4987 ret = 0;
4988 break;
4991 qemu_free(sn_tab);
4992 return ret;
4995 #ifdef CONFIG_DM
4996 /* We use simpler state save/load functions for Xen */
4997 void do_savevm(const char *name)
4999 QEMUFile *f;
5000 int saved_vm_running, ret;
5002 f = qemu_fopen(name, "wb");
5004 /* ??? Should this occur after vm_stop? */
5005 qemu_aio_flush();
5007 saved_vm_running = vm_running;
5008 vm_stop(0);
5010 if (!f) {
5011 fprintf(logfile, "Failed to open savevm file '%s'\n", name);
5012 goto the_end;
5015 ret = qemu_savevm_state(f);
5016 qemu_fclose(f);
5018 if (ret < 0)
5019 fprintf(logfile, "Error %d while writing VM to savevm file '%s'\n",
5020 ret, name);
5022 the_end:
5023 if (saved_vm_running)
5024 vm_start();
5026 return;
5028 void do_loadvm(const char *name)
5030 QEMUFile *f;
5031 int saved_vm_running, ret;
5033 /* Flush all IO requests so they don't interfere with the new state. */
5034 qemu_aio_flush();
5036 saved_vm_running = vm_running;
5037 vm_stop(0);
5039 /* restore the VM state */
5040 f = qemu_fopen(name, "rb");
5041 if (!f) {
5042 fprintf(logfile, "Could not open VM state file\n");
5043 goto the_end;
5046 ret = qemu_loadvm_state(f);
5047 qemu_fclose(f);
5048 if (ret < 0) {
5049 fprintf(logfile, "Error %d while loading savevm file '%s'\n",
5050 ret, name);
5051 goto the_end;
5054 #if 0
5055 /* del tmp file */
5056 if (unlink(name) == -1)
5057 fprintf(stderr, "delete tmp qemu state file failed.\n");
5058 #endif
5061 the_end:
5062 if (saved_vm_running)
5063 vm_start();
5065 #else
5066 void do_savevm(const char *name)
5068 BlockDriverState *bs, *bs1;
5069 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5070 int must_delete, ret, i;
5071 BlockDriverInfo bdi1, *bdi = &bdi1;
5072 QEMUFile *f;
5073 int saved_vm_running;
5074 #ifdef _WIN32
5075 struct _timeb tb;
5076 #else
5077 struct timeval tv;
5078 #endif
5080 bs = get_bs_snapshots();
5081 if (!bs) {
5082 term_printf("No block device can accept snapshots\n");
5083 return;
5086 /* ??? Should this occur after vm_stop? */
5087 qemu_aio_flush();
5089 saved_vm_running = vm_running;
5090 vm_stop(0);
5092 must_delete = 0;
5093 if (name) {
5094 ret = bdrv_snapshot_find(bs, old_sn, name);
5095 if (ret >= 0) {
5096 must_delete = 1;
5099 memset(sn, 0, sizeof(*sn));
5100 if (must_delete) {
5101 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5102 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5103 } else {
5104 if (name)
5105 pstrcpy(sn->name, sizeof(sn->name), name);
5108 /* fill auxiliary fields */
5109 #ifdef _WIN32
5110 _ftime(&tb);
5111 sn->date_sec = tb.time;
5112 sn->date_nsec = tb.millitm * 1000000;
5113 #else
5114 gettimeofday(&tv, NULL);
5115 sn->date_sec = tv.tv_sec;
5116 sn->date_nsec = tv.tv_usec * 1000;
5117 #endif
5118 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5120 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5121 term_printf("Device %s does not support VM state snapshots\n",
5122 bdrv_get_device_name(bs));
5123 goto the_end;
5126 /* save the VM state */
5127 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5128 if (!f) {
5129 term_printf("Could not open VM state file\n");
5130 goto the_end;
5132 ret = qemu_savevm_state(f);
5133 sn->vm_state_size = qemu_ftell(f);
5134 qemu_fclose(f);
5135 if (ret < 0) {
5136 term_printf("Error %d while writing VM\n", ret);
5137 goto the_end;
5140 /* create the snapshots */
5142 for(i = 0; i < MAX_DISKS; i++) {
5143 bs1 = bs_table[i];
5144 if (bdrv_has_snapshot(bs1)) {
5145 if (must_delete) {
5146 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5147 if (ret < 0) {
5148 term_printf("Error while deleting snapshot on '%s'\n",
5149 bdrv_get_device_name(bs1));
5152 ret = bdrv_snapshot_create(bs1, sn);
5153 if (ret < 0) {
5154 term_printf("Error while creating snapshot on '%s'\n",
5155 bdrv_get_device_name(bs1));
5160 the_end:
5161 if (saved_vm_running)
5162 vm_start();
5165 void do_loadvm(const char *name)
5167 BlockDriverState *bs, *bs1;
5168 BlockDriverInfo bdi1, *bdi = &bdi1;
5169 QEMUFile *f;
5170 int i, ret;
5171 int saved_vm_running;
5173 bs = get_bs_snapshots();
5174 if (!bs) {
5175 term_printf("No block device supports snapshots\n");
5176 return;
5179 /* Flush all IO requests so they don't interfere with the new state. */
5180 qemu_aio_flush();
5182 saved_vm_running = vm_running;
5183 vm_stop(0);
5185 for(i = 0; i <= MAX_DISKS; i++) {
5186 bs1 = bs_table[i];
5187 if (bdrv_has_snapshot(bs1)) {
5188 ret = bdrv_snapshot_goto(bs1, name);
5189 if (ret < 0) {
5190 if (bs != bs1)
5191 term_printf("Warning: ");
5192 switch(ret) {
5193 case -ENOTSUP:
5194 term_printf("Snapshots not supported on device '%s'\n",
5195 bdrv_get_device_name(bs1));
5196 break;
5197 case -ENOENT:
5198 term_printf("Could not find snapshot '%s' on device '%s'\n",
5199 name, bdrv_get_device_name(bs1));
5200 break;
5201 default:
5202 term_printf("Error %d while activating snapshot on '%s'\n",
5203 ret, bdrv_get_device_name(bs1));
5204 break;
5206 /* fatal on snapshot block device */
5207 if (bs == bs1)
5208 goto the_end;
5213 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5214 term_printf("Device %s does not support VM state snapshots\n",
5215 bdrv_get_device_name(bs));
5216 return;
5219 /* restore the VM state */
5220 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5221 if (!f) {
5222 term_printf("Could not open VM state file\n");
5223 goto the_end;
5225 ret = qemu_loadvm_state(f);
5226 qemu_fclose(f);
5227 if (ret < 0) {
5228 term_printf("Error %d while loading VM state\n", ret);
5231 /* del tmp file */
5232 if (unlink(name) == -1)
5233 fprintf(stderr, "delete tmp qemu state file failed.\n");
5235 the_end:
5236 if (saved_vm_running)
5237 vm_start();
5239 #endif
5241 void do_delvm(const char *name)
5243 BlockDriverState *bs, *bs1;
5244 int i, ret;
5246 bs = get_bs_snapshots();
5247 if (!bs) {
5248 term_printf("No block device supports snapshots\n");
5249 return;
5252 for(i = 0; i <= MAX_DISKS; i++) {
5253 bs1 = bs_table[i];
5254 if (bdrv_has_snapshot(bs1)) {
5255 ret = bdrv_snapshot_delete(bs1, name);
5256 if (ret < 0) {
5257 if (ret == -ENOTSUP)
5258 term_printf("Snapshots not supported on device '%s'\n",
5259 bdrv_get_device_name(bs1));
5260 else
5261 term_printf("Error %d while deleting snapshot on '%s'\n",
5262 ret, bdrv_get_device_name(bs1));
5268 void do_info_snapshots(void)
5270 BlockDriverState *bs, *bs1;
5271 QEMUSnapshotInfo *sn_tab, *sn;
5272 int nb_sns, i;
5273 char buf[256];
5275 bs = get_bs_snapshots();
5276 if (!bs) {
5277 term_printf("No available block device supports snapshots\n");
5278 return;
5280 term_printf("Snapshot devices:");
5281 for(i = 0; i <= MAX_DISKS; i++) {
5282 bs1 = bs_table[i];
5283 if (bdrv_has_snapshot(bs1)) {
5284 if (bs == bs1)
5285 term_printf(" %s", bdrv_get_device_name(bs1));
5288 term_printf("\n");
5290 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5291 if (nb_sns < 0) {
5292 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5293 return;
5295 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5296 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5297 for(i = 0; i < nb_sns; i++) {
5298 sn = &sn_tab[i];
5299 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5301 qemu_free(sn_tab);
5304 #ifndef CONFIG_DM
5305 /***********************************************************/
5306 /* cpu save/restore */
5308 #if defined(TARGET_I386)
5310 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5312 qemu_put_be32(f, dt->selector);
5313 qemu_put_betl(f, dt->base);
5314 qemu_put_be32(f, dt->limit);
5315 qemu_put_be32(f, dt->flags);
5318 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5320 dt->selector = qemu_get_be32(f);
5321 dt->base = qemu_get_betl(f);
5322 dt->limit = qemu_get_be32(f);
5323 dt->flags = qemu_get_be32(f);
5326 void cpu_save(QEMUFile *f, void *opaque)
5328 CPUState *env = opaque;
5329 uint16_t fptag, fpus, fpuc, fpregs_format;
5330 uint32_t hflags;
5331 int i;
5333 for(i = 0; i < CPU_NB_REGS; i++)
5334 qemu_put_betls(f, &env->regs[i]);
5335 qemu_put_betls(f, &env->eip);
5336 qemu_put_betls(f, &env->eflags);
5337 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5338 qemu_put_be32s(f, &hflags);
5340 /* FPU */
5341 fpuc = env->fpuc;
5342 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5343 fptag = 0;
5344 for(i = 0; i < 8; i++) {
5345 fptag |= ((!env->fptags[i]) << i);
5348 qemu_put_be16s(f, &fpuc);
5349 qemu_put_be16s(f, &fpus);
5350 qemu_put_be16s(f, &fptag);
5352 #ifdef USE_X86LDOUBLE
5353 fpregs_format = 0;
5354 #else
5355 fpregs_format = 1;
5356 #endif
5357 qemu_put_be16s(f, &fpregs_format);
5359 for(i = 0; i < 8; i++) {
5360 #ifdef USE_X86LDOUBLE
5362 uint64_t mant;
5363 uint16_t exp;
5364 /* we save the real CPU data (in case of MMX usage only 'mant'
5365 contains the MMX register */
5366 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5367 qemu_put_be64(f, mant);
5368 qemu_put_be16(f, exp);
5370 #else
5371 /* if we use doubles for float emulation, we save the doubles to
5372 avoid losing information in case of MMX usage. It can give
5373 problems if the image is restored on a CPU where long
5374 doubles are used instead. */
5375 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5376 #endif
5379 for(i = 0; i < 6; i++)
5380 cpu_put_seg(f, &env->segs[i]);
5381 cpu_put_seg(f, &env->ldt);
5382 cpu_put_seg(f, &env->tr);
5383 cpu_put_seg(f, &env->gdt);
5384 cpu_put_seg(f, &env->idt);
5386 qemu_put_be32s(f, &env->sysenter_cs);
5387 qemu_put_be32s(f, &env->sysenter_esp);
5388 qemu_put_be32s(f, &env->sysenter_eip);
5390 qemu_put_betls(f, &env->cr[0]);
5391 qemu_put_betls(f, &env->cr[2]);
5392 qemu_put_betls(f, &env->cr[3]);
5393 qemu_put_betls(f, &env->cr[4]);
5395 for(i = 0; i < 8; i++)
5396 qemu_put_betls(f, &env->dr[i]);
5398 /* MMU */
5399 qemu_put_be32s(f, &env->a20_mask);
5401 /* XMM */
5402 qemu_put_be32s(f, &env->mxcsr);
5403 for(i = 0; i < CPU_NB_REGS; i++) {
5404 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5405 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5408 #ifdef TARGET_X86_64
5409 qemu_put_be64s(f, &env->efer);
5410 qemu_put_be64s(f, &env->star);
5411 qemu_put_be64s(f, &env->lstar);
5412 qemu_put_be64s(f, &env->cstar);
5413 qemu_put_be64s(f, &env->fmask);
5414 qemu_put_be64s(f, &env->kernelgsbase);
5415 #endif
5416 qemu_put_be32s(f, &env->smbase);
5419 #ifdef USE_X86LDOUBLE
5420 /* XXX: add that in a FPU generic layer */
5421 union x86_longdouble {
5422 uint64_t mant;
5423 uint16_t exp;
5424 };
5426 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5427 #define EXPBIAS1 1023
5428 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5429 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5431 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5433 int e;
5434 /* mantissa */
5435 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5436 /* exponent + sign */
5437 e = EXPD1(temp) - EXPBIAS1 + 16383;
5438 e |= SIGND1(temp) >> 16;
5439 p->exp = e;
5441 #endif
5443 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5445 CPUState *env = opaque;
5446 int i, guess_mmx;
5447 uint32_t hflags;
5448 uint16_t fpus, fpuc, fptag, fpregs_format;
5450 if (version_id != 3 && version_id != 4)
5451 return -EINVAL;
5452 for(i = 0; i < CPU_NB_REGS; i++)
5453 qemu_get_betls(f, &env->regs[i]);
5454 qemu_get_betls(f, &env->eip);
5455 qemu_get_betls(f, &env->eflags);
5456 qemu_get_be32s(f, &hflags);
5458 qemu_get_be16s(f, &fpuc);
5459 qemu_get_be16s(f, &fpus);
5460 qemu_get_be16s(f, &fptag);
5461 qemu_get_be16s(f, &fpregs_format);
5463 /* NOTE: we cannot always restore the FPU state if the image come
5464 from a host with a different 'USE_X86LDOUBLE' define. We guess
5465 if we are in an MMX state to restore correctly in that case. */
5466 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5467 for(i = 0; i < 8; i++) {
5468 uint64_t mant;
5469 uint16_t exp;
5471 switch(fpregs_format) {
5472 case 0:
5473 mant = qemu_get_be64(f);
5474 exp = qemu_get_be16(f);
5475 #ifdef USE_X86LDOUBLE
5476 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5477 #else
5478 /* difficult case */
5479 if (guess_mmx)
5480 env->fpregs[i].mmx.MMX_Q(0) = mant;
5481 else
5482 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5483 #endif
5484 break;
5485 case 1:
5486 mant = qemu_get_be64(f);
5487 #ifdef USE_X86LDOUBLE
5489 union x86_longdouble *p;
5490 /* difficult case */
5491 p = (void *)&env->fpregs[i];
5492 if (guess_mmx) {
5493 p->mant = mant;
5494 p->exp = 0xffff;
5495 } else {
5496 fp64_to_fp80(p, mant);
5499 #else
5500 env->fpregs[i].mmx.MMX_Q(0) = mant;
5501 #endif
5502 break;
5503 default:
5504 return -EINVAL;
5508 env->fpuc = fpuc;
5509 /* XXX: restore FPU round state */
5510 env->fpstt = (fpus >> 11) & 7;
5511 env->fpus = fpus & ~0x3800;
5512 fptag ^= 0xff;
5513 for(i = 0; i < 8; i++) {
5514 env->fptags[i] = (fptag >> i) & 1;
5517 for(i = 0; i < 6; i++)
5518 cpu_get_seg(f, &env->segs[i]);
5519 cpu_get_seg(f, &env->ldt);
5520 cpu_get_seg(f, &env->tr);
5521 cpu_get_seg(f, &env->gdt);
5522 cpu_get_seg(f, &env->idt);
5524 qemu_get_be32s(f, &env->sysenter_cs);
5525 qemu_get_be32s(f, &env->sysenter_esp);
5526 qemu_get_be32s(f, &env->sysenter_eip);
5528 qemu_get_betls(f, &env->cr[0]);
5529 qemu_get_betls(f, &env->cr[2]);
5530 qemu_get_betls(f, &env->cr[3]);
5531 qemu_get_betls(f, &env->cr[4]);
5533 for(i = 0; i < 8; i++)
5534 qemu_get_betls(f, &env->dr[i]);
5536 /* MMU */
5537 qemu_get_be32s(f, &env->a20_mask);
5539 qemu_get_be32s(f, &env->mxcsr);
5540 for(i = 0; i < CPU_NB_REGS; i++) {
5541 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5542 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5545 #ifdef TARGET_X86_64
5546 qemu_get_be64s(f, &env->efer);
5547 qemu_get_be64s(f, &env->star);
5548 qemu_get_be64s(f, &env->lstar);
5549 qemu_get_be64s(f, &env->cstar);
5550 qemu_get_be64s(f, &env->fmask);
5551 qemu_get_be64s(f, &env->kernelgsbase);
5552 #endif
5553 if (version_id >= 4)
5554 qemu_get_be32s(f, &env->smbase);
5556 /* XXX: compute hflags from scratch, except for CPL and IIF */
5557 env->hflags = hflags;
5558 tlb_flush(env, 1);
5559 return 0;
5562 #elif defined(TARGET_PPC)
5563 void cpu_save(QEMUFile *f, void *opaque)
5567 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5569 return 0;
5572 #elif defined(TARGET_MIPS)
5573 void cpu_save(QEMUFile *f, void *opaque)
5577 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5579 return 0;
5582 #elif defined(TARGET_SPARC)
5583 void cpu_save(QEMUFile *f, void *opaque)
5585 CPUState *env = opaque;
5586 int i;
5587 uint32_t tmp;
5589 for(i = 0; i < 8; i++)
5590 qemu_put_betls(f, &env->gregs[i]);
5591 for(i = 0; i < NWINDOWS * 16; i++)
5592 qemu_put_betls(f, &env->regbase[i]);
5594 /* FPU */
5595 for(i = 0; i < TARGET_FPREGS; i++) {
5596 union {
5597 float32 f;
5598 uint32_t i;
5599 } u;
5600 u.f = env->fpr[i];
5601 qemu_put_be32(f, u.i);
5604 qemu_put_betls(f, &env->pc);
5605 qemu_put_betls(f, &env->npc);
5606 qemu_put_betls(f, &env->y);
5607 tmp = GET_PSR(env);
5608 qemu_put_be32(f, tmp);
5609 qemu_put_betls(f, &env->fsr);
5610 qemu_put_betls(f, &env->tbr);
5611 #ifndef TARGET_SPARC64
5612 qemu_put_be32s(f, &env->wim);
5613 /* MMU */
5614 for(i = 0; i < 16; i++)
5615 qemu_put_be32s(f, &env->mmuregs[i]);
5616 #endif
5619 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5621 CPUState *env = opaque;
5622 int i;
5623 uint32_t tmp;
5625 for(i = 0; i < 8; i++)
5626 qemu_get_betls(f, &env->gregs[i]);
5627 for(i = 0; i < NWINDOWS * 16; i++)
5628 qemu_get_betls(f, &env->regbase[i]);
5630 /* FPU */
5631 for(i = 0; i < TARGET_FPREGS; i++) {
5632 union {
5633 float32 f;
5634 uint32_t i;
5635 } u;
5636 u.i = qemu_get_be32(f);
5637 env->fpr[i] = u.f;
5640 qemu_get_betls(f, &env->pc);
5641 qemu_get_betls(f, &env->npc);
5642 qemu_get_betls(f, &env->y);
5643 tmp = qemu_get_be32(f);
5644 env->cwp = 0; /* needed to ensure that the wrapping registers are
5645 correctly updated */
5646 PUT_PSR(env, tmp);
5647 qemu_get_betls(f, &env->fsr);
5648 qemu_get_betls(f, &env->tbr);
5649 #ifndef TARGET_SPARC64
5650 qemu_get_be32s(f, &env->wim);
5651 /* MMU */
5652 for(i = 0; i < 16; i++)
5653 qemu_get_be32s(f, &env->mmuregs[i]);
5654 #endif
5655 tlb_flush(env, 1);
5656 return 0;
5659 #elif defined(TARGET_ARM)
5661 /* ??? Need to implement these. */
5662 void cpu_save(QEMUFile *f, void *opaque)
5666 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5668 return 0;
5671 #else
5673 #warning No CPU save/restore functions
5675 #endif
5677 /***********************************************************/
5678 /* ram save/restore */
5680 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5682 int v;
5684 v = qemu_get_byte(f);
5685 switch(v) {
5686 case 0:
5687 if (qemu_get_buffer(f, buf, len) != len)
5688 return -EIO;
5689 break;
5690 case 1:
5691 v = qemu_get_byte(f);
5692 memset(buf, v, len);
5693 break;
5694 default:
5695 return -EINVAL;
5697 return 0;
5700 static int ram_load_v1(QEMUFile *f, void *opaque)
5702 int i, ret;
5704 if (qemu_get_be32(f) != phys_ram_size)
5705 return -EINVAL;
5706 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5707 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5708 if (ret)
5709 return ret;
5711 return 0;
5714 #define BDRV_HASH_BLOCK_SIZE 1024
5715 #define IOBUF_SIZE 4096
5716 #define RAM_CBLOCK_MAGIC 0xfabe
5718 typedef struct RamCompressState {
5719 z_stream zstream;
5720 QEMUFile *f;
5721 uint8_t buf[IOBUF_SIZE];
5722 } RamCompressState;
5724 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5726 int ret;
5727 memset(s, 0, sizeof(*s));
5728 s->f = f;
5729 ret = deflateInit2(&s->zstream, 1,
5730 Z_DEFLATED, 15,
5731 9, Z_DEFAULT_STRATEGY);
5732 if (ret != Z_OK)
5733 return -1;
5734 s->zstream.avail_out = IOBUF_SIZE;
5735 s->zstream.next_out = s->buf;
5736 return 0;
5739 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5741 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5742 qemu_put_be16(s->f, len);
5743 qemu_put_buffer(s->f, buf, len);
5746 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5748 int ret;
5750 s->zstream.avail_in = len;
5751 s->zstream.next_in = (uint8_t *)buf;
5752 while (s->zstream.avail_in > 0) {
5753 ret = deflate(&s->zstream, Z_NO_FLUSH);
5754 if (ret != Z_OK)
5755 return -1;
5756 if (s->zstream.avail_out == 0) {
5757 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5758 s->zstream.avail_out = IOBUF_SIZE;
5759 s->zstream.next_out = s->buf;
5762 return 0;
5765 static void ram_compress_close(RamCompressState *s)
5767 int len, ret;
5769 /* compress last bytes */
5770 for(;;) {
5771 ret = deflate(&s->zstream, Z_FINISH);
5772 if (ret == Z_OK || ret == Z_STREAM_END) {
5773 len = IOBUF_SIZE - s->zstream.avail_out;
5774 if (len > 0) {
5775 ram_put_cblock(s, s->buf, len);
5777 s->zstream.avail_out = IOBUF_SIZE;
5778 s->zstream.next_out = s->buf;
5779 if (ret == Z_STREAM_END)
5780 break;
5781 } else {
5782 goto fail;
5785 fail:
5786 deflateEnd(&s->zstream);
5789 typedef struct RamDecompressState {
5790 z_stream zstream;
5791 QEMUFile *f;
5792 uint8_t buf[IOBUF_SIZE];
5793 } RamDecompressState;
5795 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5797 int ret;
5798 memset(s, 0, sizeof(*s));
5799 s->f = f;
5800 ret = inflateInit(&s->zstream);
5801 if (ret != Z_OK)
5802 return -1;
5803 return 0;
5806 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5808 int ret, clen;
5810 s->zstream.avail_out = len;
5811 s->zstream.next_out = buf;
5812 while (s->zstream.avail_out > 0) {
5813 if (s->zstream.avail_in == 0) {
5814 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5815 return -1;
5816 clen = qemu_get_be16(s->f);
5817 if (clen > IOBUF_SIZE)
5818 return -1;
5819 qemu_get_buffer(s->f, s->buf, clen);
5820 s->zstream.avail_in = clen;
5821 s->zstream.next_in = s->buf;
5823 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5824 if (ret != Z_OK && ret != Z_STREAM_END) {
5825 return -1;
5828 return 0;
5831 static void ram_decompress_close(RamDecompressState *s)
5833 inflateEnd(&s->zstream);
5836 static void ram_save(QEMUFile *f, void *opaque)
5838 int i;
5839 RamCompressState s1, *s = &s1;
5840 uint8_t buf[10];
5842 qemu_put_be32(f, phys_ram_size);
5843 if (ram_compress_open(s, f) < 0)
5844 return;
5845 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5846 #if 0
5847 if (tight_savevm_enabled) {
5848 int64_t sector_num;
5849 int j;
5851 /* find if the memory block is available on a virtual
5852 block device */
5853 sector_num = -1;
5854 for(j = 0; j < MAX_DISKS; j++) {
5855 if (bs_table[j]) {
5856 sector_num = bdrv_hash_find(bs_table[j],
5857 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5858 if (sector_num >= 0)
5859 break;
5862 if (j == MAX_DISKS)
5863 goto normal_compress;
5864 buf[0] = 1;
5865 buf[1] = j;
5866 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5867 ram_compress_buf(s, buf, 10);
5868 } else
5869 #endif
5871 // normal_compress:
5872 buf[0] = 0;
5873 ram_compress_buf(s, buf, 1);
5874 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5877 ram_compress_close(s);
5880 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5882 RamDecompressState s1, *s = &s1;
5883 uint8_t buf[10];
5884 int i;
5886 if (version_id == 1)
5887 return ram_load_v1(f, opaque);
5888 if (version_id != 2)
5889 return -EINVAL;
5890 if (qemu_get_be32(f) != phys_ram_size)
5891 return -EINVAL;
5892 if (ram_decompress_open(s, f) < 0)
5893 return -EINVAL;
5894 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5895 if (ram_decompress_buf(s, buf, 1) < 0) {
5896 fprintf(stderr, "Error while reading ram block header\n");
5897 goto error;
5899 if (buf[0] == 0) {
5900 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5901 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5902 goto error;
5904 } else
5905 #if 0
5906 if (buf[0] == 1) {
5907 int bs_index;
5908 int64_t sector_num;
5910 ram_decompress_buf(s, buf + 1, 9);
5911 bs_index = buf[1];
5912 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5913 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5914 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5915 goto error;
5917 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5918 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5919 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5920 bs_index, sector_num);
5921 goto error;
5923 } else
5924 #endif
5926 error:
5927 printf("Error block header\n");
5928 return -EINVAL;
5931 ram_decompress_close(s);
5932 return 0;
5934 #else /* CONFIG_DM */
5935 void cpu_save(QEMUFile *f, void *opaque)
5939 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5941 return 0;
5944 static void ram_save(QEMUFile *f, void *opaque)
5948 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5950 return 0;
5952 #endif /* CONFIG_DM */
5954 /***********************************************************/
5955 /* bottom halves (can be seen as timers which expire ASAP) */
5957 struct QEMUBH {
5958 QEMUBHFunc *cb;
5959 void *opaque;
5960 int scheduled;
5961 QEMUBH *next;
5962 };
5964 static QEMUBH *first_bh = NULL;
5966 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5968 QEMUBH *bh;
5969 bh = qemu_mallocz(sizeof(QEMUBH));
5970 if (!bh)
5971 return NULL;
5972 bh->cb = cb;
5973 bh->opaque = opaque;
5974 return bh;
5977 int qemu_bh_poll(void)
5979 QEMUBH *bh, **pbh;
5980 int ret;
5982 ret = 0;
5983 for(;;) {
5984 pbh = &first_bh;
5985 bh = *pbh;
5986 if (!bh)
5987 break;
5988 ret = 1;
5989 *pbh = bh->next;
5990 bh->scheduled = 0;
5991 bh->cb(bh->opaque);
5993 return ret;
5996 void qemu_bh_schedule(QEMUBH *bh)
5998 CPUState *env = cpu_single_env;
5999 if (bh->scheduled)
6000 return;
6001 bh->scheduled = 1;
6002 bh->next = first_bh;
6003 first_bh = bh;
6005 /* stop the currently executing CPU to execute the BH ASAP */
6006 if (env) {
6007 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6011 void qemu_bh_cancel(QEMUBH *bh)
6013 QEMUBH **pbh;
6014 if (bh->scheduled) {
6015 pbh = &first_bh;
6016 while (*pbh != bh)
6017 pbh = &(*pbh)->next;
6018 *pbh = bh->next;
6019 bh->scheduled = 0;
6023 void qemu_bh_delete(QEMUBH *bh)
6025 qemu_bh_cancel(bh);
6026 qemu_free(bh);
6029 /***********************************************************/
6030 /* machine registration */
6032 QEMUMachine *first_machine = NULL;
6034 int qemu_register_machine(QEMUMachine *m)
6036 QEMUMachine **pm;
6037 pm = &first_machine;
6038 while (*pm != NULL)
6039 pm = &(*pm)->next;
6040 m->next = NULL;
6041 *pm = m;
6042 return 0;
6045 QEMUMachine *find_machine(const char *name)
6047 QEMUMachine *m;
6049 for(m = first_machine; m != NULL; m = m->next) {
6050 if (!strcmp(m->name, name))
6051 return m;
6053 return NULL;
6056 /***********************************************************/
6057 /* main execution loop */
6059 void gui_update(void *opaque)
6061 display_state.dpy_refresh(&display_state);
6062 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6065 struct vm_change_state_entry {
6066 VMChangeStateHandler *cb;
6067 void *opaque;
6068 LIST_ENTRY (vm_change_state_entry) entries;
6069 };
6071 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6073 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6074 void *opaque)
6076 VMChangeStateEntry *e;
6078 e = qemu_mallocz(sizeof (*e));
6079 if (!e)
6080 return NULL;
6082 e->cb = cb;
6083 e->opaque = opaque;
6084 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6085 return e;
6088 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6090 LIST_REMOVE (e, entries);
6091 qemu_free (e);
6094 static void vm_state_notify(int running)
6096 VMChangeStateEntry *e;
6098 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6099 e->cb(e->opaque, running);
6103 /* XXX: support several handlers */
6104 static VMStopHandler *vm_stop_cb;
6105 static void *vm_stop_opaque;
6107 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6109 vm_stop_cb = cb;
6110 vm_stop_opaque = opaque;
6111 return 0;
6114 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6116 vm_stop_cb = NULL;
6119 void vm_start(void)
6121 if (!vm_running) {
6122 cpu_enable_ticks();
6123 vm_running = 1;
6124 vm_state_notify(1);
6128 void vm_stop(int reason)
6130 if (vm_running) {
6131 cpu_disable_ticks();
6132 vm_running = 0;
6133 if (reason != 0) {
6134 if (vm_stop_cb) {
6135 vm_stop_cb(vm_stop_opaque, reason);
6138 vm_state_notify(0);
6142 /* reset/shutdown handler */
6144 typedef struct QEMUResetEntry {
6145 QEMUResetHandler *func;
6146 void *opaque;
6147 struct QEMUResetEntry *next;
6148 } QEMUResetEntry;
6150 static QEMUResetEntry *first_reset_entry;
6151 int reset_requested;
6152 int shutdown_requested;
6153 int suspend_requested;
6154 static int powerdown_requested;
6156 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6158 QEMUResetEntry **pre, *re;
6160 pre = &first_reset_entry;
6161 while (*pre != NULL)
6162 pre = &(*pre)->next;
6163 re = qemu_mallocz(sizeof(QEMUResetEntry));
6164 re->func = func;
6165 re->opaque = opaque;
6166 re->next = NULL;
6167 *pre = re;
6170 void qemu_system_reset(void)
6172 QEMUResetEntry *re;
6174 /* reset all devices */
6175 for(re = first_reset_entry; re != NULL; re = re->next) {
6176 re->func(re->opaque);
6180 void qemu_system_reset_request(void)
6182 if (no_reboot) {
6183 shutdown_requested = 1;
6184 } else {
6185 reset_requested = 1;
6187 if (cpu_single_env)
6188 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6191 void qemu_system_shutdown_request(void)
6193 shutdown_requested = 1;
6194 if (cpu_single_env)
6195 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6198 void qemu_system_powerdown_request(void)
6200 powerdown_requested = 1;
6201 if (cpu_single_env)
6202 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6205 void main_loop_wait(int timeout)
6207 IOHandlerRecord *ioh;
6208 fd_set rfds, wfds, xfds;
6209 int ret, nfds;
6210 struct timeval tv;
6211 PollingEntry *pe;
6214 /* XXX: need to suppress polling by better using win32 events */
6215 ret = 0;
6216 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6217 ret |= pe->func(pe->opaque);
6219 #ifdef _WIN32
6220 if (ret == 0 && timeout > 0) {
6221 int err;
6222 WaitObjects *w = &wait_objects;
6224 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6225 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6226 if (w->func[ret - WAIT_OBJECT_0])
6227 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6228 } else if (ret == WAIT_TIMEOUT) {
6229 } else {
6230 err = GetLastError();
6231 fprintf(stderr, "Wait error %d %d\n", ret, err);
6234 #endif
6235 /* poll any events */
6236 /* XXX: separate device handlers from system ones */
6237 nfds = -1;
6238 FD_ZERO(&rfds);
6239 FD_ZERO(&wfds);
6240 FD_ZERO(&xfds);
6241 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6242 if (ioh->deleted)
6243 continue;
6244 if (ioh->fd_read &&
6245 (!ioh->fd_read_poll ||
6246 ioh->fd_read_poll(ioh->opaque) != 0)) {
6247 FD_SET(ioh->fd, &rfds);
6248 if (ioh->fd > nfds)
6249 nfds = ioh->fd;
6251 if (ioh->fd_write) {
6252 FD_SET(ioh->fd, &wfds);
6253 if (ioh->fd > nfds)
6254 nfds = ioh->fd;
6258 tv.tv_sec = 0;
6259 #ifdef _WIN32
6260 tv.tv_usec = 0;
6261 #else
6262 tv.tv_usec = timeout * 1000;
6263 #endif
6264 #if defined(CONFIG_SLIRP)
6265 if (slirp_inited) {
6266 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6268 #endif
6269 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6270 if (ret > 0) {
6271 IOHandlerRecord **pioh;
6273 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6274 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6275 ioh->fd_read(ioh->opaque);
6277 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6278 ioh->fd_write(ioh->opaque);
6282 /* remove deleted IO handlers */
6283 pioh = &first_io_handler;
6284 while (*pioh) {
6285 ioh = *pioh;
6286 if (ioh->deleted) {
6287 *pioh = ioh->next;
6288 qemu_free(ioh);
6289 } else
6290 pioh = &ioh->next;
6293 #if defined(CONFIG_SLIRP)
6294 if (slirp_inited) {
6295 if (ret < 0) {
6296 FD_ZERO(&rfds);
6297 FD_ZERO(&wfds);
6298 FD_ZERO(&xfds);
6300 slirp_select_poll(&rfds, &wfds, &xfds);
6302 #endif
6303 qemu_aio_poll();
6304 qemu_bh_poll();
6306 if (vm_running) {
6307 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6308 qemu_get_clock(vm_clock));
6309 /* run dma transfers, if any */
6310 DMA_run();
6313 /* real time timers */
6314 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6315 qemu_get_clock(rt_clock));
6318 #ifndef CONFIG_DM
6319 static CPUState *cur_cpu;
6321 int main_loop(void)
6323 int ret, timeout;
6324 #ifdef CONFIG_PROFILER
6325 int64_t ti;
6326 #endif
6327 CPUState *env;
6329 cur_cpu = first_cpu;
6330 for(;;) {
6331 if (vm_running) {
6333 env = cur_cpu;
6334 for(;;) {
6335 /* get next cpu */
6336 env = env->next_cpu;
6337 if (!env)
6338 env = first_cpu;
6339 #ifdef CONFIG_PROFILER
6340 ti = profile_getclock();
6341 #endif
6342 ret = cpu_exec(env);
6343 #ifdef CONFIG_PROFILER
6344 qemu_time += profile_getclock() - ti;
6345 #endif
6346 if (ret != EXCP_HALTED)
6347 break;
6348 /* all CPUs are halted ? */
6349 if (env == cur_cpu) {
6350 ret = EXCP_HLT;
6351 break;
6354 cur_cpu = env;
6356 if (shutdown_requested) {
6357 ret = EXCP_INTERRUPT;
6358 break;
6360 if (reset_requested) {
6361 reset_requested = 0;
6362 qemu_system_reset();
6363 ret = EXCP_INTERRUPT;
6365 if (powerdown_requested) {
6366 powerdown_requested = 0;
6367 qemu_system_powerdown();
6368 ret = EXCP_INTERRUPT;
6370 if (ret == EXCP_DEBUG) {
6371 vm_stop(EXCP_DEBUG);
6373 /* if hlt instruction, we wait until the next IRQ */
6374 /* XXX: use timeout computed from timers */
6375 if (ret == EXCP_HLT)
6376 timeout = 10;
6377 else
6378 timeout = 0;
6379 } else {
6380 timeout = 10;
6382 #ifdef CONFIG_PROFILER
6383 ti = profile_getclock();
6384 #endif
6385 main_loop_wait(timeout);
6386 #ifdef CONFIG_PROFILER
6387 dev_time += profile_getclock() - ti;
6388 #endif
6390 cpu_disable_ticks();
6391 return ret;
6393 #endif /* !CONFIG_DM */
6395 void help(void)
6397 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6398 "usage: %s [options] [disk_image]\n"
6399 "\n"
6400 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6401 "\n"
6402 "Standard options:\n"
6403 "-M machine select emulated machine (-M ? for list)\n"
6404 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6405 #ifndef CONFIG_DM
6406 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6407 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6408 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6409 #endif /* !CONFIG_DM */
6410 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6411 "-snapshot write to temporary files instead of disk image files\n"
6412 #ifdef CONFIG_SDL
6413 "-no-quit disable SDL window close capability\n"
6414 #endif
6415 #ifdef TARGET_I386
6416 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6417 #endif
6418 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6419 "-smp n set the number of CPUs to 'n' [default=1]\n"
6420 "-nographic disable graphical output and redirect serial I/Os to console\n"
6421 "-vcpus set CPU number of guest platform\n"
6422 #ifndef _WIN32
6423 "-k language use keyboard layout (for example \"fr\" for French)\n"
6424 #endif
6425 #ifdef HAS_AUDIO
6426 "-audio-help print list of audio drivers and their options\n"
6427 "-soundhw c1,... enable audio support\n"
6428 " and only specified sound cards (comma separated list)\n"
6429 " use -soundhw ? to get the list of supported cards\n"
6430 " use -soundhw all to enable all of them\n"
6431 #endif
6432 "-localtime set the real time clock to local time [default=utc]\n"
6433 "-full-screen start in full screen\n"
6434 #ifdef TARGET_I386
6435 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6436 #endif
6437 "-usb enable the USB driver (will be the default soon)\n"
6438 "-usbdevice name add the host or guest USB device 'name'\n"
6439 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6440 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6441 #endif
6442 "\n"
6443 "Network options:\n"
6444 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6445 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6446 #ifdef CONFIG_SLIRP
6447 "-net user[,vlan=n][,hostname=host]\n"
6448 " connect the user mode network stack to VLAN 'n' and send\n"
6449 " hostname 'host' to DHCP clients\n"
6450 #endif
6451 #ifdef _WIN32
6452 "-net tap[,vlan=n],ifname=name\n"
6453 " connect the host TAP network interface to VLAN 'n'\n"
6454 #else
6455 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
6456 " connect the host TAP network interface to VLAN 'n' and use\n"
6457 " the network script 'file' (default=%s);\n"
6458 " use 'script=no' to disable script execution;\n"
6459 " use 'fd=h' to connect to an already opened TAP interface\n"
6460 #endif
6461 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6462 " connect the vlan 'n' to another VLAN using a socket connection\n"
6463 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6464 " connect the vlan 'n' to multicast maddr and port\n"
6465 "-net none use it alone to have zero network devices; if no -net option\n"
6466 " is provided, the default is '-net nic -net user'\n"
6467 "\n"
6468 #ifdef CONFIG_SLIRP
6469 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6470 #ifndef _WIN32
6471 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6472 #endif
6473 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6474 " redirect TCP or UDP connections from host to guest [-net user]\n"
6475 #endif
6476 "\n"
6477 "Linux boot specific:\n"
6478 "-kernel bzImage use 'bzImage' as kernel image\n"
6479 "-append cmdline use 'cmdline' as kernel command line\n"
6480 "-initrd file use 'file' as initial ram disk\n"
6481 "\n"
6482 "Debug/Expert options:\n"
6483 "-monitor dev redirect the monitor to char device 'dev'\n"
6484 "-serial dev redirect the serial port to char device 'dev'\n"
6485 "-parallel dev redirect the parallel port to char device 'dev'\n"
6486 "-pidfile file Write PID to 'file'\n"
6487 "-S freeze CPU at startup (use 'c' to start execution)\n"
6488 "-s wait gdb connection to port %d\n"
6489 "-p port change gdb connection port\n"
6490 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
6491 "-d domain domain that we're serving\n"
6492 "-domain-name domain name that we're serving\n"
6493 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6494 " translation (t=none or lba) (usually qemu can guess them)\n"
6495 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6496 #ifdef USE_KQEMU
6497 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6498 "-no-kqemu disable KQEMU kernel module usage\n"
6499 #endif
6500 #ifdef USE_CODE_COPY
6501 "-no-code-copy disable code copy acceleration\n"
6502 #endif
6503 #ifdef TARGET_I386
6504 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6505 " (default is CL-GD5446 PCI VGA)\n"
6506 "-no-acpi disable ACPI\n"
6507 #endif
6508 "-no-reboot exit instead of rebooting\n"
6509 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6510 "-vnc display start a VNC server on display\n"
6511 "-vncviewer start a vncviewer process for this domain\n"
6512 "-vncunused bind the VNC server to an unused port\n"
6513 #ifndef _WIN32
6514 "-daemonize daemonize QEMU after initializing\n"
6515 #endif
6516 "-option-rom rom load a file, rom, into the option ROM space\n"
6517 "-acpi disable or enable ACPI of HVM domain \n"
6518 "\n"
6519 "During emulation, the following keys are useful:\n"
6520 "ctrl-alt-f toggle full screen\n"
6521 "ctrl-alt-n switch to virtual console 'n'\n"
6522 "ctrl-alt toggle mouse and keyboard grab\n"
6523 "\n"
6524 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6526 "qemu",
6527 DEFAULT_RAM_SIZE,
6528 #ifndef _WIN32
6529 DEFAULT_NETWORK_SCRIPT,
6530 #endif
6531 DEFAULT_GDBSTUB_PORT,
6532 "/tmp/qemu.log");
6533 exit(1);
6536 #define HAS_ARG 0x0001
6538 enum {
6539 QEMU_OPTION_h,
6541 QEMU_OPTION_M,
6542 QEMU_OPTION_fda,
6543 QEMU_OPTION_fdb,
6544 #ifndef CONFIG_DM
6545 QEMU_OPTION_hda,
6546 QEMU_OPTION_hdb,
6547 QEMU_OPTION_hdc,
6548 QEMU_OPTION_hdd,
6549 QEMU_OPTION_cdrom,
6550 #endif /* !CONFIG_DM */
6551 QEMU_OPTION_boot,
6552 QEMU_OPTION_snapshot,
6553 #ifdef TARGET_I386
6554 QEMU_OPTION_no_fd_bootchk,
6555 #endif
6556 QEMU_OPTION_m,
6557 QEMU_OPTION_nographic,
6558 #ifdef HAS_AUDIO
6559 QEMU_OPTION_audio_help,
6560 QEMU_OPTION_soundhw,
6561 #endif
6563 QEMU_OPTION_net,
6564 QEMU_OPTION_tftp,
6565 QEMU_OPTION_smb,
6566 QEMU_OPTION_redir,
6568 QEMU_OPTION_kernel,
6569 QEMU_OPTION_append,
6570 QEMU_OPTION_initrd,
6572 QEMU_OPTION_S,
6573 QEMU_OPTION_s,
6574 QEMU_OPTION_p,
6575 QEMU_OPTION_l,
6576 QEMU_OPTION_hdachs,
6577 QEMU_OPTION_L,
6578 #ifdef USE_CODE_COPY
6579 QEMU_OPTION_no_code_copy,
6580 #endif
6581 QEMU_OPTION_k,
6582 QEMU_OPTION_localtime,
6583 QEMU_OPTION_cirrusvga,
6584 QEMU_OPTION_g,
6585 QEMU_OPTION_std_vga,
6586 QEMU_OPTION_monitor,
6587 QEMU_OPTION_domainname,
6588 QEMU_OPTION_serial,
6589 QEMU_OPTION_parallel,
6590 QEMU_OPTION_loadvm,
6591 QEMU_OPTION_full_screen,
6592 QEMU_OPTION_no_quit,
6593 QEMU_OPTION_pidfile,
6594 QEMU_OPTION_no_kqemu,
6595 QEMU_OPTION_kernel_kqemu,
6596 QEMU_OPTION_win2k_hack,
6597 QEMU_OPTION_usb,
6598 QEMU_OPTION_usbdevice,
6599 QEMU_OPTION_smp,
6600 QEMU_OPTION_vnc,
6601 QEMU_OPTION_no_acpi,
6602 QEMU_OPTION_no_reboot,
6603 QEMU_OPTION_daemonize,
6604 QEMU_OPTION_option_rom,
6605 QEMU_OPTION_semihosting
6607 QEMU_OPTION_d,
6608 QEMU_OPTION_vcpus,
6609 QEMU_OPTION_acpi,
6610 QEMU_OPTION_vncviewer,
6611 QEMU_OPTION_vncunused,
6612 QEMU_OPTION_pci,
6613 };
6615 typedef struct QEMUOption {
6616 const char *name;
6617 int flags;
6618 int index;
6619 } QEMUOption;
6621 const QEMUOption qemu_options[] = {
6622 { "h", 0, QEMU_OPTION_h },
6623 { "help", 0, QEMU_OPTION_h },
6625 { "M", HAS_ARG, QEMU_OPTION_M },
6626 { "fda", HAS_ARG, QEMU_OPTION_fda },
6627 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6628 #ifndef CONFIG_DM
6629 { "hda", HAS_ARG, QEMU_OPTION_hda },
6630 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6631 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6632 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6633 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6634 #endif /* !CONFIG_DM */
6635 { "boot", HAS_ARG, QEMU_OPTION_boot },
6636 { "snapshot", 0, QEMU_OPTION_snapshot },
6637 #ifdef TARGET_I386
6638 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6639 #endif
6640 { "m", HAS_ARG, QEMU_OPTION_m },
6641 { "nographic", 0, QEMU_OPTION_nographic },
6642 { "k", HAS_ARG, QEMU_OPTION_k },
6643 #ifdef HAS_AUDIO
6644 { "audio-help", 0, QEMU_OPTION_audio_help },
6645 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6646 #endif
6648 { "net", HAS_ARG, QEMU_OPTION_net},
6649 #ifdef CONFIG_SLIRP
6650 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6651 #ifndef _WIN32
6652 { "smb", HAS_ARG, QEMU_OPTION_smb },
6653 #endif
6654 { "redir", HAS_ARG, QEMU_OPTION_redir },
6655 #endif
6657 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6658 { "append", HAS_ARG, QEMU_OPTION_append },
6659 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6661 { "S", 0, QEMU_OPTION_S },
6662 { "s", 0, QEMU_OPTION_s },
6663 { "p", HAS_ARG, QEMU_OPTION_p },
6664 { "l", HAS_ARG, QEMU_OPTION_l },
6665 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6666 { "L", HAS_ARG, QEMU_OPTION_L },
6667 #ifdef USE_CODE_COPY
6668 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6669 #endif
6670 #ifdef USE_KQEMU
6671 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6672 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6673 #endif
6674 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6675 { "g", 1, QEMU_OPTION_g },
6676 #endif
6677 { "localtime", 0, QEMU_OPTION_localtime },
6678 { "std-vga", 0, QEMU_OPTION_std_vga },
6679 { "monitor", 1, QEMU_OPTION_monitor },
6680 { "domain-name", 1, QEMU_OPTION_domainname },
6681 { "serial", 1, QEMU_OPTION_serial },
6682 { "parallel", 1, QEMU_OPTION_parallel },
6683 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6684 { "full-screen", 0, QEMU_OPTION_full_screen },
6685 #ifdef CONFIG_SDL
6686 { "no-quit", 0, QEMU_OPTION_no_quit },
6687 #endif
6688 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6689 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6690 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6691 { "smp", HAS_ARG, QEMU_OPTION_smp },
6692 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6693 { "vncviewer", 0, QEMU_OPTION_vncviewer },
6694 { "vncunused", 0, QEMU_OPTION_vncunused },
6696 /* temporary options */
6697 { "usb", 0, QEMU_OPTION_usb },
6698 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6699 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6700 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6701 { "daemonize", 0, QEMU_OPTION_daemonize },
6702 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6703 #if defined(TARGET_ARM)
6704 { "semihosting", 0, QEMU_OPTION_semihosting },
6705 #endif
6707 { "d", HAS_ARG, QEMU_OPTION_d },
6708 { "vcpus", 1, QEMU_OPTION_vcpus },
6709 { "acpi", 0, QEMU_OPTION_acpi },
6710 { "pci", HAS_ARG, QEMU_OPTION_pci},
6711 { NULL },
6712 };
6714 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6716 /* this stack is only used during signal handling */
6717 #define SIGNAL_STACK_SIZE 32768
6719 static uint8_t *signal_stack;
6721 #endif
6723 /* password input */
6725 static BlockDriverState *get_bdrv(int index)
6727 BlockDriverState *bs;
6729 if (index < 4) {
6730 bs = bs_table[index];
6731 } else if (index < 6) {
6732 bs = fd_table[index - 4];
6733 } else {
6734 bs = NULL;
6736 return bs;
6739 static void read_passwords(void)
6741 BlockDriverState *bs;
6742 int i, j;
6743 char password[256];
6745 for(i = 0; i < 6; i++) {
6746 bs = get_bdrv(i);
6747 if (bs && bdrv_is_encrypted(bs)) {
6748 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6749 for(j = 0; j < 3; j++) {
6750 monitor_readline("Password: ",
6751 1, password, sizeof(password));
6752 if (bdrv_set_key(bs, password) == 0)
6753 break;
6754 term_printf("invalid password\n");
6760 /* XXX: currently we cannot use simultaneously different CPUs */
6761 void register_machines(void)
6763 #if defined(TARGET_I386)
6764 #ifndef CONFIG_DM
6765 qemu_register_machine(&pc_machine);
6766 qemu_register_machine(&isapc_machine);
6767 #else
6768 qemu_register_machine(&xenfv_machine);
6769 qemu_register_machine(&xenpv_machine);
6770 #endif
6771 #elif defined(TARGET_PPC)
6772 qemu_register_machine(&heathrow_machine);
6773 qemu_register_machine(&core99_machine);
6774 qemu_register_machine(&prep_machine);
6775 #elif defined(TARGET_MIPS)
6776 qemu_register_machine(&mips_machine);
6777 qemu_register_machine(&mips_malta_machine);
6778 #elif defined(TARGET_SPARC)
6779 #ifdef TARGET_SPARC64
6780 qemu_register_machine(&sun4u_machine);
6781 #else
6782 qemu_register_machine(&sun4m_machine);
6783 #endif
6784 #elif defined(TARGET_ARM)
6785 qemu_register_machine(&integratorcp926_machine);
6786 qemu_register_machine(&integratorcp1026_machine);
6787 qemu_register_machine(&versatilepb_machine);
6788 qemu_register_machine(&versatileab_machine);
6789 qemu_register_machine(&realview_machine);
6790 #elif defined(TARGET_SH4)
6791 qemu_register_machine(&shix_machine);
6792 #else
6793 #error unsupported CPU
6794 #endif
6797 #ifdef HAS_AUDIO
6798 struct soundhw soundhw[] = {
6799 #ifndef CONFIG_DM
6800 #ifdef TARGET_I386
6802 "pcspk",
6803 "PC speaker",
6804 0,
6805 1,
6806 { .init_isa = pcspk_audio_init }
6807 },
6808 #endif
6809 #endif /* !CONFIG_DM */
6811 "sb16",
6812 "Creative Sound Blaster 16",
6813 0,
6814 1,
6815 { .init_isa = SB16_init }
6816 },
6818 #ifdef CONFIG_ADLIB
6820 "adlib",
6821 #ifdef HAS_YMF262
6822 "Yamaha YMF262 (OPL3)",
6823 #else
6824 "Yamaha YM3812 (OPL2)",
6825 #endif
6826 0,
6827 1,
6828 { .init_isa = Adlib_init }
6829 },
6830 #endif
6832 #ifdef CONFIG_GUS
6834 "gus",
6835 "Gravis Ultrasound GF1",
6836 0,
6837 1,
6838 { .init_isa = GUS_init }
6839 },
6840 #endif
6843 "es1370",
6844 "ENSONIQ AudioPCI ES1370",
6845 0,
6846 0,
6847 { .init_pci = es1370_init }
6848 },
6850 { NULL, NULL, 0, 0, { NULL } }
6851 };
6853 static void select_soundhw (const char *optarg)
6855 struct soundhw *c;
6857 if (*optarg == '?') {
6858 show_valid_cards:
6860 printf ("Valid sound card names (comma separated):\n");
6861 for (c = soundhw; c->name; ++c) {
6862 printf ("%-11s %s\n", c->name, c->descr);
6864 printf ("\n-soundhw all will enable all of the above\n");
6865 exit (*optarg != '?');
6867 else {
6868 size_t l;
6869 const char *p;
6870 char *e;
6871 int bad_card = 0;
6873 if (!strcmp (optarg, "all")) {
6874 for (c = soundhw; c->name; ++c) {
6875 c->enabled = 1;
6877 return;
6880 p = optarg;
6881 while (*p) {
6882 e = strchr (p, ',');
6883 l = !e ? strlen (p) : (size_t) (e - p);
6885 for (c = soundhw; c->name; ++c) {
6886 if (!strncmp (c->name, p, l)) {
6887 c->enabled = 1;
6888 break;
6892 if (!c->name) {
6893 if (l > 80) {
6894 fprintf (stderr,
6895 "Unknown sound card name (too big to show)\n");
6897 else {
6898 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6899 (int) l, p);
6901 bad_card = 1;
6903 p += l + (e != NULL);
6906 if (bad_card)
6907 goto show_valid_cards;
6910 #endif
6912 #ifdef _WIN32
6913 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6915 exit(STATUS_CONTROL_C_EXIT);
6916 return TRUE;
6918 #endif
6920 #define MAX_NET_CLIENTS 32
6922 #include <xg_private.h>
6924 /* FIXME Flush the shadow page */
6925 int unset_mm_mapping(int xc_handle, uint32_t domid,
6926 unsigned long nr_pages, unsigned int address_bits,
6927 xen_pfn_t *extent_start)
6929 int err = 0;
6930 xc_dominfo_t info;
6932 xc_domain_getinfo(xc_handle, domid, 1, &info);
6933 if ((info.nr_pages - nr_pages) <= 0) {
6934 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
6935 err = -1;
6938 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
6939 nr_pages, 0, extent_start);
6940 if (err)
6941 fprintf(stderr, "Failed to decrease physmap\n");
6944 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
6945 PAGE_SIZE/1024) != 0) {
6946 fprintf(logfile, "set maxmem returned error %d\n", errno);
6947 err = -1;
6950 return err;
6953 int set_mm_mapping(int xc_handle, uint32_t domid,
6954 unsigned long nr_pages, unsigned int address_bits,
6955 xen_pfn_t *extent_start)
6957 xc_dominfo_t info;
6958 int err = 0;
6960 xc_domain_getinfo(xc_handle, domid, 1, &info);
6962 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
6963 nr_pages * PAGE_SIZE/1024) != 0) {
6964 fprintf(logfile, "set maxmem returned error %d\n", errno);
6965 return -1;
6968 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
6969 address_bits, extent_start);
6970 if (err) {
6971 fprintf(stderr, "Failed to populate physmap\n");
6972 return -1;
6975 return 0;
6979 int main(int argc, char **argv)
6981 #ifdef CONFIG_GDBSTUB
6982 int use_gdbstub, gdbstub_port;
6983 #endif
6984 int i;
6985 #ifndef CONFIG_DM
6986 int cdrom_index;
6987 #endif /* !CONFIG_DM */
6988 int snapshot, linux_boot;
6989 const char *initrd_filename;
6990 #ifndef CONFIG_DM
6991 const char *hd_filename[MAX_DISKS + MAX_SCSI_DISKS];
6992 #endif /* !CONFIG_DM */
6993 const char *fd_filename[MAX_FD];
6994 const char *kernel_filename, *kernel_cmdline;
6995 DisplayState *ds = &display_state;
6996 int cyls, heads, secs, translation;
6997 char net_clients[MAX_NET_CLIENTS][256];
6998 int nb_net_clients;
6999 int optind;
7000 const char *r, *optarg;
7001 CharDriverState *monitor_hd;
7002 char monitor_device[128];
7003 char serial_devices[MAX_SERIAL_PORTS][128];
7004 int serial_device_index;
7005 char parallel_devices[MAX_PARALLEL_PORTS][128];
7006 int parallel_device_index;
7007 const char *loadvm = NULL;
7008 QEMUMachine *machine;
7009 char usb_devices[MAX_USB_CMDLINE][128];
7010 int usb_devices_index;
7011 int fds[2];
7012 struct rlimit rl;
7013 sigset_t set;
7014 char qemu_dm_logfilename[128];
7015 const char *direct_pci = NULL;
7017 #ifndef __sun__
7018 /* Maximise rlimits. Needed where default constraints are tight (*BSD). */
7019 if (getrlimit(RLIMIT_STACK, &rl) != 0) {
7020 perror("getrlimit(RLIMIT_STACK)");
7021 exit(1);
7023 rl.rlim_cur = rl.rlim_max;
7024 if (setrlimit(RLIMIT_STACK, &rl) != 0)
7025 perror("setrlimit(RLIMIT_STACK)");
7026 if (getrlimit(RLIMIT_DATA, &rl) != 0) {
7027 perror("getrlimit(RLIMIT_DATA)");
7028 exit(1);
7030 rl.rlim_cur = rl.rlim_max;
7031 if (setrlimit(RLIMIT_DATA, &rl) != 0)
7032 perror("setrlimit(RLIMIT_DATA)");
7033 rl.rlim_cur = RLIM_INFINITY;
7034 rl.rlim_max = RLIM_INFINITY;
7035 if (setrlimit(RLIMIT_RSS, &rl) != 0)
7036 perror("setrlimit(RLIMIT_RSS)");
7037 rl.rlim_cur = RLIM_INFINITY;
7038 rl.rlim_max = RLIM_INFINITY;
7039 if (setrlimit(RLIMIT_MEMLOCK, &rl) != 0)
7040 perror("setrlimit(RLIMIT_MEMLOCK)");
7041 #endif
7043 /* Ensure that SIGUSR2 is blocked by default when a new thread is created,
7044 then only the threads that use the signal unblock it -- this fixes a
7045 race condition in Qcow support where the AIO signal is misdelivered. */
7047 extern const int aio_sig_num;
7048 sigset_t set;
7050 sigemptyset(&set);
7051 sigaddset(&set, aio_sig_num);
7052 sigprocmask(SIG_BLOCK, &set, NULL);
7055 LIST_INIT (&vm_change_state_head);
7056 #ifndef _WIN32
7058 struct sigaction act;
7059 sigfillset(&act.sa_mask);
7060 act.sa_flags = 0;
7061 act.sa_handler = SIG_IGN;
7062 sigaction(SIGPIPE, &act, NULL);
7064 #else
7065 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7066 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7067 QEMU to run on a single CPU */
7069 HANDLE h;
7070 DWORD mask, smask;
7071 int i;
7072 h = GetCurrentProcess();
7073 if (GetProcessAffinityMask(h, &mask, &smask)) {
7074 for(i = 0; i < 32; i++) {
7075 if (mask & (1 << i))
7076 break;
7078 if (i != 32) {
7079 mask = 1 << i;
7080 SetProcessAffinityMask(h, mask);
7084 #endif
7086 register_machines();
7087 machine = first_machine;
7088 initrd_filename = NULL;
7089 for(i = 0; i < MAX_FD; i++)
7090 fd_filename[i] = NULL;
7091 #ifndef CONFIG_DM
7092 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++)
7093 hd_filename[i] = NULL;
7094 #endif /* !CONFIG_DM */
7095 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7096 vga_ram_size = VGA_RAM_SIZE;
7097 bios_size = BIOS_SIZE;
7098 #ifdef CONFIG_GDBSTUB
7099 use_gdbstub = 0;
7100 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7101 #endif
7102 snapshot = 0;
7103 nographic = 0;
7104 vncviewer = 0;
7105 vncunused = 0;
7106 kernel_filename = NULL;
7107 kernel_cmdline = "";
7108 #ifndef CONFIG_DM
7109 #ifdef TARGET_PPC
7110 cdrom_index = 1;
7111 #else
7112 cdrom_index = 2;
7113 #endif
7114 #endif /* !CONFIG_DM */
7115 cyls = heads = secs = 0;
7116 translation = BIOS_ATA_TRANSLATION_AUTO;
7117 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7119 for(i = 0; i < MAX_SERIAL_PORTS; i++)
7120 serial_devices[i][0] = '\0';
7121 serial_device_index = 0;
7123 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7124 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7125 parallel_devices[i][0] = '\0';
7126 parallel_device_index = 0;
7128 usb_devices_index = 0;
7130 nb_net_clients = 0;
7132 nb_nics = 0;
7133 /* default mac address of the first network interface */
7135 /* Init logs to stderr to start with */
7136 cpu_set_log(0);
7138 optind = 1;
7139 for(;;) {
7140 if (optind >= argc)
7141 break;
7142 r = argv[optind];
7143 if (r[0] != '-') {
7144 #ifndef CONFIG_DM
7145 hd_filename[0] = argv[optind++];
7146 #else
7147 help();
7148 #endif /* !CONFIG_DM */
7149 } else {
7150 const QEMUOption *popt;
7152 optind++;
7153 /* Treat --foo the same as -foo. */
7154 if (r[1] == '-')
7155 r++;
7156 popt = qemu_options;
7157 for(;;) {
7158 if (!popt->name) {
7159 fprintf(stderr, "%s: invalid option -- '%s'\n",
7160 argv[0], r);
7161 exit(1);
7163 if (!strcmp(popt->name, r + 1))
7164 break;
7165 popt++;
7167 if (popt->flags & HAS_ARG) {
7168 if (optind >= argc) {
7169 fprintf(stderr, "%s: option '%s' requires an argument\n",
7170 argv[0], r);
7171 exit(1);
7173 optarg = argv[optind++];
7174 } else {
7175 optarg = NULL;
7178 switch(popt->index) {
7179 case QEMU_OPTION_M:
7180 machine = find_machine(optarg);
7181 if (!machine) {
7182 QEMUMachine *m;
7183 printf("Supported machines are:\n");
7184 for(m = first_machine; m != NULL; m = m->next) {
7185 printf("%-10s %s%s\n",
7186 m->name, m->desc,
7187 m == first_machine ? " (default)" : "");
7189 exit(1);
7191 break;
7192 case QEMU_OPTION_initrd:
7193 initrd_filename = optarg;
7194 break;
7195 #ifndef CONFIG_DM
7196 case QEMU_OPTION_hda:
7197 case QEMU_OPTION_hdb:
7198 case QEMU_OPTION_hdc:
7199 case QEMU_OPTION_hdd:
7201 int hd_index;
7202 hd_index = popt->index - QEMU_OPTION_hda;
7203 hd_filename[hd_index] = optarg;
7204 if (hd_index == cdrom_index)
7205 cdrom_index = -1;
7207 break;
7208 #endif /* !CONFIG_DM */
7209 case QEMU_OPTION_snapshot:
7210 snapshot = 1;
7211 break;
7212 case QEMU_OPTION_hdachs:
7214 const char *p;
7215 p = optarg;
7216 cyls = strtol(p, (char **)&p, 0);
7217 if (cyls < 1 || cyls > 16383)
7218 goto chs_fail;
7219 if (*p != ',')
7220 goto chs_fail;
7221 p++;
7222 heads = strtol(p, (char **)&p, 0);
7223 if (heads < 1 || heads > 16)
7224 goto chs_fail;
7225 if (*p != ',')
7226 goto chs_fail;
7227 p++;
7228 secs = strtol(p, (char **)&p, 0);
7229 if (secs < 1 || secs > 63)
7230 goto chs_fail;
7231 if (*p == ',') {
7232 p++;
7233 if (!strcmp(p, "none"))
7234 translation = BIOS_ATA_TRANSLATION_NONE;
7235 else if (!strcmp(p, "lba"))
7236 translation = BIOS_ATA_TRANSLATION_LBA;
7237 else if (!strcmp(p, "auto"))
7238 translation = BIOS_ATA_TRANSLATION_AUTO;
7239 else
7240 goto chs_fail;
7241 } else if (*p != '\0') {
7242 chs_fail:
7243 fprintf(stderr, "qemu: invalid physical CHS format\n");
7244 exit(1);
7247 break;
7248 case QEMU_OPTION_nographic:
7249 if(!strcmp(monitor_device, "vc"))
7250 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7251 if(!strcmp(serial_devices[0], "vc"))
7252 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
7253 "null");
7254 nographic = 1;
7255 break;
7256 case QEMU_OPTION_kernel:
7257 kernel_filename = optarg;
7258 break;
7259 case QEMU_OPTION_append:
7260 kernel_cmdline = optarg;
7261 break;
7262 #ifndef CONFIG_DM
7263 case QEMU_OPTION_cdrom:
7264 if (cdrom_index >= 0) {
7265 hd_filename[cdrom_index] = optarg;
7267 break;
7268 #endif /* !CONFIG_DM */
7269 case QEMU_OPTION_boot:
7270 boot_device = strdup(optarg);
7271 if (strspn(boot_device, "a"
7272 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7273 // Network boot
7274 "n"
7275 #endif
7276 "cd") != strlen(boot_device)) {
7277 fprintf(stderr, "qemu: invalid boot device in '%s'\n", boot_device);
7278 exit(1);
7280 break;
7281 case QEMU_OPTION_fda:
7282 fd_filename[0] = optarg;
7283 break;
7284 case QEMU_OPTION_fdb:
7285 fd_filename[1] = optarg;
7286 break;
7287 #ifdef TARGET_I386
7288 case QEMU_OPTION_no_fd_bootchk:
7289 fd_bootchk = 0;
7290 break;
7291 #endif
7292 #ifdef USE_CODE_COPY
7293 case QEMU_OPTION_no_code_copy:
7294 code_copy_enabled = 0;
7295 break;
7296 #endif
7297 case QEMU_OPTION_net:
7298 if (nb_net_clients >= MAX_NET_CLIENTS) {
7299 fprintf(stderr, "qemu: too many network clients\n");
7300 exit(1);
7302 pstrcpy(net_clients[nb_net_clients],
7303 sizeof(net_clients[0]),
7304 optarg);
7305 nb_net_clients++;
7306 break;
7307 #ifdef CONFIG_SLIRP
7308 case QEMU_OPTION_tftp:
7309 tftp_prefix = optarg;
7310 break;
7311 #ifndef _WIN32
7312 case QEMU_OPTION_smb:
7313 net_slirp_smb(optarg);
7314 break;
7315 #endif
7316 case QEMU_OPTION_redir:
7317 net_slirp_redir(optarg);
7318 break;
7319 #endif
7320 #ifdef HAS_AUDIO
7321 case QEMU_OPTION_audio_help:
7322 AUD_help ();
7323 exit (0);
7324 break;
7325 case QEMU_OPTION_soundhw:
7326 select_soundhw (optarg);
7327 break;
7328 #endif
7329 case QEMU_OPTION_h:
7330 help();
7331 break;
7332 case QEMU_OPTION_m:
7333 ram_size = atol(optarg) * 1024 * 1024;
7334 ram_size = (uint64_t)atol(optarg) * 1024 * 1024;
7335 if (ram_size <= 0)
7336 help();
7337 #ifndef CONFIG_DM
7338 if (ram_size > PHYS_RAM_MAX_SIZE) {
7339 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7340 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7341 exit(1);
7343 #endif /* !CONFIG_DM */
7344 break;
7345 case QEMU_OPTION_l:
7347 int mask;
7348 CPULogItem *item;
7350 mask = cpu_str_to_log_mask(optarg);
7351 if (!mask) {
7352 printf("Log items (comma separated):\n");
7353 for(item = cpu_log_items; item->mask != 0; item++) {
7354 printf("%-10s %s\n", item->name, item->help);
7356 exit(1);
7358 cpu_set_log(mask);
7360 break;
7361 #ifdef CONFIG_GDBSTUB
7362 case QEMU_OPTION_s:
7363 use_gdbstub = 1;
7364 break;
7365 case QEMU_OPTION_p:
7366 gdbstub_port = atoi(optarg);
7367 break;
7368 #endif
7369 case QEMU_OPTION_L:
7370 bios_dir = optarg;
7371 break;
7372 case QEMU_OPTION_S:
7373 autostart = 0;
7374 break;
7375 case QEMU_OPTION_k:
7376 keyboard_layout = optarg;
7377 break;
7378 case QEMU_OPTION_localtime:
7379 rtc_utc = 0;
7380 break;
7381 case QEMU_OPTION_cirrusvga:
7382 cirrus_vga_enabled = 1;
7383 break;
7384 case QEMU_OPTION_std_vga:
7385 cirrus_vga_enabled = 0;
7386 break;
7387 case QEMU_OPTION_g:
7389 const char *p;
7390 int w, h, depth;
7391 p = optarg;
7392 w = strtol(p, (char **)&p, 10);
7393 if (w <= 0) {
7394 graphic_error:
7395 fprintf(stderr, "qemu: invalid resolution or depth\n");
7396 exit(1);
7398 if (*p != 'x')
7399 goto graphic_error;
7400 p++;
7401 h = strtol(p, (char **)&p, 10);
7402 if (h <= 0)
7403 goto graphic_error;
7404 if (*p == 'x') {
7405 p++;
7406 depth = strtol(p, (char **)&p, 10);
7407 if (depth != 8 && depth != 15 && depth != 16 &&
7408 depth != 24 && depth != 32)
7409 goto graphic_error;
7410 } else if (*p == '\0') {
7411 depth = graphic_depth;
7412 } else {
7413 goto graphic_error;
7416 graphic_width = w;
7417 graphic_height = h;
7418 graphic_depth = depth;
7420 break;
7421 case QEMU_OPTION_monitor:
7422 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7423 break;
7424 case QEMU_OPTION_serial:
7425 if (serial_device_index >= MAX_SERIAL_PORTS) {
7426 fprintf(stderr, "qemu: too many serial ports\n");
7427 exit(1);
7429 pstrcpy(serial_devices[serial_device_index],
7430 sizeof(serial_devices[0]), optarg);
7431 serial_device_index++;
7432 break;
7433 case QEMU_OPTION_parallel:
7434 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7435 fprintf(stderr, "qemu: too many parallel ports\n");
7436 exit(1);
7438 pstrcpy(parallel_devices[parallel_device_index],
7439 sizeof(parallel_devices[0]), optarg);
7440 parallel_device_index++;
7441 break;
7442 case QEMU_OPTION_loadvm:
7443 loadvm = optarg;
7444 break;
7445 case QEMU_OPTION_full_screen:
7446 full_screen = 1;
7447 break;
7448 #ifdef CONFIG_SDL
7449 case QEMU_OPTION_no_quit:
7450 no_quit = 1;
7451 break;
7452 #endif
7453 case QEMU_OPTION_pidfile:
7454 create_pidfile(optarg);
7455 break;
7456 #ifdef TARGET_I386
7457 case QEMU_OPTION_win2k_hack:
7458 win2k_install_hack = 1;
7459 break;
7460 #endif
7461 #ifdef USE_KQEMU
7462 case QEMU_OPTION_no_kqemu:
7463 kqemu_allowed = 0;
7464 break;
7465 case QEMU_OPTION_kernel_kqemu:
7466 kqemu_allowed = 2;
7467 break;
7468 #endif
7469 case QEMU_OPTION_usb:
7470 usb_enabled = 1;
7471 break;
7472 case QEMU_OPTION_usbdevice:
7473 usb_enabled = 1;
7474 if (usb_devices_index >= MAX_USB_CMDLINE) {
7475 fprintf(stderr, "Too many USB devices\n");
7476 exit(1);
7478 pstrcpy(usb_devices[usb_devices_index],
7479 sizeof(usb_devices[usb_devices_index]),
7480 optarg);
7481 usb_devices_index++;
7482 break;
7483 case QEMU_OPTION_smp:
7484 smp_cpus = atoi(optarg);
7485 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7486 fprintf(stderr, "Invalid number of CPUs\n");
7487 exit(1);
7489 break;
7490 case QEMU_OPTION_vnc:
7491 vnc_display = optarg;
7492 break;
7493 case QEMU_OPTION_no_acpi:
7494 acpi_enabled = 0;
7495 break;
7496 case QEMU_OPTION_no_reboot:
7497 no_reboot = 1;
7498 break;
7499 case QEMU_OPTION_daemonize:
7500 daemonize = 1;
7501 break;
7502 case QEMU_OPTION_option_rom:
7503 if (nb_option_roms >= MAX_OPTION_ROMS) {
7504 fprintf(stderr, "Too many option ROMs\n");
7505 exit(1);
7507 option_rom[nb_option_roms] = optarg;
7508 nb_option_roms++;
7509 break;
7510 case QEMU_OPTION_semihosting:
7511 semihosting_enabled = 1;
7512 break;
7513 case QEMU_OPTION_domainname:
7514 snprintf(domain_name, sizeof(domain_name),
7515 "Xen-%s", optarg);
7516 break;
7517 case QEMU_OPTION_d:
7518 domid = atoi(optarg);
7519 fprintf(logfile, "domid: %d\n", domid);
7520 break;
7521 case QEMU_OPTION_vcpus:
7522 vcpus = atoi(optarg);
7523 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
7524 break;
7525 case QEMU_OPTION_acpi:
7526 acpi_enabled = 1;
7527 break;
7528 case QEMU_OPTION_vncviewer:
7529 vncviewer++;
7530 break;
7531 case QEMU_OPTION_vncunused:
7532 vncunused++;
7533 break;
7534 case QEMU_OPTION_pci:
7535 direct_pci = optarg;
7536 break;
7541 /* Now send logs to our named config */
7542 sprintf(qemu_dm_logfilename, "/var/log/xen/qemu-dm-%d.log", domid);
7543 cpu_set_log_filename(qemu_dm_logfilename);
7545 #ifndef _WIN32
7546 if (daemonize && !nographic && vnc_display == NULL && vncunused == 0) {
7547 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7548 daemonize = 0;
7551 if (daemonize) {
7552 pid_t pid;
7554 if (pipe(fds) == -1)
7555 exit(1);
7557 pid = fork();
7558 if (pid > 0) {
7559 uint8_t status;
7560 ssize_t len;
7562 close(fds[1]);
7564 again:
7565 len = read(fds[0], &status, 1);
7566 if (len == -1 && (errno == EINTR))
7567 goto again;
7569 if (len != 1 || status != 0)
7570 exit(1);
7571 else
7572 exit(0);
7573 } else if (pid < 0)
7574 exit(1);
7576 setsid();
7578 pid = fork();
7579 if (pid > 0)
7580 exit(0);
7581 else if (pid < 0)
7582 exit(1);
7584 umask(027);
7585 chdir("/");
7587 signal(SIGTSTP, SIG_IGN);
7588 signal(SIGTTOU, SIG_IGN);
7589 signal(SIGTTIN, SIG_IGN);
7591 #endif
7593 #ifdef CONFIG_DM
7594 bdrv_init();
7595 xc_handle = xc_interface_open();
7596 xenstore_parse_domain_config(domid);
7597 #endif /* CONFIG_DM */
7599 #ifdef USE_KQEMU
7600 if (smp_cpus > 1)
7601 kqemu_allowed = 0;
7602 #endif
7603 linux_boot = (kernel_filename != NULL);
7605 #ifndef CONFIG_DM
7606 if (!linux_boot &&
7607 hd_filename[0] == '\0' &&
7608 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7609 fd_filename[0] == '\0')
7610 help();
7612 /* boot to floppy or the default cd if no hard disk defined yet */
7613 if (hd_filename[0] == '\0' && boot_device == 'c') {
7614 if (fd_filename[0] != '\0')
7615 boot_device = 'a';
7616 else
7617 boot_device = 'd';
7619 #endif /* !CONFIG_DM */
7621 setvbuf(stdout, NULL, _IOLBF, 0);
7623 init_timers();
7624 init_timer_alarm();
7625 qemu_aio_init();
7627 #ifdef _WIN32
7628 socket_init();
7629 #endif
7631 #ifndef CONFIG_DM
7632 /* init network clients */
7633 if (nb_net_clients == 0) {
7634 /* if no clients, we use a default config */
7635 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7636 "nic");
7637 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7638 "user");
7639 nb_net_clients = 2;
7641 #endif /* !CONFIG_DM */
7643 for(i = 0;i < nb_net_clients; i++) {
7644 if (net_client_init(net_clients[i]) < 0)
7645 exit(1);
7648 #ifndef CONFIG_DM
7649 #ifdef TARGET_I386
7650 if (boot_device == 'n') {
7651 for (i = 0; i < nb_nics; i++) {
7652 const char *model = nd_table[i].model;
7653 char buf[1024];
7654 if (model == NULL)
7655 model = "ne2k_pci";
7656 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7657 if (get_image_size(buf) > 0) {
7658 option_rom[nb_option_roms] = strdup(buf);
7659 nb_option_roms++;
7660 break;
7663 if (i == nb_nics) {
7664 fprintf(stderr, "No valid PXE rom found for network device\n");
7665 exit(1);
7667 boot_device = 'c'; /* to prevent confusion by the BIOS */
7669 #endif
7670 #endif /* !CONFIG_DM */
7672 #if defined (__ia64__)
7673 if (ram_size > MMIO_START)
7674 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
7675 #endif
7677 /* init the memory */
7678 phys_ram_size = ram_size + vga_ram_size + bios_size;
7680 #ifndef CONFIG_DM
7681 for (i = 0; i < nb_option_roms; i++) {
7682 int ret = get_image_size(option_rom[i]);
7683 if (ret == -1) {
7684 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7685 exit(1);
7687 phys_ram_size += ret;
7690 phys_ram_base = qemu_vmalloc(phys_ram_size);
7691 if (!phys_ram_base) {
7692 fprintf(stderr, "Could not allocate physical memory\n");
7693 exit(1);
7696 /* we always create the cdrom drive, even if no disk is there */
7697 bdrv_init();
7698 if (cdrom_index >= 0) {
7699 bs_table[cdrom_index] = bdrv_new("cdrom");
7700 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7703 /* open the virtual block devices */
7704 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
7705 if (hd_filename[i]) {
7706 if (!bs_table[i]) {
7707 char buf[64];
7708 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7709 bs_table[i] = bdrv_new(buf);
7711 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7712 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7713 hd_filename[i]);
7714 exit(1);
7716 if (i == 0 && cyls != 0) {
7717 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7718 bdrv_set_translation_hint(bs_table[i], translation);
7722 #endif /* !CONFIG_DM */
7724 /* we always create at least one floppy disk */
7725 fd_table[0] = bdrv_new("fda");
7726 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7728 for(i = 0; i < MAX_FD; i++) {
7729 if (fd_filename[i]) {
7730 if (!fd_table[i]) {
7731 char buf[64];
7732 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7733 fd_table[i] = bdrv_new(buf);
7734 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7736 if (fd_filename[i] != '\0') {
7737 if (bdrv_open(fd_table[i], fd_filename[i],
7738 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7739 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7740 fd_filename[i]);
7741 exit(1);
7747 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7748 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7750 init_ioports();
7752 /* terminal init */
7753 if (nographic) {
7754 dumb_display_init(ds);
7755 } else if (vnc_display != NULL || vncunused != 0) {
7756 int vnc_display_port;
7757 char password[20];
7758 vnc_display_init(ds);
7759 if (xenstore_read_vncpasswd(domid, password, sizeof(password)) < 0)
7760 exit(0);
7761 vnc_display_password(ds, password);
7762 if ((vnc_display_port = vnc_display_open(ds, vnc_display, vncunused)) < 0)
7763 exit (0);
7764 if (vncviewer)
7765 vnc_start_viewer(vnc_display_port);
7766 xenstore_write_vncport(vnc_display_port);
7767 } else {
7768 #if defined(CONFIG_SDL)
7769 sdl_display_init(ds, full_screen);
7770 #elif defined(CONFIG_COCOA)
7771 cocoa_display_init(ds, full_screen);
7772 #else
7773 dumb_display_init(ds);
7774 #endif
7777 monitor_hd = qemu_chr_open(monitor_device);
7778 if (!monitor_hd) {
7779 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7780 exit(1);
7782 store_dev_info(monitor_device, domid, monitor_hd, "/monitor");
7783 monitor_init(monitor_hd, !nographic);
7785 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7786 const char *devname = serial_devices[i];
7787 if (devname[0] != '\0' && strcmp(devname, "none")) {
7788 char buf[16];
7789 serial_hds[i] = qemu_chr_open(devname);
7790 if (!serial_hds[i]) {
7791 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7792 devname);
7793 exit(1);
7795 snprintf(buf, sizeof(buf), "/serial/%d", i);
7796 store_dev_info(serial_devices[i], domid, serial_hds[i], buf);
7797 if (i == 0) /* serial 0 is also called the console */
7798 store_dev_info(serial_devices[i], domid,
7799 serial_hds[i], "/console");
7800 if (!strcmp(devname, "vc"))
7801 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7805 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7806 const char *devname = parallel_devices[i];
7807 if (devname[0] != '\0' && strcmp(devname, "none")) {
7808 char buf[16];
7809 parallel_hds[i] = qemu_chr_open(devname);
7810 if (!parallel_hds[i]) {
7811 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7812 devname);
7813 exit(1);
7815 snprintf(buf, sizeof(buf), "/parallel/%d", i);
7816 store_dev_info(parallel_devices[i], domid, parallel_hds[i], buf);
7817 if (!strcmp(devname, "vc"))
7818 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7822 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
7824 machine->init(ram_size, vga_ram_size, boot_device,
7825 ds, fd_filename, snapshot,
7826 kernel_filename, kernel_cmdline, initrd_filename,
7827 direct_pci);
7828 free(boot_device);
7830 /* init USB devices */
7831 if (usb_enabled) {
7832 for(i = 0; i < usb_devices_index; i++) {
7833 if (usb_device_add(usb_devices[i]) < 0) {
7834 fprintf(stderr, "Warning: could not add USB device %s\n",
7835 usb_devices[i]);
7840 if (vnc_display == NULL && vncunused == 0) {
7841 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7842 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7845 #ifdef CONFIG_GDBSTUB
7846 if (use_gdbstub) {
7847 /* XXX: use standard host:port notation and modify options
7848 accordingly. */
7849 if (gdbserver_start_port(gdbstub_port) < 0) {
7850 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7851 gdbstub_port);
7852 exit(1);
7854 } else
7855 #endif
7856 if (loadvm)
7857 do_loadvm(loadvm);
7860 /* XXX: simplify init */
7861 read_passwords();
7862 if (autostart) {
7863 vm_start();
7867 if (daemonize) {
7868 uint8_t status = 0;
7869 ssize_t len;
7870 int fd;
7872 again1:
7873 len = write(fds[1], &status, 1);
7874 if (len == -1 && (errno == EINTR))
7875 goto again1;
7877 if (len != 1)
7878 exit(1);
7880 fd = open("/dev/null", O_RDWR);
7881 if (fd == -1)
7882 exit(1);
7884 dup2(fd, 0);
7885 dup2(fd, 1);
7886 dup2(fd, 2);
7888 close(fd);
7891 /* Unblock SIGTERM, which may have been blocked by the caller */
7892 sigemptyset(&set);
7893 sigaddset(&set, SIGTERM);
7894 if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
7895 fprintf(stderr, "Failed to unblock SIGTERM\n");
7897 main_loop();
7898 quit_timers();
7899 return 0;