ia64/xen-unstable

view tools/ioemu/vl.c @ 17186:854b0704962b

ioemu: Slown down refresh interval when SDL is minimized
as that saves us the VGA refresh scanning.

Signed-off-by: Samuel Thibault <samuel.thibault@eu.citrix.com>
author Keir Fraser <keir.fraser@citrix.com>
date Wed Mar 05 09:43:03 2008 +0000 (2008-03-05)
parents e44c6b67a483
children e1898e917373
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 #ifndef CONFIG_STUBDOM
40 #include <sys/poll.h>
41 #endif
42 #include <sys/mman.h>
43 #include <sys/ioctl.h>
44 #include <sys/resource.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #ifndef CONFIG_STUBDOM
48 #include <net/if.h>
49 #endif
50 #if defined(__NetBSD__)
51 #include <net/if_tap.h>
52 #endif
53 #if defined(__linux__) || defined(__Linux__)
54 #include <linux/if_tun.h>
55 #endif
56 #ifndef CONFIG_STUBDOM
57 #include <arpa/inet.h>
58 #include <dirent.h>
59 #endif
60 #include <netdb.h>
61 #ifndef CONFIG_STUBDOM
62 #ifdef _BSD
63 #include <sys/stat.h>
64 #ifndef _BSD
65 #include <libutil.h>
66 #else
67 #include <util.h>
68 #endif
69 #else
70 #ifndef __sun__
71 #include <pty.h>
72 #include <linux/rtc.h>
73 #include <linux/ppdev.h>
74 #endif
75 #endif
76 #if defined(__sun__)
77 #include <stropts.h>
78 #endif
79 #endif
80 #endif
82 #if defined(CONFIG_SLIRP)
83 #include "libslirp.h"
84 #endif
86 #ifdef _WIN32
87 #include <sys/timeb.h>
88 #include <windows.h>
89 #define getopt_long_only getopt_long
90 #define memalign(align, size) malloc(size)
91 #define NO_DAEMONIZE 1
92 #endif
94 #include "qemu_socket.h"
96 #ifdef CONFIG_SDL
97 #ifdef __APPLE__
98 #include <SDL/SDL.h>
99 #endif
100 #endif /* CONFIG_SDL */
102 #ifdef CONFIG_COCOA
103 #undef main
104 #define main qemu_main
105 #endif /* CONFIG_COCOA */
107 #include "disas.h"
109 #include "exec-all.h"
111 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
112 #ifdef _BSD
113 #define DEFAULT_BRIDGE "bridge0"
114 #else
115 #define DEFAULT_BRIDGE "xenbr0"
116 #endif
117 #ifdef __sun__
118 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
119 #else
120 #define SMBD_COMMAND "/usr/sbin/smbd"
121 #endif
123 //#define DEBUG_UNUSED_IOPORT
124 //#define DEBUG_IOPORT
126 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
128 #ifdef TARGET_PPC
129 #define DEFAULT_RAM_SIZE 144
130 #else
131 #define DEFAULT_RAM_SIZE 128
132 #endif
133 /* in ms */
134 #define GUI_REFRESH_INTERVAL 30
136 /* Max number of USB devices that can be specified on the commandline. */
137 #define MAX_USB_CMDLINE 8
139 /* XXX: use a two level table to limit memory usage */
140 #define MAX_IOPORTS 65536
142 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
143 void **ioport_opaque;
144 IOPortReadFunc *(*ioport_read_table)[MAX_IOPORTS];
145 IOPortWriteFunc *(*ioport_write_table)[MAX_IOPORTS];
146 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
147 to store the VM snapshots */
148 BlockDriverState *bs_table[MAX_DISKS + MAX_SCSI_DISKS + 1], *fd_table[MAX_FD];
149 /* point to the block driver where the snapshots are managed */
150 BlockDriverState *bs_snapshots;
151 int vga_ram_size;
152 int bios_size;
153 static DisplayState display_state;
154 int nographic;
155 int vncviewer;
156 int vncunused;
157 const char* keyboard_layout = NULL;
158 int64_t ticks_per_sec;
159 char *boot_device = NULL;
160 uint64_t ram_size;
161 int pit_min_timer_count = 0;
162 int nb_nics;
163 NICInfo nd_table[MAX_NICS];
164 QEMUTimer *gui_timer;
165 int vm_running;
166 int rtc_utc = 1;
167 int cirrus_vga_enabled = 1;
168 #ifdef TARGET_SPARC
169 int graphic_width = 1024;
170 int graphic_height = 768;
171 #else
172 int graphic_width = 800;
173 int graphic_height = 600;
174 #endif
175 int graphic_depth = 15;
176 int full_screen = 0;
177 int no_quit = 0;
178 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
179 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
180 #ifdef TARGET_I386
181 int win2k_install_hack = 0;
182 #endif
183 int usb_enabled = 0;
184 static VLANState *first_vlan;
185 int smp_cpus = 1;
186 const char *vnc_display;
187 #if defined(TARGET_SPARC)
188 #define MAX_CPUS 16
189 #elif defined(TARGET_I386)
190 #define MAX_CPUS 255
191 #else
192 #define MAX_CPUS 1
193 #endif
194 int acpi_enabled = 0;
195 int fd_bootchk = 1;
196 int no_reboot = 0;
197 #ifndef NO_DAEMONIZE
198 int daemonize = 0;
199 #endif
200 const char *option_rom[MAX_OPTION_ROMS];
201 int nb_option_roms;
202 int semihosting_enabled = 0;
203 int autostart = 1;
205 extern int vcpus;
207 int xc_handle;
209 char domain_name[64] = "Xen-no-name";
210 extern int domid;
212 /***********************************************************/
213 /* x86 ISA bus support */
215 target_phys_addr_t isa_mem_base = 0;
216 PicState2 *isa_pic;
218 uint32_t default_ioport_readb(void *opaque, uint32_t address)
219 {
220 #ifdef DEBUG_UNUSED_IOPORT
221 fprintf(stderr, "inb: port=0x%04x\n", address);
222 #endif
223 return 0xff;
224 }
226 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
227 {
228 #ifdef DEBUG_UNUSED_IOPORT
229 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
230 #endif
231 }
233 /* default is to make two byte accesses */
234 uint32_t default_ioport_readw(void *opaque, uint32_t address)
235 {
236 uint32_t data;
237 IOPortReadFunc *func = ioport_read_table[0][address];
238 if (!func)
239 func = default_ioport_readb;
240 data = func(ioport_opaque[address], address);
241 address = (address + 1) & (MAX_IOPORTS - 1);
242 func = ioport_read_table[0][address];
243 if (!func)
244 func = default_ioport_readb;
245 data |= func(ioport_opaque[address], address) << 8;
246 return data;
247 }
249 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
250 {
251 IOPortWriteFunc *func = ioport_write_table[0][address];
252 if (!func)
253 func = default_ioport_writeb;
254 func(ioport_opaque[address], address, data & 0xff);
255 address = (address + 1) & (MAX_IOPORTS - 1);
256 func = ioport_write_table[0][address];
257 if (!func)
258 func = default_ioport_writeb;
259 func(ioport_opaque[address], address, (data >> 8) & 0xff);
260 }
262 uint32_t default_ioport_readl(void *opaque, uint32_t address)
263 {
264 #ifdef DEBUG_UNUSED_IOPORT
265 fprintf(stderr, "inl: port=0x%04x\n", address);
266 #endif
267 return 0xffffffff;
268 }
270 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
271 {
272 #ifdef DEBUG_UNUSED_IOPORT
273 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
274 #endif
275 }
277 void init_ioports(void)
278 {
279 ioport_opaque = malloc(MAX_IOPORTS * sizeof(*ioport_opaque));
280 ioport_read_table = malloc(3 * MAX_IOPORTS * sizeof(**ioport_read_table));
281 ioport_write_table = malloc(3 * MAX_IOPORTS * sizeof(**ioport_write_table));
282 }
284 /* size is the word size in byte */
285 int register_ioport_read(int start, int length, int size,
286 IOPortReadFunc *func, void *opaque)
287 {
288 int i, bsize;
290 if (size == 1) {
291 bsize = 0;
292 } else if (size == 2) {
293 bsize = 1;
294 } else if (size == 4) {
295 bsize = 2;
296 } else {
297 hw_error("register_ioport_read: invalid size");
298 return -1;
299 }
300 for(i = start; i < start + length; i += size) {
301 ioport_read_table[bsize][i] = func;
302 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
303 hw_error("register_ioport_write: invalid opaque");
304 ioport_opaque[i] = opaque;
305 }
306 return 0;
307 }
309 /* size is the word size in byte */
310 int register_ioport_write(int start, int length, int size,
311 IOPortWriteFunc *func, void *opaque)
312 {
313 int i, bsize;
315 if (size == 1) {
316 bsize = 0;
317 } else if (size == 2) {
318 bsize = 1;
319 } else if (size == 4) {
320 bsize = 2;
321 } else {
322 hw_error("register_ioport_write: invalid size");
323 return -1;
324 }
325 for(i = start; i < start + length; i += size) {
326 ioport_write_table[bsize][i] = func;
327 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
328 hw_error("register_ioport_write: invalid opaque");
329 ioport_opaque[i] = opaque;
330 }
331 return 0;
332 }
334 void isa_unassign_ioport(int start, int length)
335 {
336 int i;
338 for(i = start; i < start + length; i++) {
339 ioport_read_table[0][i] = default_ioport_readb;
340 ioport_read_table[1][i] = default_ioport_readw;
341 ioport_read_table[2][i] = default_ioport_readl;
343 ioport_write_table[0][i] = default_ioport_writeb;
344 ioport_write_table[1][i] = default_ioport_writew;
345 ioport_write_table[2][i] = default_ioport_writel;
346 }
347 }
349 /***********************************************************/
351 void cpu_outb(CPUState *env, int addr, int val)
352 {
353 IOPortWriteFunc *func = ioport_write_table[0][addr];
354 if (!func)
355 func = default_ioport_writeb;
356 #ifdef DEBUG_IOPORT
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outb: %04x %02x\n", addr, val);
359 #endif
360 func(ioport_opaque[addr], addr, val);
361 #ifdef USE_KQEMU
362 if (env)
363 env->last_io_time = cpu_get_time_fast();
364 #endif
365 }
367 void cpu_outw(CPUState *env, int addr, int val)
368 {
369 IOPortWriteFunc *func = ioport_write_table[1][addr];
370 if (!func)
371 func = default_ioport_writew;
372 #ifdef DEBUG_IOPORT
373 if (loglevel & CPU_LOG_IOPORT)
374 fprintf(logfile, "outw: %04x %04x\n", addr, val);
375 #endif
376 func(ioport_opaque[addr], addr, val);
377 #ifdef USE_KQEMU
378 if (env)
379 env->last_io_time = cpu_get_time_fast();
380 #endif
381 }
383 void cpu_outl(CPUState *env, int addr, int val)
384 {
385 IOPortWriteFunc *func = ioport_write_table[2][addr];
386 if (!func)
387 func = default_ioport_writel;
388 #ifdef DEBUG_IOPORT
389 if (loglevel & CPU_LOG_IOPORT)
390 fprintf(logfile, "outl: %04x %08x\n", addr, val);
391 #endif
392 func(ioport_opaque[addr], addr, val);
393 #ifdef USE_KQEMU
394 if (env)
395 env->last_io_time = cpu_get_time_fast();
396 #endif
397 }
399 int cpu_inb(CPUState *env, int addr)
400 {
401 int val;
402 IOPortReadFunc *func = ioport_read_table[0][addr];
403 if (!func)
404 func = default_ioport_readb;
405 val = func(ioport_opaque[addr], addr);
406 #ifdef DEBUG_IOPORT
407 if (loglevel & CPU_LOG_IOPORT)
408 fprintf(logfile, "inb : %04x %02x\n", addr, val);
409 #endif
410 #ifdef USE_KQEMU
411 if (env)
412 env->last_io_time = cpu_get_time_fast();
413 #endif
414 return val;
415 }
417 int cpu_inw(CPUState *env, int addr)
418 {
419 int val;
420 IOPortReadFunc *func = ioport_read_table[1][addr];
421 if (!func)
422 func = default_ioport_readw;
423 val = func(ioport_opaque[addr], addr);
424 #ifdef DEBUG_IOPORT
425 if (loglevel & CPU_LOG_IOPORT)
426 fprintf(logfile, "inw : %04x %04x\n", addr, val);
427 #endif
428 #ifdef USE_KQEMU
429 if (env)
430 env->last_io_time = cpu_get_time_fast();
431 #endif
432 return val;
433 }
435 int cpu_inl(CPUState *env, int addr)
436 {
437 int val;
438 IOPortReadFunc *func = ioport_read_table[2][addr];
439 if (!func)
440 func = default_ioport_readl;
441 val = func(ioport_opaque[addr], addr);
442 #ifdef DEBUG_IOPORT
443 if (loglevel & CPU_LOG_IOPORT)
444 fprintf(logfile, "inl : %04x %08x\n", addr, val);
445 #endif
446 #ifdef USE_KQEMU
447 if (env)
448 env->last_io_time = cpu_get_time_fast();
449 #endif
450 return val;
451 }
453 /***********************************************************/
454 void hw_error(const char *fmt, ...)
455 {
456 va_list ap;
457 #ifndef CONFIG_DM
458 CPUState *env;
459 #endif /* !CONFIG_DM */
461 va_start(ap, fmt);
462 fprintf(stderr, "qemu: hardware error: ");
463 vfprintf(stderr, fmt, ap);
464 fprintf(stderr, "\n");
465 #ifndef CONFIG_DM
466 for(env = first_cpu; env != NULL; env = env->next_cpu) {
467 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
468 #ifdef TARGET_I386
469 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
470 #else
471 cpu_dump_state(env, stderr, fprintf, 0);
472 #endif
473 }
474 #endif /* !CONFIG_DM */
475 va_end(ap);
476 abort();
477 }
479 /***********************************************************/
480 /* keyboard/mouse */
482 static QEMUPutKBDEvent *qemu_put_kbd_event;
483 static void *qemu_put_kbd_event_opaque;
484 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
485 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
487 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
488 {
489 qemu_put_kbd_event_opaque = opaque;
490 qemu_put_kbd_event = func;
491 }
493 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
494 void *opaque, int absolute,
495 const char *name)
496 {
497 QEMUPutMouseEntry *s, *cursor;
499 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
500 if (!s)
501 return NULL;
503 s->qemu_put_mouse_event = func;
504 s->qemu_put_mouse_event_opaque = opaque;
505 s->qemu_put_mouse_event_absolute = absolute;
506 s->qemu_put_mouse_event_name = qemu_strdup(name);
507 s->next = NULL;
509 if (!qemu_put_mouse_event_head) {
510 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
511 return s;
512 }
514 cursor = qemu_put_mouse_event_head;
515 while (cursor->next != NULL)
516 cursor = cursor->next;
518 cursor->next = s;
519 qemu_put_mouse_event_current = s;
521 return s;
522 }
524 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
525 {
526 QEMUPutMouseEntry *prev = NULL, *cursor;
528 if (!qemu_put_mouse_event_head || entry == NULL)
529 return;
531 cursor = qemu_put_mouse_event_head;
532 while (cursor != NULL && cursor != entry) {
533 prev = cursor;
534 cursor = cursor->next;
535 }
537 if (cursor == NULL) // does not exist or list empty
538 return;
539 else if (prev == NULL) { // entry is head
540 qemu_put_mouse_event_head = cursor->next;
541 if (qemu_put_mouse_event_current == entry)
542 qemu_put_mouse_event_current = cursor->next;
543 qemu_free(entry->qemu_put_mouse_event_name);
544 qemu_free(entry);
545 return;
546 }
548 prev->next = entry->next;
550 if (qemu_put_mouse_event_current == entry)
551 qemu_put_mouse_event_current = prev;
553 qemu_free(entry->qemu_put_mouse_event_name);
554 qemu_free(entry);
555 }
557 void kbd_put_keycode(int keycode)
558 {
559 if (qemu_put_kbd_event) {
560 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
561 }
562 }
564 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
565 {
566 QEMUPutMouseEvent *mouse_event;
567 void *mouse_event_opaque;
569 if (!qemu_put_mouse_event_current) {
570 return;
571 }
573 mouse_event =
574 qemu_put_mouse_event_current->qemu_put_mouse_event;
575 mouse_event_opaque =
576 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
578 if (mouse_event) {
579 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
580 }
581 }
583 int kbd_mouse_is_absolute(void)
584 {
585 if (!qemu_put_mouse_event_current)
586 return 0;
588 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
589 }
591 void do_info_mice(void)
592 {
593 QEMUPutMouseEntry *cursor;
594 int index = 0;
596 if (!qemu_put_mouse_event_head) {
597 term_printf("No mouse devices connected\n");
598 return;
599 }
601 term_printf("Mouse devices available:\n");
602 cursor = qemu_put_mouse_event_head;
603 while (cursor != NULL) {
604 term_printf("%c Mouse #%d: %s\n",
605 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
606 index, cursor->qemu_put_mouse_event_name);
607 index++;
608 cursor = cursor->next;
609 }
610 }
612 void do_mouse_set(int index)
613 {
614 QEMUPutMouseEntry *cursor;
615 int i = 0;
617 if (!qemu_put_mouse_event_head) {
618 term_printf("No mouse devices connected\n");
619 return;
620 }
622 cursor = qemu_put_mouse_event_head;
623 while (cursor != NULL && index != i) {
624 i++;
625 cursor = cursor->next;
626 }
628 if (cursor != NULL)
629 qemu_put_mouse_event_current = cursor;
630 else
631 term_printf("Mouse at given index not found\n");
632 }
634 /* compute with 96 bit intermediate result: (a*b)/c */
635 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
636 {
637 union {
638 uint64_t ll;
639 struct {
640 #ifdef WORDS_BIGENDIAN
641 uint32_t high, low;
642 #else
643 uint32_t low, high;
644 #endif
645 } l;
646 } u, res;
647 uint64_t rl, rh;
649 u.ll = a;
650 rl = (uint64_t)u.l.low * (uint64_t)b;
651 rh = (uint64_t)u.l.high * (uint64_t)b;
652 rh += (rl >> 32);
653 res.l.high = rh / c;
654 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
655 return res.ll;
656 }
658 /***********************************************************/
659 /* real time host monotonic timer */
661 #define QEMU_TIMER_BASE 1000000000LL
663 #ifdef WIN32
665 static int64_t clock_freq;
667 static void init_get_clock(void)
668 {
669 LARGE_INTEGER freq;
670 int ret;
671 ret = QueryPerformanceFrequency(&freq);
672 if (ret == 0) {
673 fprintf(stderr, "Could not calibrate ticks\n");
674 exit(1);
675 }
676 clock_freq = freq.QuadPart;
677 }
679 static int64_t get_clock(void)
680 {
681 LARGE_INTEGER ti;
682 QueryPerformanceCounter(&ti);
683 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
684 }
686 #else
688 static int use_rt_clock;
690 static void init_get_clock(void)
691 {
692 use_rt_clock = 0;
693 #if defined(__linux__)
694 {
695 struct timespec ts;
696 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
697 use_rt_clock = 1;
698 }
699 }
700 #endif
701 }
703 static int64_t get_clock(void)
704 {
705 #if defined(__linux__)
706 if (use_rt_clock) {
707 struct timespec ts;
708 clock_gettime(CLOCK_MONOTONIC, &ts);
709 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
710 } else
711 #endif
712 {
713 /* XXX: using gettimeofday leads to problems if the date
714 changes, so it should be avoided. */
715 struct timeval tv;
716 gettimeofday(&tv, NULL);
717 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
718 }
719 }
721 #endif
723 /***********************************************************/
724 /* guest cycle counter */
726 static int64_t cpu_ticks_prev;
727 static int64_t cpu_ticks_offset;
728 static int64_t cpu_clock_offset;
729 static int cpu_ticks_enabled;
731 /* return the host CPU cycle counter and handle stop/restart */
732 int64_t cpu_get_ticks(void)
733 {
734 if (!cpu_ticks_enabled) {
735 return cpu_ticks_offset;
736 } else {
737 int64_t ticks;
738 ticks = cpu_get_real_ticks();
739 if (cpu_ticks_prev > ticks) {
740 /* Note: non increasing ticks may happen if the host uses
741 software suspend */
742 cpu_ticks_offset += cpu_ticks_prev - ticks;
743 }
744 cpu_ticks_prev = ticks;
745 return ticks + cpu_ticks_offset;
746 }
747 }
749 /* return the host CPU monotonic timer and handle stop/restart */
750 static int64_t cpu_get_clock(void)
751 {
752 int64_t ti;
753 if (!cpu_ticks_enabled) {
754 return cpu_clock_offset;
755 } else {
756 ti = get_clock();
757 return ti + cpu_clock_offset;
758 }
759 }
761 /* enable cpu_get_ticks() */
762 void cpu_enable_ticks(void)
763 {
764 if (!cpu_ticks_enabled) {
765 cpu_ticks_offset -= cpu_get_real_ticks();
766 cpu_clock_offset -= get_clock();
767 cpu_ticks_enabled = 1;
768 }
769 }
771 /* disable cpu_get_ticks() : the clock is stopped. You must not call
772 cpu_get_ticks() after that. */
773 void cpu_disable_ticks(void)
774 {
775 if (cpu_ticks_enabled) {
776 cpu_ticks_offset = cpu_get_ticks();
777 cpu_clock_offset = cpu_get_clock();
778 cpu_ticks_enabled = 0;
779 }
780 }
782 /***********************************************************/
783 /* timers */
785 #define QEMU_TIMER_REALTIME 0
786 #define QEMU_TIMER_VIRTUAL 1
788 struct QEMUClock {
789 int type;
790 /* XXX: add frequency */
791 };
793 struct QEMUTimer {
794 QEMUClock *clock;
795 int64_t expire_time;
796 QEMUTimerCB *cb;
797 void *opaque;
798 struct QEMUTimer *next;
799 };
801 QEMUClock *rt_clock;
802 QEMUClock *vm_clock;
804 static QEMUTimer *active_timers[2];
805 #ifdef _WIN32
806 static MMRESULT timerID;
807 static HANDLE host_alarm = NULL;
808 static unsigned int period = 1;
809 #endif
811 QEMUClock *qemu_new_clock(int type)
812 {
813 QEMUClock *clock;
814 clock = qemu_mallocz(sizeof(QEMUClock));
815 if (!clock)
816 return NULL;
817 clock->type = type;
818 return clock;
819 }
821 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
822 {
823 QEMUTimer *ts;
825 ts = qemu_mallocz(sizeof(QEMUTimer));
826 ts->clock = clock;
827 ts->cb = cb;
828 ts->opaque = opaque;
829 return ts;
830 }
832 void qemu_free_timer(QEMUTimer *ts)
833 {
834 qemu_free(ts);
835 }
837 /* stop a timer, but do not dealloc it */
838 void qemu_del_timer(QEMUTimer *ts)
839 {
840 QEMUTimer **pt, *t;
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 == ts) {
850 *pt = t->next;
851 break;
852 }
853 pt = &t->next;
854 }
855 }
857 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
858 {
859 if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
860 qemu_mod_timer(ts, expire_time);
861 }
863 /* modify the current timer so that it will be fired when current_time
864 >= expire_time. The corresponding callback will be called. */
865 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
866 {
867 QEMUTimer **pt, *t;
869 qemu_del_timer(ts);
871 /* add the timer in the sorted list */
872 /* NOTE: this code must be signal safe because
873 qemu_timer_expired() can be called from a signal. */
874 pt = &active_timers[ts->clock->type];
875 for(;;) {
876 t = *pt;
877 if (!t)
878 break;
879 if (t->expire_time > expire_time)
880 break;
881 pt = &t->next;
882 }
883 ts->expire_time = expire_time;
884 ts->next = *pt;
885 *pt = ts;
886 }
888 int qemu_timer_pending(QEMUTimer *ts)
889 {
890 QEMUTimer *t;
891 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
892 if (t == ts)
893 return 1;
894 }
895 return 0;
896 }
898 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
899 {
900 if (!timer_head)
901 return 0;
902 return (timer_head->expire_time <= current_time);
903 }
905 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
906 {
907 QEMUTimer *ts;
909 for(;;) {
910 ts = *ptimer_head;
911 if (!ts || ts->expire_time > current_time)
912 break;
913 /* remove timer from the list before calling the callback */
914 *ptimer_head = ts->next;
915 ts->next = NULL;
917 /* run the callback (the timer list can be modified) */
918 ts->cb(ts->opaque);
919 }
920 }
922 int64_t qemu_get_clock(QEMUClock *clock)
923 {
924 switch(clock->type) {
925 case QEMU_TIMER_REALTIME:
926 return get_clock() / 1000000;
927 default:
928 case QEMU_TIMER_VIRTUAL:
929 return cpu_get_clock();
930 }
931 }
933 static void init_timers(void)
934 {
935 init_get_clock();
936 ticks_per_sec = QEMU_TIMER_BASE;
937 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
938 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
939 }
941 /* save a timer */
942 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
943 {
944 uint64_t expire_time;
946 if (qemu_timer_pending(ts)) {
947 expire_time = ts->expire_time;
948 } else {
949 expire_time = -1;
950 }
951 qemu_put_be64(f, expire_time);
952 }
954 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
955 {
956 uint64_t expire_time;
958 expire_time = qemu_get_be64(f);
959 if (expire_time != -1) {
960 qemu_mod_timer(ts, expire_time);
961 } else {
962 qemu_del_timer(ts);
963 }
964 }
966 #ifdef CONFIG_DM
967 static void timer_save(QEMUFile *f, void *opaque)
968 {
969 /* need timer for save/restoe qemu_timer in usb_uhci */
970 if (cpu_ticks_enabled) {
971 hw_error("cannot save state if virtual timers are running");
972 }
973 qemu_put_be64s(f, &cpu_clock_offset);
974 }
976 static int timer_load(QEMUFile *f, void *opaque, int version_id)
977 {
978 if (version_id != 1 && version_id != 2)
979 return -EINVAL;
980 if (cpu_ticks_enabled) {
981 return -EINVAL;
982 }
984 qemu_get_be64s(f, &cpu_clock_offset);
985 return 0;
986 }
987 #else /* !CONFIG_DM */
988 static void timer_save(QEMUFile *f, void *opaque)
989 {
990 if (cpu_ticks_enabled) {
991 hw_error("cannot save state if virtual timers are running");
992 }
993 qemu_put_be64s(f, &cpu_ticks_offset);
994 qemu_put_be64s(f, &ticks_per_sec);
995 qemu_put_be64s(f, &cpu_clock_offset);
996 }
998 static int timer_load(QEMUFile *f, void *opaque, int version_id)
999 {
1000 if (version_id != 1 && version_id != 2)
1001 return -EINVAL;
1002 if (cpu_ticks_enabled) {
1003 return -EINVAL;
1005 qemu_get_be64s(f, &cpu_ticks_offset);
1006 qemu_get_be64s(f, &ticks_per_sec);
1007 if (version_id == 2) {
1008 qemu_get_be64s(f, &cpu_clock_offset);
1010 return 0;
1013 #ifdef _WIN32
1014 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1015 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1016 #else
1017 static void host_alarm_handler(int host_signum)
1018 #endif
1020 #if 0
1021 #define DISP_FREQ 1000
1023 static int64_t delta_min = INT64_MAX;
1024 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1025 static int count;
1026 ti = qemu_get_clock(vm_clock);
1027 if (last_clock != 0) {
1028 delta = ti - last_clock;
1029 if (delta < delta_min)
1030 delta_min = delta;
1031 if (delta > delta_max)
1032 delta_max = delta;
1033 delta_cum += delta;
1034 if (++count == DISP_FREQ) {
1035 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1036 muldiv64(delta_min, 1000000, ticks_per_sec),
1037 muldiv64(delta_max, 1000000, ticks_per_sec),
1038 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1039 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1040 count = 0;
1041 delta_min = INT64_MAX;
1042 delta_max = 0;
1043 delta_cum = 0;
1046 last_clock = ti;
1048 #endif
1049 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1050 qemu_get_clock(vm_clock)) ||
1051 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1052 qemu_get_clock(rt_clock))) {
1053 #ifdef _WIN32
1054 SetEvent(host_alarm);
1055 #endif
1056 CPUState *env = cpu_single_env;
1057 if (env) {
1058 /* stop the currently executing cpu because a timer occured */
1059 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1060 #ifdef USE_KQEMU
1061 if (env->kqemu_enabled) {
1062 kqemu_cpu_interrupt(env);
1064 #endif
1069 #ifndef _WIN32
1071 #if defined(__linux__)
1073 #define RTC_FREQ 1024
1075 static int rtc_fd;
1077 static int start_rtc_timer(void)
1079 rtc_fd = open("/dev/rtc", O_RDONLY);
1080 if (rtc_fd < 0)
1081 return -1;
1082 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1083 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1084 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1085 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1086 goto fail;
1088 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1089 fail:
1090 close(rtc_fd);
1091 return -1;
1093 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1094 return 0;
1097 #else
1099 static int start_rtc_timer(void)
1101 return -1;
1104 #endif /* !defined(__linux__) */
1106 #endif /* !defined(_WIN32) */
1108 #endif /* !CONFIG_DM */
1110 static void init_timer_alarm(void)
1112 #ifdef _WIN32
1114 int count=0;
1115 TIMECAPS tc;
1117 ZeroMemory(&tc, sizeof(TIMECAPS));
1118 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1119 if (period < tc.wPeriodMin)
1120 period = tc.wPeriodMin;
1121 timeBeginPeriod(period);
1122 timerID = timeSetEvent(1, // interval (ms)
1123 period, // resolution
1124 host_alarm_handler, // function
1125 (DWORD)&count, // user parameter
1126 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1127 if( !timerID ) {
1128 perror("failed timer alarm");
1129 exit(1);
1131 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1132 if (!host_alarm) {
1133 perror("failed CreateEvent");
1134 exit(1);
1136 qemu_add_wait_object(host_alarm, NULL, NULL);
1138 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1139 #else
1141 #ifndef CONFIG_DM
1142 struct sigaction act;
1143 struct itimerval itv;
1144 #endif
1146 #ifndef CONFIG_DM
1147 /* timer signal */
1148 sigfillset(&act.sa_mask);
1149 act.sa_flags = 0;
1150 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1151 act.sa_flags |= SA_ONSTACK;
1152 #endif
1153 act.sa_handler = host_alarm_handler;
1154 sigaction(SIGALRM, &act, NULL);
1156 itv.it_interval.tv_sec = 0;
1157 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1158 itv.it_value.tv_sec = 0;
1159 itv.it_value.tv_usec = 10 * 1000;
1160 setitimer(ITIMER_REAL, &itv, NULL);
1161 /* we probe the tick duration of the kernel to inform the user if
1162 the emulated kernel requested a too high timer frequency */
1163 getitimer(ITIMER_REAL, &itv);
1165 #if defined(__linux__)
1166 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1167 have timers with 1 ms resolution. The correct solution will
1168 be to use the POSIX real time timers available in recent
1169 2.6 kernels */
1170 if (itv.it_interval.tv_usec > 1000 || 1) {
1171 /* try to use /dev/rtc to have a faster timer */
1172 if (start_rtc_timer() < 0)
1173 goto use_itimer;
1174 /* disable itimer */
1175 itv.it_interval.tv_sec = 0;
1176 itv.it_interval.tv_usec = 0;
1177 itv.it_value.tv_sec = 0;
1178 itv.it_value.tv_usec = 0;
1179 setitimer(ITIMER_REAL, &itv, NULL);
1181 /* use the RTC */
1182 sigaction(SIGIO, &act, NULL);
1183 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1184 fcntl(rtc_fd, F_SETOWN, getpid());
1185 } else
1186 #endif /* defined(__linux__) */
1188 use_itimer:
1189 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1190 PIT_FREQ) / 1000000;
1192 #endif /* CONFIG_DM */
1194 #endif
1197 void quit_timers(void)
1199 #ifdef _WIN32
1200 timeKillEvent(timerID);
1201 timeEndPeriod(period);
1202 if (host_alarm) {
1203 CloseHandle(host_alarm);
1204 host_alarm = NULL;
1206 #endif
1209 /***********************************************************/
1210 /* character device */
1212 static void qemu_chr_event(CharDriverState *s, int event)
1214 if (!s->chr_event)
1215 return;
1216 s->chr_event(s->handler_opaque, event);
1219 static void qemu_chr_reset_bh(void *opaque)
1221 CharDriverState *s = opaque;
1222 qemu_chr_event(s, CHR_EVENT_RESET);
1223 qemu_bh_delete(s->bh);
1224 s->bh = NULL;
1227 void qemu_chr_reset(CharDriverState *s)
1229 if (s->bh == NULL) {
1230 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1231 qemu_bh_schedule(s->bh);
1235 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1237 return s->chr_write(s, buf, len);
1240 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1242 if (!s->chr_ioctl)
1243 return -ENOTSUP;
1244 return s->chr_ioctl(s, cmd, arg);
1247 int qemu_chr_can_read(CharDriverState *s)
1249 if (!s->chr_can_read)
1250 return 0;
1251 return s->chr_can_read(s->handler_opaque);
1254 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1256 s->chr_read(s->handler_opaque, buf, len);
1260 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1262 char buf[4096];
1263 va_list ap;
1264 va_start(ap, fmt);
1265 vsnprintf(buf, sizeof(buf), fmt, ap);
1266 qemu_chr_write(s, buf, strlen(buf));
1267 va_end(ap);
1270 void qemu_chr_send_event(CharDriverState *s, int event)
1272 if (s->chr_send_event)
1273 s->chr_send_event(s, event);
1276 void qemu_chr_add_handlers(CharDriverState *s,
1277 IOCanRWHandler *fd_can_read,
1278 IOReadHandler *fd_read,
1279 IOEventHandler *fd_event,
1280 void *opaque)
1282 s->chr_can_read = fd_can_read;
1283 s->chr_read = fd_read;
1284 s->chr_event = fd_event;
1285 s->handler_opaque = opaque;
1286 if (s->chr_update_read_handler)
1287 s->chr_update_read_handler(s);
1290 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1292 return len;
1295 static CharDriverState *qemu_chr_open_null(void)
1297 CharDriverState *chr;
1299 chr = qemu_mallocz(sizeof(CharDriverState));
1300 if (!chr)
1301 return NULL;
1302 chr->chr_write = null_chr_write;
1303 return chr;
1306 #ifdef _WIN32
1308 static void socket_cleanup(void)
1310 WSACleanup();
1313 static int socket_init(void)
1315 WSADATA Data;
1316 int ret, err;
1318 ret = WSAStartup(MAKEWORD(2,2), &Data);
1319 if (ret != 0) {
1320 err = WSAGetLastError();
1321 fprintf(stderr, "WSAStartup: %d\n", err);
1322 return -1;
1324 atexit(socket_cleanup);
1325 return 0;
1328 static int send_all(int fd, const uint8_t *buf, int len1)
1330 int ret, len;
1332 len = len1;
1333 while (len > 0) {
1334 ret = send(fd, buf, len, 0);
1335 if (ret < 0) {
1336 int errno;
1337 errno = WSAGetLastError();
1338 if (errno != WSAEWOULDBLOCK) {
1339 return -1;
1341 } else if (ret == 0) {
1342 break;
1343 } else {
1344 buf += ret;
1345 len -= ret;
1348 return len1 - len;
1351 void socket_set_nonblock(int fd)
1353 unsigned long opt = 1;
1354 ioctlsocket(fd, FIONBIO, &opt);
1357 #else
1359 static int unix_write(int fd, const uint8_t *buf, int len1)
1361 int ret, sel_ret, len;
1362 int max_fd;
1363 fd_set writefds;
1364 struct timeval timeout;
1366 max_fd = fd;
1368 len = len1;
1369 while (len > 0) {
1370 FD_ZERO(&writefds);
1371 FD_SET(fd, &writefds);
1372 timeout.tv_sec = 0;
1373 timeout.tv_usec = 0;
1374 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1375 if (sel_ret <= 0) {
1376 /* Timeout or select error */
1377 return -1;
1378 } else {
1379 ret = write(fd, buf, len);
1380 if (ret < 0) {
1381 if (errno != EINTR && errno != EAGAIN)
1382 return -1;
1383 } else if (ret == 0) {
1384 break;
1385 } else {
1386 buf += ret;
1387 len -= ret;
1391 return len1 - len;
1394 static inline int send_all(int fd, const uint8_t *buf, int len1)
1396 return unix_write(fd, buf, len1);
1399 void socket_set_nonblock(int fd)
1401 fcntl(fd, F_SETFL, O_NONBLOCK);
1403 #endif /* !_WIN32 */
1405 #ifndef _WIN32
1407 typedef struct {
1408 int fd_in, fd_out;
1409 int max_size;
1410 } FDCharDriver;
1412 #define STDIO_MAX_CLIENTS 2
1414 static int stdio_nb_clients;
1415 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1417 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1419 FDCharDriver *s = chr->opaque;
1420 return unix_write(s->fd_out, buf, len);
1423 static int fd_chr_read_poll(void *opaque)
1425 CharDriverState *chr = opaque;
1426 FDCharDriver *s = chr->opaque;
1428 s->max_size = qemu_chr_can_read(chr);
1429 return s->max_size;
1432 static void fd_chr_read(void *opaque)
1434 CharDriverState *chr = opaque;
1435 FDCharDriver *s = chr->opaque;
1436 int size, len;
1437 uint8_t buf[1024];
1439 len = sizeof(buf);
1440 if (len > s->max_size)
1441 len = s->max_size;
1442 if (len == 0)
1443 return;
1444 size = read(s->fd_in, buf, len);
1445 if (size == 0) {
1446 /* FD has been closed. Remove it from the active list. */
1447 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1448 return;
1450 if (size > 0) {
1451 qemu_chr_read(chr, buf, size);
1455 static void fd_chr_update_read_handler(CharDriverState *chr)
1457 FDCharDriver *s = chr->opaque;
1459 if (s->fd_in >= 0) {
1460 if (nographic && s->fd_in == 0) {
1461 } else {
1462 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1463 fd_chr_read, NULL, chr);
1468 /* open a character device to a unix fd */
1469 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1471 CharDriverState *chr;
1472 FDCharDriver *s;
1474 chr = qemu_mallocz(sizeof(CharDriverState));
1475 if (!chr)
1476 return NULL;
1477 s = qemu_mallocz(sizeof(FDCharDriver));
1478 if (!s) {
1479 free(chr);
1480 return NULL;
1482 s->fd_in = fd_in;
1483 s->fd_out = fd_out;
1484 chr->opaque = s;
1485 chr->chr_write = fd_chr_write;
1486 chr->chr_update_read_handler = fd_chr_update_read_handler;
1488 qemu_chr_reset(chr);
1490 return chr;
1493 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1495 int fd_out;
1497 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1498 if (fd_out < 0)
1499 return NULL;
1500 return qemu_chr_open_fd(-1, fd_out);
1503 #ifndef CONFIG_STUBDOM
1504 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1506 int fd_in, fd_out;
1507 char filename_in[256], filename_out[256];
1509 snprintf(filename_in, 256, "%s.in", filename);
1510 snprintf(filename_out, 256, "%s.out", filename);
1511 fd_in = open(filename_in, O_RDWR | O_BINARY);
1512 fd_out = open(filename_out, O_RDWR | O_BINARY);
1513 if (fd_in < 0 || fd_out < 0) {
1514 if (fd_in >= 0)
1515 close(fd_in);
1516 if (fd_out >= 0)
1517 close(fd_out);
1518 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1519 if (fd_in < 0)
1520 return NULL;
1522 return qemu_chr_open_fd(fd_in, fd_out);
1526 /* for STDIO, we handle the case where several clients use it
1527 (nographic mode) */
1529 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1531 #define TERM_FIFO_MAX_SIZE 1
1533 static int term_got_escape, client_index;
1534 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1535 static int term_fifo_size;
1536 static int term_timestamps;
1537 static int64_t term_timestamps_start;
1539 void term_print_help(void)
1541 printf("\n"
1542 "C-a h print this help\n"
1543 "C-a x exit emulator\n"
1544 "C-a s save disk data back to file (if -snapshot)\n"
1545 "C-a b send break (magic sysrq)\n"
1546 "C-a t toggle console timestamps\n"
1547 "C-a c switch between console and monitor\n"
1548 "C-a C-a send C-a\n"
1549 );
1552 /* called when a char is received */
1553 static void stdio_received_byte(int ch)
1555 if (term_got_escape) {
1556 term_got_escape = 0;
1557 switch(ch) {
1558 case 'h':
1559 term_print_help();
1560 break;
1561 case 'x':
1562 exit(0);
1563 break;
1564 case 's':
1566 int i;
1567 for (i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
1568 if (bs_table[i])
1569 bdrv_commit(bs_table[i]);
1572 break;
1573 case 'b':
1574 if (client_index < stdio_nb_clients) {
1575 CharDriverState *chr;
1576 FDCharDriver *s;
1578 chr = stdio_clients[client_index];
1579 s = chr->opaque;
1580 qemu_chr_event(chr, CHR_EVENT_BREAK);
1582 break;
1583 case 'c':
1584 client_index++;
1585 if (client_index >= stdio_nb_clients)
1586 client_index = 0;
1587 if (client_index == 0) {
1588 /* send a new line in the monitor to get the prompt */
1589 ch = '\r';
1590 goto send_char;
1592 break;
1593 case 't':
1594 term_timestamps = !term_timestamps;
1595 term_timestamps_start = -1;
1596 break;
1597 case TERM_ESCAPE:
1598 goto send_char;
1600 } else if (ch == TERM_ESCAPE) {
1601 term_got_escape = 1;
1602 } else {
1603 send_char:
1604 if (client_index < stdio_nb_clients) {
1605 uint8_t buf[1];
1606 CharDriverState *chr;
1608 chr = stdio_clients[client_index];
1609 if (qemu_chr_can_read(chr) > 0) {
1610 buf[0] = ch;
1611 qemu_chr_read(chr, buf, 1);
1612 } else if (term_fifo_size == 0) {
1613 term_fifo[term_fifo_size++] = ch;
1619 static int stdio_read_poll(void *opaque)
1621 CharDriverState *chr;
1623 if (client_index < stdio_nb_clients) {
1624 chr = stdio_clients[client_index];
1625 /* try to flush the queue if needed */
1626 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1627 qemu_chr_read(chr, term_fifo, 1);
1628 term_fifo_size = 0;
1630 /* see if we can absorb more chars */
1631 if (term_fifo_size == 0)
1632 return 1;
1633 else
1634 return 0;
1635 } else {
1636 return 1;
1640 static void stdio_read(void *opaque)
1642 int size;
1643 uint8_t buf[1];
1645 size = read(0, buf, 1);
1646 if (size == 0) {
1647 /* stdin has been closed. Remove it from the active list. */
1648 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1649 return;
1651 if (size > 0)
1652 stdio_received_byte(buf[0]);
1655 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1657 FDCharDriver *s = chr->opaque;
1658 if (!term_timestamps) {
1659 return unix_write(s->fd_out, buf, len);
1660 } else {
1661 int i;
1662 char buf1[64];
1664 for(i = 0; i < len; i++) {
1665 unix_write(s->fd_out, buf + i, 1);
1666 if (buf[i] == '\n') {
1667 int64_t ti;
1668 int secs;
1670 ti = get_clock();
1671 if (term_timestamps_start == -1)
1672 term_timestamps_start = ti;
1673 ti -= term_timestamps_start;
1674 secs = ti / 1000000000;
1675 snprintf(buf1, sizeof(buf1),
1676 "[%02d:%02d:%02d.%03d] ",
1677 secs / 3600,
1678 (secs / 60) % 60,
1679 secs % 60,
1680 (int)((ti / 1000000) % 1000));
1681 unix_write(s->fd_out, buf1, strlen(buf1));
1684 return len;
1688 /* init terminal so that we can grab keys */
1689 static struct termios oldtty;
1690 static int old_fd0_flags;
1692 static void term_exit(void)
1694 tcsetattr (0, TCSANOW, &oldtty);
1695 fcntl(0, F_SETFL, old_fd0_flags);
1698 static void term_init(void)
1700 struct termios tty;
1702 tcgetattr (0, &tty);
1703 oldtty = tty;
1704 old_fd0_flags = fcntl(0, F_GETFL);
1706 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1707 |INLCR|IGNCR|ICRNL|IXON);
1708 tty.c_oflag |= OPOST;
1709 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1710 /* if graphical mode, we allow Ctrl-C handling */
1711 if (nographic)
1712 tty.c_lflag &= ~ISIG;
1713 tty.c_cflag &= ~(CSIZE|PARENB);
1714 tty.c_cflag |= CS8;
1715 tty.c_cc[VMIN] = 1;
1716 tty.c_cc[VTIME] = 0;
1718 tcsetattr (0, TCSANOW, &tty);
1720 atexit(term_exit);
1722 fcntl(0, F_SETFL, O_NONBLOCK);
1725 static CharDriverState *qemu_chr_open_stdio(void)
1727 CharDriverState *chr;
1729 if (nographic) {
1730 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1731 return NULL;
1732 chr = qemu_chr_open_fd(0, 1);
1733 chr->chr_write = stdio_write;
1734 if (stdio_nb_clients == 0)
1735 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1736 client_index = stdio_nb_clients;
1737 } else {
1738 if (stdio_nb_clients != 0)
1739 return NULL;
1740 chr = qemu_chr_open_fd(0, 1);
1742 stdio_clients[stdio_nb_clients++] = chr;
1743 if (stdio_nb_clients == 1) {
1744 /* set the terminal in raw mode */
1745 term_init();
1747 return chr;
1749 #endif
1751 /*
1752 * Create a store entry for a device (e.g., monitor, serial/parallel lines).
1753 * The entry is <domain-path><storeString>/tty and the value is the name
1754 * of the pty associated with the device.
1755 */
1756 static int store_dev_info(char *devName, int domid,
1757 CharDriverState *cState, char *storeString)
1759 #ifdef CONFIG_STUBDOM
1760 return 0;
1761 #else
1762 int xc_handle;
1763 struct xs_handle *xs;
1764 char *path;
1765 char *newpath;
1766 FDCharDriver *s;
1767 char *pts;
1769 /* Check for valid arguments (at least, prevent segfaults). */
1770 if ((devName == NULL) || (cState == NULL) || (storeString == NULL)) {
1771 fprintf(logfile, "%s - invalid arguments\n", __FUNCTION__);
1772 return EINVAL;
1775 /*
1776 * Only continue if we're talking to a pty
1777 * Actually, the following code works for any CharDriverState using
1778 * FDCharDriver, but we really only care about pty's here
1779 */
1780 if (strcmp(devName, "pty"))
1781 return 0;
1783 s = cState->opaque;
1784 if (s == NULL) {
1785 fprintf(logfile, "%s - unable to retrieve fd for '%s'/'%s'\n",
1786 __FUNCTION__, storeString, devName);
1787 return EBADF;
1790 pts = ptsname(s->fd_in);
1791 if (pts == NULL) {
1792 fprintf(logfile, "%s - unable to determine ptsname '%s'/'%s', "
1793 "error %d (%s)\n",
1794 __FUNCTION__, storeString, devName, errno, strerror(errno));
1795 return errno;
1798 /* We now have everything we need to set the xenstore entry. */
1799 xs = xs_daemon_open();
1800 if (xs == NULL) {
1801 fprintf(logfile, "Could not contact XenStore\n");
1802 return -1;
1805 xc_handle = xc_interface_open();
1806 if (xc_handle == -1) {
1807 fprintf(logfile, "xc_interface_open() error\n");
1808 return -1;
1811 path = xs_get_domain_path(xs, domid);
1812 if (path == NULL) {
1813 fprintf(logfile, "xs_get_domain_path() error\n");
1814 return -1;
1816 newpath = realloc(path, (strlen(path) + strlen(storeString) +
1817 strlen("/tty") + 1));
1818 if (newpath == NULL) {
1819 free(path); /* realloc errors leave old block */
1820 fprintf(logfile, "realloc error\n");
1821 return -1;
1823 path = newpath;
1825 strcat(path, storeString);
1826 strcat(path, "/tty");
1827 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1828 fprintf(logfile, "xs_write for '%s' fail", storeString);
1829 return -1;
1832 free(path);
1833 xs_daemon_close(xs);
1834 close(xc_handle);
1836 return 0;
1837 #endif
1840 #ifndef CONFIG_STUBDOM
1841 #ifdef __sun__
1842 /* Once Solaris has openpty(), this is going to be removed. */
1843 int openpty(int *amaster, int *aslave, char *name,
1844 struct termios *termp, struct winsize *winp)
1846 const char *slave;
1847 int mfd = -1, sfd = -1;
1849 *amaster = *aslave = -1;
1851 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
1852 if (mfd < 0)
1853 goto err;
1855 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
1856 goto err;
1858 if ((slave = ptsname(mfd)) == NULL)
1859 goto err;
1861 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
1862 goto err;
1864 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
1865 (termp != NULL && tcgetattr(sfd, termp) < 0))
1866 goto err;
1868 if (amaster)
1869 *amaster = mfd;
1870 if (aslave)
1871 *aslave = sfd;
1872 if (winp)
1873 ioctl(sfd, TIOCSWINSZ, winp);
1875 return 0;
1877 err:
1878 if (sfd != -1)
1879 close(sfd);
1880 close(mfd);
1881 return -1;
1884 void cfmakeraw (struct termios *termios_p)
1886 termios_p->c_iflag &=
1887 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
1888 termios_p->c_oflag &= ~OPOST;
1889 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1890 termios_p->c_cflag &= ~(CSIZE|PARENB);
1891 termios_p->c_cflag |= CS8;
1893 termios_p->c_cc[VMIN] = 0;
1894 termios_p->c_cc[VTIME] = 0;
1897 #endif
1899 #if defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__sun__)
1900 static CharDriverState *qemu_chr_open_pty(void)
1902 struct termios tty;
1903 int master_fd, slave_fd;
1905 /* Not satisfying */
1906 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1907 return NULL;
1910 /* Set raw attributes on the pty. */
1911 cfmakeraw(&tty);
1912 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1914 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1916 return qemu_chr_open_fd(master_fd, master_fd);
1919 static void tty_serial_init(int fd, int speed,
1920 int parity, int data_bits, int stop_bits)
1922 struct termios tty;
1923 speed_t spd;
1925 #if 0
1926 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1927 speed, parity, data_bits, stop_bits);
1928 #endif
1929 tcgetattr (fd, &tty);
1931 switch(speed) {
1932 case 50:
1933 spd = B50;
1934 break;
1935 case 75:
1936 spd = B75;
1937 break;
1938 case 300:
1939 spd = B300;
1940 break;
1941 case 600:
1942 spd = B600;
1943 break;
1944 case 1200:
1945 spd = B1200;
1946 break;
1947 case 2400:
1948 spd = B2400;
1949 break;
1950 case 4800:
1951 spd = B4800;
1952 break;
1953 case 9600:
1954 spd = B9600;
1955 break;
1956 case 19200:
1957 spd = B19200;
1958 break;
1959 case 38400:
1960 spd = B38400;
1961 break;
1962 case 57600:
1963 spd = B57600;
1964 break;
1965 default:
1966 case 115200:
1967 spd = B115200;
1968 break;
1971 cfsetispeed(&tty, spd);
1972 cfsetospeed(&tty, spd);
1974 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1975 |INLCR|IGNCR|ICRNL|IXON);
1976 tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1977 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1978 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1979 switch(data_bits) {
1980 default:
1981 case 8:
1982 tty.c_cflag |= CS8;
1983 break;
1984 case 7:
1985 tty.c_cflag |= CS7;
1986 break;
1987 case 6:
1988 tty.c_cflag |= CS6;
1989 break;
1990 case 5:
1991 tty.c_cflag |= CS5;
1992 break;
1994 switch(parity) {
1995 default:
1996 case 'N':
1997 break;
1998 case 'E':
1999 tty.c_cflag |= PARENB;
2000 break;
2001 case 'O':
2002 tty.c_cflag |= PARENB | PARODD;
2003 break;
2005 if (stop_bits == 2)
2006 tty.c_cflag |= CSTOPB;
2008 tcsetattr (fd, TCSANOW, &tty);
2011 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2013 FDCharDriver *s = chr->opaque;
2015 switch(cmd) {
2016 case CHR_IOCTL_SERIAL_SET_PARAMS:
2018 QEMUSerialSetParams *ssp = arg;
2019 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2020 ssp->data_bits, ssp->stop_bits);
2022 break;
2023 case CHR_IOCTL_SERIAL_SET_BREAK:
2025 int enable = *(int *)arg;
2026 if (enable)
2027 tcsendbreak(s->fd_in, 1);
2029 break;
2030 case CHR_IOCTL_SERIAL_GET_TIOCM:
2032 ioctl(s->fd_in, TIOCMGET, arg);
2034 break;
2035 case CHR_IOCTL_SERIAL_SET_TIOCM:
2037 ioctl(s->fd_in, TIOCMSET, arg);
2039 break;
2040 default:
2041 return -ENOTSUP;
2043 return 0;
2046 static CharDriverState *qemu_chr_open_tty(const char *filename)
2048 CharDriverState *chr;
2049 int fd;
2051 fd = open(filename, O_RDWR | O_NONBLOCK);
2052 if (fd < 0)
2053 return NULL;
2054 fcntl(fd, F_SETFL, O_NONBLOCK);
2055 tty_serial_init(fd, 115200, 'N', 8, 1);
2056 chr = qemu_chr_open_fd(fd, fd);
2057 if (!chr)
2058 return NULL;
2059 chr->chr_ioctl = tty_serial_ioctl;
2060 qemu_chr_reset(chr);
2061 return chr;
2064 #if defined(__linux__)
2065 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2067 int fd = (int)chr->opaque;
2068 uint8_t b;
2070 switch(cmd) {
2071 case CHR_IOCTL_PP_READ_DATA:
2072 if (ioctl(fd, PPRDATA, &b) < 0)
2073 return -ENOTSUP;
2074 *(uint8_t *)arg = b;
2075 break;
2076 case CHR_IOCTL_PP_WRITE_DATA:
2077 b = *(uint8_t *)arg;
2078 if (ioctl(fd, PPWDATA, &b) < 0)
2079 return -ENOTSUP;
2080 break;
2081 case CHR_IOCTL_PP_READ_CONTROL:
2082 if (ioctl(fd, PPRCONTROL, &b) < 0)
2083 return -ENOTSUP;
2084 *(uint8_t *)arg = b;
2085 break;
2086 case CHR_IOCTL_PP_WRITE_CONTROL:
2087 b = *(uint8_t *)arg;
2088 if (ioctl(fd, PPWCONTROL, &b) < 0)
2089 return -ENOTSUP;
2090 break;
2091 case CHR_IOCTL_PP_READ_STATUS:
2092 if (ioctl(fd, PPRSTATUS, &b) < 0)
2093 return -ENOTSUP;
2094 *(uint8_t *)arg = b;
2095 break;
2096 default:
2097 return -ENOTSUP;
2099 return 0;
2102 static CharDriverState *qemu_chr_open_pp(const char *filename)
2104 CharDriverState *chr;
2105 int fd;
2107 fd = open(filename, O_RDWR);
2108 if (fd < 0)
2109 return NULL;
2111 if (ioctl(fd, PPCLAIM) < 0) {
2112 close(fd);
2113 return NULL;
2116 chr = qemu_mallocz(sizeof(CharDriverState));
2117 if (!chr) {
2118 close(fd);
2119 return NULL;
2121 chr->opaque = (void *)fd;
2122 chr->chr_write = null_chr_write;
2123 chr->chr_ioctl = pp_ioctl;
2125 qemu_chr_reset(chr);
2127 return chr;
2129 #endif /* __linux__ */
2131 #else
2132 static CharDriverState *qemu_chr_open_pty(void)
2134 return NULL;
2136 #endif /* __linux__ || __NetBSD__ || __OpenBSD__ || __sun__ */
2138 #endif /* !defined(_WIN32) */
2140 #ifdef _WIN32
2141 typedef struct {
2142 CharDriverState *chr;
2143 int max_size;
2144 HANDLE hcom, hrecv, hsend;
2145 OVERLAPPED orecv, osend;
2146 BOOL fpipe;
2147 DWORD len;
2148 } WinCharState;
2150 #define NSENDBUF 2048
2151 #define NRECVBUF 2048
2152 #define MAXCONNECT 1
2153 #define NTIMEOUT 5000
2155 static int win_chr_poll(void *opaque);
2156 static int win_chr_pipe_poll(void *opaque);
2158 static void win_chr_close2(WinCharState *s)
2160 if (s->hsend) {
2161 CloseHandle(s->hsend);
2162 s->hsend = NULL;
2164 if (s->hrecv) {
2165 CloseHandle(s->hrecv);
2166 s->hrecv = NULL;
2168 if (s->hcom) {
2169 CloseHandle(s->hcom);
2170 s->hcom = NULL;
2172 if (s->fpipe)
2173 qemu_del_polling_cb(win_chr_pipe_poll, s);
2174 else
2175 qemu_del_polling_cb(win_chr_poll, s);
2178 static void win_chr_close(CharDriverState *chr)
2180 WinCharState *s = chr->opaque;
2181 win_chr_close2(s);
2184 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
2186 COMMCONFIG comcfg;
2187 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2188 COMSTAT comstat;
2189 DWORD size;
2190 DWORD err;
2192 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2193 if (!s->hsend) {
2194 fprintf(stderr, "Failed CreateEvent\n");
2195 goto fail;
2197 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2198 if (!s->hrecv) {
2199 fprintf(stderr, "Failed CreateEvent\n");
2200 goto fail;
2203 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2204 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2205 if (s->hcom == INVALID_HANDLE_VALUE) {
2206 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2207 s->hcom = NULL;
2208 goto fail;
2211 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2212 fprintf(stderr, "Failed SetupComm\n");
2213 goto fail;
2216 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2217 size = sizeof(COMMCONFIG);
2218 GetDefaultCommConfig(filename, &comcfg, &size);
2219 comcfg.dcb.DCBlength = sizeof(DCB);
2220 CommConfigDialog(filename, NULL, &comcfg);
2222 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2223 fprintf(stderr, "Failed SetCommState\n");
2224 goto fail;
2227 if (!SetCommMask(s->hcom, EV_ERR)) {
2228 fprintf(stderr, "Failed SetCommMask\n");
2229 goto fail;
2232 cto.ReadIntervalTimeout = MAXDWORD;
2233 if (!SetCommTimeouts(s->hcom, &cto)) {
2234 fprintf(stderr, "Failed SetCommTimeouts\n");
2235 goto fail;
2238 if (!ClearCommError(s->hcom, &err, &comstat)) {
2239 fprintf(stderr, "Failed ClearCommError\n");
2240 goto fail;
2242 s->chr = chr;
2243 qemu_add_polling_cb(win_chr_poll, s);
2244 return 0;
2246 fail:
2247 win_chr_close2(s);
2248 return -1;
2251 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2253 WinCharState *s = chr->opaque;
2254 DWORD len, ret, size, err;
2256 len = len1;
2257 ZeroMemory(&s->osend, sizeof(s->osend));
2258 s->osend.hEvent = s->hsend;
2259 while (len > 0) {
2260 if (s->hsend)
2261 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2262 else
2263 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2264 if (!ret) {
2265 err = GetLastError();
2266 if (err == ERROR_IO_PENDING) {
2267 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2268 if (ret) {
2269 buf += size;
2270 len -= size;
2271 } else {
2272 break;
2274 } else {
2275 break;
2277 } else {
2278 buf += size;
2279 len -= size;
2282 return len1 - len;
2285 static int win_chr_read_poll(WinCharState *s)
2287 s->max_size = qemu_chr_can_read(s->chr);
2288 return s->max_size;
2291 static void win_chr_readfile(WinCharState *s)
2293 int ret, err;
2294 uint8_t buf[1024];
2295 DWORD size;
2297 ZeroMemory(&s->orecv, sizeof(s->orecv));
2298 s->orecv.hEvent = s->hrecv;
2299 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2300 if (!ret) {
2301 err = GetLastError();
2302 if (err == ERROR_IO_PENDING) {
2303 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2307 if (size > 0) {
2308 qemu_chr_read(s->chr, buf, size);
2312 static void win_chr_read(WinCharState *s)
2314 if (s->len > s->max_size)
2315 s->len = s->max_size;
2316 if (s->len == 0)
2317 return;
2319 win_chr_readfile(s);
2322 static int win_chr_poll(void *opaque)
2324 WinCharState *s = opaque;
2325 COMSTAT status;
2326 DWORD comerr;
2328 ClearCommError(s->hcom, &comerr, &status);
2329 if (status.cbInQue > 0) {
2330 s->len = status.cbInQue;
2331 win_chr_read_poll(s);
2332 win_chr_read(s);
2333 return 1;
2335 return 0;
2338 static CharDriverState *qemu_chr_open_win(const char *filename)
2340 CharDriverState *chr;
2341 WinCharState *s;
2343 chr = qemu_mallocz(sizeof(CharDriverState));
2344 if (!chr)
2345 return NULL;
2346 s = qemu_mallocz(sizeof(WinCharState));
2347 if (!s) {
2348 free(chr);
2349 return NULL;
2351 chr->opaque = s;
2352 chr->chr_write = win_chr_write;
2353 chr->chr_close = win_chr_close;
2355 if (win_chr_init(s, chr, filename) < 0) {
2356 free(s);
2357 free(chr);
2358 return NULL;
2360 qemu_chr_reset(chr);
2361 return chr;
2364 static int win_chr_pipe_poll(void *opaque)
2366 WinCharState *s = opaque;
2367 DWORD size;
2369 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2370 if (size > 0) {
2371 s->len = size;
2372 win_chr_read_poll(s);
2373 win_chr_read(s);
2374 return 1;
2376 return 0;
2379 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2381 OVERLAPPED ov;
2382 int ret;
2383 DWORD size;
2384 char openname[256];
2386 s->fpipe = TRUE;
2388 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2389 if (!s->hsend) {
2390 fprintf(stderr, "Failed CreateEvent\n");
2391 goto fail;
2393 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2394 if (!s->hrecv) {
2395 fprintf(stderr, "Failed CreateEvent\n");
2396 goto fail;
2399 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2400 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2401 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2402 PIPE_WAIT,
2403 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2404 if (s->hcom == INVALID_HANDLE_VALUE) {
2405 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2406 s->hcom = NULL;
2407 goto fail;
2410 ZeroMemory(&ov, sizeof(ov));
2411 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2412 ret = ConnectNamedPipe(s->hcom, &ov);
2413 if (ret) {
2414 fprintf(stderr, "Failed ConnectNamedPipe\n");
2415 goto fail;
2418 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2419 if (!ret) {
2420 fprintf(stderr, "Failed GetOverlappedResult\n");
2421 if (ov.hEvent) {
2422 CloseHandle(ov.hEvent);
2423 ov.hEvent = NULL;
2425 goto fail;
2428 if (ov.hEvent) {
2429 CloseHandle(ov.hEvent);
2430 ov.hEvent = NULL;
2432 qemu_add_polling_cb(win_chr_pipe_poll, s);
2433 return 0;
2435 fail:
2436 win_chr_close2(s);
2437 return -1;
2441 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2443 CharDriverState *chr;
2444 WinCharState *s;
2446 chr = qemu_mallocz(sizeof(CharDriverState));
2447 if (!chr)
2448 return NULL;
2449 s = qemu_mallocz(sizeof(WinCharState));
2450 if (!s) {
2451 free(chr);
2452 return NULL;
2454 chr->opaque = s;
2455 chr->chr_write = win_chr_write;
2456 chr->chr_close = win_chr_close;
2458 if (win_chr_pipe_init(s, filename) < 0) {
2459 free(s);
2460 free(chr);
2461 return NULL;
2463 qemu_chr_reset(chr);
2464 return chr;
2467 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2469 CharDriverState *chr;
2470 WinCharState *s;
2472 chr = qemu_mallocz(sizeof(CharDriverState));
2473 if (!chr)
2474 return NULL;
2475 s = qemu_mallocz(sizeof(WinCharState));
2476 if (!s) {
2477 free(chr);
2478 return NULL;
2480 s->hcom = fd_out;
2481 chr->opaque = s;
2482 chr->chr_write = win_chr_write;
2483 qemu_chr_reset(chr);
2484 return chr;
2487 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2489 HANDLE fd_out;
2491 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2492 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2493 if (fd_out == INVALID_HANDLE_VALUE)
2494 return NULL;
2496 return qemu_chr_open_win_file(fd_out);
2498 #endif
2499 #endif
2501 /***********************************************************/
2502 /* UDP Net console */
2504 typedef struct {
2505 int fd;
2506 struct sockaddr_in daddr;
2507 char buf[1024];
2508 int bufcnt;
2509 int bufptr;
2510 int max_size;
2511 } NetCharDriver;
2513 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2515 NetCharDriver *s = chr->opaque;
2517 return sendto(s->fd, buf, len, 0,
2518 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2521 static int udp_chr_read_poll(void *opaque)
2523 CharDriverState *chr = opaque;
2524 NetCharDriver *s = chr->opaque;
2526 s->max_size = qemu_chr_can_read(chr);
2528 /* If there were any stray characters in the queue process them
2529 * first
2530 */
2531 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2532 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2533 s->bufptr++;
2534 s->max_size = qemu_chr_can_read(chr);
2536 return s->max_size;
2539 static void udp_chr_read(void *opaque)
2541 CharDriverState *chr = opaque;
2542 NetCharDriver *s = chr->opaque;
2544 if (s->max_size == 0)
2545 return;
2546 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2547 s->bufptr = s->bufcnt;
2548 if (s->bufcnt <= 0)
2549 return;
2551 s->bufptr = 0;
2552 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2553 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2554 s->bufptr++;
2555 s->max_size = qemu_chr_can_read(chr);
2559 static void udp_chr_update_read_handler(CharDriverState *chr)
2561 NetCharDriver *s = chr->opaque;
2563 if (s->fd >= 0) {
2564 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2565 udp_chr_read, NULL, chr);
2569 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2570 #ifndef NO_UNIX_SOCKETS
2571 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2572 #endif
2573 int parse_host_src_port(struct sockaddr_in *haddr,
2574 struct sockaddr_in *saddr,
2575 const char *str);
2577 static CharDriverState *qemu_chr_open_udp(const char *def)
2579 CharDriverState *chr = NULL;
2580 NetCharDriver *s = NULL;
2581 int fd = -1;
2582 struct sockaddr_in saddr;
2584 chr = qemu_mallocz(sizeof(CharDriverState));
2585 if (!chr)
2586 goto return_err;
2587 s = qemu_mallocz(sizeof(NetCharDriver));
2588 if (!s)
2589 goto return_err;
2591 fd = socket(PF_INET, SOCK_DGRAM, 0);
2592 if (fd < 0) {
2593 perror("socket(PF_INET, SOCK_DGRAM)");
2594 goto return_err;
2597 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2598 printf("Could not parse: %s\n", def);
2599 goto return_err;
2602 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2604 perror("bind");
2605 goto return_err;
2608 s->fd = fd;
2609 s->bufcnt = 0;
2610 s->bufptr = 0;
2611 chr->opaque = s;
2612 chr->chr_write = udp_chr_write;
2613 chr->chr_update_read_handler = udp_chr_update_read_handler;
2614 return chr;
2616 return_err:
2617 if (chr)
2618 free(chr);
2619 if (s)
2620 free(s);
2621 if (fd >= 0)
2622 closesocket(fd);
2623 return NULL;
2626 /***********************************************************/
2627 /* TCP Net console */
2629 typedef struct {
2630 int fd, listen_fd;
2631 int connected;
2632 int max_size;
2633 int do_telnetopt;
2634 int do_nodelay;
2635 int is_unix;
2636 } TCPCharDriver;
2638 static void tcp_chr_accept(void *opaque);
2640 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2642 TCPCharDriver *s = chr->opaque;
2643 if (s->connected) {
2644 return send_all(s->fd, buf, len);
2645 } else {
2646 /* XXX: indicate an error ? */
2647 return len;
2651 static int tcp_chr_read_poll(void *opaque)
2653 CharDriverState *chr = opaque;
2654 TCPCharDriver *s = chr->opaque;
2655 if (!s->connected)
2656 return 0;
2657 s->max_size = qemu_chr_can_read(chr);
2658 return s->max_size;
2661 #define IAC 255
2662 #define IAC_BREAK 243
2663 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2664 TCPCharDriver *s,
2665 char *buf, int *size)
2667 /* Handle any telnet client's basic IAC options to satisfy char by
2668 * char mode with no echo. All IAC options will be removed from
2669 * the buf and the do_telnetopt variable will be used to track the
2670 * state of the width of the IAC information.
2672 * IAC commands come in sets of 3 bytes with the exception of the
2673 * "IAC BREAK" command and the double IAC.
2674 */
2676 int i;
2677 int j = 0;
2679 for (i = 0; i < *size; i++) {
2680 if (s->do_telnetopt > 1) {
2681 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2682 /* Double IAC means send an IAC */
2683 if (j != i)
2684 buf[j] = buf[i];
2685 j++;
2686 s->do_telnetopt = 1;
2687 } else {
2688 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2689 /* Handle IAC break commands by sending a serial break */
2690 qemu_chr_event(chr, CHR_EVENT_BREAK);
2691 s->do_telnetopt++;
2693 s->do_telnetopt++;
2695 if (s->do_telnetopt >= 4) {
2696 s->do_telnetopt = 1;
2698 } else {
2699 if ((unsigned char)buf[i] == IAC) {
2700 s->do_telnetopt = 2;
2701 } else {
2702 if (j != i)
2703 buf[j] = buf[i];
2704 j++;
2708 *size = j;
2711 static void tcp_chr_read(void *opaque)
2713 CharDriverState *chr = opaque;
2714 TCPCharDriver *s = chr->opaque;
2715 uint8_t buf[1024];
2716 int len, size;
2718 if (!s->connected || s->max_size <= 0)
2719 return;
2720 len = sizeof(buf);
2721 if (len > s->max_size)
2722 len = s->max_size;
2723 size = recv(s->fd, buf, len, 0);
2724 if (size == 0) {
2725 /* connection closed */
2726 s->connected = 0;
2727 if (s->listen_fd >= 0) {
2728 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2730 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2731 closesocket(s->fd);
2732 s->fd = -1;
2733 } else if (size > 0) {
2734 if (s->do_telnetopt)
2735 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2736 if (size > 0)
2737 qemu_chr_read(chr, buf, size);
2741 static void tcp_chr_connect(void *opaque)
2743 CharDriverState *chr = opaque;
2744 TCPCharDriver *s = chr->opaque;
2746 s->connected = 1;
2747 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2748 tcp_chr_read, NULL, chr);
2749 qemu_chr_reset(chr);
2752 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2753 static void tcp_chr_telnet_init(int fd)
2755 char buf[3];
2756 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2757 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2758 send(fd, (char *)buf, 3, 0);
2759 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2760 send(fd, (char *)buf, 3, 0);
2761 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2762 send(fd, (char *)buf, 3, 0);
2763 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2764 send(fd, (char *)buf, 3, 0);
2767 static void socket_set_nodelay(int fd)
2769 int val = 1;
2770 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2773 static void tcp_chr_accept(void *opaque)
2775 CharDriverState *chr = opaque;
2776 TCPCharDriver *s = chr->opaque;
2777 struct sockaddr_in saddr;
2778 #ifndef NO_UNIX_SOCKETS
2779 struct sockaddr_un uaddr;
2780 #endif
2781 struct sockaddr *addr;
2782 socklen_t len;
2783 int fd;
2785 for(;;) {
2786 #ifndef NO_UNIX_SOCKETS
2787 if (s->is_unix) {
2788 len = sizeof(uaddr);
2789 addr = (struct sockaddr *)&uaddr;
2790 } else
2791 #endif
2793 len = sizeof(saddr);
2794 addr = (struct sockaddr *)&saddr;
2796 fd = accept(s->listen_fd, addr, &len);
2797 if (fd < 0 && errno != EINTR) {
2798 return;
2799 } else if (fd >= 0) {
2800 if (s->do_telnetopt)
2801 tcp_chr_telnet_init(fd);
2802 break;
2805 socket_set_nonblock(fd);
2806 if (s->do_nodelay)
2807 socket_set_nodelay(fd);
2808 s->fd = fd;
2809 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2810 tcp_chr_connect(chr);
2813 static void tcp_chr_close(CharDriverState *chr)
2815 TCPCharDriver *s = chr->opaque;
2816 if (s->fd >= 0)
2817 closesocket(s->fd);
2818 if (s->listen_fd >= 0)
2819 closesocket(s->listen_fd);
2820 qemu_free(s);
2823 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2824 int is_telnet,
2825 int is_unix)
2827 CharDriverState *chr = NULL;
2828 TCPCharDriver *s = NULL;
2829 int fd = -1, ret, err, val;
2830 int is_listen = 0;
2831 int is_waitconnect = 1;
2832 int do_nodelay = 0;
2833 const char *ptr;
2834 struct sockaddr_in saddr;
2835 #ifndef NO_UNIX_SOCKETS
2836 struct sockaddr_un uaddr;
2837 #endif
2838 struct sockaddr *addr;
2839 socklen_t addrlen;
2841 #ifndef NO_UNIX_SOCKETS
2842 if (is_unix) {
2843 addr = (struct sockaddr *)&uaddr;
2844 addrlen = sizeof(uaddr);
2845 if (parse_unix_path(&uaddr, host_str) < 0)
2846 goto fail;
2847 } else
2848 #endif
2850 addr = (struct sockaddr *)&saddr;
2851 addrlen = sizeof(saddr);
2852 if (parse_host_port(&saddr, host_str) < 0)
2853 goto fail;
2856 ptr = host_str;
2857 while((ptr = strchr(ptr,','))) {
2858 ptr++;
2859 if (!strncmp(ptr,"server",6)) {
2860 is_listen = 1;
2861 } else if (!strncmp(ptr,"nowait",6)) {
2862 is_waitconnect = 0;
2863 } else if (!strncmp(ptr,"nodelay",6)) {
2864 do_nodelay = 1;
2865 } else {
2866 printf("Unknown option: %s\n", ptr);
2867 goto fail;
2870 if (!is_listen)
2871 is_waitconnect = 0;
2873 chr = qemu_mallocz(sizeof(CharDriverState));
2874 if (!chr)
2875 goto fail;
2876 s = qemu_mallocz(sizeof(TCPCharDriver));
2877 if (!s)
2878 goto fail;
2880 #ifndef NO_UNIX_SOCKETS
2881 if (is_unix)
2882 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2883 else
2884 #endif
2885 fd = socket(PF_INET, SOCK_STREAM, 0);
2887 if (fd < 0)
2888 goto fail;
2890 if (!is_waitconnect)
2891 socket_set_nonblock(fd);
2893 s->connected = 0;
2894 s->fd = -1;
2895 s->listen_fd = -1;
2896 s->is_unix = is_unix;
2897 s->do_nodelay = do_nodelay && !is_unix;
2899 chr->opaque = s;
2900 chr->chr_write = tcp_chr_write;
2901 chr->chr_close = tcp_chr_close;
2903 if (is_listen) {
2904 /* allow fast reuse */
2905 #ifndef NO_UNIX_SOCKETS
2906 if (is_unix) {
2907 char path[109];
2908 strncpy(path, uaddr.sun_path, 108);
2909 path[108] = 0;
2910 unlink(path);
2911 } else
2912 #endif
2914 val = 1;
2915 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2918 ret = bind(fd, addr, addrlen);
2919 if (ret < 0)
2920 goto fail;
2922 ret = listen(fd, 0);
2923 if (ret < 0)
2924 goto fail;
2926 s->listen_fd = fd;
2927 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2928 if (is_telnet)
2929 s->do_telnetopt = 1;
2930 } else {
2931 for(;;) {
2932 ret = connect(fd, addr, addrlen);
2933 if (ret < 0) {
2934 err = socket_error();
2935 if (err == EINTR || err == EWOULDBLOCK) {
2936 } else if (err == EINPROGRESS) {
2937 break;
2938 } else {
2939 goto fail;
2941 } else {
2942 s->connected = 1;
2943 break;
2946 s->fd = fd;
2947 socket_set_nodelay(fd);
2948 if (s->connected)
2949 tcp_chr_connect(chr);
2950 else
2951 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2954 if (is_listen && is_waitconnect) {
2955 printf("QEMU waiting for connection on: %s\n", host_str);
2956 tcp_chr_accept(chr);
2957 socket_set_nonblock(s->listen_fd);
2960 return chr;
2961 fail:
2962 if (fd >= 0)
2963 closesocket(fd);
2964 qemu_free(s);
2965 qemu_free(chr);
2966 return NULL;
2969 CharDriverState *qemu_chr_open(const char *filename)
2971 const char *p;
2973 if (!strcmp(filename, "vc")) {
2974 return text_console_init(&display_state);
2975 } else if (!strcmp(filename, "null")) {
2976 return qemu_chr_open_null();
2977 } else
2978 if (strstart(filename, "tcp:", &p)) {
2979 return qemu_chr_open_tcp(p, 0, 0);
2980 } else
2981 if (strstart(filename, "telnet:", &p)) {
2982 return qemu_chr_open_tcp(p, 1, 0);
2983 } else
2984 if (strstart(filename, "udp:", &p)) {
2985 return qemu_chr_open_udp(p);
2986 } else
2987 #ifndef _WIN32
2988 if (strstart(filename, "unix:", &p)) {
2989 return qemu_chr_open_tcp(p, 0, 1);
2990 } else if (strstart(filename, "file:", &p)) {
2991 return qemu_chr_open_file_out(p);
2992 #ifndef CONFIG_STUBDOM
2993 } else if (strstart(filename, "pipe:", &p)) {
2994 return qemu_chr_open_pipe(p);
2995 } else if (!strcmp(filename, "pty")) {
2996 return qemu_chr_open_pty();
2997 } else if (!strcmp(filename, "stdio")) {
2998 return qemu_chr_open_stdio();
2999 #endif
3000 } else
3001 #endif
3002 #if defined(__linux__)
3003 if (strstart(filename, "/dev/parport", NULL)) {
3004 return qemu_chr_open_pp(filename);
3005 } else
3006 if (strstart(filename, "/dev/", NULL)) {
3007 return qemu_chr_open_tty(filename);
3008 } else
3009 #endif
3010 #ifdef _WIN32
3011 if (strstart(filename, "COM", NULL)) {
3012 return qemu_chr_open_win(filename);
3013 } else
3014 if (strstart(filename, "pipe:", &p)) {
3015 return qemu_chr_open_win_pipe(p);
3016 } else
3017 if (strstart(filename, "file:", &p)) {
3018 return qemu_chr_open_win_file_out(p);
3020 #endif
3022 return NULL;
3026 void qemu_chr_close(CharDriverState *chr)
3028 if (chr->chr_close)
3029 chr->chr_close(chr);
3032 /***********************************************************/
3033 /* network device redirectors */
3035 void hex_dump(FILE *f, const uint8_t *buf, int size)
3037 int len, i, j, c;
3039 for(i=0;i<size;i+=16) {
3040 len = size - i;
3041 if (len > 16)
3042 len = 16;
3043 fprintf(f, "%08x ", i);
3044 for(j=0;j<16;j++) {
3045 if (j < len)
3046 fprintf(f, " %02x", buf[i+j]);
3047 else
3048 fprintf(f, " ");
3050 fprintf(f, " ");
3051 for(j=0;j<len;j++) {
3052 c = buf[i+j];
3053 if (c < ' ' || c > '~')
3054 c = '.';
3055 fprintf(f, "%c", c);
3057 fprintf(f, "\n");
3061 static int parse_macaddr(uint8_t *macaddr, const char *p)
3063 int i;
3064 for(i = 0; i < 6; i++) {
3065 macaddr[i] = strtol(p, (char **)&p, 16);
3066 if (i == 5) {
3067 if (*p != '\0')
3068 return -1;
3069 } else {
3070 if (*p != ':')
3071 return -1;
3072 p++;
3075 return 0;
3078 static int get_str_sep(char *buf, size_t buf_size, const char **pp, int sep)
3080 const char *p, *p1;
3081 int len;
3082 p = *pp;
3083 p1 = strchr(p, sep);
3084 if (!p1)
3085 return -1;
3086 len = p1 - p;
3087 p1++;
3088 if (buf_size > 0) {
3089 if (len > buf_size - 1)
3090 len = buf_size - 1;
3091 memcpy(buf, p, len);
3092 buf[len] = '\0';
3094 *pp = p1;
3095 return 0;
3098 int parse_host_src_port(struct sockaddr_in *haddr,
3099 struct sockaddr_in *saddr,
3100 const char *input_str)
3102 char *str = strdup(input_str);
3103 char *host_str = str;
3104 char *src_str;
3105 char *ptr;
3107 /*
3108 * Chop off any extra arguments at the end of the string which
3109 * would start with a comma, then fill in the src port information
3110 * if it was provided else use the "any address" and "any port".
3111 */
3112 if ((ptr = strchr(str,',')))
3113 *ptr = '\0';
3115 if ((src_str = strchr(input_str,'@'))) {
3116 *src_str = '\0';
3117 src_str++;
3120 if (parse_host_port(haddr, host_str) < 0)
3121 goto fail;
3123 if (!src_str || *src_str == '\0')
3124 src_str = ":0";
3126 if (parse_host_port(saddr, src_str) < 0)
3127 goto fail;
3129 free(str);
3130 return(0);
3132 fail:
3133 free(str);
3134 return -1;
3137 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3139 char buf[512];
3140 struct hostent *he;
3141 const char *p, *r;
3142 int port;
3144 p = str;
3145 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3146 return -1;
3147 saddr->sin_family = AF_INET;
3148 if (buf[0] == '\0') {
3149 saddr->sin_addr.s_addr = 0;
3150 } else {
3151 if (isdigit((uint8_t)buf[0])) {
3152 if (!inet_aton(buf, &saddr->sin_addr))
3153 return -1;
3154 } else {
3155 if ((he = gethostbyname(buf)) == NULL)
3156 return - 1;
3157 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3160 port = strtol(p, (char **)&r, 0);
3161 if (r == p)
3162 return -1;
3163 saddr->sin_port = htons(port);
3164 return 0;
3167 #ifndef NO_UNIX_SOCKETS
3168 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3170 const char *p;
3171 int len;
3173 len = MIN(108, strlen(str));
3174 p = strchr(str, ',');
3175 if (p)
3176 len = MIN(len, p - str);
3178 memset(uaddr, 0, sizeof(*uaddr));
3180 uaddr->sun_family = AF_UNIX;
3181 memcpy(uaddr->sun_path, str, len);
3183 return 0;
3185 #endif
3187 /* find or alloc a new VLAN */
3188 VLANState *qemu_find_vlan(int id)
3190 VLANState **pvlan, *vlan;
3191 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3192 if (vlan->id == id)
3193 return vlan;
3195 vlan = qemu_mallocz(sizeof(VLANState));
3196 if (!vlan)
3197 return NULL;
3198 vlan->id = id;
3199 vlan->next = NULL;
3200 pvlan = &first_vlan;
3201 while (*pvlan != NULL)
3202 pvlan = &(*pvlan)->next;
3203 *pvlan = vlan;
3204 return vlan;
3207 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3208 IOReadHandler *fd_read,
3209 IOCanRWHandler *fd_can_read,
3210 void *opaque)
3212 VLANClientState *vc, **pvc;
3213 vc = qemu_mallocz(sizeof(VLANClientState));
3214 if (!vc)
3215 return NULL;
3216 vc->fd_read = fd_read;
3217 vc->fd_can_read = fd_can_read;
3218 vc->opaque = opaque;
3219 vc->vlan = vlan;
3221 vc->next = NULL;
3222 pvc = &vlan->first_client;
3223 while (*pvc != NULL)
3224 pvc = &(*pvc)->next;
3225 *pvc = vc;
3226 return vc;
3229 int qemu_can_send_packet(VLANClientState *vc1)
3231 VLANState *vlan = vc1->vlan;
3232 VLANClientState *vc;
3234 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3235 if (vc != vc1) {
3236 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3237 return 0;
3240 return 1;
3243 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3245 VLANState *vlan = vc1->vlan;
3246 VLANClientState *vc;
3248 #if 0
3249 printf("vlan %d send:\n", vlan->id);
3250 hex_dump(stdout, buf, size);
3251 #endif
3252 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3253 if (vc != vc1) {
3254 vc->fd_read(vc->opaque, buf, size);
3259 #if defined(CONFIG_SLIRP)
3261 /* slirp network adapter */
3263 static int slirp_inited;
3264 static VLANClientState *slirp_vc;
3266 int slirp_can_output(void)
3268 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3271 void slirp_output(const uint8_t *pkt, int pkt_len)
3273 #if 0
3274 printf("slirp output:\n");
3275 hex_dump(stdout, pkt, pkt_len);
3276 #endif
3277 if (!slirp_vc)
3278 return;
3279 qemu_send_packet(slirp_vc, pkt, pkt_len);
3282 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3284 #if 0
3285 printf("slirp input:\n");
3286 hex_dump(stdout, buf, size);
3287 #endif
3288 slirp_input(buf, size);
3291 static int net_slirp_init(VLANState *vlan)
3293 if (!slirp_inited) {
3294 slirp_inited = 1;
3295 slirp_init();
3297 slirp_vc = qemu_new_vlan_client(vlan,
3298 slirp_receive, NULL, NULL);
3299 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3300 return 0;
3303 static void net_slirp_redir(const char *redir_str)
3305 int is_udp;
3306 char buf[256], *r;
3307 const char *p;
3308 struct in_addr guest_addr;
3309 int host_port, guest_port;
3311 if (!slirp_inited) {
3312 slirp_inited = 1;
3313 slirp_init();
3316 p = redir_str;
3317 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3318 goto fail;
3319 if (!strcmp(buf, "tcp")) {
3320 is_udp = 0;
3321 } else if (!strcmp(buf, "udp")) {
3322 is_udp = 1;
3323 } else {
3324 goto fail;
3327 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3328 goto fail;
3329 host_port = strtol(buf, &r, 0);
3330 if (r == buf)
3331 goto fail;
3333 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3334 goto fail;
3335 if (buf[0] == '\0') {
3336 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3338 if (!inet_aton(buf, &guest_addr))
3339 goto fail;
3341 guest_port = strtol(p, &r, 0);
3342 if (r == p)
3343 goto fail;
3345 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3346 fprintf(stderr, "qemu: could not set up redirection\n");
3347 exit(1);
3349 return;
3350 fail:
3351 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3352 exit(1);
3355 #ifndef _WIN32
3357 char smb_dir[1024];
3359 static void smb_exit(void)
3361 DIR *d;
3362 struct dirent *de;
3363 char filename[1024];
3365 /* erase all the files in the directory */
3366 d = opendir(smb_dir);
3367 for(;;) {
3368 de = readdir(d);
3369 if (!de)
3370 break;
3371 if (strcmp(de->d_name, ".") != 0 &&
3372 strcmp(de->d_name, "..") != 0) {
3373 snprintf(filename, sizeof(filename), "%s/%s",
3374 smb_dir, de->d_name);
3375 unlink(filename);
3378 closedir(d);
3379 rmdir(smb_dir);
3382 /* automatic user mode samba server configuration */
3383 void net_slirp_smb(const char *exported_dir)
3385 char smb_conf[1024];
3386 char smb_cmdline[1024];
3387 FILE *f;
3389 if (!slirp_inited) {
3390 slirp_inited = 1;
3391 slirp_init();
3394 /* XXX: better tmp dir construction */
3395 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3396 if (mkdir(smb_dir, 0700) < 0) {
3397 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3398 exit(1);
3400 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3402 f = fopen(smb_conf, "w");
3403 if (!f) {
3404 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3405 exit(1);
3407 fprintf(f,
3408 "[global]\n"
3409 "private dir=%s\n"
3410 "smb ports=0\n"
3411 "socket address=127.0.0.1\n"
3412 "pid directory=%s\n"
3413 "lock directory=%s\n"
3414 "log file=%s/log.smbd\n"
3415 "smb passwd file=%s/smbpasswd\n"
3416 "security = share\n"
3417 "[qemu]\n"
3418 "path=%s\n"
3419 "read only=no\n"
3420 "guest ok=yes\n",
3421 smb_dir,
3422 smb_dir,
3423 smb_dir,
3424 smb_dir,
3425 smb_dir,
3426 exported_dir
3427 );
3428 fclose(f);
3429 atexit(smb_exit);
3431 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3432 SMBD_COMMAND, smb_conf);
3434 slirp_add_exec(0, smb_cmdline, 4, 139);
3437 #endif /* !defined(_WIN32) */
3439 #endif /* CONFIG_SLIRP */
3441 #if !defined(_WIN32)
3443 typedef struct TAPState {
3444 VLANClientState *vc;
3445 int fd;
3446 } TAPState;
3448 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3450 TAPState *s = opaque;
3451 int ret;
3452 for(;;) {
3453 ret = write(s->fd, buf, size);
3454 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3455 } else {
3456 break;
3461 static void tap_send(void *opaque)
3463 TAPState *s = opaque;
3464 uint8_t buf[4096];
3465 int size;
3467 size = read(s->fd, buf, sizeof(buf));
3468 if (size > 0) {
3469 qemu_send_packet(s->vc, buf, size);
3473 /* fd support */
3475 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3477 TAPState *s;
3479 s = qemu_mallocz(sizeof(TAPState));
3480 if (!s)
3481 return NULL;
3482 s->fd = fd;
3483 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3484 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3485 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3486 return s;
3489 #ifdef CONFIG_STUBDOM
3490 #include <netfront.h>
3491 static int tap_open(char *ifname, int ifname_size)
3493 char nodename[64];
3494 static int num = 1; // 0 is for our own TCP/IP networking
3495 snprintf(nodename, sizeof(nodename), "device/vif/%d", num++);
3496 return netfront_tap_open(nodename);
3498 #elif defined(_BSD)
3499 static int tap_open(char *ifname, int ifname_size)
3501 int fd;
3502 #ifndef TAPGIFNAME
3503 char *dev;
3504 struct stat s;
3505 #endif
3506 struct ifreq ifr;
3508 fd = open("/dev/tap", O_RDWR);
3509 if (fd < 0) {
3510 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation %s\n", strerror(errno));
3511 return -1;
3514 #ifdef TAPGIFNAME
3515 if (ioctl (fd, TAPGIFNAME, (void*)&ifr) < 0) {
3516 fprintf(stderr, "warning: could not open get tap name: %s\n",
3517 strerror(errno));
3518 return -1;
3520 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3521 #else
3522 fstat(fd, &s);
3523 dev = devname(s.st_rdev, S_IFCHR);
3524 pstrcpy(ifname, ifname_size, dev);
3525 #endif
3527 fcntl(fd, F_SETFL, O_NONBLOCK);
3528 return fd;
3530 #elif defined(__sun__)
3531 static int tap_open(char *ifname, int ifname_size)
3533 fprintf(stderr, "warning: tap_open not yet implemented\n");
3534 return -1;
3536 #else
3537 static int tap_open(char *ifname, int ifname_size)
3539 struct ifreq ifr;
3540 int fd, ret, retries = 0;
3542 fd = open("/dev/net/tun", O_RDWR);
3543 if (fd < 0) {
3544 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3545 return -1;
3547 memset(&ifr, 0, sizeof(ifr));
3548 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3549 if (ifname[0] != '\0')
3550 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3551 else
3552 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3553 do {
3554 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3555 } while ((ret != 0) && (retries++ < 3));
3556 if (ret != 0) {
3557 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3558 close(fd);
3559 return -1;
3561 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3562 fcntl(fd, F_SETFL, O_NONBLOCK);
3563 return fd;
3565 #endif
3567 static int net_tap_init(VLANState *vlan, const char *ifname1,
3568 const char *setup_script, const char *bridge)
3570 TAPState *s;
3571 int pid, status, fd;
3572 char *args[4];
3573 char **parg;
3574 char ifname[128];
3576 memset(ifname, 0, sizeof(ifname));
3578 if (ifname1 != NULL)
3579 pstrcpy(ifname, sizeof(ifname), ifname1);
3580 else
3581 ifname[0] = '\0';
3582 fd = tap_open(ifname, sizeof(ifname));
3583 if (fd < 0)
3584 return -1;
3586 #ifndef CONFIG_STUBDOM
3587 if (!setup_script || !strcmp(setup_script, "no"))
3588 setup_script = "";
3589 if (setup_script[0] != '\0') {
3590 /* try to launch network init script */
3591 pid = fork();
3592 if (pid >= 0) {
3593 if (pid == 0) {
3594 int open_max = sysconf(_SC_OPEN_MAX), i;
3595 for (i = 0; i < open_max; i++)
3596 if (i != STDIN_FILENO &&
3597 i != STDOUT_FILENO &&
3598 i != STDERR_FILENO &&
3599 i != fd)
3600 close(i);
3602 parg = args;
3603 *parg++ = (char *)setup_script;
3604 *parg++ = ifname;
3605 *parg++ = (char *)bridge;
3606 *parg++ = NULL;
3607 execv(setup_script, args);
3608 _exit(1);
3610 while (waitpid(pid, &status, 0) != pid);
3611 if (!WIFEXITED(status) ||
3612 WEXITSTATUS(status) != 0) {
3613 fprintf(stderr, "%s: could not launch network script\n",
3614 setup_script);
3615 return -1;
3619 #endif
3620 s = net_tap_fd_init(vlan, fd);
3621 if (!s)
3622 return -1;
3623 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3624 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3625 return 0;
3628 #endif /* !_WIN32 */
3630 /* network connection */
3631 typedef struct NetSocketState {
3632 VLANClientState *vc;
3633 int fd;
3634 int state; /* 0 = getting length, 1 = getting data */
3635 int index;
3636 int packet_len;
3637 uint8_t buf[4096];
3638 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3639 } NetSocketState;
3641 typedef struct NetSocketListenState {
3642 VLANState *vlan;
3643 int fd;
3644 } NetSocketListenState;
3646 /* XXX: we consider we can send the whole packet without blocking */
3647 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3649 NetSocketState *s = opaque;
3650 uint32_t len;
3651 len = htonl(size);
3653 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3654 send_all(s->fd, buf, size);
3657 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3659 NetSocketState *s = opaque;
3660 sendto(s->fd, buf, size, 0,
3661 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3664 static void net_socket_send(void *opaque)
3666 NetSocketState *s = opaque;
3667 int l, size, err;
3668 uint8_t buf1[4096];
3669 const uint8_t *buf;
3671 size = recv(s->fd, buf1, sizeof(buf1), 0);
3672 if (size < 0) {
3673 err = socket_error();
3674 if (err != EWOULDBLOCK)
3675 goto eoc;
3676 } else if (size == 0) {
3677 /* end of connection */
3678 eoc:
3679 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3680 closesocket(s->fd);
3681 return;
3683 buf = buf1;
3684 while (size > 0) {
3685 /* reassemble a packet from the network */
3686 switch(s->state) {
3687 case 0:
3688 l = 4 - s->index;
3689 if (l > size)
3690 l = size;
3691 memcpy(s->buf + s->index, buf, l);
3692 buf += l;
3693 size -= l;
3694 s->index += l;
3695 if (s->index == 4) {
3696 /* got length */
3697 s->packet_len = ntohl(*(uint32_t *)s->buf);
3698 s->index = 0;
3699 s->state = 1;
3701 break;
3702 case 1:
3703 l = s->packet_len - s->index;
3704 if (l > size)
3705 l = size;
3706 memcpy(s->buf + s->index, buf, l);
3707 s->index += l;
3708 buf += l;
3709 size -= l;
3710 if (s->index >= s->packet_len) {
3711 qemu_send_packet(s->vc, s->buf, s->packet_len);
3712 s->index = 0;
3713 s->state = 0;
3715 break;
3720 static void net_socket_send_dgram(void *opaque)
3722 NetSocketState *s = opaque;
3723 int size;
3725 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3726 if (size < 0)
3727 return;
3728 if (size == 0) {
3729 /* end of connection */
3730 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3731 return;
3733 qemu_send_packet(s->vc, s->buf, size);
3736 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3738 struct ip_mreq imr;
3739 int fd;
3740 int val, ret;
3741 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3742 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3743 inet_ntoa(mcastaddr->sin_addr),
3744 (int)ntohl(mcastaddr->sin_addr.s_addr));
3745 return -1;
3748 fd = socket(PF_INET, SOCK_DGRAM, 0);
3749 if (fd < 0) {
3750 perror("socket(PF_INET, SOCK_DGRAM)");
3751 return -1;
3754 val = 1;
3755 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3756 (const char *)&val, sizeof(char));
3757 if (ret < 0) {
3758 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3759 goto fail;
3762 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3763 if (ret < 0) {
3764 perror("bind");
3765 goto fail;
3768 /* Add host to multicast group */
3769 imr.imr_multiaddr = mcastaddr->sin_addr;
3770 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3772 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3773 (const char *)&imr, sizeof(struct ip_mreq));
3774 if (ret < 0) {
3775 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3776 goto fail;
3779 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3780 val = 1;
3781 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3782 (const char *)&val, sizeof(val));
3783 if (ret < 0) {
3784 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3785 goto fail;
3788 socket_set_nonblock(fd);
3789 return fd;
3790 fail:
3791 if (fd >= 0)
3792 closesocket(fd);
3793 return -1;
3796 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3797 int is_connected)
3799 struct sockaddr_in saddr;
3800 int newfd;
3801 socklen_t saddr_len;
3802 NetSocketState *s;
3804 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3805 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3806 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3807 */
3809 if (is_connected) {
3810 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3811 /* must be bound */
3812 if (saddr.sin_addr.s_addr==0) {
3813 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3814 fd);
3815 return NULL;
3817 /* clone dgram socket */
3818 newfd = net_socket_mcast_create(&saddr);
3819 if (newfd < 0) {
3820 /* error already reported by net_socket_mcast_create() */
3821 close(fd);
3822 return NULL;
3824 /* clone newfd to fd, close newfd */
3825 dup2(newfd, fd);
3826 close(newfd);
3828 } else {
3829 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3830 fd, strerror(errno));
3831 return NULL;
3835 s = qemu_mallocz(sizeof(NetSocketState));
3836 if (!s)
3837 return NULL;
3838 s->fd = fd;
3840 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3841 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3843 /* mcast: save bound address as dst */
3844 if (is_connected) s->dgram_dst=saddr;
3846 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3847 "socket: fd=%d (%s mcast=%s:%d)",
3848 fd, is_connected? "cloned" : "",
3849 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3850 return s;
3853 static void net_socket_connect(void *opaque)
3855 NetSocketState *s = opaque;
3856 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3859 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3860 int is_connected)
3862 NetSocketState *s;
3863 s = qemu_mallocz(sizeof(NetSocketState));
3864 if (!s)
3865 return NULL;
3866 s->fd = fd;
3867 s->vc = qemu_new_vlan_client(vlan,
3868 net_socket_receive, NULL, s);
3869 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3870 "socket: fd=%d", fd);
3871 if (is_connected) {
3872 net_socket_connect(s);
3873 } else {
3874 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3876 return s;
3879 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3880 int is_connected)
3882 int so_type=-1, optlen=sizeof(so_type);
3884 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3885 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3886 return NULL;
3888 switch(so_type) {
3889 case SOCK_DGRAM:
3890 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3891 case SOCK_STREAM:
3892 return net_socket_fd_init_stream(vlan, fd, is_connected);
3893 default:
3894 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3895 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3896 return net_socket_fd_init_stream(vlan, fd, is_connected);
3898 return NULL;
3901 static void net_socket_accept(void *opaque)
3903 NetSocketListenState *s = opaque;
3904 NetSocketState *s1;
3905 struct sockaddr_in saddr;
3906 socklen_t len;
3907 int fd;
3909 for(;;) {
3910 len = sizeof(saddr);
3911 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3912 if (fd < 0 && errno != EINTR) {
3913 return;
3914 } else if (fd >= 0) {
3915 break;
3918 s1 = net_socket_fd_init(s->vlan, fd, 1);
3919 if (!s1) {
3920 closesocket(fd);
3921 } else {
3922 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3923 "socket: connection from %s:%d",
3924 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3928 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3930 NetSocketListenState *s;
3931 int fd, val, ret;
3932 struct sockaddr_in saddr;
3934 if (parse_host_port(&saddr, host_str) < 0)
3935 return -1;
3937 s = qemu_mallocz(sizeof(NetSocketListenState));
3938 if (!s)
3939 return -1;
3941 fd = socket(PF_INET, SOCK_STREAM, 0);
3942 if (fd < 0) {
3943 perror("socket");
3944 return -1;
3946 socket_set_nonblock(fd);
3948 /* allow fast reuse */
3949 val = 1;
3950 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3952 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3953 if (ret < 0) {
3954 perror("bind");
3955 return -1;
3957 ret = listen(fd, 0);
3958 if (ret < 0) {
3959 perror("listen");
3960 return -1;
3962 s->vlan = vlan;
3963 s->fd = fd;
3964 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3965 return 0;
3968 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3970 NetSocketState *s;
3971 int fd, connected, ret, err;
3972 struct sockaddr_in saddr;
3974 if (parse_host_port(&saddr, host_str) < 0)
3975 return -1;
3977 fd = socket(PF_INET, SOCK_STREAM, 0);
3978 if (fd < 0) {
3979 perror("socket");
3980 return -1;
3982 socket_set_nonblock(fd);
3984 connected = 0;
3985 for(;;) {
3986 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3987 if (ret < 0) {
3988 err = socket_error();
3989 if (err == EINTR || err == EWOULDBLOCK) {
3990 } else if (err == EINPROGRESS) {
3991 break;
3992 } else {
3993 perror("connect");
3994 closesocket(fd);
3995 return -1;
3997 } else {
3998 connected = 1;
3999 break;
4002 s = net_socket_fd_init(vlan, fd, connected);
4003 if (!s)
4004 return -1;
4005 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4006 "socket: connect to %s:%d",
4007 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4008 return 0;
4011 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4013 NetSocketState *s;
4014 int fd;
4015 struct sockaddr_in saddr;
4017 if (parse_host_port(&saddr, host_str) < 0)
4018 return -1;
4021 fd = net_socket_mcast_create(&saddr);
4022 if (fd < 0)
4023 return -1;
4025 s = net_socket_fd_init(vlan, fd, 0);
4026 if (!s)
4027 return -1;
4029 s->dgram_dst = saddr;
4031 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4032 "socket: mcast=%s:%d",
4033 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4034 return 0;
4038 static int get_param_value(char *buf, size_t buf_size,
4039 const char *tag, const char *str)
4041 const char *p;
4042 char *q;
4043 char option[128];
4045 p = str;
4046 for(;;) {
4047 q = option;
4048 while (*p != '\0' && *p != '=') {
4049 if ((q - option) < sizeof(option) - 1)
4050 *q++ = *p;
4051 p++;
4053 *q = '\0';
4054 if (*p != '=')
4055 break;
4056 p++;
4057 if (!strcmp(tag, option)) {
4058 q = buf;
4059 while (*p != '\0' && *p != ',') {
4060 if ((q - buf) < buf_size - 1)
4061 *q++ = *p;
4062 p++;
4064 *q = '\0';
4065 return q - buf;
4066 } else {
4067 while (*p != '\0' && *p != ',') {
4068 p++;
4071 if (*p != ',')
4072 break;
4073 p++;
4075 return 0;
4078 static int net_client_init(const char *str)
4080 const char *p;
4081 char *q;
4082 char device[64];
4083 char buf[1024];
4084 int vlan_id, ret;
4085 VLANState *vlan;
4087 p = str;
4088 q = device;
4089 while (*p != '\0' && *p != ',') {
4090 if ((q - device) < sizeof(device) - 1)
4091 *q++ = *p;
4092 p++;
4094 *q = '\0';
4095 if (*p == ',')
4096 p++;
4097 vlan_id = 0;
4098 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4099 vlan_id = strtol(buf, NULL, 0);
4101 vlan = qemu_find_vlan(vlan_id);
4102 if (!vlan) {
4103 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4104 return -1;
4106 if (!strcmp(device, "nic")) {
4107 NICInfo *nd;
4108 uint8_t *macaddr;
4110 if (nb_nics < MAX_NICS) {
4111 nd = &nd_table[nb_nics];
4112 macaddr = nd->macaddr;
4113 macaddr[0] = 0x52;
4114 macaddr[1] = 0x54;
4115 macaddr[2] = 0x00;
4116 macaddr[3] = 0x12;
4117 macaddr[4] = 0x34;
4118 macaddr[5] = 0x56 + nb_nics;
4120 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4121 if (parse_macaddr(macaddr, buf) < 0) {
4122 fprintf(stderr, "invalid syntax for ethernet address\n");
4123 return -1;
4126 if (get_param_value(buf, sizeof(buf), "model", p)) {
4127 nd->model = strdup(buf);
4129 nd->vlan = vlan;
4130 nb_nics++;
4131 } else {
4132 fprintf(stderr, "Too Many NICs\n");
4134 ret = 0;
4135 } else
4136 if (!strcmp(device, "none")) {
4137 /* does nothing. It is needed to signal that no network cards
4138 are wanted */
4139 ret = 0;
4140 } else
4141 #ifdef CONFIG_SLIRP
4142 if (!strcmp(device, "user")) {
4143 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4144 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4146 ret = net_slirp_init(vlan);
4147 } else
4148 #endif
4149 #ifdef _WIN32
4150 if (!strcmp(device, "tap")) {
4151 char ifname[64];
4152 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4153 fprintf(stderr, "tap: no interface name\n");
4154 return -1;
4156 ret = tap_win32_init(vlan, ifname);
4157 } else
4158 #else
4159 if (!strcmp(device, "tap")) {
4160 char ifname[64];
4161 char setup_script[1024];
4162 char bridge[16];
4163 int fd;
4165 memset(ifname, 0, sizeof(ifname));
4166 memset(setup_script, 0, sizeof(setup_script));
4168 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4169 fd = strtol(buf, NULL, 0);
4170 ret = -1;
4171 if (net_tap_fd_init(vlan, fd))
4172 ret = 0;
4173 } else {
4174 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4175 ifname[0] = '\0';
4177 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4178 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4180 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
4181 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
4183 ret = net_tap_init(vlan, ifname, setup_script, bridge);
4185 } else
4186 #endif
4187 if (!strcmp(device, "socket")) {
4188 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4189 int fd;
4190 fd = strtol(buf, NULL, 0);
4191 ret = -1;
4192 if (net_socket_fd_init(vlan, fd, 1))
4193 ret = 0;
4194 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4195 ret = net_socket_listen_init(vlan, buf);
4196 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4197 ret = net_socket_connect_init(vlan, buf);
4198 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4199 ret = net_socket_mcast_init(vlan, buf);
4200 } else {
4201 fprintf(stderr, "Unknown socket options: %s\n", p);
4202 return -1;
4204 } else
4206 fprintf(stderr, "Unknown network device: %s\n", device);
4207 return -1;
4209 if (ret < 0) {
4210 fprintf(stderr, "Could not initialize device '%s'\n", device);
4213 return ret;
4216 void do_info_network(void)
4218 VLANState *vlan;
4219 VLANClientState *vc;
4221 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4222 term_printf("VLAN %d devices:\n", vlan->id);
4223 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4224 term_printf(" %s\n", vc->info_str);
4228 /***********************************************************/
4229 /* USB devices */
4231 static USBPort *used_usb_ports;
4232 static USBPort *free_usb_ports;
4234 /* ??? Maybe change this to register a hub to keep track of the topology. */
4235 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4236 usb_attachfn attach)
4238 port->opaque = opaque;
4239 port->index = index;
4240 port->attach = attach;
4241 port->next = free_usb_ports;
4242 free_usb_ports = port;
4245 static int usb_device_add(const char *devname)
4247 const char *p;
4248 USBDevice *dev;
4249 USBPort *port;
4250 char usb_name[256] = "USB ";
4252 if (!free_usb_ports)
4253 return -1;
4255 if (strstart(devname, "host:", &p)) {
4256 dev = usb_host_device_open(p);
4257 } else if (!strcmp(devname, "mouse")) {
4258 dev = usb_mouse_init();
4259 } else if (!strcmp(devname, "tablet")) {
4260 dev = usb_tablet_init();
4261 } else if (strstart(devname, "disk:", &p)) {
4262 dev = usb_msd_init(p);
4263 } else {
4264 return -1;
4266 if (!dev)
4267 return -1;
4269 /* Find a USB port to add the device to. */
4270 port = free_usb_ports;
4271 if (!port->next) {
4272 USBDevice *hub;
4274 /* Create a new hub and chain it on. */
4275 free_usb_ports = NULL;
4276 port->next = used_usb_ports;
4277 used_usb_ports = port;
4279 hub = usb_hub_init(VM_USB_HUB_SIZE);
4280 usb_attach(port, hub);
4281 port = free_usb_ports;
4284 free_usb_ports = port->next;
4285 port->next = used_usb_ports;
4286 used_usb_ports = port;
4288 pstrcpy(usb_name + strlen(usb_name),
4289 sizeof(usb_name) - strlen(usb_name),
4290 devname);
4291 register_savevm(usb_name, 0, 1, generic_usb_save, generic_usb_load, dev);
4293 usb_attach(port, dev);
4294 return 0;
4297 static int usb_device_del(const char *devname)
4299 USBPort *port;
4300 USBPort **lastp;
4301 USBDevice *dev;
4302 int bus_num, addr;
4303 const char *p;
4305 if (!used_usb_ports)
4306 return -1;
4308 p = strchr(devname, '.');
4309 if (!p)
4310 return -1;
4311 bus_num = strtoul(devname, NULL, 0);
4312 addr = strtoul(p + 1, NULL, 0);
4313 if (bus_num != 0)
4314 return -1;
4316 lastp = &used_usb_ports;
4317 port = used_usb_ports;
4318 while (port && port->dev->addr != addr) {
4319 lastp = &port->next;
4320 port = port->next;
4323 if (!port)
4324 return -1;
4326 dev = port->dev;
4327 *lastp = port->next;
4328 usb_attach(port, NULL);
4329 dev->handle_destroy(dev);
4330 port->next = free_usb_ports;
4331 free_usb_ports = port;
4332 return 0;
4335 void do_usb_add(const char *devname)
4337 int ret;
4338 ret = usb_device_add(devname);
4339 if (ret < 0)
4340 term_printf("Could not add USB device '%s'\n", devname);
4343 void do_usb_del(const char *devname)
4345 int ret;
4346 ret = usb_device_del(devname);
4347 if (ret < 0)
4348 term_printf("Could not remove USB device '%s'\n", devname);
4351 void usb_info(void)
4353 USBDevice *dev;
4354 USBPort *port;
4355 const char *speed_str;
4357 if (!usb_enabled) {
4358 term_printf("USB support not enabled\n");
4359 return;
4362 for (port = used_usb_ports; port; port = port->next) {
4363 dev = port->dev;
4364 if (!dev)
4365 continue;
4366 switch(dev->speed) {
4367 case USB_SPEED_LOW:
4368 speed_str = "1.5";
4369 break;
4370 case USB_SPEED_FULL:
4371 speed_str = "12";
4372 break;
4373 case USB_SPEED_HIGH:
4374 speed_str = "480";
4375 break;
4376 default:
4377 speed_str = "?";
4378 break;
4380 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4381 0, dev->addr, speed_str, dev->devname);
4385 void do_pci_del(char *devname)
4387 #ifdef CONFIG_PASSTHROUGH
4388 int pci_slot = bdf_to_slot(devname);
4389 acpi_php_del(pci_slot);
4390 #endif
4393 void do_pci_add(char *devname)
4395 #ifdef CONFIG_PASSTHROUGH
4396 int pci_slot = insert_to_pci_slot(devname);
4397 acpi_php_add(pci_slot);
4398 #endif
4402 /***********************************************************/
4403 /* pid file */
4405 static char *pid_filename;
4407 /* Remove PID file. Called on normal exit */
4409 static void remove_pidfile(void)
4411 unlink (pid_filename);
4414 static void create_pidfile(const char *filename)
4416 struct stat pidstat;
4417 FILE *f;
4419 /* Try to write our PID to the named file */
4420 if (stat(filename, &pidstat) < 0) {
4421 if (errno == ENOENT) {
4422 if ((f = fopen (filename, "w")) == NULL) {
4423 perror("Opening pidfile");
4424 exit(1);
4426 fprintf(f, "%ld\n", (long)getpid());
4427 fclose(f);
4428 pid_filename = qemu_strdup(filename);
4429 if (!pid_filename) {
4430 fprintf(stderr, "Could not save PID filename");
4431 exit(1);
4433 atexit(remove_pidfile);
4435 } else {
4436 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4437 filename);
4438 exit(1);
4442 /***********************************************************/
4443 /* dumb display */
4445 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4449 static void dumb_resize(DisplayState *ds, int w, int h)
4453 static void dumb_refresh(DisplayState *ds)
4455 vga_hw_update();
4458 void dumb_display_init(DisplayState *ds)
4460 ds->data = NULL;
4461 ds->linesize = 0;
4462 ds->depth = 0;
4463 ds->dpy_update = dumb_update;
4464 ds->dpy_resize = dumb_resize;
4465 ds->dpy_colourdepth = NULL;
4466 ds->dpy_refresh = dumb_refresh;
4469 /***********************************************************/
4470 /* I/O handling */
4472 #define MAX_IO_HANDLERS 64
4474 typedef struct IOHandlerRecord {
4475 int fd;
4476 IOCanRWHandler *fd_read_poll;
4477 IOHandler *fd_read;
4478 IOHandler *fd_write;
4479 int deleted;
4480 void *opaque;
4481 /* temporary data */
4482 struct pollfd *ufd;
4483 struct IOHandlerRecord *next;
4484 } IOHandlerRecord;
4486 static IOHandlerRecord *first_io_handler;
4488 /* XXX: fd_read_poll should be suppressed, but an API change is
4489 necessary in the character devices to suppress fd_can_read(). */
4490 int qemu_set_fd_handler2(int fd,
4491 IOCanRWHandler *fd_read_poll,
4492 IOHandler *fd_read,
4493 IOHandler *fd_write,
4494 void *opaque)
4496 IOHandlerRecord **pioh, *ioh;
4498 if (!fd_read && !fd_write) {
4499 pioh = &first_io_handler;
4500 for(;;) {
4501 ioh = *pioh;
4502 if (ioh == NULL)
4503 break;
4504 if (ioh->fd == fd) {
4505 ioh->deleted = 1;
4506 break;
4508 pioh = &ioh->next;
4510 } else {
4511 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4512 if (ioh->fd == fd)
4513 goto found;
4515 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4516 if (!ioh)
4517 return -1;
4518 ioh->next = first_io_handler;
4519 first_io_handler = ioh;
4520 found:
4521 ioh->fd = fd;
4522 ioh->fd_read_poll = fd_read_poll;
4523 ioh->fd_read = fd_read;
4524 ioh->fd_write = fd_write;
4525 ioh->opaque = opaque;
4526 ioh->deleted = 0;
4528 return 0;
4531 int qemu_set_fd_handler(int fd,
4532 IOHandler *fd_read,
4533 IOHandler *fd_write,
4534 void *opaque)
4536 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4539 /***********************************************************/
4540 /* Polling handling */
4542 typedef struct PollingEntry {
4543 PollingFunc *func;
4544 void *opaque;
4545 struct PollingEntry *next;
4546 } PollingEntry;
4548 static PollingEntry *first_polling_entry;
4550 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4552 PollingEntry **ppe, *pe;
4553 pe = qemu_mallocz(sizeof(PollingEntry));
4554 if (!pe)
4555 return -1;
4556 pe->func = func;
4557 pe->opaque = opaque;
4558 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4559 *ppe = pe;
4560 return 0;
4563 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4565 PollingEntry **ppe, *pe;
4566 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4567 pe = *ppe;
4568 if (pe->func == func && pe->opaque == opaque) {
4569 *ppe = pe->next;
4570 qemu_free(pe);
4571 break;
4576 #ifdef _WIN32
4577 /***********************************************************/
4578 /* Wait objects support */
4579 typedef struct WaitObjects {
4580 int num;
4581 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4582 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4583 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4584 } WaitObjects;
4586 static WaitObjects wait_objects = {0};
4588 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4590 WaitObjects *w = &wait_objects;
4592 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4593 return -1;
4594 w->events[w->num] = handle;
4595 w->func[w->num] = func;
4596 w->opaque[w->num] = opaque;
4597 w->num++;
4598 return 0;
4601 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4603 int i, found;
4604 WaitObjects *w = &wait_objects;
4606 found = 0;
4607 for (i = 0; i < w->num; i++) {
4608 if (w->events[i] == handle)
4609 found = 1;
4610 if (found) {
4611 w->events[i] = w->events[i + 1];
4612 w->func[i] = w->func[i + 1];
4613 w->opaque[i] = w->opaque[i + 1];
4616 if (found)
4617 w->num--;
4619 #endif
4621 /***********************************************************/
4622 /* savevm/loadvm support */
4624 #define IO_BUF_SIZE 32768
4626 struct QEMUFile {
4627 FILE *outfile;
4628 BlockDriverState *bs;
4629 int is_file;
4630 int is_writable;
4631 int64_t base_offset;
4632 int64_t buf_offset; /* start of buffer when writing, end of buffer
4633 when reading */
4634 int buf_index;
4635 int buf_size; /* 0 when writing */
4636 uint8_t buf[IO_BUF_SIZE];
4637 };
4639 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4641 QEMUFile *f;
4643 f = qemu_mallocz(sizeof(QEMUFile));
4644 if (!f)
4645 return NULL;
4646 if (!strcmp(mode, "wb")) {
4647 f->is_writable = 1;
4648 } else if (!strcmp(mode, "rb")) {
4649 f->is_writable = 0;
4650 } else {
4651 goto fail;
4653 f->outfile = fopen(filename, mode);
4654 if (!f->outfile)
4655 goto fail;
4656 f->is_file = 1;
4657 return f;
4658 fail:
4659 if (f->outfile)
4660 fclose(f->outfile);
4661 qemu_free(f);
4662 return NULL;
4665 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4667 QEMUFile *f;
4669 f = qemu_mallocz(sizeof(QEMUFile));
4670 if (!f)
4671 return NULL;
4672 f->is_file = 0;
4673 f->bs = bs;
4674 f->is_writable = is_writable;
4675 f->base_offset = offset;
4676 return f;
4679 void qemu_fflush(QEMUFile *f)
4681 if (!f->is_writable)
4682 return;
4683 if (f->buf_index > 0) {
4684 if (f->is_file) {
4685 fseek(f->outfile, f->buf_offset, SEEK_SET);
4686 fwrite(f->buf, 1, f->buf_index, f->outfile);
4687 } else {
4688 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4689 f->buf, f->buf_index);
4691 f->buf_offset += f->buf_index;
4692 f->buf_index = 0;
4696 static void qemu_fill_buffer(QEMUFile *f)
4698 int len;
4700 if (f->is_writable)
4701 return;
4702 if (f->is_file) {
4703 fseek(f->outfile, f->buf_offset, SEEK_SET);
4704 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4705 if (len < 0)
4706 len = 0;
4707 } else {
4708 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4709 f->buf, IO_BUF_SIZE);
4710 if (len < 0)
4711 len = 0;
4713 f->buf_index = 0;
4714 f->buf_size = len;
4715 f->buf_offset += len;
4718 void qemu_fclose(QEMUFile *f)
4720 if (f->is_writable)
4721 qemu_fflush(f);
4722 if (f->is_file) {
4723 fclose(f->outfile);
4725 qemu_free(f);
4728 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4730 int l;
4731 while (size > 0) {
4732 l = IO_BUF_SIZE - f->buf_index;
4733 if (l > size)
4734 l = size;
4735 memcpy(f->buf + f->buf_index, buf, l);
4736 f->buf_index += l;
4737 buf += l;
4738 size -= l;
4739 if (f->buf_index >= IO_BUF_SIZE)
4740 qemu_fflush(f);
4744 void qemu_put_byte(QEMUFile *f, int v)
4746 f->buf[f->buf_index++] = v;
4747 if (f->buf_index >= IO_BUF_SIZE)
4748 qemu_fflush(f);
4751 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4753 int size, l;
4755 size = size1;
4756 while (size > 0) {
4757 l = f->buf_size - f->buf_index;
4758 if (l == 0) {
4759 qemu_fill_buffer(f);
4760 l = f->buf_size - f->buf_index;
4761 if (l == 0)
4762 break;
4764 if (l > size)
4765 l = size;
4766 memcpy(buf, f->buf + f->buf_index, l);
4767 f->buf_index += l;
4768 buf += l;
4769 size -= l;
4771 return size1 - size;
4774 int qemu_get_byte(QEMUFile *f)
4776 if (f->buf_index >= f->buf_size) {
4777 qemu_fill_buffer(f);
4778 if (f->buf_index >= f->buf_size)
4779 return 0;
4781 return f->buf[f->buf_index++];
4784 int64_t qemu_ftell(QEMUFile *f)
4786 return f->buf_offset - f->buf_size + f->buf_index;
4789 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4791 if (whence == SEEK_SET) {
4792 /* nothing to do */
4793 } else if (whence == SEEK_CUR) {
4794 pos += qemu_ftell(f);
4795 } else {
4796 /* SEEK_END not supported */
4797 return -1;
4799 if (f->is_writable) {
4800 qemu_fflush(f);
4801 f->buf_offset = pos;
4802 } else {
4803 f->buf_offset = pos;
4804 f->buf_index = 0;
4805 f->buf_size = 0;
4807 return pos;
4810 void qemu_put_be16(QEMUFile *f, unsigned int v)
4812 qemu_put_byte(f, v >> 8);
4813 qemu_put_byte(f, v);
4816 void qemu_put_be32(QEMUFile *f, unsigned int v)
4818 qemu_put_byte(f, v >> 24);
4819 qemu_put_byte(f, v >> 16);
4820 qemu_put_byte(f, v >> 8);
4821 qemu_put_byte(f, v);
4824 void qemu_put_be64(QEMUFile *f, uint64_t v)
4826 qemu_put_be32(f, v >> 32);
4827 qemu_put_be32(f, v);
4830 unsigned int qemu_get_be16(QEMUFile *f)
4832 unsigned int v;
4833 v = qemu_get_byte(f) << 8;
4834 v |= qemu_get_byte(f);
4835 return v;
4838 unsigned int qemu_get_be32(QEMUFile *f)
4840 unsigned int v;
4841 v = qemu_get_byte(f) << 24;
4842 v |= qemu_get_byte(f) << 16;
4843 v |= qemu_get_byte(f) << 8;
4844 v |= qemu_get_byte(f);
4845 return v;
4848 uint64_t qemu_get_be64(QEMUFile *f)
4850 uint64_t v;
4851 v = (uint64_t)qemu_get_be32(f) << 32;
4852 v |= qemu_get_be32(f);
4853 return v;
4856 typedef struct SaveStateEntry {
4857 char idstr[256];
4858 int instance_id;
4859 int version_id;
4860 SaveStateHandler *save_state;
4861 LoadStateHandler *load_state;
4862 void *opaque;
4863 struct SaveStateEntry *next;
4864 } SaveStateEntry;
4866 static SaveStateEntry *first_se;
4868 int register_savevm(const char *idstr,
4869 int instance_id,
4870 int version_id,
4871 SaveStateHandler *save_state,
4872 LoadStateHandler *load_state,
4873 void *opaque)
4875 SaveStateEntry *se, **pse;
4877 se = qemu_malloc(sizeof(SaveStateEntry));
4878 if (!se)
4879 return -1;
4880 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4881 se->instance_id = instance_id;
4882 se->version_id = version_id;
4883 se->save_state = save_state;
4884 se->load_state = load_state;
4885 se->opaque = opaque;
4886 se->next = NULL;
4888 /* add at the end of list */
4889 pse = &first_se;
4890 while (*pse != NULL)
4891 pse = &(*pse)->next;
4892 *pse = se;
4893 return 0;
4896 #define QEMU_VM_FILE_MAGIC 0x5145564d
4897 #define QEMU_VM_FILE_VERSION 0x00000002
4899 int qemu_savevm_state(QEMUFile *f)
4901 SaveStateEntry *se;
4902 int len, ret;
4903 int64_t cur_pos, len_pos, total_len_pos;
4905 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4906 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4907 total_len_pos = qemu_ftell(f);
4908 qemu_put_be64(f, 0); /* total size */
4910 for(se = first_se; se != NULL; se = se->next) {
4911 /* ID string */
4912 len = strlen(se->idstr);
4913 qemu_put_byte(f, len);
4914 qemu_put_buffer(f, se->idstr, len);
4916 qemu_put_be32(f, se->instance_id);
4917 qemu_put_be32(f, se->version_id);
4919 /* record size: filled later */
4920 len_pos = qemu_ftell(f);
4921 qemu_put_be32(f, 0);
4923 se->save_state(f, se->opaque);
4925 /* fill record size */
4926 cur_pos = qemu_ftell(f);
4927 len = cur_pos - len_pos - 4;
4928 qemu_fseek(f, len_pos, SEEK_SET);
4929 qemu_put_be32(f, len);
4930 qemu_fseek(f, cur_pos, SEEK_SET);
4932 cur_pos = qemu_ftell(f);
4933 qemu_fseek(f, total_len_pos, SEEK_SET);
4934 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4935 qemu_fseek(f, cur_pos, SEEK_SET);
4937 ret = 0;
4938 return ret;
4941 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4943 SaveStateEntry *se;
4945 for(se = first_se; se != NULL; se = se->next) {
4946 if (!strcmp(se->idstr, idstr) &&
4947 instance_id == se->instance_id)
4948 return se;
4950 return NULL;
4953 int qemu_loadvm_state(QEMUFile *f)
4955 SaveStateEntry *se;
4956 int len, ret, instance_id, record_len, version_id;
4957 int64_t total_len, end_pos, cur_pos;
4958 unsigned int v;
4959 char idstr[256];
4961 v = qemu_get_be32(f);
4962 if (v != QEMU_VM_FILE_MAGIC)
4963 goto fail;
4964 v = qemu_get_be32(f);
4965 if (v != QEMU_VM_FILE_VERSION) {
4966 fail:
4967 ret = -1;
4968 goto the_end;
4970 total_len = qemu_get_be64(f);
4971 end_pos = total_len + qemu_ftell(f);
4972 for(;;) {
4973 if (qemu_ftell(f) >= end_pos)
4974 break;
4975 len = qemu_get_byte(f);
4976 qemu_get_buffer(f, idstr, len);
4977 idstr[len] = '\0';
4978 instance_id = qemu_get_be32(f);
4979 version_id = qemu_get_be32(f);
4980 record_len = qemu_get_be32(f);
4981 #if 0
4982 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4983 idstr, instance_id, version_id, record_len);
4984 #endif
4985 cur_pos = qemu_ftell(f);
4986 se = find_se(idstr, instance_id);
4987 if (!se) {
4988 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4989 instance_id, idstr);
4990 } else {
4991 ret = se->load_state(f, se->opaque, version_id);
4992 if (ret < 0) {
4993 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4994 instance_id, idstr);
4997 /* always seek to exact end of record */
4998 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5000 ret = 0;
5001 the_end:
5002 return ret;
5005 /* device can contain snapshots */
5006 static int bdrv_can_snapshot(BlockDriverState *bs)
5008 return (bs &&
5009 !bdrv_is_removable(bs) &&
5010 !bdrv_is_read_only(bs));
5013 /* device must be snapshots in order to have a reliable snapshot */
5014 static int bdrv_has_snapshot(BlockDriverState *bs)
5016 return (bs &&
5017 !bdrv_is_removable(bs) &&
5018 !bdrv_is_read_only(bs));
5021 static BlockDriverState *get_bs_snapshots(void)
5023 BlockDriverState *bs;
5024 int i;
5026 if (bs_snapshots)
5027 return bs_snapshots;
5028 for(i = 0; i <= MAX_DISKS; i++) {
5029 bs = bs_table[i];
5030 if (bdrv_can_snapshot(bs))
5031 goto ok;
5033 return NULL;
5034 ok:
5035 bs_snapshots = bs;
5036 return bs;
5039 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5040 const char *name)
5042 QEMUSnapshotInfo *sn_tab, *sn;
5043 int nb_sns, i, ret;
5045 ret = -ENOENT;
5046 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5047 if (nb_sns < 0)
5048 return ret;
5049 for(i = 0; i < nb_sns; i++) {
5050 sn = &sn_tab[i];
5051 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5052 *sn_info = *sn;
5053 ret = 0;
5054 break;
5057 qemu_free(sn_tab);
5058 return ret;
5061 #ifdef CONFIG_DM
5062 /* We use simpler state save/load functions for Xen */
5063 void do_savevm(const char *name)
5065 QEMUFile *f;
5066 int saved_vm_running, ret;
5068 f = qemu_fopen(name, "wb");
5070 /* ??? Should this occur after vm_stop? */
5071 qemu_aio_flush();
5073 saved_vm_running = vm_running;
5074 vm_stop(0);
5076 if (!f) {
5077 fprintf(logfile, "Failed to open savevm file '%s'\n", name);
5078 goto the_end;
5081 ret = qemu_savevm_state(f);
5082 qemu_fclose(f);
5084 if (ret < 0)
5085 fprintf(logfile, "Error %d while writing VM to savevm file '%s'\n",
5086 ret, name);
5088 the_end:
5089 if (saved_vm_running)
5090 vm_start();
5092 return;
5094 void do_loadvm(const char *name)
5096 QEMUFile *f;
5097 int saved_vm_running, ret;
5099 /* Flush all IO requests so they don't interfere with the new state. */
5100 qemu_aio_flush();
5102 saved_vm_running = vm_running;
5103 vm_stop(0);
5105 /* restore the VM state */
5106 f = qemu_fopen(name, "rb");
5107 if (!f) {
5108 fprintf(logfile, "Could not open VM state file\n");
5109 goto the_end;
5112 ret = qemu_loadvm_state(f);
5113 qemu_fclose(f);
5114 if (ret < 0) {
5115 fprintf(logfile, "Error %d while loading savevm file '%s'\n",
5116 ret, name);
5117 goto the_end;
5120 #if 0
5121 /* del tmp file */
5122 if (unlink(name) == -1)
5123 fprintf(stderr, "delete tmp qemu state file failed.\n");
5124 #endif
5127 the_end:
5128 if (saved_vm_running)
5129 vm_start();
5131 #else
5132 void do_savevm(const char *name)
5134 BlockDriverState *bs, *bs1;
5135 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5136 int must_delete, ret, i;
5137 BlockDriverInfo bdi1, *bdi = &bdi1;
5138 QEMUFile *f;
5139 int saved_vm_running;
5140 #ifdef _WIN32
5141 struct _timeb tb;
5142 #else
5143 struct timeval tv;
5144 #endif
5146 bs = get_bs_snapshots();
5147 if (!bs) {
5148 term_printf("No block device can accept snapshots\n");
5149 return;
5152 /* ??? Should this occur after vm_stop? */
5153 qemu_aio_flush();
5155 saved_vm_running = vm_running;
5156 vm_stop(0);
5158 must_delete = 0;
5159 if (name) {
5160 ret = bdrv_snapshot_find(bs, old_sn, name);
5161 if (ret >= 0) {
5162 must_delete = 1;
5165 memset(sn, 0, sizeof(*sn));
5166 if (must_delete) {
5167 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5168 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5169 } else {
5170 if (name)
5171 pstrcpy(sn->name, sizeof(sn->name), name);
5174 /* fill auxiliary fields */
5175 #ifdef _WIN32
5176 _ftime(&tb);
5177 sn->date_sec = tb.time;
5178 sn->date_nsec = tb.millitm * 1000000;
5179 #else
5180 gettimeofday(&tv, NULL);
5181 sn->date_sec = tv.tv_sec;
5182 sn->date_nsec = tv.tv_usec * 1000;
5183 #endif
5184 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5186 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5187 term_printf("Device %s does not support VM state snapshots\n",
5188 bdrv_get_device_name(bs));
5189 goto the_end;
5192 /* save the VM state */
5193 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5194 if (!f) {
5195 term_printf("Could not open VM state file\n");
5196 goto the_end;
5198 ret = qemu_savevm_state(f);
5199 sn->vm_state_size = qemu_ftell(f);
5200 qemu_fclose(f);
5201 if (ret < 0) {
5202 term_printf("Error %d while writing VM\n", ret);
5203 goto the_end;
5206 /* create the snapshots */
5208 for(i = 0; i < MAX_DISKS; i++) {
5209 bs1 = bs_table[i];
5210 if (bdrv_has_snapshot(bs1)) {
5211 if (must_delete) {
5212 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5213 if (ret < 0) {
5214 term_printf("Error while deleting snapshot on '%s'\n",
5215 bdrv_get_device_name(bs1));
5218 ret = bdrv_snapshot_create(bs1, sn);
5219 if (ret < 0) {
5220 term_printf("Error while creating snapshot on '%s'\n",
5221 bdrv_get_device_name(bs1));
5226 the_end:
5227 if (saved_vm_running)
5228 vm_start();
5231 void do_loadvm(const char *name)
5233 BlockDriverState *bs, *bs1;
5234 BlockDriverInfo bdi1, *bdi = &bdi1;
5235 QEMUFile *f;
5236 int i, ret;
5237 int saved_vm_running;
5239 bs = get_bs_snapshots();
5240 if (!bs) {
5241 term_printf("No block device supports snapshots\n");
5242 return;
5245 /* Flush all IO requests so they don't interfere with the new state. */
5246 qemu_aio_flush();
5248 saved_vm_running = vm_running;
5249 vm_stop(0);
5251 for(i = 0; i <= MAX_DISKS; i++) {
5252 bs1 = bs_table[i];
5253 if (bdrv_has_snapshot(bs1)) {
5254 ret = bdrv_snapshot_goto(bs1, name);
5255 if (ret < 0) {
5256 if (bs != bs1)
5257 term_printf("Warning: ");
5258 switch(ret) {
5259 case -ENOTSUP:
5260 term_printf("Snapshots not supported on device '%s'\n",
5261 bdrv_get_device_name(bs1));
5262 break;
5263 case -ENOENT:
5264 term_printf("Could not find snapshot '%s' on device '%s'\n",
5265 name, bdrv_get_device_name(bs1));
5266 break;
5267 default:
5268 term_printf("Error %d while activating snapshot on '%s'\n",
5269 ret, bdrv_get_device_name(bs1));
5270 break;
5272 /* fatal on snapshot block device */
5273 if (bs == bs1)
5274 goto the_end;
5279 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5280 term_printf("Device %s does not support VM state snapshots\n",
5281 bdrv_get_device_name(bs));
5282 return;
5285 /* restore the VM state */
5286 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5287 if (!f) {
5288 term_printf("Could not open VM state file\n");
5289 goto the_end;
5291 ret = qemu_loadvm_state(f);
5292 qemu_fclose(f);
5293 if (ret < 0) {
5294 term_printf("Error %d while loading VM state\n", ret);
5297 /* del tmp file */
5298 if (unlink(name) == -1)
5299 fprintf(stderr, "delete tmp qemu state file failed.\n");
5301 the_end:
5302 if (saved_vm_running)
5303 vm_start();
5305 #endif
5307 void do_delvm(const char *name)
5309 BlockDriverState *bs, *bs1;
5310 int i, ret;
5312 bs = get_bs_snapshots();
5313 if (!bs) {
5314 term_printf("No block device supports snapshots\n");
5315 return;
5318 for(i = 0; i <= MAX_DISKS; i++) {
5319 bs1 = bs_table[i];
5320 if (bdrv_has_snapshot(bs1)) {
5321 ret = bdrv_snapshot_delete(bs1, name);
5322 if (ret < 0) {
5323 if (ret == -ENOTSUP)
5324 term_printf("Snapshots not supported on device '%s'\n",
5325 bdrv_get_device_name(bs1));
5326 else
5327 term_printf("Error %d while deleting snapshot on '%s'\n",
5328 ret, bdrv_get_device_name(bs1));
5334 void do_info_snapshots(void)
5336 BlockDriverState *bs, *bs1;
5337 QEMUSnapshotInfo *sn_tab, *sn;
5338 int nb_sns, i;
5339 char buf[256];
5341 bs = get_bs_snapshots();
5342 if (!bs) {
5343 term_printf("No available block device supports snapshots\n");
5344 return;
5346 term_printf("Snapshot devices:");
5347 for(i = 0; i <= MAX_DISKS; i++) {
5348 bs1 = bs_table[i];
5349 if (bdrv_has_snapshot(bs1)) {
5350 if (bs == bs1)
5351 term_printf(" %s", bdrv_get_device_name(bs1));
5354 term_printf("\n");
5356 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5357 if (nb_sns < 0) {
5358 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5359 return;
5361 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5362 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5363 for(i = 0; i < nb_sns; i++) {
5364 sn = &sn_tab[i];
5365 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5367 qemu_free(sn_tab);
5370 #ifndef CONFIG_DM
5371 /***********************************************************/
5372 /* cpu save/restore */
5374 #if defined(TARGET_I386)
5376 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5378 qemu_put_be32(f, dt->selector);
5379 qemu_put_betl(f, dt->base);
5380 qemu_put_be32(f, dt->limit);
5381 qemu_put_be32(f, dt->flags);
5384 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5386 dt->selector = qemu_get_be32(f);
5387 dt->base = qemu_get_betl(f);
5388 dt->limit = qemu_get_be32(f);
5389 dt->flags = qemu_get_be32(f);
5392 void cpu_save(QEMUFile *f, void *opaque)
5394 CPUState *env = opaque;
5395 uint16_t fptag, fpus, fpuc, fpregs_format;
5396 uint32_t hflags;
5397 int i;
5399 for(i = 0; i < CPU_NB_REGS; i++)
5400 qemu_put_betls(f, &env->regs[i]);
5401 qemu_put_betls(f, &env->eip);
5402 qemu_put_betls(f, &env->eflags);
5403 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5404 qemu_put_be32s(f, &hflags);
5406 /* FPU */
5407 fpuc = env->fpuc;
5408 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5409 fptag = 0;
5410 for(i = 0; i < 8; i++) {
5411 fptag |= ((!env->fptags[i]) << i);
5414 qemu_put_be16s(f, &fpuc);
5415 qemu_put_be16s(f, &fpus);
5416 qemu_put_be16s(f, &fptag);
5418 #ifdef USE_X86LDOUBLE
5419 fpregs_format = 0;
5420 #else
5421 fpregs_format = 1;
5422 #endif
5423 qemu_put_be16s(f, &fpregs_format);
5425 for(i = 0; i < 8; i++) {
5426 #ifdef USE_X86LDOUBLE
5428 uint64_t mant;
5429 uint16_t exp;
5430 /* we save the real CPU data (in case of MMX usage only 'mant'
5431 contains the MMX register */
5432 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5433 qemu_put_be64(f, mant);
5434 qemu_put_be16(f, exp);
5436 #else
5437 /* if we use doubles for float emulation, we save the doubles to
5438 avoid losing information in case of MMX usage. It can give
5439 problems if the image is restored on a CPU where long
5440 doubles are used instead. */
5441 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5442 #endif
5445 for(i = 0; i < 6; i++)
5446 cpu_put_seg(f, &env->segs[i]);
5447 cpu_put_seg(f, &env->ldt);
5448 cpu_put_seg(f, &env->tr);
5449 cpu_put_seg(f, &env->gdt);
5450 cpu_put_seg(f, &env->idt);
5452 qemu_put_be32s(f, &env->sysenter_cs);
5453 qemu_put_be32s(f, &env->sysenter_esp);
5454 qemu_put_be32s(f, &env->sysenter_eip);
5456 qemu_put_betls(f, &env->cr[0]);
5457 qemu_put_betls(f, &env->cr[2]);
5458 qemu_put_betls(f, &env->cr[3]);
5459 qemu_put_betls(f, &env->cr[4]);
5461 for(i = 0; i < 8; i++)
5462 qemu_put_betls(f, &env->dr[i]);
5464 /* MMU */
5465 qemu_put_be32s(f, &env->a20_mask);
5467 /* XMM */
5468 qemu_put_be32s(f, &env->mxcsr);
5469 for(i = 0; i < CPU_NB_REGS; i++) {
5470 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5471 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5474 #ifdef TARGET_X86_64
5475 qemu_put_be64s(f, &env->efer);
5476 qemu_put_be64s(f, &env->star);
5477 qemu_put_be64s(f, &env->lstar);
5478 qemu_put_be64s(f, &env->cstar);
5479 qemu_put_be64s(f, &env->fmask);
5480 qemu_put_be64s(f, &env->kernelgsbase);
5481 #endif
5482 qemu_put_be32s(f, &env->smbase);
5485 #ifdef USE_X86LDOUBLE
5486 /* XXX: add that in a FPU generic layer */
5487 union x86_longdouble {
5488 uint64_t mant;
5489 uint16_t exp;
5490 };
5492 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5493 #define EXPBIAS1 1023
5494 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5495 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5497 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5499 int e;
5500 /* mantissa */
5501 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5502 /* exponent + sign */
5503 e = EXPD1(temp) - EXPBIAS1 + 16383;
5504 e |= SIGND1(temp) >> 16;
5505 p->exp = e;
5507 #endif
5509 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5511 CPUState *env = opaque;
5512 int i, guess_mmx;
5513 uint32_t hflags;
5514 uint16_t fpus, fpuc, fptag, fpregs_format;
5516 if (version_id != 3 && version_id != 4)
5517 return -EINVAL;
5518 for(i = 0; i < CPU_NB_REGS; i++)
5519 qemu_get_betls(f, &env->regs[i]);
5520 qemu_get_betls(f, &env->eip);
5521 qemu_get_betls(f, &env->eflags);
5522 qemu_get_be32s(f, &hflags);
5524 qemu_get_be16s(f, &fpuc);
5525 qemu_get_be16s(f, &fpus);
5526 qemu_get_be16s(f, &fptag);
5527 qemu_get_be16s(f, &fpregs_format);
5529 /* NOTE: we cannot always restore the FPU state if the image come
5530 from a host with a different 'USE_X86LDOUBLE' define. We guess
5531 if we are in an MMX state to restore correctly in that case. */
5532 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5533 for(i = 0; i < 8; i++) {
5534 uint64_t mant;
5535 uint16_t exp;
5537 switch(fpregs_format) {
5538 case 0:
5539 mant = qemu_get_be64(f);
5540 exp = qemu_get_be16(f);
5541 #ifdef USE_X86LDOUBLE
5542 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5543 #else
5544 /* difficult case */
5545 if (guess_mmx)
5546 env->fpregs[i].mmx.MMX_Q(0) = mant;
5547 else
5548 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5549 #endif
5550 break;
5551 case 1:
5552 mant = qemu_get_be64(f);
5553 #ifdef USE_X86LDOUBLE
5555 union x86_longdouble *p;
5556 /* difficult case */
5557 p = (void *)&env->fpregs[i];
5558 if (guess_mmx) {
5559 p->mant = mant;
5560 p->exp = 0xffff;
5561 } else {
5562 fp64_to_fp80(p, mant);
5565 #else
5566 env->fpregs[i].mmx.MMX_Q(0) = mant;
5567 #endif
5568 break;
5569 default:
5570 return -EINVAL;
5574 env->fpuc = fpuc;
5575 /* XXX: restore FPU round state */
5576 env->fpstt = (fpus >> 11) & 7;
5577 env->fpus = fpus & ~0x3800;
5578 fptag ^= 0xff;
5579 for(i = 0; i < 8; i++) {
5580 env->fptags[i] = (fptag >> i) & 1;
5583 for(i = 0; i < 6; i++)
5584 cpu_get_seg(f, &env->segs[i]);
5585 cpu_get_seg(f, &env->ldt);
5586 cpu_get_seg(f, &env->tr);
5587 cpu_get_seg(f, &env->gdt);
5588 cpu_get_seg(f, &env->idt);
5590 qemu_get_be32s(f, &env->sysenter_cs);
5591 qemu_get_be32s(f, &env->sysenter_esp);
5592 qemu_get_be32s(f, &env->sysenter_eip);
5594 qemu_get_betls(f, &env->cr[0]);
5595 qemu_get_betls(f, &env->cr[2]);
5596 qemu_get_betls(f, &env->cr[3]);
5597 qemu_get_betls(f, &env->cr[4]);
5599 for(i = 0; i < 8; i++)
5600 qemu_get_betls(f, &env->dr[i]);
5602 /* MMU */
5603 qemu_get_be32s(f, &env->a20_mask);
5605 qemu_get_be32s(f, &env->mxcsr);
5606 for(i = 0; i < CPU_NB_REGS; i++) {
5607 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5608 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5611 #ifdef TARGET_X86_64
5612 qemu_get_be64s(f, &env->efer);
5613 qemu_get_be64s(f, &env->star);
5614 qemu_get_be64s(f, &env->lstar);
5615 qemu_get_be64s(f, &env->cstar);
5616 qemu_get_be64s(f, &env->fmask);
5617 qemu_get_be64s(f, &env->kernelgsbase);
5618 #endif
5619 if (version_id >= 4)
5620 qemu_get_be32s(f, &env->smbase);
5622 /* XXX: compute hflags from scratch, except for CPL and IIF */
5623 env->hflags = hflags;
5624 tlb_flush(env, 1);
5625 return 0;
5628 #elif defined(TARGET_PPC)
5629 void cpu_save(QEMUFile *f, void *opaque)
5633 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5635 return 0;
5638 #elif defined(TARGET_MIPS)
5639 void cpu_save(QEMUFile *f, void *opaque)
5643 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5645 return 0;
5648 #elif defined(TARGET_SPARC)
5649 void cpu_save(QEMUFile *f, void *opaque)
5651 CPUState *env = opaque;
5652 int i;
5653 uint32_t tmp;
5655 for(i = 0; i < 8; i++)
5656 qemu_put_betls(f, &env->gregs[i]);
5657 for(i = 0; i < NWINDOWS * 16; i++)
5658 qemu_put_betls(f, &env->regbase[i]);
5660 /* FPU */
5661 for(i = 0; i < TARGET_FPREGS; i++) {
5662 union {
5663 float32 f;
5664 uint32_t i;
5665 } u;
5666 u.f = env->fpr[i];
5667 qemu_put_be32(f, u.i);
5670 qemu_put_betls(f, &env->pc);
5671 qemu_put_betls(f, &env->npc);
5672 qemu_put_betls(f, &env->y);
5673 tmp = GET_PSR(env);
5674 qemu_put_be32(f, tmp);
5675 qemu_put_betls(f, &env->fsr);
5676 qemu_put_betls(f, &env->tbr);
5677 #ifndef TARGET_SPARC64
5678 qemu_put_be32s(f, &env->wim);
5679 /* MMU */
5680 for(i = 0; i < 16; i++)
5681 qemu_put_be32s(f, &env->mmuregs[i]);
5682 #endif
5685 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5687 CPUState *env = opaque;
5688 int i;
5689 uint32_t tmp;
5691 for(i = 0; i < 8; i++)
5692 qemu_get_betls(f, &env->gregs[i]);
5693 for(i = 0; i < NWINDOWS * 16; i++)
5694 qemu_get_betls(f, &env->regbase[i]);
5696 /* FPU */
5697 for(i = 0; i < TARGET_FPREGS; i++) {
5698 union {
5699 float32 f;
5700 uint32_t i;
5701 } u;
5702 u.i = qemu_get_be32(f);
5703 env->fpr[i] = u.f;
5706 qemu_get_betls(f, &env->pc);
5707 qemu_get_betls(f, &env->npc);
5708 qemu_get_betls(f, &env->y);
5709 tmp = qemu_get_be32(f);
5710 env->cwp = 0; /* needed to ensure that the wrapping registers are
5711 correctly updated */
5712 PUT_PSR(env, tmp);
5713 qemu_get_betls(f, &env->fsr);
5714 qemu_get_betls(f, &env->tbr);
5715 #ifndef TARGET_SPARC64
5716 qemu_get_be32s(f, &env->wim);
5717 /* MMU */
5718 for(i = 0; i < 16; i++)
5719 qemu_get_be32s(f, &env->mmuregs[i]);
5720 #endif
5721 tlb_flush(env, 1);
5722 return 0;
5725 #elif defined(TARGET_ARM)
5727 /* ??? Need to implement these. */
5728 void cpu_save(QEMUFile *f, void *opaque)
5732 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5734 return 0;
5737 #else
5739 #warning No CPU save/restore functions
5741 #endif
5743 /***********************************************************/
5744 /* ram save/restore */
5746 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5748 int v;
5750 v = qemu_get_byte(f);
5751 switch(v) {
5752 case 0:
5753 if (qemu_get_buffer(f, buf, len) != len)
5754 return -EIO;
5755 break;
5756 case 1:
5757 v = qemu_get_byte(f);
5758 memset(buf, v, len);
5759 break;
5760 default:
5761 return -EINVAL;
5763 return 0;
5766 static int ram_load_v1(QEMUFile *f, void *opaque)
5768 int i, ret;
5770 if (qemu_get_be32(f) != phys_ram_size)
5771 return -EINVAL;
5772 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5773 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5774 if (ret)
5775 return ret;
5777 return 0;
5780 #define BDRV_HASH_BLOCK_SIZE 1024
5781 #define IOBUF_SIZE 4096
5782 #define RAM_CBLOCK_MAGIC 0xfabe
5784 typedef struct RamCompressState {
5785 z_stream zstream;
5786 QEMUFile *f;
5787 uint8_t buf[IOBUF_SIZE];
5788 } RamCompressState;
5790 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5792 int ret;
5793 memset(s, 0, sizeof(*s));
5794 s->f = f;
5795 ret = deflateInit2(&s->zstream, 1,
5796 Z_DEFLATED, 15,
5797 9, Z_DEFAULT_STRATEGY);
5798 if (ret != Z_OK)
5799 return -1;
5800 s->zstream.avail_out = IOBUF_SIZE;
5801 s->zstream.next_out = s->buf;
5802 return 0;
5805 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5807 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5808 qemu_put_be16(s->f, len);
5809 qemu_put_buffer(s->f, buf, len);
5812 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5814 int ret;
5816 s->zstream.avail_in = len;
5817 s->zstream.next_in = (uint8_t *)buf;
5818 while (s->zstream.avail_in > 0) {
5819 ret = deflate(&s->zstream, Z_NO_FLUSH);
5820 if (ret != Z_OK)
5821 return -1;
5822 if (s->zstream.avail_out == 0) {
5823 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5824 s->zstream.avail_out = IOBUF_SIZE;
5825 s->zstream.next_out = s->buf;
5828 return 0;
5831 static void ram_compress_close(RamCompressState *s)
5833 int len, ret;
5835 /* compress last bytes */
5836 for(;;) {
5837 ret = deflate(&s->zstream, Z_FINISH);
5838 if (ret == Z_OK || ret == Z_STREAM_END) {
5839 len = IOBUF_SIZE - s->zstream.avail_out;
5840 if (len > 0) {
5841 ram_put_cblock(s, s->buf, len);
5843 s->zstream.avail_out = IOBUF_SIZE;
5844 s->zstream.next_out = s->buf;
5845 if (ret == Z_STREAM_END)
5846 break;
5847 } else {
5848 goto fail;
5851 fail:
5852 deflateEnd(&s->zstream);
5855 typedef struct RamDecompressState {
5856 z_stream zstream;
5857 QEMUFile *f;
5858 uint8_t buf[IOBUF_SIZE];
5859 } RamDecompressState;
5861 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5863 int ret;
5864 memset(s, 0, sizeof(*s));
5865 s->f = f;
5866 ret = inflateInit(&s->zstream);
5867 if (ret != Z_OK)
5868 return -1;
5869 return 0;
5872 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5874 int ret, clen;
5876 s->zstream.avail_out = len;
5877 s->zstream.next_out = buf;
5878 while (s->zstream.avail_out > 0) {
5879 if (s->zstream.avail_in == 0) {
5880 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5881 return -1;
5882 clen = qemu_get_be16(s->f);
5883 if (clen > IOBUF_SIZE)
5884 return -1;
5885 qemu_get_buffer(s->f, s->buf, clen);
5886 s->zstream.avail_in = clen;
5887 s->zstream.next_in = s->buf;
5889 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5890 if (ret != Z_OK && ret != Z_STREAM_END) {
5891 return -1;
5894 return 0;
5897 static void ram_decompress_close(RamDecompressState *s)
5899 inflateEnd(&s->zstream);
5902 static void ram_save(QEMUFile *f, void *opaque)
5904 int i;
5905 RamCompressState s1, *s = &s1;
5906 uint8_t buf[10];
5908 qemu_put_be32(f, phys_ram_size);
5909 if (ram_compress_open(s, f) < 0)
5910 return;
5911 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5912 #if 0
5913 if (tight_savevm_enabled) {
5914 int64_t sector_num;
5915 int j;
5917 /* find if the memory block is available on a virtual
5918 block device */
5919 sector_num = -1;
5920 for(j = 0; j < MAX_DISKS; j++) {
5921 if (bs_table[j]) {
5922 sector_num = bdrv_hash_find(bs_table[j],
5923 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5924 if (sector_num >= 0)
5925 break;
5928 if (j == MAX_DISKS)
5929 goto normal_compress;
5930 buf[0] = 1;
5931 buf[1] = j;
5932 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5933 ram_compress_buf(s, buf, 10);
5934 } else
5935 #endif
5937 // normal_compress:
5938 buf[0] = 0;
5939 ram_compress_buf(s, buf, 1);
5940 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5943 ram_compress_close(s);
5946 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5948 RamDecompressState s1, *s = &s1;
5949 uint8_t buf[10];
5950 int i;
5952 if (version_id == 1)
5953 return ram_load_v1(f, opaque);
5954 if (version_id != 2)
5955 return -EINVAL;
5956 if (qemu_get_be32(f) != phys_ram_size)
5957 return -EINVAL;
5958 if (ram_decompress_open(s, f) < 0)
5959 return -EINVAL;
5960 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5961 if (ram_decompress_buf(s, buf, 1) < 0) {
5962 fprintf(stderr, "Error while reading ram block header\n");
5963 goto error;
5965 if (buf[0] == 0) {
5966 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5967 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5968 goto error;
5970 } else
5971 #if 0
5972 if (buf[0] == 1) {
5973 int bs_index;
5974 int64_t sector_num;
5976 ram_decompress_buf(s, buf + 1, 9);
5977 bs_index = buf[1];
5978 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5979 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5980 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5981 goto error;
5983 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5984 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5985 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5986 bs_index, sector_num);
5987 goto error;
5989 } else
5990 #endif
5992 error:
5993 printf("Error block header\n");
5994 return -EINVAL;
5997 ram_decompress_close(s);
5998 return 0;
6000 #else /* CONFIG_DM */
6001 void cpu_save(QEMUFile *f, void *opaque)
6005 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6007 return 0;
6010 static void ram_save(QEMUFile *f, void *opaque)
6014 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6016 return 0;
6018 #endif /* CONFIG_DM */
6020 /***********************************************************/
6021 /* bottom halves (can be seen as timers which expire ASAP) */
6023 struct QEMUBH {
6024 QEMUBHFunc *cb;
6025 void *opaque;
6026 int scheduled;
6027 QEMUBH *next;
6028 };
6030 static QEMUBH *first_bh = NULL;
6032 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6034 QEMUBH *bh;
6035 bh = qemu_mallocz(sizeof(QEMUBH));
6036 if (!bh)
6037 return NULL;
6038 bh->cb = cb;
6039 bh->opaque = opaque;
6040 return bh;
6043 int qemu_bh_poll(void)
6045 QEMUBH *bh, **pbh;
6046 int ret;
6048 ret = 0;
6049 for(;;) {
6050 pbh = &first_bh;
6051 bh = *pbh;
6052 if (!bh)
6053 break;
6054 ret = 1;
6055 *pbh = bh->next;
6056 bh->scheduled = 0;
6057 bh->cb(bh->opaque);
6059 return ret;
6062 void qemu_bh_schedule(QEMUBH *bh)
6064 CPUState *env = cpu_single_env;
6065 if (bh->scheduled)
6066 return;
6067 bh->scheduled = 1;
6068 bh->next = first_bh;
6069 first_bh = bh;
6071 /* stop the currently executing CPU to execute the BH ASAP */
6072 if (env) {
6073 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6077 void qemu_bh_cancel(QEMUBH *bh)
6079 QEMUBH **pbh;
6080 if (bh->scheduled) {
6081 pbh = &first_bh;
6082 while (*pbh != bh)
6083 pbh = &(*pbh)->next;
6084 *pbh = bh->next;
6085 bh->scheduled = 0;
6089 void qemu_bh_delete(QEMUBH *bh)
6091 qemu_bh_cancel(bh);
6092 qemu_free(bh);
6095 /***********************************************************/
6096 /* machine registration */
6098 QEMUMachine *first_machine = NULL;
6100 int qemu_register_machine(QEMUMachine *m)
6102 QEMUMachine **pm;
6103 pm = &first_machine;
6104 while (*pm != NULL)
6105 pm = &(*pm)->next;
6106 m->next = NULL;
6107 *pm = m;
6108 return 0;
6111 QEMUMachine *find_machine(const char *name)
6113 QEMUMachine *m;
6115 for(m = first_machine; m != NULL; m = m->next) {
6116 if (!strcmp(m->name, name))
6117 return m;
6119 return NULL;
6122 /***********************************************************/
6123 /* main execution loop */
6125 void gui_update(void *opaque)
6127 display_state.dpy_refresh(&display_state);
6128 qemu_mod_timer(gui_timer,
6129 (display_state.gui_timer_interval ?
6130 display_state.gui_timer_interval :
6131 GUI_REFRESH_INTERVAL)
6132 + qemu_get_clock(rt_clock));
6135 struct vm_change_state_entry {
6136 VMChangeStateHandler *cb;
6137 void *opaque;
6138 QEMU_LIST_ENTRY (vm_change_state_entry) entries;
6139 };
6141 static QEMU_LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6143 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6144 void *opaque)
6146 VMChangeStateEntry *e;
6148 e = qemu_mallocz(sizeof (*e));
6149 if (!e)
6150 return NULL;
6152 e->cb = cb;
6153 e->opaque = opaque;
6154 QEMU_LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6155 return e;
6158 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6160 QEMU_LIST_REMOVE (e, entries);
6161 qemu_free (e);
6164 static void vm_state_notify(int running)
6166 VMChangeStateEntry *e;
6168 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6169 e->cb(e->opaque, running);
6173 /* XXX: support several handlers */
6174 static VMStopHandler *vm_stop_cb;
6175 static void *vm_stop_opaque;
6177 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6179 vm_stop_cb = cb;
6180 vm_stop_opaque = opaque;
6181 return 0;
6184 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6186 vm_stop_cb = NULL;
6189 void vm_start(void)
6191 if (!vm_running) {
6192 cpu_enable_ticks();
6193 vm_running = 1;
6194 vm_state_notify(1);
6198 void vm_stop(int reason)
6200 if (vm_running) {
6201 cpu_disable_ticks();
6202 vm_running = 0;
6203 if (reason != 0) {
6204 if (vm_stop_cb) {
6205 vm_stop_cb(vm_stop_opaque, reason);
6208 vm_state_notify(0);
6212 /* reset/shutdown handler */
6214 typedef struct QEMUResetEntry {
6215 QEMUResetHandler *func;
6216 void *opaque;
6217 struct QEMUResetEntry *next;
6218 } QEMUResetEntry;
6220 static QEMUResetEntry *first_reset_entry;
6221 int reset_requested;
6222 int shutdown_requested;
6223 int suspend_requested;
6224 static int powerdown_requested;
6226 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6228 QEMUResetEntry **pre, *re;
6230 pre = &first_reset_entry;
6231 while (*pre != NULL)
6232 pre = &(*pre)->next;
6233 re = qemu_mallocz(sizeof(QEMUResetEntry));
6234 re->func = func;
6235 re->opaque = opaque;
6236 re->next = NULL;
6237 *pre = re;
6240 void qemu_system_reset(void)
6242 QEMUResetEntry *re;
6244 /* reset all devices */
6245 for(re = first_reset_entry; re != NULL; re = re->next) {
6246 re->func(re->opaque);
6250 void qemu_system_reset_request(void)
6252 if (no_reboot) {
6253 shutdown_requested = 1;
6254 } else {
6255 reset_requested = 1;
6257 if (cpu_single_env)
6258 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6261 void qemu_system_shutdown_request(void)
6263 shutdown_requested = 1;
6264 if (cpu_single_env)
6265 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6268 void qemu_system_powerdown_request(void)
6270 powerdown_requested = 1;
6271 if (cpu_single_env)
6272 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6275 void main_loop_wait(int timeout)
6277 IOHandlerRecord *ioh;
6278 fd_set rfds, wfds, xfds;
6279 int ret, nfds;
6280 struct timeval tv;
6281 PollingEntry *pe;
6284 /* XXX: need to suppress polling by better using win32 events */
6285 ret = 0;
6286 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6287 ret |= pe->func(pe->opaque);
6289 #ifdef _WIN32
6290 if (ret == 0 && timeout > 0) {
6291 int err;
6292 WaitObjects *w = &wait_objects;
6294 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6295 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6296 if (w->func[ret - WAIT_OBJECT_0])
6297 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6298 } else if (ret == WAIT_TIMEOUT) {
6299 } else {
6300 err = GetLastError();
6301 fprintf(stderr, "Wait error %d %d\n", ret, err);
6304 #endif
6305 /* poll any events */
6306 /* XXX: separate device handlers from system ones */
6307 nfds = -1;
6308 FD_ZERO(&rfds);
6309 FD_ZERO(&wfds);
6310 FD_ZERO(&xfds);
6311 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6312 if (ioh->deleted)
6313 continue;
6314 if (ioh->fd_read &&
6315 (!ioh->fd_read_poll ||
6316 ioh->fd_read_poll(ioh->opaque) != 0)) {
6317 FD_SET(ioh->fd, &rfds);
6318 if (ioh->fd > nfds)
6319 nfds = ioh->fd;
6321 if (ioh->fd_write) {
6322 FD_SET(ioh->fd, &wfds);
6323 if (ioh->fd > nfds)
6324 nfds = ioh->fd;
6328 tv.tv_sec = 0;
6329 #ifdef _WIN32
6330 tv.tv_usec = 0;
6331 #else
6332 tv.tv_usec = timeout * 1000;
6333 #endif
6334 #if defined(CONFIG_SLIRP)
6335 if (slirp_inited) {
6336 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6338 #endif
6339 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6340 if (ret > 0) {
6341 IOHandlerRecord **pioh;
6343 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6344 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6345 ioh->fd_read(ioh->opaque);
6347 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6348 ioh->fd_write(ioh->opaque);
6352 /* remove deleted IO handlers */
6353 pioh = &first_io_handler;
6354 while (*pioh) {
6355 ioh = *pioh;
6356 if (ioh->deleted) {
6357 *pioh = ioh->next;
6358 qemu_free(ioh);
6359 } else
6360 pioh = &ioh->next;
6363 #if defined(CONFIG_SLIRP)
6364 if (slirp_inited) {
6365 if (ret < 0) {
6366 FD_ZERO(&rfds);
6367 FD_ZERO(&wfds);
6368 FD_ZERO(&xfds);
6370 slirp_select_poll(&rfds, &wfds, &xfds);
6372 #endif
6373 qemu_aio_poll();
6374 qemu_bh_poll();
6376 if (vm_running) {
6377 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6378 qemu_get_clock(vm_clock));
6379 /* run dma transfers, if any */
6380 DMA_run();
6383 /* real time timers */
6384 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6385 qemu_get_clock(rt_clock));
6388 #ifndef CONFIG_DM
6389 static CPUState *cur_cpu;
6391 int main_loop(void)
6393 int ret, timeout;
6394 #ifdef CONFIG_PROFILER
6395 int64_t ti;
6396 #endif
6397 CPUState *env;
6399 cur_cpu = first_cpu;
6400 for(;;) {
6401 if (vm_running) {
6403 env = cur_cpu;
6404 for(;;) {
6405 /* get next cpu */
6406 env = env->next_cpu;
6407 if (!env)
6408 env = first_cpu;
6409 #ifdef CONFIG_PROFILER
6410 ti = profile_getclock();
6411 #endif
6412 ret = cpu_exec(env);
6413 #ifdef CONFIG_PROFILER
6414 qemu_time += profile_getclock() - ti;
6415 #endif
6416 if (ret != EXCP_HALTED)
6417 break;
6418 /* all CPUs are halted ? */
6419 if (env == cur_cpu) {
6420 ret = EXCP_HLT;
6421 break;
6424 cur_cpu = env;
6426 if (shutdown_requested) {
6427 ret = EXCP_INTERRUPT;
6428 break;
6430 if (reset_requested) {
6431 reset_requested = 0;
6432 qemu_system_reset();
6433 ret = EXCP_INTERRUPT;
6435 if (powerdown_requested) {
6436 powerdown_requested = 0;
6437 qemu_system_powerdown();
6438 ret = EXCP_INTERRUPT;
6440 if (ret == EXCP_DEBUG) {
6441 vm_stop(EXCP_DEBUG);
6443 /* if hlt instruction, we wait until the next IRQ */
6444 /* XXX: use timeout computed from timers */
6445 if (ret == EXCP_HLT)
6446 timeout = 10;
6447 else
6448 timeout = 0;
6449 } else {
6450 timeout = 10;
6452 #ifdef CONFIG_PROFILER
6453 ti = profile_getclock();
6454 #endif
6455 main_loop_wait(timeout);
6456 #ifdef CONFIG_PROFILER
6457 dev_time += profile_getclock() - ti;
6458 #endif
6460 cpu_disable_ticks();
6461 return ret;
6463 #endif /* !CONFIG_DM */
6465 void help(void)
6467 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6468 "usage: %s [options] [disk_image]\n"
6469 "\n"
6470 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6471 "\n"
6472 "Standard options:\n"
6473 "-M machine select emulated machine (-M ? for list)\n"
6474 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6475 #ifndef CONFIG_DM
6476 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6477 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6478 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6479 #endif /* !CONFIG_DM */
6480 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6481 "-snapshot write to temporary files instead of disk image files\n"
6482 #ifdef CONFIG_SDL
6483 "-no-quit disable SDL window close capability\n"
6484 #endif
6485 #ifdef TARGET_I386
6486 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6487 #endif
6488 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6489 "-smp n set the number of CPUs to 'n' [default=1]\n"
6490 "-nographic disable graphical output and redirect serial I/Os to console\n"
6491 "-vcpus set CPU number of guest platform\n"
6492 #ifndef _WIN32
6493 "-k language use keyboard layout (for example \"fr\" for French)\n"
6494 #endif
6495 #ifdef HAS_AUDIO
6496 "-audio-help print list of audio drivers and their options\n"
6497 "-soundhw c1,... enable audio support\n"
6498 " and only specified sound cards (comma separated list)\n"
6499 " use -soundhw ? to get the list of supported cards\n"
6500 " use -soundhw all to enable all of them\n"
6501 #endif
6502 "-localtime set the real time clock to local time [default=utc]\n"
6503 "-full-screen start in full screen\n"
6504 #ifdef TARGET_I386
6505 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6506 #endif
6507 "-usb enable the USB driver (will be the default soon)\n"
6508 "-usbdevice name add the host or guest USB device 'name'\n"
6509 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6510 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6511 #endif
6512 "\n"
6513 "Network options:\n"
6514 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6515 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6516 #ifdef CONFIG_SLIRP
6517 "-net user[,vlan=n][,hostname=host]\n"
6518 " connect the user mode network stack to VLAN 'n' and send\n"
6519 " hostname 'host' to DHCP clients\n"
6520 #endif
6521 #ifdef _WIN32
6522 "-net tap[,vlan=n],ifname=name\n"
6523 " connect the host TAP network interface to VLAN 'n'\n"
6524 #else
6525 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
6526 " connect the host TAP network interface to VLAN 'n' and use\n"
6527 " the network script 'file' (default=%s);\n"
6528 " use 'script=no' to disable script execution;\n"
6529 " use 'fd=h' to connect to an already opened TAP interface\n"
6530 #endif
6531 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6532 " connect the vlan 'n' to another VLAN using a socket connection\n"
6533 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6534 " connect the vlan 'n' to multicast maddr and port\n"
6535 "-net none use it alone to have zero network devices; if no -net option\n"
6536 " is provided, the default is '-net nic -net user'\n"
6537 "\n"
6538 #ifdef CONFIG_SLIRP
6539 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6540 #ifndef _WIN32
6541 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6542 #endif
6543 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6544 " redirect TCP or UDP connections from host to guest [-net user]\n"
6545 #endif
6546 "\n"
6547 "Linux boot specific:\n"
6548 "-kernel bzImage use 'bzImage' as kernel image\n"
6549 "-append cmdline use 'cmdline' as kernel command line\n"
6550 "-initrd file use 'file' as initial ram disk\n"
6551 "\n"
6552 "Debug/Expert options:\n"
6553 "-monitor dev redirect the monitor to char device 'dev'\n"
6554 "-serial dev redirect the serial port to char device 'dev'\n"
6555 "-parallel dev redirect the parallel port to char device 'dev'\n"
6556 "-pidfile file Write PID to 'file'\n"
6557 "-S freeze CPU at startup (use 'c' to start execution)\n"
6558 "-s wait gdb connection to port %d\n"
6559 "-p port change gdb connection port\n"
6560 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
6561 "-d domain domain that we're serving\n"
6562 "-domain-name domain name that we're serving\n"
6563 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6564 " translation (t=none or lba) (usually qemu can guess them)\n"
6565 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6566 #ifdef USE_KQEMU
6567 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6568 "-no-kqemu disable KQEMU kernel module usage\n"
6569 #endif
6570 #ifdef USE_CODE_COPY
6571 "-no-code-copy disable code copy acceleration\n"
6572 #endif
6573 #ifdef TARGET_I386
6574 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6575 " (default is CL-GD5446 PCI VGA)\n"
6576 "-no-acpi disable ACPI\n"
6577 #endif
6578 "-no-reboot exit instead of rebooting\n"
6579 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6580 "-vnc display start a VNC server on display\n"
6581 "-vncviewer start a vncviewer process for this domain\n"
6582 "-vncunused bind the VNC server to an unused port\n"
6583 #ifndef NO_DAEMONIZE
6584 "-daemonize daemonize QEMU after initializing\n"
6585 #endif
6586 "-option-rom rom load a file, rom, into the option ROM space\n"
6587 "-acpi disable or enable ACPI of HVM domain \n"
6588 "\n"
6589 "During emulation, the following keys are useful:\n"
6590 "ctrl-alt-f toggle full screen\n"
6591 "ctrl-alt-n switch to virtual console 'n'\n"
6592 "ctrl-alt toggle mouse and keyboard grab\n"
6593 "\n"
6594 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6596 "qemu",
6597 DEFAULT_RAM_SIZE,
6598 #ifndef _WIN32
6599 DEFAULT_NETWORK_SCRIPT,
6600 #endif
6601 DEFAULT_GDBSTUB_PORT,
6602 "/tmp/qemu.log");
6603 exit(1);
6606 #define HAS_ARG 0x0001
6608 enum {
6609 QEMU_OPTION_h,
6611 QEMU_OPTION_M,
6612 QEMU_OPTION_fda,
6613 QEMU_OPTION_fdb,
6614 #ifndef CONFIG_DM
6615 QEMU_OPTION_hda,
6616 QEMU_OPTION_hdb,
6617 QEMU_OPTION_hdc,
6618 QEMU_OPTION_hdd,
6619 QEMU_OPTION_cdrom,
6620 #endif /* !CONFIG_DM */
6621 QEMU_OPTION_boot,
6622 QEMU_OPTION_snapshot,
6623 #ifdef TARGET_I386
6624 QEMU_OPTION_no_fd_bootchk,
6625 #endif
6626 QEMU_OPTION_m,
6627 QEMU_OPTION_nographic,
6628 #ifdef HAS_AUDIO
6629 QEMU_OPTION_audio_help,
6630 QEMU_OPTION_soundhw,
6631 #endif
6633 QEMU_OPTION_net,
6634 QEMU_OPTION_tftp,
6635 QEMU_OPTION_smb,
6636 QEMU_OPTION_redir,
6638 QEMU_OPTION_kernel,
6639 QEMU_OPTION_append,
6640 QEMU_OPTION_initrd,
6642 QEMU_OPTION_S,
6643 QEMU_OPTION_s,
6644 QEMU_OPTION_p,
6645 QEMU_OPTION_l,
6646 QEMU_OPTION_hdachs,
6647 QEMU_OPTION_L,
6648 #ifdef USE_CODE_COPY
6649 QEMU_OPTION_no_code_copy,
6650 #endif
6651 QEMU_OPTION_k,
6652 QEMU_OPTION_localtime,
6653 QEMU_OPTION_cirrusvga,
6654 QEMU_OPTION_g,
6655 QEMU_OPTION_std_vga,
6656 QEMU_OPTION_monitor,
6657 QEMU_OPTION_domainname,
6658 QEMU_OPTION_serial,
6659 QEMU_OPTION_parallel,
6660 QEMU_OPTION_loadvm,
6661 QEMU_OPTION_full_screen,
6662 QEMU_OPTION_no_quit,
6663 QEMU_OPTION_pidfile,
6664 QEMU_OPTION_no_kqemu,
6665 QEMU_OPTION_kernel_kqemu,
6666 QEMU_OPTION_win2k_hack,
6667 QEMU_OPTION_usb,
6668 QEMU_OPTION_usbdevice,
6669 QEMU_OPTION_smp,
6670 QEMU_OPTION_vnc,
6671 QEMU_OPTION_no_acpi,
6672 QEMU_OPTION_no_reboot,
6673 #ifndef NO_DAEMONIZE
6674 QEMU_OPTION_daemonize,
6675 #endif
6676 QEMU_OPTION_option_rom,
6677 QEMU_OPTION_semihosting
6679 QEMU_OPTION_d,
6680 QEMU_OPTION_vcpus,
6681 QEMU_OPTION_acpi,
6682 QEMU_OPTION_vncviewer,
6683 QEMU_OPTION_vncunused,
6684 QEMU_OPTION_pci,
6685 };
6687 typedef struct QEMUOption {
6688 const char *name;
6689 int flags;
6690 int index;
6691 } QEMUOption;
6693 const QEMUOption qemu_options[] = {
6694 { "h", 0, QEMU_OPTION_h },
6695 { "help", 0, QEMU_OPTION_h },
6697 { "M", HAS_ARG, QEMU_OPTION_M },
6698 { "fda", HAS_ARG, QEMU_OPTION_fda },
6699 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6700 #ifndef CONFIG_DM
6701 { "hda", HAS_ARG, QEMU_OPTION_hda },
6702 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6703 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6704 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6705 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6706 #endif /* !CONFIG_DM */
6707 { "boot", HAS_ARG, QEMU_OPTION_boot },
6708 { "snapshot", 0, QEMU_OPTION_snapshot },
6709 #ifdef TARGET_I386
6710 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6711 #endif
6712 { "m", HAS_ARG, QEMU_OPTION_m },
6713 { "nographic", 0, QEMU_OPTION_nographic },
6714 { "k", HAS_ARG, QEMU_OPTION_k },
6715 #ifdef HAS_AUDIO
6716 { "audio-help", 0, QEMU_OPTION_audio_help },
6717 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6718 #endif
6720 { "net", HAS_ARG, QEMU_OPTION_net},
6721 #ifdef CONFIG_SLIRP
6722 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6723 #ifndef _WIN32
6724 { "smb", HAS_ARG, QEMU_OPTION_smb },
6725 #endif
6726 { "redir", HAS_ARG, QEMU_OPTION_redir },
6727 #endif
6729 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6730 { "append", HAS_ARG, QEMU_OPTION_append },
6731 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6733 { "S", 0, QEMU_OPTION_S },
6734 { "s", 0, QEMU_OPTION_s },
6735 { "p", HAS_ARG, QEMU_OPTION_p },
6736 { "l", HAS_ARG, QEMU_OPTION_l },
6737 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6738 { "L", HAS_ARG, QEMU_OPTION_L },
6739 #ifdef USE_CODE_COPY
6740 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6741 #endif
6742 #ifdef USE_KQEMU
6743 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6744 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6745 #endif
6746 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6747 { "g", 1, QEMU_OPTION_g },
6748 #endif
6749 { "localtime", 0, QEMU_OPTION_localtime },
6750 { "std-vga", 0, QEMU_OPTION_std_vga },
6751 { "monitor", 1, QEMU_OPTION_monitor },
6752 { "domain-name", 1, QEMU_OPTION_domainname },
6753 { "serial", 1, QEMU_OPTION_serial },
6754 { "parallel", 1, QEMU_OPTION_parallel },
6755 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6756 { "full-screen", 0, QEMU_OPTION_full_screen },
6757 #ifdef CONFIG_SDL
6758 { "no-quit", 0, QEMU_OPTION_no_quit },
6759 #endif
6760 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6761 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6762 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6763 { "smp", HAS_ARG, QEMU_OPTION_smp },
6764 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6765 { "vncviewer", 0, QEMU_OPTION_vncviewer },
6766 { "vncunused", 0, QEMU_OPTION_vncunused },
6768 /* temporary options */
6769 { "usb", 0, QEMU_OPTION_usb },
6770 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6771 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6772 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6773 #ifndef NO_DAEMONIZE
6774 { "daemonize", 0, QEMU_OPTION_daemonize },
6775 #endif
6776 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6777 #if defined(TARGET_ARM)
6778 { "semihosting", 0, QEMU_OPTION_semihosting },
6779 #endif
6781 { "d", HAS_ARG, QEMU_OPTION_d },
6782 { "vcpus", 1, QEMU_OPTION_vcpus },
6783 { "acpi", 0, QEMU_OPTION_acpi },
6784 { "pci", HAS_ARG, QEMU_OPTION_pci},
6785 { NULL },
6786 };
6788 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6790 /* this stack is only used during signal handling */
6791 #define SIGNAL_STACK_SIZE 32768
6793 static uint8_t *signal_stack;
6795 #endif
6797 /* password input */
6799 static BlockDriverState *get_bdrv(int index)
6801 BlockDriverState *bs;
6803 if (index < 4) {
6804 bs = bs_table[index];
6805 } else if (index < 6) {
6806 bs = fd_table[index - 4];
6807 } else {
6808 bs = NULL;
6810 return bs;
6813 static void read_passwords(void)
6815 BlockDriverState *bs;
6816 int i, j;
6817 char password[256];
6819 for(i = 0; i < 6; i++) {
6820 bs = get_bdrv(i);
6821 if (bs && bdrv_is_encrypted(bs)) {
6822 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6823 for(j = 0; j < 3; j++) {
6824 monitor_readline("Password: ",
6825 1, password, sizeof(password));
6826 if (bdrv_set_key(bs, password) == 0)
6827 break;
6828 term_printf("invalid password\n");
6834 /* XXX: currently we cannot use simultaneously different CPUs */
6835 void register_machines(void)
6837 #if defined(TARGET_I386)
6838 #ifndef CONFIG_DM
6839 qemu_register_machine(&pc_machine);
6840 qemu_register_machine(&isapc_machine);
6841 #else
6842 qemu_register_machine(&xenfv_machine);
6843 qemu_register_machine(&xenpv_machine);
6844 #endif
6845 #elif defined(TARGET_PPC)
6846 qemu_register_machine(&heathrow_machine);
6847 qemu_register_machine(&core99_machine);
6848 qemu_register_machine(&prep_machine);
6849 #elif defined(TARGET_MIPS)
6850 qemu_register_machine(&mips_machine);
6851 qemu_register_machine(&mips_malta_machine);
6852 #elif defined(TARGET_SPARC)
6853 #ifdef TARGET_SPARC64
6854 qemu_register_machine(&sun4u_machine);
6855 #else
6856 qemu_register_machine(&sun4m_machine);
6857 #endif
6858 #elif defined(TARGET_ARM)
6859 qemu_register_machine(&integratorcp926_machine);
6860 qemu_register_machine(&integratorcp1026_machine);
6861 qemu_register_machine(&versatilepb_machine);
6862 qemu_register_machine(&versatileab_machine);
6863 qemu_register_machine(&realview_machine);
6864 #elif defined(TARGET_SH4)
6865 qemu_register_machine(&shix_machine);
6866 #else
6867 #error unsupported CPU
6868 #endif
6871 #ifdef HAS_AUDIO
6872 struct soundhw soundhw[] = {
6873 #ifndef CONFIG_DM
6874 #ifdef TARGET_I386
6876 "pcspk",
6877 "PC speaker",
6878 0,
6879 1,
6880 { .init_isa = pcspk_audio_init }
6881 },
6882 #endif
6883 #endif /* !CONFIG_DM */
6885 "sb16",
6886 "Creative Sound Blaster 16",
6887 0,
6888 1,
6889 { .init_isa = SB16_init }
6890 },
6892 #ifdef CONFIG_ADLIB
6894 "adlib",
6895 #ifdef HAS_YMF262
6896 "Yamaha YMF262 (OPL3)",
6897 #else
6898 "Yamaha YM3812 (OPL2)",
6899 #endif
6900 0,
6901 1,
6902 { .init_isa = Adlib_init }
6903 },
6904 #endif
6906 #ifdef CONFIG_GUS
6908 "gus",
6909 "Gravis Ultrasound GF1",
6910 0,
6911 1,
6912 { .init_isa = GUS_init }
6913 },
6914 #endif
6917 "es1370",
6918 "ENSONIQ AudioPCI ES1370",
6919 0,
6920 0,
6921 { .init_pci = es1370_init }
6922 },
6924 { NULL, NULL, 0, 0, { NULL } }
6925 };
6927 static void select_soundhw (const char *optarg)
6929 struct soundhw *c;
6931 if (*optarg == '?') {
6932 show_valid_cards:
6934 printf ("Valid sound card names (comma separated):\n");
6935 for (c = soundhw; c->name; ++c) {
6936 printf ("%-11s %s\n", c->name, c->descr);
6938 printf ("\n-soundhw all will enable all of the above\n");
6939 exit (*optarg != '?');
6941 else {
6942 size_t l;
6943 const char *p;
6944 char *e;
6945 int bad_card = 0;
6947 if (!strcmp (optarg, "all")) {
6948 for (c = soundhw; c->name; ++c) {
6949 c->enabled = 1;
6951 return;
6954 p = optarg;
6955 while (*p) {
6956 e = strchr (p, ',');
6957 l = !e ? strlen (p) : (size_t) (e - p);
6959 for (c = soundhw; c->name; ++c) {
6960 if (!strncmp (c->name, p, l)) {
6961 c->enabled = 1;
6962 break;
6966 if (!c->name) {
6967 if (l > 80) {
6968 fprintf (stderr,
6969 "Unknown sound card name (too big to show)\n");
6971 else {
6972 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6973 (int) l, p);
6975 bad_card = 1;
6977 p += l + (e != NULL);
6980 if (bad_card)
6981 goto show_valid_cards;
6984 #endif
6986 #ifdef _WIN32
6987 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6989 exit(STATUS_CONTROL_C_EXIT);
6990 return TRUE;
6992 #endif
6994 #define MAX_NET_CLIENTS 32
6996 #include <xg_private.h>
6998 /* FIXME Flush the shadow page */
6999 int unset_mm_mapping(int xc_handle, uint32_t domid,
7000 unsigned long nr_pages, unsigned int address_bits,
7001 xen_pfn_t *extent_start)
7003 int err = 0;
7004 xc_dominfo_t info;
7006 xc_domain_getinfo(xc_handle, domid, 1, &info);
7007 if ((info.nr_pages - nr_pages) <= 0) {
7008 fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
7009 err = -1;
7012 err = xc_domain_memory_decrease_reservation(xc_handle, domid,
7013 nr_pages, 0, extent_start);
7014 if (err)
7015 fprintf(stderr, "Failed to decrease physmap\n");
7018 if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
7019 PAGE_SIZE/1024) != 0) {
7020 fprintf(logfile, "set maxmem returned error %d\n", errno);
7021 err = -1;
7024 return err;
7027 int set_mm_mapping(int xc_handle, uint32_t domid,
7028 unsigned long nr_pages, unsigned int address_bits,
7029 xen_pfn_t *extent_start)
7031 xc_dominfo_t info;
7032 int err = 0;
7034 xc_domain_getinfo(xc_handle, domid, 1, &info);
7036 if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
7037 nr_pages * PAGE_SIZE/1024) != 0) {
7038 fprintf(logfile, "set maxmem returned error %d\n", errno);
7039 return -1;
7042 err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
7043 address_bits, extent_start);
7044 if (err) {
7045 fprintf(stderr, "Failed to populate physmap\n");
7046 return -1;
7049 return 0;
7053 int main(int argc, char **argv)
7055 #ifdef CONFIG_GDBSTUB
7056 int use_gdbstub, gdbstub_port;
7057 #endif
7058 int i;
7059 #ifndef CONFIG_DM
7060 int cdrom_index;
7061 #endif /* !CONFIG_DM */
7062 int snapshot, linux_boot;
7063 const char *initrd_filename;
7064 #ifndef CONFIG_DM
7065 const char *hd_filename[MAX_DISKS + MAX_SCSI_DISKS];
7066 #endif /* !CONFIG_DM */
7067 const char *fd_filename[MAX_FD];
7068 const char *kernel_filename, *kernel_cmdline;
7069 DisplayState *ds = &display_state;
7070 int cyls, heads, secs, translation;
7071 char net_clients[MAX_NET_CLIENTS][256];
7072 int nb_net_clients;
7073 int optind;
7074 const char *r, *optarg;
7075 CharDriverState *monitor_hd;
7076 char monitor_device[128];
7077 char serial_devices[MAX_SERIAL_PORTS][128];
7078 int serial_device_index;
7079 char parallel_devices[MAX_PARALLEL_PORTS][128];
7080 int parallel_device_index;
7081 const char *loadvm = NULL;
7082 QEMUMachine *machine;
7083 char usb_devices[MAX_USB_CMDLINE][128];
7084 int usb_devices_index;
7085 int fds[2];
7086 #ifndef CONFIG_STUBDOM
7087 struct rlimit rl;
7088 #endif
7089 sigset_t set;
7090 char qemu_dm_logfilename[128];
7091 const char *direct_pci = direct_pci_str;
7093 #if !defined(__sun__) && !defined(CONFIG_STUBDOM)
7094 /* Maximise rlimits. Needed where default constraints are tight (*BSD). */
7095 if (getrlimit(RLIMIT_STACK, &rl) != 0) {
7096 perror("getrlimit(RLIMIT_STACK)");
7097 exit(1);
7099 rl.rlim_cur = rl.rlim_max;
7100 if (setrlimit(RLIMIT_STACK, &rl) != 0)
7101 perror("setrlimit(RLIMIT_STACK)");
7102 if (getrlimit(RLIMIT_DATA, &rl) != 0) {
7103 perror("getrlimit(RLIMIT_DATA)");
7104 exit(1);
7106 rl.rlim_cur = rl.rlim_max;
7107 if (setrlimit(RLIMIT_DATA, &rl) != 0)
7108 perror("setrlimit(RLIMIT_DATA)");
7109 rl.rlim_cur = RLIM_INFINITY;
7110 rl.rlim_max = RLIM_INFINITY;
7111 if (setrlimit(RLIMIT_RSS, &rl) != 0)
7112 perror("setrlimit(RLIMIT_RSS)");
7113 rl.rlim_cur = RLIM_INFINITY;
7114 rl.rlim_max = RLIM_INFINITY;
7115 if (setrlimit(RLIMIT_MEMLOCK, &rl) != 0)
7116 perror("setrlimit(RLIMIT_MEMLOCK)");
7117 #endif
7119 #ifndef CONFIG_STUBDOM
7120 /* Ensure that SIGUSR2 is blocked by default when a new thread is created,
7121 then only the threads that use the signal unblock it -- this fixes a
7122 race condition in Qcow support where the AIO signal is misdelivered. */
7124 extern const int aio_sig_num;
7125 sigset_t set;
7127 sigemptyset(&set);
7128 sigaddset(&set, aio_sig_num);
7129 sigprocmask(SIG_BLOCK, &set, NULL);
7132 QEMU_LIST_INIT (&vm_change_state_head);
7133 #ifndef _WIN32
7135 struct sigaction act;
7136 sigfillset(&act.sa_mask);
7137 act.sa_flags = 0;
7138 act.sa_handler = SIG_IGN;
7139 sigaction(SIGPIPE, &act, NULL);
7141 #else
7142 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7143 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7144 QEMU to run on a single CPU */
7146 HANDLE h;
7147 DWORD mask, smask;
7148 int i;
7149 h = GetCurrentProcess();
7150 if (GetProcessAffinityMask(h, &mask, &smask)) {
7151 for(i = 0; i < 32; i++) {
7152 if (mask & (1 << i))
7153 break;
7155 if (i != 32) {
7156 mask = 1 << i;
7157 SetProcessAffinityMask(h, mask);
7161 #endif
7162 #endif
7164 register_machines();
7165 machine = first_machine;
7166 initrd_filename = NULL;
7167 for(i = 0; i < MAX_FD; i++)
7168 fd_filename[i] = NULL;
7169 #ifndef CONFIG_DM
7170 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++)
7171 hd_filename[i] = NULL;
7172 #endif /* !CONFIG_DM */
7173 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7174 vga_ram_size = VGA_RAM_SIZE;
7175 bios_size = BIOS_SIZE;
7176 #ifdef CONFIG_GDBSTUB
7177 use_gdbstub = 0;
7178 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7179 #endif
7180 snapshot = 0;
7181 nographic = 0;
7182 vncviewer = 0;
7183 vncunused = 0;
7184 kernel_filename = NULL;
7185 kernel_cmdline = "";
7186 #ifndef CONFIG_DM
7187 #ifdef TARGET_PPC
7188 cdrom_index = 1;
7189 #else
7190 cdrom_index = 2;
7191 #endif
7192 #endif /* !CONFIG_DM */
7193 cyls = heads = secs = 0;
7194 translation = BIOS_ATA_TRANSLATION_AUTO;
7195 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7197 for(i = 0; i < MAX_SERIAL_PORTS; i++)
7198 serial_devices[i][0] = '\0';
7199 serial_device_index = 0;
7201 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7202 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7203 parallel_devices[i][0] = '\0';
7204 parallel_device_index = 0;
7206 usb_devices_index = 0;
7208 nb_net_clients = 0;
7210 nb_nics = 0;
7211 /* default mac address of the first network interface */
7213 /* Init logs to stderr to start with */
7214 cpu_set_log(0);
7216 optind = 1;
7217 for(;;) {
7218 if (optind >= argc)
7219 break;
7220 r = argv[optind];
7221 if (r[0] != '-') {
7222 #ifndef CONFIG_DM
7223 hd_filename[0] = argv[optind++];
7224 #else
7225 help();
7226 #endif /* !CONFIG_DM */
7227 } else {
7228 const QEMUOption *popt;
7230 optind++;
7231 /* Treat --foo the same as -foo. */
7232 if (r[1] == '-')
7233 r++;
7234 popt = qemu_options;
7235 for(;;) {
7236 if (!popt->name) {
7237 fprintf(stderr, "%s: invalid option -- '%s'\n",
7238 argv[0], r);
7239 exit(1);
7241 if (!strcmp(popt->name, r + 1))
7242 break;
7243 popt++;
7245 if (popt->flags & HAS_ARG) {
7246 if (optind >= argc) {
7247 fprintf(stderr, "%s: option '%s' requires an argument\n",
7248 argv[0], r);
7249 exit(1);
7251 optarg = argv[optind++];
7252 } else {
7253 optarg = NULL;
7256 switch(popt->index) {
7257 case QEMU_OPTION_M:
7258 machine = find_machine(optarg);
7259 if (!machine) {
7260 QEMUMachine *m;
7261 printf("Supported machines are:\n");
7262 for(m = first_machine; m != NULL; m = m->next) {
7263 printf("%-10s %s%s\n",
7264 m->name, m->desc,
7265 m == first_machine ? " (default)" : "");
7267 exit(1);
7269 break;
7270 case QEMU_OPTION_initrd:
7271 initrd_filename = optarg;
7272 break;
7273 #ifndef CONFIG_DM
7274 case QEMU_OPTION_hda:
7275 case QEMU_OPTION_hdb:
7276 case QEMU_OPTION_hdc:
7277 case QEMU_OPTION_hdd:
7279 int hd_index;
7280 hd_index = popt->index - QEMU_OPTION_hda;
7281 hd_filename[hd_index] = optarg;
7282 if (hd_index == cdrom_index)
7283 cdrom_index = -1;
7285 break;
7286 #endif /* !CONFIG_DM */
7287 case QEMU_OPTION_snapshot:
7288 snapshot = 1;
7289 break;
7290 case QEMU_OPTION_hdachs:
7292 const char *p;
7293 p = optarg;
7294 cyls = strtol(p, (char **)&p, 0);
7295 if (cyls < 1 || cyls > 16383)
7296 goto chs_fail;
7297 if (*p != ',')
7298 goto chs_fail;
7299 p++;
7300 heads = strtol(p, (char **)&p, 0);
7301 if (heads < 1 || heads > 16)
7302 goto chs_fail;
7303 if (*p != ',')
7304 goto chs_fail;
7305 p++;
7306 secs = strtol(p, (char **)&p, 0);
7307 if (secs < 1 || secs > 63)
7308 goto chs_fail;
7309 if (*p == ',') {
7310 p++;
7311 if (!strcmp(p, "none"))
7312 translation = BIOS_ATA_TRANSLATION_NONE;
7313 else if (!strcmp(p, "lba"))
7314 translation = BIOS_ATA_TRANSLATION_LBA;
7315 else if (!strcmp(p, "auto"))
7316 translation = BIOS_ATA_TRANSLATION_AUTO;
7317 else
7318 goto chs_fail;
7319 } else if (*p != '\0') {
7320 chs_fail:
7321 fprintf(stderr, "qemu: invalid physical CHS format\n");
7322 exit(1);
7325 break;
7326 case QEMU_OPTION_nographic:
7327 if(!strcmp(monitor_device, "vc"))
7328 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7329 if(!strcmp(serial_devices[0], "vc"))
7330 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
7331 "null");
7332 nographic = 1;
7333 break;
7334 case QEMU_OPTION_kernel:
7335 kernel_filename = optarg;
7336 break;
7337 case QEMU_OPTION_append:
7338 kernel_cmdline = optarg;
7339 break;
7340 #ifndef CONFIG_DM
7341 case QEMU_OPTION_cdrom:
7342 if (cdrom_index >= 0) {
7343 hd_filename[cdrom_index] = optarg;
7345 break;
7346 #endif /* !CONFIG_DM */
7347 case QEMU_OPTION_boot:
7348 boot_device = strdup(optarg);
7349 if (strspn(boot_device, "a"
7350 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7351 // Network boot
7352 "n"
7353 #endif
7354 "cd") != strlen(boot_device)) {
7355 fprintf(stderr, "qemu: invalid boot device in '%s'\n", boot_device);
7356 exit(1);
7358 break;
7359 case QEMU_OPTION_fda:
7360 fd_filename[0] = optarg;
7361 break;
7362 case QEMU_OPTION_fdb:
7363 fd_filename[1] = optarg;
7364 break;
7365 #ifdef TARGET_I386
7366 case QEMU_OPTION_no_fd_bootchk:
7367 fd_bootchk = 0;
7368 break;
7369 #endif
7370 #ifdef USE_CODE_COPY
7371 case QEMU_OPTION_no_code_copy:
7372 code_copy_enabled = 0;
7373 break;
7374 #endif
7375 case QEMU_OPTION_net:
7376 if (nb_net_clients >= MAX_NET_CLIENTS) {
7377 fprintf(stderr, "qemu: too many network clients\n");
7378 exit(1);
7380 pstrcpy(net_clients[nb_net_clients],
7381 sizeof(net_clients[0]),
7382 optarg);
7383 nb_net_clients++;
7384 break;
7385 #ifdef CONFIG_SLIRP
7386 case QEMU_OPTION_tftp:
7387 tftp_prefix = optarg;
7388 break;
7389 #ifndef _WIN32
7390 case QEMU_OPTION_smb:
7391 net_slirp_smb(optarg);
7392 break;
7393 #endif
7394 case QEMU_OPTION_redir:
7395 net_slirp_redir(optarg);
7396 break;
7397 #endif
7398 #ifdef HAS_AUDIO
7399 case QEMU_OPTION_audio_help:
7400 AUD_help ();
7401 exit (0);
7402 break;
7403 case QEMU_OPTION_soundhw:
7404 select_soundhw (optarg);
7405 break;
7406 #endif
7407 case QEMU_OPTION_h:
7408 help();
7409 break;
7410 case QEMU_OPTION_m:
7411 ram_size = atol(optarg) * 1024 * 1024;
7412 ram_size = (uint64_t)atol(optarg) * 1024 * 1024;
7413 if (ram_size <= 0)
7414 help();
7415 #ifndef CONFIG_DM
7416 if (ram_size > PHYS_RAM_MAX_SIZE) {
7417 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7418 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7419 exit(1);
7421 #endif /* !CONFIG_DM */
7422 break;
7423 case QEMU_OPTION_l:
7425 int mask;
7426 CPULogItem *item;
7428 mask = cpu_str_to_log_mask(optarg);
7429 if (!mask) {
7430 printf("Log items (comma separated):\n");
7431 for(item = cpu_log_items; item->mask != 0; item++) {
7432 printf("%-10s %s\n", item->name, item->help);
7434 exit(1);
7436 cpu_set_log(mask);
7438 break;
7439 #ifdef CONFIG_GDBSTUB
7440 case QEMU_OPTION_s:
7441 use_gdbstub = 1;
7442 break;
7443 case QEMU_OPTION_p:
7444 gdbstub_port = atoi(optarg);
7445 break;
7446 #endif
7447 case QEMU_OPTION_L:
7448 bios_dir = optarg;
7449 break;
7450 case QEMU_OPTION_S:
7451 autostart = 0;
7452 break;
7453 case QEMU_OPTION_k:
7454 keyboard_layout = optarg;
7455 break;
7456 case QEMU_OPTION_localtime:
7457 rtc_utc = 0;
7458 break;
7459 case QEMU_OPTION_cirrusvga:
7460 cirrus_vga_enabled = 1;
7461 break;
7462 case QEMU_OPTION_std_vga:
7463 cirrus_vga_enabled = 0;
7464 break;
7465 case QEMU_OPTION_g:
7467 const char *p;
7468 int w, h, depth;
7469 p = optarg;
7470 w = strtol(p, (char **)&p, 10);
7471 if (w <= 0) {
7472 graphic_error:
7473 fprintf(stderr, "qemu: invalid resolution or depth\n");
7474 exit(1);
7476 if (*p != 'x')
7477 goto graphic_error;
7478 p++;
7479 h = strtol(p, (char **)&p, 10);
7480 if (h <= 0)
7481 goto graphic_error;
7482 if (*p == 'x') {
7483 p++;
7484 depth = strtol(p, (char **)&p, 10);
7485 if (depth != 8 && depth != 15 && depth != 16 &&
7486 depth != 24 && depth != 32)
7487 goto graphic_error;
7488 } else if (*p == '\0') {
7489 depth = graphic_depth;
7490 } else {
7491 goto graphic_error;
7494 graphic_width = w;
7495 graphic_height = h;
7496 graphic_depth = depth;
7498 break;
7499 case QEMU_OPTION_monitor:
7500 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7501 break;
7502 case QEMU_OPTION_serial:
7503 if (serial_device_index >= MAX_SERIAL_PORTS) {
7504 fprintf(stderr, "qemu: too many serial ports\n");
7505 exit(1);
7507 pstrcpy(serial_devices[serial_device_index],
7508 sizeof(serial_devices[0]), optarg);
7509 serial_device_index++;
7510 break;
7511 case QEMU_OPTION_parallel:
7512 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7513 fprintf(stderr, "qemu: too many parallel ports\n");
7514 exit(1);
7516 pstrcpy(parallel_devices[parallel_device_index],
7517 sizeof(parallel_devices[0]), optarg);
7518 parallel_device_index++;
7519 break;
7520 case QEMU_OPTION_loadvm:
7521 loadvm = optarg;
7522 break;
7523 case QEMU_OPTION_full_screen:
7524 full_screen = 1;
7525 break;
7526 #ifdef CONFIG_SDL
7527 case QEMU_OPTION_no_quit:
7528 no_quit = 1;
7529 break;
7530 #endif
7531 case QEMU_OPTION_pidfile:
7532 create_pidfile(optarg);
7533 break;
7534 #ifdef TARGET_I386
7535 case QEMU_OPTION_win2k_hack:
7536 win2k_install_hack = 1;
7537 break;
7538 #endif
7539 #ifdef USE_KQEMU
7540 case QEMU_OPTION_no_kqemu:
7541 kqemu_allowed = 0;
7542 break;
7543 case QEMU_OPTION_kernel_kqemu:
7544 kqemu_allowed = 2;
7545 break;
7546 #endif
7547 case QEMU_OPTION_usb:
7548 usb_enabled = 1;
7549 break;
7550 case QEMU_OPTION_usbdevice:
7551 usb_enabled = 1;
7552 if (usb_devices_index >= MAX_USB_CMDLINE) {
7553 fprintf(stderr, "Too many USB devices\n");
7554 exit(1);
7556 pstrcpy(usb_devices[usb_devices_index],
7557 sizeof(usb_devices[usb_devices_index]),
7558 optarg);
7559 usb_devices_index++;
7560 break;
7561 case QEMU_OPTION_smp:
7562 smp_cpus = atoi(optarg);
7563 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7564 fprintf(stderr, "Invalid number of CPUs\n");
7565 exit(1);
7567 break;
7568 case QEMU_OPTION_vnc:
7569 vnc_display = optarg;
7570 break;
7571 case QEMU_OPTION_no_acpi:
7572 acpi_enabled = 0;
7573 break;
7574 case QEMU_OPTION_no_reboot:
7575 no_reboot = 1;
7576 break;
7577 #ifndef NO_DAEMONIZE
7578 case QEMU_OPTION_daemonize:
7579 daemonize = 1;
7580 break;
7581 #endif
7582 case QEMU_OPTION_option_rom:
7583 if (nb_option_roms >= MAX_OPTION_ROMS) {
7584 fprintf(stderr, "Too many option ROMs\n");
7585 exit(1);
7587 option_rom[nb_option_roms] = optarg;
7588 nb_option_roms++;
7589 break;
7590 case QEMU_OPTION_semihosting:
7591 semihosting_enabled = 1;
7592 break;
7593 case QEMU_OPTION_domainname:
7594 snprintf(domain_name, sizeof(domain_name),
7595 "Xen-%s", optarg);
7596 break;
7597 case QEMU_OPTION_d:
7598 domid = atoi(optarg);
7599 fprintf(logfile, "domid: %d\n", domid);
7600 break;
7601 case QEMU_OPTION_vcpus:
7602 vcpus = atoi(optarg);
7603 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
7604 break;
7605 case QEMU_OPTION_acpi:
7606 acpi_enabled = 1;
7607 break;
7608 case QEMU_OPTION_vncviewer:
7609 vncviewer++;
7610 break;
7611 case QEMU_OPTION_vncunused:
7612 vncunused++;
7613 break;
7618 cpu_set_log(0);
7620 #ifndef NO_DAEMONIZE
7621 if (daemonize && !nographic && vnc_display == NULL && vncunused == 0) {
7622 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7623 daemonize = 0;
7626 if (daemonize) {
7627 pid_t pid;
7629 if (pipe(fds) == -1)
7630 exit(1);
7632 pid = fork();
7633 if (pid > 0) {
7634 uint8_t status;
7635 ssize_t len;
7637 close(fds[1]);
7639 again:
7640 len = read(fds[0], &status, 1);
7641 if (len == -1 && (errno == EINTR))
7642 goto again;
7644 if (len != 1 || status != 0)
7645 exit(1);
7646 else
7647 exit(0);
7648 } else if (pid < 0)
7649 exit(1);
7651 setsid();
7653 pid = fork();
7654 if (pid > 0)
7655 exit(0);
7656 else if (pid < 0)
7657 exit(1);
7659 umask(027);
7660 chdir("/");
7662 signal(SIGTSTP, SIG_IGN);
7663 signal(SIGTTOU, SIG_IGN);
7664 signal(SIGTTIN, SIG_IGN);
7666 #endif
7668 #ifdef CONFIG_DM
7669 bdrv_init();
7670 xc_handle = xc_interface_open();
7671 #ifdef CONFIG_STUBDOM
7672 char *domid_s, *msg;
7673 if ((msg = xenbus_read(XBT_NIL, "domid", &domid_s)))
7674 fprintf(stderr,"Can not read our own domid\n", msg);
7675 else
7676 xenstore_parse_domain_config(atoi(domid_s));
7677 #else /* CONFIG_STUBDOM */
7678 xenstore_parse_domain_config(domid);
7679 #endif /* CONFIG_STUBDOM */
7680 #endif /* CONFIG_DM */
7682 #ifdef USE_KQEMU
7683 if (smp_cpus > 1)
7684 kqemu_allowed = 0;
7685 #endif
7686 linux_boot = (kernel_filename != NULL);
7688 #ifndef CONFIG_DM
7689 if (!linux_boot &&
7690 hd_filename[0] == '\0' &&
7691 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7692 fd_filename[0] == '\0')
7693 help();
7695 /* boot to floppy or the default cd if no hard disk defined yet */
7696 if (hd_filename[0] == '\0' && boot_device == 'c') {
7697 if (fd_filename[0] != '\0')
7698 boot_device = 'a';
7699 else
7700 boot_device = 'd';
7702 #endif /* !CONFIG_DM */
7704 setvbuf(stdout, NULL, _IOLBF, 0);
7706 init_timers();
7707 init_timer_alarm();
7708 qemu_aio_init();
7710 #ifdef _WIN32
7711 socket_init();
7712 #endif
7714 #ifndef CONFIG_DM
7715 /* init network clients */
7716 if (nb_net_clients == 0) {
7717 /* if no clients, we use a default config */
7718 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7719 "nic");
7720 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7721 "user");
7722 nb_net_clients = 2;
7724 #endif /* !CONFIG_DM */
7726 for(i = 0;i < nb_net_clients; i++) {
7727 if (net_client_init(net_clients[i]) < 0)
7728 exit(1);
7731 #ifndef CONFIG_DM
7732 #ifdef TARGET_I386
7733 if (boot_device == 'n') {
7734 for (i = 0; i < nb_nics; i++) {
7735 const char *model = nd_table[i].model;
7736 char buf[1024];
7737 if (model == NULL)
7738 model = "ne2k_pci";
7739 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7740 if (get_image_size(buf) > 0) {
7741 option_rom[nb_option_roms] = strdup(buf);
7742 nb_option_roms++;
7743 break;
7746 if (i == nb_nics) {
7747 fprintf(stderr, "No valid PXE rom found for network device\n");
7748 exit(1);
7750 boot_device = 'c'; /* to prevent confusion by the BIOS */
7752 #endif
7753 #endif /* !CONFIG_DM */
7755 #if defined (__ia64__)
7756 if (ram_size > MMIO_START)
7757 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
7758 #endif
7760 /* init the memory */
7761 phys_ram_size = ram_size + vga_ram_size + bios_size;
7763 #ifndef CONFIG_DM
7764 for (i = 0; i < nb_option_roms; i++) {
7765 int ret = get_image_size(option_rom[i]);
7766 if (ret == -1) {
7767 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7768 exit(1);
7770 phys_ram_size += ret;
7773 phys_ram_base = qemu_vmalloc(phys_ram_size);
7774 if (!phys_ram_base) {
7775 fprintf(stderr, "Could not allocate physical memory\n");
7776 exit(1);
7779 /* we always create the cdrom drive, even if no disk is there */
7780 bdrv_init();
7781 if (cdrom_index >= 0) {
7782 bs_table[cdrom_index] = bdrv_new("cdrom");
7783 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7786 /* open the virtual block devices */
7787 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
7788 if (hd_filename[i]) {
7789 if (!bs_table[i]) {
7790 char buf[64];
7791 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7792 bs_table[i] = bdrv_new(buf);
7794 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7795 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7796 hd_filename[i]);
7797 exit(1);
7799 if (i == 0 && cyls != 0) {
7800 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7801 bdrv_set_translation_hint(bs_table[i], translation);
7805 #endif /* !CONFIG_DM */
7807 /* we always create at least one floppy disk */
7808 fd_table[0] = bdrv_new("fda");
7809 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7811 for(i = 0; i < MAX_FD; i++) {
7812 if (fd_filename[i]) {
7813 if (!fd_table[i]) {
7814 char buf[64];
7815 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7816 fd_table[i] = bdrv_new(buf);
7817 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7819 if (fd_filename[i] != '\0') {
7820 if (bdrv_open(fd_table[i], fd_filename[i],
7821 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7822 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7823 fd_filename[i]);
7824 exit(1);
7830 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7831 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7833 init_ioports();
7835 /* terminal init */
7836 #ifdef CONFIG_STUBDOM
7837 if (xenfb_pv_display_init(ds) == 0) {
7838 } else
7839 #endif
7840 if (nographic) {
7841 dumb_display_init(ds);
7842 } else if (vnc_display != NULL || vncunused != 0) {
7843 int vnc_display_port;
7844 char password[20];
7845 vnc_display_init(ds);
7846 xenstore_read_vncpasswd(domid, password, sizeof(password));
7847 vnc_display_password(ds, password);
7848 if ((vnc_display_port = vnc_display_open(ds, vnc_display, vncunused)) < 0)
7849 exit (0);
7850 #ifndef CONFIG_STUBDOM
7851 if (vncviewer)
7852 vnc_start_viewer(vnc_display_port);
7853 #endif
7854 xenstore_write_vncport(vnc_display_port);
7855 } else {
7856 #if defined(CONFIG_SDL)
7857 sdl_display_init(ds, full_screen);
7858 #elif defined(CONFIG_COCOA)
7859 cocoa_display_init(ds, full_screen);
7860 #else
7861 dumb_display_init(ds);
7862 #endif
7865 monitor_hd = qemu_chr_open(monitor_device);
7866 if (!monitor_hd) {
7867 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7868 exit(1);
7870 store_dev_info(monitor_device, domid, monitor_hd, "/monitor");
7871 monitor_init(monitor_hd, !nographic);
7873 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7874 const char *devname = serial_devices[i];
7875 if (devname[0] != '\0' && strcmp(devname, "none")) {
7876 char buf[16];
7877 serial_hds[i] = qemu_chr_open(devname);
7878 if (!serial_hds[i]) {
7879 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7880 devname);
7881 exit(1);
7883 snprintf(buf, sizeof(buf), "/serial/%d", i);
7884 store_dev_info(serial_devices[i], domid, serial_hds[i], buf);
7885 if (i == 0) /* serial 0 is also called the console */
7886 store_dev_info(serial_devices[i], domid,
7887 serial_hds[i], "/console");
7888 if (!strcmp(devname, "vc"))
7889 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7893 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7894 const char *devname = parallel_devices[i];
7895 if (devname[0] != '\0' && strcmp(devname, "none")) {
7896 char buf[16];
7897 parallel_hds[i] = qemu_chr_open(devname);
7898 if (!parallel_hds[i]) {
7899 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7900 devname);
7901 exit(1);
7903 snprintf(buf, sizeof(buf), "/parallel/%d", i);
7904 store_dev_info(parallel_devices[i], domid, parallel_hds[i], buf);
7905 if (!strcmp(devname, "vc"))
7906 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7910 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
7912 machine->init(ram_size, vga_ram_size, boot_device,
7913 ds, fd_filename, snapshot,
7914 kernel_filename, kernel_cmdline, initrd_filename,
7915 direct_pci);
7916 free(boot_device);
7918 /* init USB devices */
7919 if (usb_enabled) {
7920 for(i = 0; i < usb_devices_index; i++) {
7921 if (usb_device_add(usb_devices[i]) < 0) {
7922 fprintf(stderr, "Warning: could not add USB device %s\n",
7923 usb_devices[i]);
7928 if (vnc_display == NULL && vncunused == 0) {
7929 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7930 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7933 #ifdef CONFIG_GDBSTUB
7934 if (use_gdbstub) {
7935 /* XXX: use standard host:port notation and modify options
7936 accordingly. */
7937 if (gdbserver_start_port(gdbstub_port) < 0) {
7938 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7939 gdbstub_port);
7940 exit(1);
7942 } else
7943 #endif
7944 if (loadvm)
7945 do_loadvm(loadvm);
7948 /* XXX: simplify init */
7949 read_passwords();
7950 if (autostart) {
7951 vm_start();
7955 #ifndef NO_DAEMONIZE
7956 if (daemonize) {
7957 uint8_t status = 0;
7958 ssize_t len;
7959 int fd;
7961 again1:
7962 len = write(fds[1], &status, 1);
7963 if (len == -1 && (errno == EINTR))
7964 goto again1;
7966 if (len != 1)
7967 exit(1);
7969 fd = open("/dev/null", O_RDWR);
7970 if (fd == -1)
7971 exit(1);
7973 dup2(fd, 0);
7974 dup2(fd, 1);
7975 dup2(fd, 2);
7977 close(fd);
7979 #endif
7981 #ifndef CONFIG_STUBDOM
7982 /* Unblock SIGTERM and SIGHUP, which may have been blocked by the caller */
7983 signal(SIGHUP, SIG_DFL);
7984 sigemptyset(&set);
7985 sigaddset(&set, SIGTERM);
7986 sigaddset(&set, SIGHUP);
7987 if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
7988 fprintf(stderr, "Failed to unblock SIGTERM and SIGHUP\n");
7989 #endif
7991 main_loop();
7992 quit_timers();
7993 return 0;