ia64/xen-unstable

view tools/ioemu/vl.c @ 18394:dade7f0bdc8d

hvm: Use main memory for video memory.

When creating an HVM domain, if e.g. another domain is created before
qemu allocates video memory, the extra 8MB memory ballooning is not
available any more, because it got consumed by the other domain.

This fixes it by taking video memory from the main memory:

- make hvmloader use e820_malloc to reserve some of the main memory
and notify ioemu of its address through the Xen platform PCI card.
- add XENMAPSPACE_mfn to the xen_add_to_physmap memory op, to allow
ioemu to move the MFNs between the original position and the PCI
mapping, when LFB acceleration is disabled/enabled
- add a remove_from_physmap memory op, to allow ioemu to unmap it
completely for the case of old guests with acceleration disabled.
- add xc_domain_memory_translate_gpfn_list to libxc to allow ioemu to
get the MFNs of the video memory.
- have xend save the PCI memory space instead of ioemu: if a memory
page is there, the guest can access it like usual memory, so xend
can safely be responsible to save it. The extra benefit is that
live migration will apply the logdirty optimization there too.
- handle old saved images, populating the video memory from ioemu if
really needed.

Signed-off-by: Samuel Thibault <samuel.thibault@eu.citrix.com>
author Keir Fraser <keir.fraser@citrix.com>
date Wed Aug 27 14:53:39 2008 +0100 (2008-08-27)
parents 3ab0e76fb8e2
children
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
134 /* Max number of USB devices that can be specified on the commandline. */
135 #define MAX_USB_CMDLINE 8
137 /* XXX: use a two level table to limit memory usage */
138 #define MAX_IOPORTS 65536
140 /* Max number of PCI emulation */
141 #define MAX_PCI_EMULATION 32
143 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
144 void *ioport_opaque[MAX_IOPORTS];
145 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
146 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
147 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
148 to store the VM snapshots */
149 BlockDriverState *bs_table[MAX_DISKS + MAX_SCSI_DISKS + 1], *fd_table[MAX_FD];
150 /* point to the block driver where the snapshots are managed */
151 BlockDriverState *bs_snapshots;
152 int vga_ram_size;
153 int bios_size;
154 static DisplayState display_state;
155 int nographic;
156 int vncviewer;
157 int vncunused;
158 const char* keyboard_layout = NULL;
159 int64_t ticks_per_sec;
160 char *boot_device = NULL;
161 uint64_t ram_size;
162 int pit_min_timer_count = 0;
163 int nb_nics;
164 NICInfo nd_table[MAX_NICS];
165 QEMUTimer *gui_timer;
166 int vm_running;
167 int rtc_utc = 1;
168 int cirrus_vga_enabled = 1;
169 #ifdef TARGET_SPARC
170 int graphic_width = 1024;
171 int graphic_height = 768;
172 #else
173 int graphic_width = 800;
174 int graphic_height = 600;
175 #endif
176 int graphic_depth = 15;
177 int full_screen = 0;
178 #ifdef CONFIG_OPENGL
179 int opengl_enabled = 1;
180 #else
181 int opengl_enabled = 0;
182 #endif
183 int no_quit = 0;
184 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
185 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
186 #ifdef TARGET_I386
187 int win2k_install_hack = 0;
188 #endif
189 int usb_enabled = 0;
190 static VLANState *first_vlan;
191 int smp_cpus = 1;
192 const char *vnc_display;
193 #if defined(TARGET_SPARC)
194 #define MAX_CPUS 16
195 #elif defined(TARGET_I386)
196 #define MAX_CPUS 255
197 #else
198 #define MAX_CPUS 1
199 #endif
200 int acpi_enabled = 0;
201 int fd_bootchk = 1;
202 int no_reboot = 0;
203 #ifndef NO_DAEMONIZE
204 int daemonize = 0;
205 #endif
206 const char *option_rom[MAX_OPTION_ROMS];
207 int nb_option_roms;
208 int semihosting_enabled = 0;
209 int autostart = 1;
211 extern int vcpus;
213 int xc_handle;
215 char domain_name[64] = "Xen-no-name";
216 extern int domid;
218 PCI_EMULATION_INFO *PciEmulationInfoHead = NULL;
220 /***********************************************************/
221 /* x86 ISA bus support */
223 target_phys_addr_t isa_mem_base = 0;
224 PicState2 *isa_pic;
226 uint32_t default_ioport_readb(void *opaque, uint32_t address)
227 {
228 #ifdef DEBUG_UNUSED_IOPORT
229 fprintf(stderr, "inb: port=0x%04x\n", address);
230 #endif
231 return 0xff;
232 }
234 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
235 {
236 #ifdef DEBUG_UNUSED_IOPORT
237 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
238 #endif
239 }
241 /* default is to make two byte accesses */
242 uint32_t default_ioport_readw(void *opaque, uint32_t address)
243 {
244 uint32_t data;
245 IOPortReadFunc *func = ioport_read_table[0][address];
246 if (!func)
247 func = default_ioport_readb;
248 data = func(ioport_opaque[address], address);
249 address = (address + 1) & (MAX_IOPORTS - 1);
250 func = ioport_read_table[0][address];
251 if (!func)
252 func = default_ioport_readb;
253 data |= func(ioport_opaque[address], address) << 8;
254 return data;
255 }
257 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
258 {
259 IOPortWriteFunc *func = ioport_write_table[0][address];
260 if (!func)
261 func = default_ioport_writeb;
262 func(ioport_opaque[address], address, data & 0xff);
263 address = (address + 1) & (MAX_IOPORTS - 1);
264 func = ioport_write_table[0][address];
265 if (!func)
266 func = default_ioport_writeb;
267 func(ioport_opaque[address], address, (data >> 8) & 0xff);
268 }
270 uint32_t default_ioport_readl(void *opaque, uint32_t address)
271 {
272 #ifdef DEBUG_UNUSED_IOPORT
273 fprintf(stderr, "inl: port=0x%04x\n", address);
274 #endif
275 return 0xffffffff;
276 }
278 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
279 {
280 #ifdef DEBUG_UNUSED_IOPORT
281 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
282 #endif
283 }
285 void init_ioports(void)
286 {
287 }
289 /* size is the word size in byte */
290 int register_ioport_read(int start, int length, int size,
291 IOPortReadFunc *func, void *opaque)
292 {
293 int i, bsize;
295 if (size == 1) {
296 bsize = 0;
297 } else if (size == 2) {
298 bsize = 1;
299 } else if (size == 4) {
300 bsize = 2;
301 } else {
302 hw_error("register_ioport_read: invalid size");
303 return -1;
304 }
305 for(i = start; i < start + length; i += size) {
306 ioport_read_table[bsize][i] = func;
307 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
308 hw_error("register_ioport_write: invalid opaque");
309 ioport_opaque[i] = opaque;
310 }
311 return 0;
312 }
314 /* size is the word size in byte */
315 int register_ioport_write(int start, int length, int size,
316 IOPortWriteFunc *func, void *opaque)
317 {
318 int i, bsize;
320 if (size == 1) {
321 bsize = 0;
322 } else if (size == 2) {
323 bsize = 1;
324 } else if (size == 4) {
325 bsize = 2;
326 } else {
327 hw_error("register_ioport_write: invalid size");
328 return -1;
329 }
330 for(i = start; i < start + length; i += size) {
331 ioport_write_table[bsize][i] = func;
332 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
333 hw_error("register_ioport_write: invalid opaque");
334 ioport_opaque[i] = opaque;
335 }
336 return 0;
337 }
339 void isa_unassign_ioport(int start, int length)
340 {
341 int i;
343 for(i = start; i < start + length; i++) {
344 ioport_read_table[0][i] = default_ioport_readb;
345 ioport_read_table[1][i] = default_ioport_readw;
346 ioport_read_table[2][i] = default_ioport_readl;
348 ioport_write_table[0][i] = default_ioport_writeb;
349 ioport_write_table[1][i] = default_ioport_writew;
350 ioport_write_table[2][i] = default_ioport_writel;
351 }
352 }
354 /***********************************************************/
356 void cpu_outb(CPUState *env, int addr, int val)
357 {
358 IOPortWriteFunc *func = ioport_write_table[0][addr];
359 if (!func)
360 func = default_ioport_writeb;
361 #ifdef DEBUG_IOPORT
362 if (loglevel & CPU_LOG_IOPORT)
363 fprintf(logfile, "outb: %04x %02x\n", addr, val);
364 #endif
365 func(ioport_opaque[addr], addr, val);
366 #ifdef USE_KQEMU
367 if (env)
368 env->last_io_time = cpu_get_time_fast();
369 #endif
370 }
372 void cpu_outw(CPUState *env, int addr, int val)
373 {
374 IOPortWriteFunc *func = ioport_write_table[1][addr];
375 if (!func)
376 func = default_ioport_writew;
377 #ifdef DEBUG_IOPORT
378 if (loglevel & CPU_LOG_IOPORT)
379 fprintf(logfile, "outw: %04x %04x\n", addr, val);
380 #endif
381 func(ioport_opaque[addr], addr, val);
382 #ifdef USE_KQEMU
383 if (env)
384 env->last_io_time = cpu_get_time_fast();
385 #endif
386 }
388 void cpu_outl(CPUState *env, int addr, int val)
389 {
390 IOPortWriteFunc *func = ioport_write_table[2][addr];
391 if (!func)
392 func = default_ioport_writel;
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "outl: %04x %08x\n", addr, val);
396 #endif
397 func(ioport_opaque[addr], addr, val);
398 #ifdef USE_KQEMU
399 if (env)
400 env->last_io_time = cpu_get_time_fast();
401 #endif
402 }
404 int cpu_inb(CPUState *env, int addr)
405 {
406 int val;
407 IOPortReadFunc *func = ioport_read_table[0][addr];
408 if (!func)
409 func = default_ioport_readb;
410 val = func(ioport_opaque[addr], addr);
411 #ifdef DEBUG_IOPORT
412 if (loglevel & CPU_LOG_IOPORT)
413 fprintf(logfile, "inb : %04x %02x\n", addr, val);
414 #endif
415 #ifdef USE_KQEMU
416 if (env)
417 env->last_io_time = cpu_get_time_fast();
418 #endif
419 return val;
420 }
422 int cpu_inw(CPUState *env, int addr)
423 {
424 int val;
425 IOPortReadFunc *func = ioport_read_table[1][addr];
426 if (!func)
427 func = default_ioport_readw;
428 val = func(ioport_opaque[addr], addr);
429 #ifdef DEBUG_IOPORT
430 if (loglevel & CPU_LOG_IOPORT)
431 fprintf(logfile, "inw : %04x %04x\n", addr, val);
432 #endif
433 #ifdef USE_KQEMU
434 if (env)
435 env->last_io_time = cpu_get_time_fast();
436 #endif
437 return val;
438 }
440 int cpu_inl(CPUState *env, int addr)
441 {
442 int val;
443 IOPortReadFunc *func = ioport_read_table[2][addr];
444 if (!func)
445 func = default_ioport_readl;
446 val = func(ioport_opaque[addr], addr);
447 #ifdef DEBUG_IOPORT
448 if (loglevel & CPU_LOG_IOPORT)
449 fprintf(logfile, "inl : %04x %08x\n", addr, val);
450 #endif
451 #ifdef USE_KQEMU
452 if (env)
453 env->last_io_time = cpu_get_time_fast();
454 #endif
455 return val;
456 }
458 /***********************************************************/
459 void hw_error(const char *fmt, ...)
460 {
461 va_list ap;
462 #ifndef CONFIG_DM
463 CPUState *env;
464 #endif /* !CONFIG_DM */
466 va_start(ap, fmt);
467 fprintf(stderr, "qemu: hardware error: ");
468 vfprintf(stderr, fmt, ap);
469 fprintf(stderr, "\n");
470 #ifndef CONFIG_DM
471 for(env = first_cpu; env != NULL; env = env->next_cpu) {
472 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
473 #ifdef TARGET_I386
474 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
475 #else
476 cpu_dump_state(env, stderr, fprintf, 0);
477 #endif
478 }
479 #endif /* !CONFIG_DM */
480 va_end(ap);
481 abort();
482 }
484 /***********************************************************/
485 /* keyboard/mouse */
487 static QEMUPutKBDEvent *qemu_put_kbd_event;
488 static void *qemu_put_kbd_event_opaque;
489 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
490 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
492 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
493 {
494 qemu_put_kbd_event_opaque = opaque;
495 qemu_put_kbd_event = func;
496 }
498 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
499 void *opaque, int absolute,
500 const char *name)
501 {
502 QEMUPutMouseEntry *s, *cursor;
504 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
505 if (!s)
506 return NULL;
508 s->qemu_put_mouse_event = func;
509 s->qemu_put_mouse_event_opaque = opaque;
510 s->qemu_put_mouse_event_absolute = absolute;
511 s->qemu_put_mouse_event_name = qemu_strdup(name);
512 s->next = NULL;
514 if (!qemu_put_mouse_event_head) {
515 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
516 return s;
517 }
519 cursor = qemu_put_mouse_event_head;
520 while (cursor->next != NULL)
521 cursor = cursor->next;
523 cursor->next = s;
524 qemu_put_mouse_event_current = s;
526 return s;
527 }
529 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
530 {
531 QEMUPutMouseEntry *prev = NULL, *cursor;
533 if (!qemu_put_mouse_event_head || entry == NULL)
534 return;
536 cursor = qemu_put_mouse_event_head;
537 while (cursor != NULL && cursor != entry) {
538 prev = cursor;
539 cursor = cursor->next;
540 }
542 if (cursor == NULL) // does not exist or list empty
543 return;
544 else if (prev == NULL) { // entry is head
545 qemu_put_mouse_event_head = cursor->next;
546 if (qemu_put_mouse_event_current == entry)
547 qemu_put_mouse_event_current = cursor->next;
548 qemu_free(entry->qemu_put_mouse_event_name);
549 qemu_free(entry);
550 return;
551 }
553 prev->next = entry->next;
555 if (qemu_put_mouse_event_current == entry)
556 qemu_put_mouse_event_current = prev;
558 qemu_free(entry->qemu_put_mouse_event_name);
559 qemu_free(entry);
560 }
562 void kbd_put_keycode(int keycode)
563 {
564 if (qemu_put_kbd_event) {
565 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
566 }
567 }
569 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
570 {
571 QEMUPutMouseEvent *mouse_event;
572 void *mouse_event_opaque;
574 if (!qemu_put_mouse_event_current) {
575 return;
576 }
578 mouse_event =
579 qemu_put_mouse_event_current->qemu_put_mouse_event;
580 mouse_event_opaque =
581 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
583 if (mouse_event) {
584 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
585 }
586 }
588 int kbd_mouse_is_absolute(void)
589 {
590 if (!qemu_put_mouse_event_current)
591 return 0;
593 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
594 }
596 void do_info_mice(void)
597 {
598 QEMUPutMouseEntry *cursor;
599 int index = 0;
601 if (!qemu_put_mouse_event_head) {
602 term_printf("No mouse devices connected\n");
603 return;
604 }
606 term_printf("Mouse devices available:\n");
607 cursor = qemu_put_mouse_event_head;
608 while (cursor != NULL) {
609 term_printf("%c Mouse #%d: %s\n",
610 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
611 index, cursor->qemu_put_mouse_event_name);
612 index++;
613 cursor = cursor->next;
614 }
615 }
617 void do_mouse_set(int index)
618 {
619 QEMUPutMouseEntry *cursor;
620 int i = 0;
622 if (!qemu_put_mouse_event_head) {
623 term_printf("No mouse devices connected\n");
624 return;
625 }
627 cursor = qemu_put_mouse_event_head;
628 while (cursor != NULL && index != i) {
629 i++;
630 cursor = cursor->next;
631 }
633 if (cursor != NULL)
634 qemu_put_mouse_event_current = cursor;
635 else
636 term_printf("Mouse at given index not found\n");
637 }
639 /* compute with 96 bit intermediate result: (a*b)/c */
640 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
641 {
642 union {
643 uint64_t ll;
644 struct {
645 #ifdef WORDS_BIGENDIAN
646 uint32_t high, low;
647 #else
648 uint32_t low, high;
649 #endif
650 } l;
651 } u, res;
652 uint64_t rl, rh;
654 u.ll = a;
655 rl = (uint64_t)u.l.low * (uint64_t)b;
656 rh = (uint64_t)u.l.high * (uint64_t)b;
657 rh += (rl >> 32);
658 res.l.high = rh / c;
659 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
660 return res.ll;
661 }
663 /***********************************************************/
664 /* real time host monotonic timer */
666 #define QEMU_TIMER_BASE 1000000000LL
668 #ifdef WIN32
670 static int64_t clock_freq;
672 static void init_get_clock(void)
673 {
674 LARGE_INTEGER freq;
675 int ret;
676 ret = QueryPerformanceFrequency(&freq);
677 if (ret == 0) {
678 fprintf(stderr, "Could not calibrate ticks\n");
679 exit(1);
680 }
681 clock_freq = freq.QuadPart;
682 }
684 static int64_t get_clock(void)
685 {
686 LARGE_INTEGER ti;
687 QueryPerformanceCounter(&ti);
688 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
689 }
691 #else
693 static int use_rt_clock;
695 static void init_get_clock(void)
696 {
697 use_rt_clock = 0;
698 #if defined(__linux__)
699 {
700 struct timespec ts;
701 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
702 use_rt_clock = 1;
703 }
704 }
705 #endif
706 }
708 static int64_t get_clock(void)
709 {
710 #if defined(__linux__)
711 if (use_rt_clock) {
712 struct timespec ts;
713 clock_gettime(CLOCK_MONOTONIC, &ts);
714 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
715 } else
716 #endif
717 {
718 /* XXX: using gettimeofday leads to problems if the date
719 changes, so it should be avoided. */
720 struct timeval tv;
721 gettimeofday(&tv, NULL);
722 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
723 }
724 }
726 #endif
728 /***********************************************************/
729 /* guest cycle counter */
731 static int64_t cpu_ticks_prev;
732 static int64_t cpu_ticks_offset;
733 static int64_t cpu_clock_offset;
734 static int cpu_ticks_enabled;
736 /* return the host CPU cycle counter and handle stop/restart */
737 int64_t cpu_get_ticks(void)
738 {
739 if (!cpu_ticks_enabled) {
740 return cpu_ticks_offset;
741 } else {
742 int64_t ticks;
743 ticks = cpu_get_real_ticks();
744 if (cpu_ticks_prev > ticks) {
745 /* Note: non increasing ticks may happen if the host uses
746 software suspend */
747 cpu_ticks_offset += cpu_ticks_prev - ticks;
748 }
749 cpu_ticks_prev = ticks;
750 return ticks + cpu_ticks_offset;
751 }
752 }
754 /* return the host CPU monotonic timer and handle stop/restart */
755 static int64_t cpu_get_clock(void)
756 {
757 int64_t ti;
758 if (!cpu_ticks_enabled) {
759 return cpu_clock_offset;
760 } else {
761 ti = get_clock();
762 return ti + cpu_clock_offset;
763 }
764 }
766 /* enable cpu_get_ticks() */
767 void cpu_enable_ticks(void)
768 {
769 if (!cpu_ticks_enabled) {
770 cpu_ticks_offset -= cpu_get_real_ticks();
771 cpu_clock_offset -= get_clock();
772 cpu_ticks_enabled = 1;
773 }
774 }
776 /* disable cpu_get_ticks() : the clock is stopped. You must not call
777 cpu_get_ticks() after that. */
778 void cpu_disable_ticks(void)
779 {
780 if (cpu_ticks_enabled) {
781 cpu_ticks_offset = cpu_get_ticks();
782 cpu_clock_offset = cpu_get_clock();
783 cpu_ticks_enabled = 0;
784 }
785 }
787 /***********************************************************/
788 /* timers */
790 #define QEMU_TIMER_REALTIME 0
791 #define QEMU_TIMER_VIRTUAL 1
793 struct QEMUClock {
794 int type;
795 /* XXX: add frequency */
796 };
798 struct QEMUTimer {
799 QEMUClock *clock;
800 int64_t expire_time;
801 QEMUTimerCB *cb;
802 void *opaque;
803 struct QEMUTimer *next;
804 };
806 QEMUClock *rt_clock;
807 QEMUClock *vm_clock;
809 static QEMUTimer *active_timers[2];
810 #ifdef _WIN32
811 static MMRESULT timerID;
812 static HANDLE host_alarm = NULL;
813 static unsigned int period = 1;
814 #endif
816 QEMUClock *qemu_new_clock(int type)
817 {
818 QEMUClock *clock;
819 clock = qemu_mallocz(sizeof(QEMUClock));
820 if (!clock)
821 return NULL;
822 clock->type = type;
823 return clock;
824 }
826 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
827 {
828 QEMUTimer *ts;
830 ts = qemu_mallocz(sizeof(QEMUTimer));
831 ts->clock = clock;
832 ts->cb = cb;
833 ts->opaque = opaque;
834 return ts;
835 }
837 void qemu_free_timer(QEMUTimer *ts)
838 {
839 qemu_free(ts);
840 }
842 /* stop a timer, but do not dealloc it */
843 void qemu_del_timer(QEMUTimer *ts)
844 {
845 QEMUTimer **pt, *t;
847 /* NOTE: this code must be signal safe because
848 qemu_timer_expired() can be called from a signal. */
849 pt = &active_timers[ts->clock->type];
850 for(;;) {
851 t = *pt;
852 if (!t)
853 break;
854 if (t == ts) {
855 *pt = t->next;
856 break;
857 }
858 pt = &t->next;
859 }
860 }
862 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
863 {
864 if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
865 qemu_mod_timer(ts, expire_time);
866 }
868 /* modify the current timer so that it will be fired when current_time
869 >= expire_time. The corresponding callback will be called. */
870 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
871 {
872 QEMUTimer **pt, *t;
874 qemu_del_timer(ts);
876 /* add the timer in the sorted list */
877 /* NOTE: this code must be signal safe because
878 qemu_timer_expired() can be called from a signal. */
879 pt = &active_timers[ts->clock->type];
880 for(;;) {
881 t = *pt;
882 if (!t)
883 break;
884 if (t->expire_time > expire_time)
885 break;
886 pt = &t->next;
887 }
888 ts->expire_time = expire_time;
889 ts->next = *pt;
890 *pt = ts;
891 }
893 int qemu_timer_pending(QEMUTimer *ts)
894 {
895 QEMUTimer *t;
896 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
897 if (t == ts)
898 return 1;
899 }
900 return 0;
901 }
903 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
904 {
905 if (!timer_head)
906 return 0;
907 return (timer_head->expire_time <= current_time);
908 }
910 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
911 {
912 QEMUTimer *ts;
914 for(;;) {
915 ts = *ptimer_head;
916 if (!ts || ts->expire_time > current_time)
917 break;
918 /* remove timer from the list before calling the callback */
919 *ptimer_head = ts->next;
920 ts->next = NULL;
922 /* run the callback (the timer list can be modified) */
923 ts->cb(ts->opaque);
924 }
925 }
927 int64_t qemu_get_clock(QEMUClock *clock)
928 {
929 switch(clock->type) {
930 case QEMU_TIMER_REALTIME:
931 return get_clock() / 1000000;
932 default:
933 case QEMU_TIMER_VIRTUAL:
934 return cpu_get_clock();
935 }
936 }
938 static void init_timers(void)
939 {
940 init_get_clock();
941 ticks_per_sec = QEMU_TIMER_BASE;
942 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
943 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
944 }
946 /* save a timer */
947 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
948 {
949 uint64_t expire_time;
951 if (qemu_timer_pending(ts)) {
952 expire_time = ts->expire_time;
953 } else {
954 expire_time = -1;
955 }
956 qemu_put_be64(f, expire_time);
957 }
959 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
960 {
961 uint64_t expire_time;
963 expire_time = qemu_get_be64(f);
964 if (expire_time != -1) {
965 qemu_mod_timer(ts, expire_time);
966 } else {
967 qemu_del_timer(ts);
968 }
969 }
971 #ifdef CONFIG_DM
972 static void timer_save(QEMUFile *f, void *opaque)
973 {
974 /* need timer for save/restoe qemu_timer in usb_uhci */
975 if (cpu_ticks_enabled) {
976 hw_error("cannot save state if virtual timers are running");
977 }
978 qemu_put_be64s(f, &cpu_clock_offset);
979 }
981 static int timer_load(QEMUFile *f, void *opaque, int version_id)
982 {
983 if (version_id != 1 && version_id != 2)
984 return -EINVAL;
985 if (cpu_ticks_enabled) {
986 return -EINVAL;
987 }
989 qemu_get_be64s(f, &cpu_clock_offset);
990 return 0;
991 }
992 #else /* !CONFIG_DM */
993 static void timer_save(QEMUFile *f, void *opaque)
994 {
995 if (cpu_ticks_enabled) {
996 hw_error("cannot save state if virtual timers are running");
997 }
998 qemu_put_be64s(f, &cpu_ticks_offset);
999 qemu_put_be64s(f, &ticks_per_sec);
1000 qemu_put_be64s(f, &cpu_clock_offset);
1003 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1005 if (version_id != 1 && version_id != 2)
1006 return -EINVAL;
1007 if (cpu_ticks_enabled) {
1008 return -EINVAL;
1010 qemu_get_be64s(f, &cpu_ticks_offset);
1011 qemu_get_be64s(f, &ticks_per_sec);
1012 if (version_id == 2) {
1013 qemu_get_be64s(f, &cpu_clock_offset);
1015 return 0;
1018 #ifdef _WIN32
1019 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1020 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1021 #else
1022 static void host_alarm_handler(int host_signum)
1023 #endif
1025 #if 0
1026 #define DISP_FREQ 1000
1028 static int64_t delta_min = INT64_MAX;
1029 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1030 static int count;
1031 ti = qemu_get_clock(vm_clock);
1032 if (last_clock != 0) {
1033 delta = ti - last_clock;
1034 if (delta < delta_min)
1035 delta_min = delta;
1036 if (delta > delta_max)
1037 delta_max = delta;
1038 delta_cum += delta;
1039 if (++count == DISP_FREQ) {
1040 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1041 muldiv64(delta_min, 1000000, ticks_per_sec),
1042 muldiv64(delta_max, 1000000, ticks_per_sec),
1043 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1044 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1045 count = 0;
1046 delta_min = INT64_MAX;
1047 delta_max = 0;
1048 delta_cum = 0;
1051 last_clock = ti;
1053 #endif
1054 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1055 qemu_get_clock(vm_clock)) ||
1056 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1057 qemu_get_clock(rt_clock))) {
1058 #ifdef _WIN32
1059 SetEvent(host_alarm);
1060 #endif
1061 CPUState *env = cpu_single_env;
1062 if (env) {
1063 /* stop the currently executing cpu because a timer occured */
1064 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1065 #ifdef USE_KQEMU
1066 if (env->kqemu_enabled) {
1067 kqemu_cpu_interrupt(env);
1069 #endif
1074 #ifndef _WIN32
1076 #if defined(__linux__)
1078 #define RTC_FREQ 1024
1080 static int rtc_fd;
1082 static int start_rtc_timer(void)
1084 rtc_fd = open("/dev/rtc", O_RDONLY);
1085 if (rtc_fd < 0)
1086 return -1;
1087 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1088 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1089 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1090 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1091 goto fail;
1093 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1094 fail:
1095 close(rtc_fd);
1096 return -1;
1098 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1099 return 0;
1102 #else
1104 static int start_rtc_timer(void)
1106 return -1;
1109 #endif /* !defined(__linux__) */
1111 #endif /* !defined(_WIN32) */
1113 #endif /* !CONFIG_DM */
1115 static void init_timer_alarm(void)
1117 #ifdef _WIN32
1119 int count=0;
1120 TIMECAPS tc;
1122 ZeroMemory(&tc, sizeof(TIMECAPS));
1123 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1124 if (period < tc.wPeriodMin)
1125 period = tc.wPeriodMin;
1126 timeBeginPeriod(period);
1127 timerID = timeSetEvent(1, // interval (ms)
1128 period, // resolution
1129 host_alarm_handler, // function
1130 (DWORD)&count, // user parameter
1131 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1132 if( !timerID ) {
1133 perror("failed timer alarm");
1134 exit(1);
1136 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1137 if (!host_alarm) {
1138 perror("failed CreateEvent");
1139 exit(1);
1141 qemu_add_wait_object(host_alarm, NULL, NULL);
1143 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1144 #else
1146 #ifndef CONFIG_DM
1147 struct sigaction act;
1148 struct itimerval itv;
1149 #endif
1151 #ifndef CONFIG_DM
1152 /* timer signal */
1153 sigfillset(&act.sa_mask);
1154 act.sa_flags = 0;
1155 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1156 act.sa_flags |= SA_ONSTACK;
1157 #endif
1158 act.sa_handler = host_alarm_handler;
1159 sigaction(SIGALRM, &act, NULL);
1161 itv.it_interval.tv_sec = 0;
1162 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1163 itv.it_value.tv_sec = 0;
1164 itv.it_value.tv_usec = 10 * 1000;
1165 setitimer(ITIMER_REAL, &itv, NULL);
1166 /* we probe the tick duration of the kernel to inform the user if
1167 the emulated kernel requested a too high timer frequency */
1168 getitimer(ITIMER_REAL, &itv);
1170 #if defined(__linux__)
1171 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1172 have timers with 1 ms resolution. The correct solution will
1173 be to use the POSIX real time timers available in recent
1174 2.6 kernels */
1175 if (itv.it_interval.tv_usec > 1000 || 1) {
1176 /* try to use /dev/rtc to have a faster timer */
1177 if (start_rtc_timer() < 0)
1178 goto use_itimer;
1179 /* disable itimer */
1180 itv.it_interval.tv_sec = 0;
1181 itv.it_interval.tv_usec = 0;
1182 itv.it_value.tv_sec = 0;
1183 itv.it_value.tv_usec = 0;
1184 setitimer(ITIMER_REAL, &itv, NULL);
1186 /* use the RTC */
1187 sigaction(SIGIO, &act, NULL);
1188 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1189 fcntl(rtc_fd, F_SETOWN, getpid());
1190 } else
1191 #endif /* defined(__linux__) */
1193 use_itimer:
1194 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1195 PIT_FREQ) / 1000000;
1197 #endif /* CONFIG_DM */
1199 #endif
1202 void quit_timers(void)
1204 #ifdef _WIN32
1205 timeKillEvent(timerID);
1206 timeEndPeriod(period);
1207 if (host_alarm) {
1208 CloseHandle(host_alarm);
1209 host_alarm = NULL;
1211 #endif
1214 /***********************************************************/
1215 /* character device */
1217 static void qemu_chr_event(CharDriverState *s, int event)
1219 if (!s->chr_event)
1220 return;
1221 s->chr_event(s->handler_opaque, event);
1224 static void qemu_chr_reset_bh(void *opaque)
1226 CharDriverState *s = opaque;
1227 qemu_chr_event(s, CHR_EVENT_RESET);
1228 qemu_bh_delete(s->bh);
1229 s->bh = NULL;
1232 void qemu_chr_reset(CharDriverState *s)
1234 if (s->bh == NULL) {
1235 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1236 qemu_bh_schedule(s->bh);
1240 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1242 return s->chr_write(s, buf, len);
1245 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1247 if (!s->chr_ioctl)
1248 return -ENOTSUP;
1249 return s->chr_ioctl(s, cmd, arg);
1252 int qemu_chr_can_read(CharDriverState *s)
1254 if (!s->chr_can_read)
1255 return 0;
1256 return s->chr_can_read(s->handler_opaque);
1259 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1261 s->chr_read(s->handler_opaque, buf, len);
1265 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1267 char buf[4096];
1268 va_list ap;
1269 va_start(ap, fmt);
1270 vsnprintf(buf, sizeof(buf), fmt, ap);
1271 qemu_chr_write(s, buf, strlen(buf));
1272 va_end(ap);
1275 void qemu_chr_send_event(CharDriverState *s, int event)
1277 if (s->chr_send_event)
1278 s->chr_send_event(s, event);
1281 void qemu_chr_add_handlers(CharDriverState *s,
1282 IOCanRWHandler *fd_can_read,
1283 IOReadHandler *fd_read,
1284 IOEventHandler *fd_event,
1285 void *opaque)
1287 s->chr_can_read = fd_can_read;
1288 s->chr_read = fd_read;
1289 s->chr_event = fd_event;
1290 s->handler_opaque = opaque;
1291 if (s->chr_update_read_handler)
1292 s->chr_update_read_handler(s);
1295 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1297 return len;
1300 static CharDriverState *qemu_chr_open_null(void)
1302 CharDriverState *chr;
1304 chr = qemu_mallocz(sizeof(CharDriverState));
1305 if (!chr)
1306 return NULL;
1307 chr->chr_write = null_chr_write;
1308 return chr;
1311 #ifdef _WIN32
1313 static void socket_cleanup(void)
1315 WSACleanup();
1318 static int socket_init(void)
1320 WSADATA Data;
1321 int ret, err;
1323 ret = WSAStartup(MAKEWORD(2,2), &Data);
1324 if (ret != 0) {
1325 err = WSAGetLastError();
1326 fprintf(stderr, "WSAStartup: %d\n", err);
1327 return -1;
1329 atexit(socket_cleanup);
1330 return 0;
1333 static int send_all(int fd, const uint8_t *buf, int len1)
1335 int ret, len;
1337 len = len1;
1338 while (len > 0) {
1339 ret = send(fd, buf, len, 0);
1340 if (ret < 0) {
1341 int errno;
1342 errno = WSAGetLastError();
1343 if (errno != WSAEWOULDBLOCK) {
1344 return -1;
1346 } else if (ret == 0) {
1347 break;
1348 } else {
1349 buf += ret;
1350 len -= ret;
1353 return len1 - len;
1356 void socket_set_nonblock(int fd)
1358 unsigned long opt = 1;
1359 ioctlsocket(fd, FIONBIO, &opt);
1362 #else
1364 static int unix_write(int fd, const uint8_t *buf, int len1)
1366 int ret, sel_ret, len;
1367 int max_fd;
1368 fd_set writefds;
1369 struct timeval timeout;
1371 max_fd = fd;
1373 len = len1;
1374 while (len > 0) {
1375 FD_ZERO(&writefds);
1376 FD_SET(fd, &writefds);
1377 timeout.tv_sec = 0;
1378 timeout.tv_usec = 0;
1379 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1380 if (sel_ret <= 0) {
1381 /* Timeout or select error */
1382 return -1;
1383 } else {
1384 ret = write(fd, buf, len);
1385 if (ret < 0) {
1386 if (errno != EINTR && errno != EAGAIN)
1387 return -1;
1388 } else if (ret == 0) {
1389 break;
1390 } else {
1391 buf += ret;
1392 len -= ret;
1396 return len1 - len;
1399 static inline int send_all(int fd, const uint8_t *buf, int len1)
1401 return unix_write(fd, buf, len1);
1404 void socket_set_nonblock(int fd)
1406 fcntl(fd, F_SETFL, O_NONBLOCK);
1408 #endif /* !_WIN32 */
1410 #ifndef _WIN32
1412 typedef struct {
1413 int fd_in, fd_out;
1414 int max_size;
1415 } FDCharDriver;
1417 #define STDIO_MAX_CLIENTS 2
1419 static int stdio_nb_clients;
1420 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1422 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1424 FDCharDriver *s = chr->opaque;
1425 return unix_write(s->fd_out, buf, len);
1428 static int fd_chr_read_poll(void *opaque)
1430 CharDriverState *chr = opaque;
1431 FDCharDriver *s = chr->opaque;
1433 s->max_size = qemu_chr_can_read(chr);
1434 return s->max_size;
1437 static void fd_chr_read(void *opaque)
1439 CharDriverState *chr = opaque;
1440 FDCharDriver *s = chr->opaque;
1441 int size, len;
1442 uint8_t buf[1024];
1444 len = sizeof(buf);
1445 if (len > s->max_size)
1446 len = s->max_size;
1447 if (len == 0)
1448 return;
1449 size = read(s->fd_in, buf, len);
1450 if (size == 0) {
1451 /* FD has been closed. Remove it from the active list. */
1452 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1453 return;
1455 if (size > 0) {
1456 qemu_chr_read(chr, buf, size);
1460 static void fd_chr_update_read_handler(CharDriverState *chr)
1462 FDCharDriver *s = chr->opaque;
1464 if (s->fd_in >= 0) {
1465 if (nographic && s->fd_in == 0) {
1466 } else {
1467 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1468 fd_chr_read, NULL, chr);
1473 /* open a character device to a unix fd */
1474 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1476 CharDriverState *chr;
1477 FDCharDriver *s;
1479 chr = qemu_mallocz(sizeof(CharDriverState));
1480 if (!chr)
1481 return NULL;
1482 s = qemu_mallocz(sizeof(FDCharDriver));
1483 if (!s) {
1484 free(chr);
1485 return NULL;
1487 s->fd_in = fd_in;
1488 s->fd_out = fd_out;
1489 chr->opaque = s;
1490 chr->chr_write = fd_chr_write;
1491 chr->chr_update_read_handler = fd_chr_update_read_handler;
1493 qemu_chr_reset(chr);
1495 return chr;
1498 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1500 int fd_out;
1502 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1503 if (fd_out < 0)
1504 return NULL;
1505 return qemu_chr_open_fd(-1, fd_out);
1508 #ifndef CONFIG_STUBDOM
1509 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1511 int fd_in, fd_out;
1512 char filename_in[256], filename_out[256];
1514 snprintf(filename_in, 256, "%s.in", filename);
1515 snprintf(filename_out, 256, "%s.out", filename);
1516 fd_in = open(filename_in, O_RDWR | O_BINARY);
1517 fd_out = open(filename_out, O_RDWR | O_BINARY);
1518 if (fd_in < 0 || fd_out < 0) {
1519 if (fd_in >= 0)
1520 close(fd_in);
1521 if (fd_out >= 0)
1522 close(fd_out);
1523 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1524 if (fd_in < 0)
1525 return NULL;
1527 return qemu_chr_open_fd(fd_in, fd_out);
1531 /* for STDIO, we handle the case where several clients use it
1532 (nographic mode) */
1534 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1536 #define TERM_FIFO_MAX_SIZE 1
1538 static int term_got_escape, client_index;
1539 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1540 static int term_fifo_size;
1541 static int term_timestamps;
1542 static int64_t term_timestamps_start;
1544 void term_print_help(void)
1546 printf("\n"
1547 "C-a h print this help\n"
1548 "C-a x exit emulator\n"
1549 "C-a s save disk data back to file (if -snapshot)\n"
1550 "C-a b send break (magic sysrq)\n"
1551 "C-a t toggle console timestamps\n"
1552 "C-a c switch between console and monitor\n"
1553 "C-a C-a send C-a\n"
1554 );
1557 /* called when a char is received */
1558 static void stdio_received_byte(int ch)
1560 if (term_got_escape) {
1561 term_got_escape = 0;
1562 switch(ch) {
1563 case 'h':
1564 term_print_help();
1565 break;
1566 case 'x':
1567 exit(0);
1568 break;
1569 case 's':
1571 int i;
1572 for (i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
1573 if (bs_table[i])
1574 bdrv_commit(bs_table[i]);
1577 break;
1578 case 'b':
1579 if (client_index < stdio_nb_clients) {
1580 CharDriverState *chr;
1581 FDCharDriver *s;
1583 chr = stdio_clients[client_index];
1584 s = chr->opaque;
1585 qemu_chr_event(chr, CHR_EVENT_BREAK);
1587 break;
1588 case 'c':
1589 client_index++;
1590 if (client_index >= stdio_nb_clients)
1591 client_index = 0;
1592 if (client_index == 0) {
1593 /* send a new line in the monitor to get the prompt */
1594 ch = '\r';
1595 goto send_char;
1597 break;
1598 case 't':
1599 term_timestamps = !term_timestamps;
1600 term_timestamps_start = -1;
1601 break;
1602 case TERM_ESCAPE:
1603 goto send_char;
1605 } else if (ch == TERM_ESCAPE) {
1606 term_got_escape = 1;
1607 } else {
1608 send_char:
1609 if (client_index < stdio_nb_clients) {
1610 uint8_t buf[1];
1611 CharDriverState *chr;
1613 chr = stdio_clients[client_index];
1614 if (qemu_chr_can_read(chr) > 0) {
1615 buf[0] = ch;
1616 qemu_chr_read(chr, buf, 1);
1617 } else if (term_fifo_size == 0) {
1618 term_fifo[term_fifo_size++] = ch;
1624 static int stdio_read_poll(void *opaque)
1626 CharDriverState *chr;
1628 if (client_index < stdio_nb_clients) {
1629 chr = stdio_clients[client_index];
1630 /* try to flush the queue if needed */
1631 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1632 qemu_chr_read(chr, term_fifo, 1);
1633 term_fifo_size = 0;
1635 /* see if we can absorb more chars */
1636 if (term_fifo_size == 0)
1637 return 1;
1638 else
1639 return 0;
1640 } else {
1641 return 1;
1645 static void stdio_read(void *opaque)
1647 int size;
1648 uint8_t buf[1];
1650 size = read(0, buf, 1);
1651 if (size == 0) {
1652 /* stdin has been closed. Remove it from the active list. */
1653 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1654 return;
1656 if (size > 0)
1657 stdio_received_byte(buf[0]);
1660 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1662 FDCharDriver *s = chr->opaque;
1663 if (!term_timestamps) {
1664 return unix_write(s->fd_out, buf, len);
1665 } else {
1666 int i;
1667 char buf1[64];
1669 for(i = 0; i < len; i++) {
1670 unix_write(s->fd_out, buf + i, 1);
1671 if (buf[i] == '\n') {
1672 int64_t ti;
1673 int secs;
1675 ti = get_clock();
1676 if (term_timestamps_start == -1)
1677 term_timestamps_start = ti;
1678 ti -= term_timestamps_start;
1679 secs = ti / 1000000000;
1680 snprintf(buf1, sizeof(buf1),
1681 "[%02d:%02d:%02d.%03d] ",
1682 secs / 3600,
1683 (secs / 60) % 60,
1684 secs % 60,
1685 (int)((ti / 1000000) % 1000));
1686 unix_write(s->fd_out, buf1, strlen(buf1));
1689 return len;
1693 /* init terminal so that we can grab keys */
1694 static struct termios oldtty;
1695 static int old_fd0_flags;
1697 static void term_exit(void)
1699 tcsetattr (0, TCSANOW, &oldtty);
1700 fcntl(0, F_SETFL, old_fd0_flags);
1703 static void term_init(void)
1705 struct termios tty;
1707 tcgetattr (0, &tty);
1708 oldtty = tty;
1709 old_fd0_flags = fcntl(0, F_GETFL);
1711 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1712 |INLCR|IGNCR|ICRNL|IXON);
1713 tty.c_oflag |= OPOST;
1714 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1715 /* if graphical mode, we allow Ctrl-C handling */
1716 if (nographic)
1717 tty.c_lflag &= ~ISIG;
1718 tty.c_cflag &= ~(CSIZE|PARENB);
1719 tty.c_cflag |= CS8;
1720 tty.c_cc[VMIN] = 1;
1721 tty.c_cc[VTIME] = 0;
1723 tcsetattr (0, TCSANOW, &tty);
1725 atexit(term_exit);
1727 fcntl(0, F_SETFL, O_NONBLOCK);
1730 static CharDriverState *qemu_chr_open_stdio(void)
1732 CharDriverState *chr;
1734 if (nographic) {
1735 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1736 return NULL;
1737 chr = qemu_chr_open_fd(0, 1);
1738 chr->chr_write = stdio_write;
1739 if (stdio_nb_clients == 0)
1740 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1741 client_index = stdio_nb_clients;
1742 } else {
1743 if (stdio_nb_clients != 0)
1744 return NULL;
1745 chr = qemu_chr_open_fd(0, 1);
1747 stdio_clients[stdio_nb_clients++] = chr;
1748 if (stdio_nb_clients == 1) {
1749 /* set the terminal in raw mode */
1750 term_init();
1752 return chr;
1754 #endif
1756 /*
1757 * Create a store entry for a device (e.g., monitor, serial/parallel lines).
1758 * The entry is <domain-path><storeString>/tty and the value is the name
1759 * of the pty associated with the device.
1760 */
1761 static int store_dev_info(char *devName, int domid,
1762 CharDriverState *cState, char *storeString)
1764 #ifdef CONFIG_STUBDOM
1765 fprintf(logfile, "can't store dev %s name for domid %d in %s from a stub domain\n", devName, domid, storeString);
1766 return ENOSYS;
1767 #else
1768 int xc_handle;
1769 struct xs_handle *xs;
1770 char *path;
1771 char *newpath;
1772 FDCharDriver *s;
1773 char *pts;
1775 /* Check for valid arguments (at least, prevent segfaults). */
1776 if ((devName == NULL) || (cState == NULL) || (storeString == NULL)) {
1777 fprintf(logfile, "%s - invalid arguments\n", __FUNCTION__);
1778 return EINVAL;
1781 /*
1782 * Only continue if we're talking to a pty
1783 * Actually, the following code works for any CharDriverState using
1784 * FDCharDriver, but we really only care about pty's here
1785 */
1786 if (strcmp(devName, "pty"))
1787 return 0;
1789 s = cState->opaque;
1790 if (s == NULL) {
1791 fprintf(logfile, "%s - unable to retrieve fd for '%s'/'%s'\n",
1792 __FUNCTION__, storeString, devName);
1793 return EBADF;
1796 pts = ptsname(s->fd_in);
1797 if (pts == NULL) {
1798 fprintf(logfile, "%s - unable to determine ptsname '%s'/'%s', "
1799 "error %d (%s)\n",
1800 __FUNCTION__, storeString, devName, errno, strerror(errno));
1801 return errno;
1804 /* We now have everything we need to set the xenstore entry. */
1805 xs = xs_daemon_open();
1806 if (xs == NULL) {
1807 fprintf(logfile, "Could not contact XenStore\n");
1808 return -1;
1811 xc_handle = xc_interface_open();
1812 if (xc_handle == -1) {
1813 fprintf(logfile, "xc_interface_open() error\n");
1814 return -1;
1817 path = xs_get_domain_path(xs, domid);
1818 if (path == NULL) {
1819 fprintf(logfile, "xs_get_domain_path() error\n");
1820 return -1;
1822 newpath = realloc(path, (strlen(path) + strlen(storeString) +
1823 strlen("/tty") + 1));
1824 if (newpath == NULL) {
1825 free(path); /* realloc errors leave old block */
1826 fprintf(logfile, "realloc error\n");
1827 return -1;
1829 path = newpath;
1831 strcat(path, storeString);
1832 strcat(path, "/tty");
1833 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1834 fprintf(logfile, "xs_write for '%s' fail", storeString);
1835 return -1;
1838 free(path);
1839 xs_daemon_close(xs);
1840 close(xc_handle);
1842 return 0;
1843 #endif
1846 #ifndef CONFIG_STUBDOM
1847 #ifdef __sun__
1848 /* Once Solaris has openpty(), this is going to be removed. */
1849 int openpty(int *amaster, int *aslave, char *name,
1850 struct termios *termp, struct winsize *winp)
1852 const char *slave;
1853 int mfd = -1, sfd = -1;
1855 *amaster = *aslave = -1;
1857 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
1858 if (mfd < 0)
1859 goto err;
1861 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
1862 goto err;
1864 if ((slave = ptsname(mfd)) == NULL)
1865 goto err;
1867 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
1868 goto err;
1870 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
1871 (termp != NULL && tcgetattr(sfd, termp) < 0))
1872 goto err;
1874 if (amaster)
1875 *amaster = mfd;
1876 if (aslave)
1877 *aslave = sfd;
1878 if (winp)
1879 ioctl(sfd, TIOCSWINSZ, winp);
1881 return 0;
1883 err:
1884 if (sfd != -1)
1885 close(sfd);
1886 close(mfd);
1887 return -1;
1890 void cfmakeraw (struct termios *termios_p)
1892 termios_p->c_iflag &=
1893 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
1894 termios_p->c_oflag &= ~OPOST;
1895 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1896 termios_p->c_cflag &= ~(CSIZE|PARENB);
1897 termios_p->c_cflag |= CS8;
1899 termios_p->c_cc[VMIN] = 0;
1900 termios_p->c_cc[VTIME] = 0;
1903 #endif
1905 #if defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__sun__)
1906 static CharDriverState *qemu_chr_open_pty(void)
1908 struct termios tty;
1909 int master_fd, slave_fd;
1911 /* Not satisfying */
1912 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1913 return NULL;
1916 /* Set raw attributes on the pty. */
1917 cfmakeraw(&tty);
1918 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1920 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1922 return qemu_chr_open_fd(master_fd, master_fd);
1925 static void tty_serial_init(int fd, int speed,
1926 int parity, int data_bits, int stop_bits)
1928 struct termios tty;
1929 speed_t spd;
1931 #if 0
1932 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1933 speed, parity, data_bits, stop_bits);
1934 #endif
1935 tcgetattr (fd, &tty);
1937 switch(speed) {
1938 case 50:
1939 spd = B50;
1940 break;
1941 case 75:
1942 spd = B75;
1943 break;
1944 case 300:
1945 spd = B300;
1946 break;
1947 case 600:
1948 spd = B600;
1949 break;
1950 case 1200:
1951 spd = B1200;
1952 break;
1953 case 2400:
1954 spd = B2400;
1955 break;
1956 case 4800:
1957 spd = B4800;
1958 break;
1959 case 9600:
1960 spd = B9600;
1961 break;
1962 case 19200:
1963 spd = B19200;
1964 break;
1965 case 38400:
1966 spd = B38400;
1967 break;
1968 case 57600:
1969 spd = B57600;
1970 break;
1971 default:
1972 case 115200:
1973 spd = B115200;
1974 break;
1977 cfsetispeed(&tty, spd);
1978 cfsetospeed(&tty, spd);
1980 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1981 |INLCR|IGNCR|ICRNL|IXON);
1982 tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1983 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1984 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1985 switch(data_bits) {
1986 default:
1987 case 8:
1988 tty.c_cflag |= CS8;
1989 break;
1990 case 7:
1991 tty.c_cflag |= CS7;
1992 break;
1993 case 6:
1994 tty.c_cflag |= CS6;
1995 break;
1996 case 5:
1997 tty.c_cflag |= CS5;
1998 break;
2000 switch(parity) {
2001 default:
2002 case 'N':
2003 break;
2004 case 'E':
2005 tty.c_cflag |= PARENB;
2006 break;
2007 case 'O':
2008 tty.c_cflag |= PARENB | PARODD;
2009 break;
2011 if (stop_bits == 2)
2012 tty.c_cflag |= CSTOPB;
2014 tcsetattr (fd, TCSANOW, &tty);
2017 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2019 FDCharDriver *s = chr->opaque;
2021 switch(cmd) {
2022 case CHR_IOCTL_SERIAL_SET_PARAMS:
2024 QEMUSerialSetParams *ssp = arg;
2025 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2026 ssp->data_bits, ssp->stop_bits);
2028 break;
2029 case CHR_IOCTL_SERIAL_SET_BREAK:
2031 int enable = *(int *)arg;
2032 if (enable)
2033 tcsendbreak(s->fd_in, 1);
2035 break;
2036 case CHR_IOCTL_SERIAL_GET_TIOCM:
2038 ioctl(s->fd_in, TIOCMGET, arg);
2040 break;
2041 case CHR_IOCTL_SERIAL_SET_TIOCM:
2043 ioctl(s->fd_in, TIOCMSET, arg);
2045 break;
2046 default:
2047 return -ENOTSUP;
2049 return 0;
2052 static CharDriverState *qemu_chr_open_tty(const char *filename)
2054 CharDriverState *chr;
2055 int fd;
2057 fd = open(filename, O_RDWR | O_NONBLOCK);
2058 if (fd < 0)
2059 return NULL;
2060 fcntl(fd, F_SETFL, O_NONBLOCK);
2061 tty_serial_init(fd, 115200, 'N', 8, 1);
2062 chr = qemu_chr_open_fd(fd, fd);
2063 if (!chr)
2064 return NULL;
2065 chr->chr_ioctl = tty_serial_ioctl;
2066 qemu_chr_reset(chr);
2067 return chr;
2070 #if defined(__linux__)
2071 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2073 int fd = (int)chr->opaque;
2074 uint8_t b;
2076 switch(cmd) {
2077 case CHR_IOCTL_PP_READ_DATA:
2078 if (ioctl(fd, PPRDATA, &b) < 0)
2079 return -ENOTSUP;
2080 *(uint8_t *)arg = b;
2081 break;
2082 case CHR_IOCTL_PP_WRITE_DATA:
2083 b = *(uint8_t *)arg;
2084 if (ioctl(fd, PPWDATA, &b) < 0)
2085 return -ENOTSUP;
2086 break;
2087 case CHR_IOCTL_PP_READ_CONTROL:
2088 if (ioctl(fd, PPRCONTROL, &b) < 0)
2089 return -ENOTSUP;
2090 *(uint8_t *)arg = b;
2091 break;
2092 case CHR_IOCTL_PP_WRITE_CONTROL:
2093 b = *(uint8_t *)arg;
2094 if (ioctl(fd, PPWCONTROL, &b) < 0)
2095 return -ENOTSUP;
2096 break;
2097 case CHR_IOCTL_PP_READ_STATUS:
2098 if (ioctl(fd, PPRSTATUS, &b) < 0)
2099 return -ENOTSUP;
2100 *(uint8_t *)arg = b;
2101 break;
2102 default:
2103 return -ENOTSUP;
2105 return 0;
2108 static CharDriverState *qemu_chr_open_pp(const char *filename)
2110 CharDriverState *chr;
2111 int fd;
2113 fd = open(filename, O_RDWR);
2114 if (fd < 0)
2115 return NULL;
2117 if (ioctl(fd, PPCLAIM) < 0) {
2118 close(fd);
2119 return NULL;
2122 chr = qemu_mallocz(sizeof(CharDriverState));
2123 if (!chr) {
2124 close(fd);
2125 return NULL;
2127 chr->opaque = (void *)fd;
2128 chr->chr_write = null_chr_write;
2129 chr->chr_ioctl = pp_ioctl;
2131 qemu_chr_reset(chr);
2133 return chr;
2135 #endif /* __linux__ */
2137 #else
2138 static CharDriverState *qemu_chr_open_pty(void)
2140 return NULL;
2142 #endif /* __linux__ || __NetBSD__ || __OpenBSD__ || __sun__ */
2144 #endif /* !defined(_WIN32) */
2146 #ifdef _WIN32
2147 typedef struct {
2148 CharDriverState *chr;
2149 int max_size;
2150 HANDLE hcom, hrecv, hsend;
2151 OVERLAPPED orecv, osend;
2152 BOOL fpipe;
2153 DWORD len;
2154 } WinCharState;
2156 #define NSENDBUF 2048
2157 #define NRECVBUF 2048
2158 #define MAXCONNECT 1
2159 #define NTIMEOUT 5000
2161 static int win_chr_poll(void *opaque);
2162 static int win_chr_pipe_poll(void *opaque);
2164 static void win_chr_close2(WinCharState *s)
2166 if (s->hsend) {
2167 CloseHandle(s->hsend);
2168 s->hsend = NULL;
2170 if (s->hrecv) {
2171 CloseHandle(s->hrecv);
2172 s->hrecv = NULL;
2174 if (s->hcom) {
2175 CloseHandle(s->hcom);
2176 s->hcom = NULL;
2178 if (s->fpipe)
2179 qemu_del_polling_cb(win_chr_pipe_poll, s);
2180 else
2181 qemu_del_polling_cb(win_chr_poll, s);
2184 static void win_chr_close(CharDriverState *chr)
2186 WinCharState *s = chr->opaque;
2187 win_chr_close2(s);
2190 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
2192 COMMCONFIG comcfg;
2193 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2194 COMSTAT comstat;
2195 DWORD size;
2196 DWORD err;
2198 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2199 if (!s->hsend) {
2200 fprintf(stderr, "Failed CreateEvent\n");
2201 goto fail;
2203 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2204 if (!s->hrecv) {
2205 fprintf(stderr, "Failed CreateEvent\n");
2206 goto fail;
2209 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2210 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2211 if (s->hcom == INVALID_HANDLE_VALUE) {
2212 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2213 s->hcom = NULL;
2214 goto fail;
2217 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2218 fprintf(stderr, "Failed SetupComm\n");
2219 goto fail;
2222 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2223 size = sizeof(COMMCONFIG);
2224 GetDefaultCommConfig(filename, &comcfg, &size);
2225 comcfg.dcb.DCBlength = sizeof(DCB);
2226 CommConfigDialog(filename, NULL, &comcfg);
2228 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2229 fprintf(stderr, "Failed SetCommState\n");
2230 goto fail;
2233 if (!SetCommMask(s->hcom, EV_ERR)) {
2234 fprintf(stderr, "Failed SetCommMask\n");
2235 goto fail;
2238 cto.ReadIntervalTimeout = MAXDWORD;
2239 if (!SetCommTimeouts(s->hcom, &cto)) {
2240 fprintf(stderr, "Failed SetCommTimeouts\n");
2241 goto fail;
2244 if (!ClearCommError(s->hcom, &err, &comstat)) {
2245 fprintf(stderr, "Failed ClearCommError\n");
2246 goto fail;
2248 s->chr = chr;
2249 qemu_add_polling_cb(win_chr_poll, s);
2250 return 0;
2252 fail:
2253 win_chr_close2(s);
2254 return -1;
2257 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2259 WinCharState *s = chr->opaque;
2260 DWORD len, ret, size, err;
2262 len = len1;
2263 ZeroMemory(&s->osend, sizeof(s->osend));
2264 s->osend.hEvent = s->hsend;
2265 while (len > 0) {
2266 if (s->hsend)
2267 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2268 else
2269 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2270 if (!ret) {
2271 err = GetLastError();
2272 if (err == ERROR_IO_PENDING) {
2273 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2274 if (ret) {
2275 buf += size;
2276 len -= size;
2277 } else {
2278 break;
2280 } else {
2281 break;
2283 } else {
2284 buf += size;
2285 len -= size;
2288 return len1 - len;
2291 static int win_chr_read_poll(WinCharState *s)
2293 s->max_size = qemu_chr_can_read(s->chr);
2294 return s->max_size;
2297 static void win_chr_readfile(WinCharState *s)
2299 int ret, err;
2300 uint8_t buf[1024];
2301 DWORD size;
2303 ZeroMemory(&s->orecv, sizeof(s->orecv));
2304 s->orecv.hEvent = s->hrecv;
2305 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2306 if (!ret) {
2307 err = GetLastError();
2308 if (err == ERROR_IO_PENDING) {
2309 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2313 if (size > 0) {
2314 qemu_chr_read(s->chr, buf, size);
2318 static void win_chr_read(WinCharState *s)
2320 if (s->len > s->max_size)
2321 s->len = s->max_size;
2322 if (s->len == 0)
2323 return;
2325 win_chr_readfile(s);
2328 static int win_chr_poll(void *opaque)
2330 WinCharState *s = opaque;
2331 COMSTAT status;
2332 DWORD comerr;
2334 ClearCommError(s->hcom, &comerr, &status);
2335 if (status.cbInQue > 0) {
2336 s->len = status.cbInQue;
2337 win_chr_read_poll(s);
2338 win_chr_read(s);
2339 return 1;
2341 return 0;
2344 static CharDriverState *qemu_chr_open_win(const char *filename)
2346 CharDriverState *chr;
2347 WinCharState *s;
2349 chr = qemu_mallocz(sizeof(CharDriverState));
2350 if (!chr)
2351 return NULL;
2352 s = qemu_mallocz(sizeof(WinCharState));
2353 if (!s) {
2354 free(chr);
2355 return NULL;
2357 chr->opaque = s;
2358 chr->chr_write = win_chr_write;
2359 chr->chr_close = win_chr_close;
2361 if (win_chr_init(s, chr, filename) < 0) {
2362 free(s);
2363 free(chr);
2364 return NULL;
2366 qemu_chr_reset(chr);
2367 return chr;
2370 static int win_chr_pipe_poll(void *opaque)
2372 WinCharState *s = opaque;
2373 DWORD size;
2375 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2376 if (size > 0) {
2377 s->len = size;
2378 win_chr_read_poll(s);
2379 win_chr_read(s);
2380 return 1;
2382 return 0;
2385 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2387 OVERLAPPED ov;
2388 int ret;
2389 DWORD size;
2390 char openname[256];
2392 s->fpipe = TRUE;
2394 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2395 if (!s->hsend) {
2396 fprintf(stderr, "Failed CreateEvent\n");
2397 goto fail;
2399 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2400 if (!s->hrecv) {
2401 fprintf(stderr, "Failed CreateEvent\n");
2402 goto fail;
2405 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2406 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2407 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2408 PIPE_WAIT,
2409 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2410 if (s->hcom == INVALID_HANDLE_VALUE) {
2411 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2412 s->hcom = NULL;
2413 goto fail;
2416 ZeroMemory(&ov, sizeof(ov));
2417 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2418 ret = ConnectNamedPipe(s->hcom, &ov);
2419 if (ret) {
2420 fprintf(stderr, "Failed ConnectNamedPipe\n");
2421 goto fail;
2424 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2425 if (!ret) {
2426 fprintf(stderr, "Failed GetOverlappedResult\n");
2427 if (ov.hEvent) {
2428 CloseHandle(ov.hEvent);
2429 ov.hEvent = NULL;
2431 goto fail;
2434 if (ov.hEvent) {
2435 CloseHandle(ov.hEvent);
2436 ov.hEvent = NULL;
2438 qemu_add_polling_cb(win_chr_pipe_poll, s);
2439 return 0;
2441 fail:
2442 win_chr_close2(s);
2443 return -1;
2447 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2449 CharDriverState *chr;
2450 WinCharState *s;
2452 chr = qemu_mallocz(sizeof(CharDriverState));
2453 if (!chr)
2454 return NULL;
2455 s = qemu_mallocz(sizeof(WinCharState));
2456 if (!s) {
2457 free(chr);
2458 return NULL;
2460 chr->opaque = s;
2461 chr->chr_write = win_chr_write;
2462 chr->chr_close = win_chr_close;
2464 if (win_chr_pipe_init(s, filename) < 0) {
2465 free(s);
2466 free(chr);
2467 return NULL;
2469 qemu_chr_reset(chr);
2470 return chr;
2473 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2475 CharDriverState *chr;
2476 WinCharState *s;
2478 chr = qemu_mallocz(sizeof(CharDriverState));
2479 if (!chr)
2480 return NULL;
2481 s = qemu_mallocz(sizeof(WinCharState));
2482 if (!s) {
2483 free(chr);
2484 return NULL;
2486 s->hcom = fd_out;
2487 chr->opaque = s;
2488 chr->chr_write = win_chr_write;
2489 qemu_chr_reset(chr);
2490 return chr;
2493 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2495 HANDLE fd_out;
2497 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2498 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2499 if (fd_out == INVALID_HANDLE_VALUE)
2500 return NULL;
2502 return qemu_chr_open_win_file(fd_out);
2504 #endif
2505 #endif
2507 /***********************************************************/
2508 /* UDP Net console */
2510 typedef struct {
2511 int fd;
2512 struct sockaddr_in daddr;
2513 char buf[1024];
2514 int bufcnt;
2515 int bufptr;
2516 int max_size;
2517 } NetCharDriver;
2519 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2521 NetCharDriver *s = chr->opaque;
2523 return sendto(s->fd, buf, len, 0,
2524 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2527 static int udp_chr_read_poll(void *opaque)
2529 CharDriverState *chr = opaque;
2530 NetCharDriver *s = chr->opaque;
2532 s->max_size = qemu_chr_can_read(chr);
2534 /* If there were any stray characters in the queue process them
2535 * first
2536 */
2537 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2538 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2539 s->bufptr++;
2540 s->max_size = qemu_chr_can_read(chr);
2542 return s->max_size;
2545 static void udp_chr_read(void *opaque)
2547 CharDriverState *chr = opaque;
2548 NetCharDriver *s = chr->opaque;
2550 if (s->max_size == 0)
2551 return;
2552 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2553 s->bufptr = s->bufcnt;
2554 if (s->bufcnt <= 0)
2555 return;
2557 s->bufptr = 0;
2558 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2559 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2560 s->bufptr++;
2561 s->max_size = qemu_chr_can_read(chr);
2565 static void udp_chr_update_read_handler(CharDriverState *chr)
2567 NetCharDriver *s = chr->opaque;
2569 if (s->fd >= 0) {
2570 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2571 udp_chr_read, NULL, chr);
2575 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2576 #ifndef NO_UNIX_SOCKETS
2577 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2578 #endif
2579 int parse_host_src_port(struct sockaddr_in *haddr,
2580 struct sockaddr_in *saddr,
2581 const char *str);
2583 static CharDriverState *qemu_chr_open_udp(const char *def)
2585 CharDriverState *chr = NULL;
2586 NetCharDriver *s = NULL;
2587 int fd = -1;
2588 struct sockaddr_in saddr;
2590 chr = qemu_mallocz(sizeof(CharDriverState));
2591 if (!chr)
2592 goto return_err;
2593 s = qemu_mallocz(sizeof(NetCharDriver));
2594 if (!s)
2595 goto return_err;
2597 fd = socket(PF_INET, SOCK_DGRAM, 0);
2598 if (fd < 0) {
2599 perror("socket(PF_INET, SOCK_DGRAM)");
2600 goto return_err;
2603 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2604 printf("Could not parse: %s\n", def);
2605 goto return_err;
2608 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2610 perror("bind");
2611 goto return_err;
2614 s->fd = fd;
2615 s->bufcnt = 0;
2616 s->bufptr = 0;
2617 chr->opaque = s;
2618 chr->chr_write = udp_chr_write;
2619 chr->chr_update_read_handler = udp_chr_update_read_handler;
2620 return chr;
2622 return_err:
2623 if (chr)
2624 free(chr);
2625 if (s)
2626 free(s);
2627 if (fd >= 0)
2628 closesocket(fd);
2629 return NULL;
2632 /***********************************************************/
2633 /* TCP Net console */
2635 typedef struct {
2636 int fd, listen_fd;
2637 int connected;
2638 int max_size;
2639 int do_telnetopt;
2640 int do_nodelay;
2641 int is_unix;
2642 } TCPCharDriver;
2644 static void tcp_chr_accept(void *opaque);
2646 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2648 TCPCharDriver *s = chr->opaque;
2649 if (s->connected) {
2650 return send_all(s->fd, buf, len);
2651 } else {
2652 /* XXX: indicate an error ? */
2653 return len;
2657 static int tcp_chr_read_poll(void *opaque)
2659 CharDriverState *chr = opaque;
2660 TCPCharDriver *s = chr->opaque;
2661 if (!s->connected)
2662 return 0;
2663 s->max_size = qemu_chr_can_read(chr);
2664 return s->max_size;
2667 #define IAC 255
2668 #define IAC_BREAK 243
2669 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2670 TCPCharDriver *s,
2671 char *buf, int *size)
2673 /* Handle any telnet client's basic IAC options to satisfy char by
2674 * char mode with no echo. All IAC options will be removed from
2675 * the buf and the do_telnetopt variable will be used to track the
2676 * state of the width of the IAC information.
2678 * IAC commands come in sets of 3 bytes with the exception of the
2679 * "IAC BREAK" command and the double IAC.
2680 */
2682 int i;
2683 int j = 0;
2685 for (i = 0; i < *size; i++) {
2686 if (s->do_telnetopt > 1) {
2687 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2688 /* Double IAC means send an IAC */
2689 if (j != i)
2690 buf[j] = buf[i];
2691 j++;
2692 s->do_telnetopt = 1;
2693 } else {
2694 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2695 /* Handle IAC break commands by sending a serial break */
2696 qemu_chr_event(chr, CHR_EVENT_BREAK);
2697 s->do_telnetopt++;
2699 s->do_telnetopt++;
2701 if (s->do_telnetopt >= 4) {
2702 s->do_telnetopt = 1;
2704 } else {
2705 if ((unsigned char)buf[i] == IAC) {
2706 s->do_telnetopt = 2;
2707 } else {
2708 if (j != i)
2709 buf[j] = buf[i];
2710 j++;
2714 *size = j;
2717 static void tcp_chr_read(void *opaque)
2719 CharDriverState *chr = opaque;
2720 TCPCharDriver *s = chr->opaque;
2721 uint8_t buf[1024];
2722 int len, size;
2724 if (!s->connected || s->max_size <= 0)
2725 return;
2726 len = sizeof(buf);
2727 if (len > s->max_size)
2728 len = s->max_size;
2729 size = recv(s->fd, buf, len, 0);
2730 if (size == 0) {
2731 /* connection closed */
2732 s->connected = 0;
2733 if (s->listen_fd >= 0) {
2734 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2736 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2737 closesocket(s->fd);
2738 s->fd = -1;
2739 } else if (size > 0) {
2740 if (s->do_telnetopt)
2741 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2742 if (size > 0)
2743 qemu_chr_read(chr, buf, size);
2747 static void tcp_chr_connect(void *opaque)
2749 CharDriverState *chr = opaque;
2750 TCPCharDriver *s = chr->opaque;
2752 s->connected = 1;
2753 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2754 tcp_chr_read, NULL, chr);
2755 qemu_chr_reset(chr);
2758 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2759 static void tcp_chr_telnet_init(int fd)
2761 char buf[3];
2762 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2763 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2764 send(fd, (char *)buf, 3, 0);
2765 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2766 send(fd, (char *)buf, 3, 0);
2767 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2768 send(fd, (char *)buf, 3, 0);
2769 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2770 send(fd, (char *)buf, 3, 0);
2773 static void socket_set_nodelay(int fd)
2775 int val = 1;
2776 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2779 static void tcp_chr_accept(void *opaque)
2781 CharDriverState *chr = opaque;
2782 TCPCharDriver *s = chr->opaque;
2783 struct sockaddr_in saddr;
2784 #ifndef NO_UNIX_SOCKETS
2785 struct sockaddr_un uaddr;
2786 #endif
2787 struct sockaddr *addr;
2788 socklen_t len;
2789 int fd;
2791 for(;;) {
2792 #ifndef NO_UNIX_SOCKETS
2793 if (s->is_unix) {
2794 len = sizeof(uaddr);
2795 addr = (struct sockaddr *)&uaddr;
2796 } else
2797 #endif
2799 len = sizeof(saddr);
2800 addr = (struct sockaddr *)&saddr;
2802 fd = accept(s->listen_fd, addr, &len);
2803 if (fd < 0 && errno != EINTR) {
2804 return;
2805 } else if (fd >= 0) {
2806 if (s->do_telnetopt)
2807 tcp_chr_telnet_init(fd);
2808 break;
2811 socket_set_nonblock(fd);
2812 if (s->do_nodelay)
2813 socket_set_nodelay(fd);
2814 s->fd = fd;
2815 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2816 tcp_chr_connect(chr);
2819 static void tcp_chr_close(CharDriverState *chr)
2821 TCPCharDriver *s = chr->opaque;
2822 if (s->fd >= 0)
2823 closesocket(s->fd);
2824 if (s->listen_fd >= 0)
2825 closesocket(s->listen_fd);
2826 qemu_free(s);
2829 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2830 int is_telnet,
2831 int is_unix)
2833 CharDriverState *chr = NULL;
2834 TCPCharDriver *s = NULL;
2835 int fd = -1, ret, err, val;
2836 int is_listen = 0;
2837 int is_waitconnect = 1;
2838 int do_nodelay = 0;
2839 const char *ptr;
2840 struct sockaddr_in saddr;
2841 #ifndef NO_UNIX_SOCKETS
2842 struct sockaddr_un uaddr;
2843 #endif
2844 struct sockaddr *addr;
2845 socklen_t addrlen;
2847 #ifndef NO_UNIX_SOCKETS
2848 if (is_unix) {
2849 addr = (struct sockaddr *)&uaddr;
2850 addrlen = sizeof(uaddr);
2851 if (parse_unix_path(&uaddr, host_str) < 0)
2852 goto fail;
2853 } else
2854 #endif
2856 addr = (struct sockaddr *)&saddr;
2857 addrlen = sizeof(saddr);
2858 if (parse_host_port(&saddr, host_str) < 0)
2859 goto fail;
2862 ptr = host_str;
2863 while((ptr = strchr(ptr,','))) {
2864 ptr++;
2865 if (!strncmp(ptr,"server",6)) {
2866 is_listen = 1;
2867 } else if (!strncmp(ptr,"nowait",6)) {
2868 is_waitconnect = 0;
2869 } else if (!strncmp(ptr,"nodelay",6)) {
2870 do_nodelay = 1;
2871 } else {
2872 printf("Unknown option: %s\n", ptr);
2873 goto fail;
2876 if (!is_listen)
2877 is_waitconnect = 0;
2879 chr = qemu_mallocz(sizeof(CharDriverState));
2880 if (!chr)
2881 goto fail;
2882 s = qemu_mallocz(sizeof(TCPCharDriver));
2883 if (!s)
2884 goto fail;
2886 #ifndef NO_UNIX_SOCKETS
2887 if (is_unix)
2888 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2889 else
2890 #endif
2891 fd = socket(PF_INET, SOCK_STREAM, 0);
2893 if (fd < 0)
2894 goto fail;
2896 if (!is_waitconnect)
2897 socket_set_nonblock(fd);
2899 s->connected = 0;
2900 s->fd = -1;
2901 s->listen_fd = -1;
2902 s->is_unix = is_unix;
2903 s->do_nodelay = do_nodelay && !is_unix;
2905 chr->opaque = s;
2906 chr->chr_write = tcp_chr_write;
2907 chr->chr_close = tcp_chr_close;
2909 if (is_listen) {
2910 /* allow fast reuse */
2911 #ifndef NO_UNIX_SOCKETS
2912 if (is_unix) {
2913 char path[109];
2914 strncpy(path, uaddr.sun_path, 108);
2915 path[108] = 0;
2916 unlink(path);
2917 } else
2918 #endif
2920 val = 1;
2921 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2924 ret = bind(fd, addr, addrlen);
2925 if (ret < 0)
2926 goto fail;
2928 ret = listen(fd, 0);
2929 if (ret < 0)
2930 goto fail;
2932 s->listen_fd = fd;
2933 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2934 if (is_telnet)
2935 s->do_telnetopt = 1;
2936 } else {
2937 for(;;) {
2938 ret = connect(fd, addr, addrlen);
2939 if (ret < 0) {
2940 err = socket_error();
2941 if (err == EINTR || err == EWOULDBLOCK) {
2942 } else if (err == EINPROGRESS) {
2943 break;
2944 } else {
2945 goto fail;
2947 } else {
2948 s->connected = 1;
2949 break;
2952 s->fd = fd;
2953 socket_set_nodelay(fd);
2954 if (s->connected)
2955 tcp_chr_connect(chr);
2956 else
2957 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2960 if (is_listen && is_waitconnect) {
2961 printf("QEMU waiting for connection on: %s\n", host_str);
2962 tcp_chr_accept(chr);
2963 socket_set_nonblock(s->listen_fd);
2966 return chr;
2967 fail:
2968 if (fd >= 0)
2969 closesocket(fd);
2970 qemu_free(s);
2971 qemu_free(chr);
2972 return NULL;
2975 CharDriverState *qemu_chr_open(const char *filename)
2977 const char *p;
2979 if (!strcmp(filename, "vc")) {
2980 return text_console_init(&display_state);
2981 } else if (!strcmp(filename, "null")) {
2982 return qemu_chr_open_null();
2983 } else
2984 if (strstart(filename, "tcp:", &p)) {
2985 return qemu_chr_open_tcp(p, 0, 0);
2986 } else
2987 if (strstart(filename, "telnet:", &p)) {
2988 return qemu_chr_open_tcp(p, 1, 0);
2989 } else
2990 if (strstart(filename, "udp:", &p)) {
2991 return qemu_chr_open_udp(p);
2992 } else
2993 #ifndef _WIN32
2994 if (strstart(filename, "unix:", &p)) {
2995 return qemu_chr_open_tcp(p, 0, 1);
2996 } else if (strstart(filename, "file:", &p)) {
2997 return qemu_chr_open_file_out(p);
2998 #ifndef CONFIG_STUBDOM
2999 } else if (strstart(filename, "pipe:", &p)) {
3000 return qemu_chr_open_pipe(p);
3001 } else if (!strcmp(filename, "pty")) {
3002 return qemu_chr_open_pty();
3003 } else if (!strcmp(filename, "stdio")) {
3004 return qemu_chr_open_stdio();
3005 #endif
3006 } else
3007 #endif
3008 #if defined(__linux__)
3009 if (strstart(filename, "/dev/parport", NULL)) {
3010 return qemu_chr_open_pp(filename);
3011 } else
3012 if (strstart(filename, "/dev/", NULL)) {
3013 return qemu_chr_open_tty(filename);
3014 } else
3015 #endif
3016 #ifdef _WIN32
3017 if (strstart(filename, "COM", NULL)) {
3018 return qemu_chr_open_win(filename);
3019 } else
3020 if (strstart(filename, "pipe:", &p)) {
3021 return qemu_chr_open_win_pipe(p);
3022 } else
3023 if (strstart(filename, "file:", &p)) {
3024 return qemu_chr_open_win_file_out(p);
3026 #endif
3028 return NULL;
3032 void qemu_chr_close(CharDriverState *chr)
3034 if (chr->chr_close)
3035 chr->chr_close(chr);
3038 /***********************************************************/
3039 /* network device redirectors */
3041 void hex_dump(FILE *f, const uint8_t *buf, int size)
3043 int len, i, j, c;
3045 for(i=0;i<size;i+=16) {
3046 len = size - i;
3047 if (len > 16)
3048 len = 16;
3049 fprintf(f, "%08x ", i);
3050 for(j=0;j<16;j++) {
3051 if (j < len)
3052 fprintf(f, " %02x", buf[i+j]);
3053 else
3054 fprintf(f, " ");
3056 fprintf(f, " ");
3057 for(j=0;j<len;j++) {
3058 c = buf[i+j];
3059 if (c < ' ' || c > '~')
3060 c = '.';
3061 fprintf(f, "%c", c);
3063 fprintf(f, "\n");
3067 static int parse_macaddr(uint8_t *macaddr, const char *p)
3069 int i;
3070 for(i = 0; i < 6; i++) {
3071 macaddr[i] = strtol(p, (char **)&p, 16);
3072 if (i == 5) {
3073 if (*p != '\0')
3074 return -1;
3075 } else {
3076 if (*p != ':')
3077 return -1;
3078 p++;
3081 return 0;
3084 static int get_str_sep(char *buf, size_t buf_size, const char **pp, int sep)
3086 const char *p, *p1;
3087 int len;
3088 p = *pp;
3089 p1 = strchr(p, sep);
3090 if (!p1)
3091 return -1;
3092 len = p1 - p;
3093 p1++;
3094 if (buf_size > 0) {
3095 if (len > buf_size - 1)
3096 len = buf_size - 1;
3097 memcpy(buf, p, len);
3098 buf[len] = '\0';
3100 *pp = p1;
3101 return 0;
3104 int parse_host_src_port(struct sockaddr_in *haddr,
3105 struct sockaddr_in *saddr,
3106 const char *input_str)
3108 char *str = strdup(input_str);
3109 char *host_str = str;
3110 char *src_str;
3111 char *ptr;
3113 /*
3114 * Chop off any extra arguments at the end of the string which
3115 * would start with a comma, then fill in the src port information
3116 * if it was provided else use the "any address" and "any port".
3117 */
3118 if ((ptr = strchr(str,',')))
3119 *ptr = '\0';
3121 if ((src_str = strchr(input_str,'@'))) {
3122 *src_str = '\0';
3123 src_str++;
3126 if (parse_host_port(haddr, host_str) < 0)
3127 goto fail;
3129 if (!src_str || *src_str == '\0')
3130 src_str = ":0";
3132 if (parse_host_port(saddr, src_str) < 0)
3133 goto fail;
3135 free(str);
3136 return(0);
3138 fail:
3139 free(str);
3140 return -1;
3143 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3145 char buf[512];
3146 struct hostent *he;
3147 const char *p, *r;
3148 int port;
3150 p = str;
3151 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3152 return -1;
3153 saddr->sin_family = AF_INET;
3154 if (buf[0] == '\0') {
3155 saddr->sin_addr.s_addr = 0;
3156 } else {
3157 if (isdigit((uint8_t)buf[0])) {
3158 if (!inet_aton(buf, &saddr->sin_addr))
3159 return -1;
3160 } else {
3161 if ((he = gethostbyname(buf)) == NULL)
3162 return - 1;
3163 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3166 port = strtol(p, (char **)&r, 0);
3167 if (r == p)
3168 return -1;
3169 saddr->sin_port = htons(port);
3170 return 0;
3173 #ifndef NO_UNIX_SOCKETS
3174 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3176 const char *p;
3177 int len;
3179 len = MIN(108, strlen(str));
3180 p = strchr(str, ',');
3181 if (p)
3182 len = MIN(len, p - str);
3184 memset(uaddr, 0, sizeof(*uaddr));
3186 uaddr->sun_family = AF_UNIX;
3187 memcpy(uaddr->sun_path, str, len);
3189 return 0;
3191 #endif
3193 /* find or alloc a new VLAN */
3194 VLANState *qemu_find_vlan(int id)
3196 VLANState **pvlan, *vlan;
3197 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3198 if (vlan->id == id)
3199 return vlan;
3201 vlan = qemu_mallocz(sizeof(VLANState));
3202 if (!vlan)
3203 return NULL;
3204 vlan->id = id;
3205 vlan->next = NULL;
3206 pvlan = &first_vlan;
3207 while (*pvlan != NULL)
3208 pvlan = &(*pvlan)->next;
3209 *pvlan = vlan;
3210 return vlan;
3213 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3214 IOReadHandler *fd_read,
3215 IOCanRWHandler *fd_can_read,
3216 void *opaque)
3218 VLANClientState *vc, **pvc;
3219 vc = qemu_mallocz(sizeof(VLANClientState));
3220 if (!vc)
3221 return NULL;
3222 vc->fd_read = fd_read;
3223 vc->fd_can_read = fd_can_read;
3224 vc->opaque = opaque;
3225 vc->vlan = vlan;
3227 vc->next = NULL;
3228 pvc = &vlan->first_client;
3229 while (*pvc != NULL)
3230 pvc = &(*pvc)->next;
3231 *pvc = vc;
3232 return vc;
3235 int qemu_can_send_packet(VLANClientState *vc1)
3237 VLANState *vlan = vc1->vlan;
3238 VLANClientState *vc;
3240 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3241 if (vc != vc1) {
3242 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3243 return 0;
3246 return 1;
3249 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3251 VLANState *vlan = vc1->vlan;
3252 VLANClientState *vc;
3254 #if 0
3255 printf("vlan %d send:\n", vlan->id);
3256 hex_dump(stdout, buf, size);
3257 #endif
3258 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3259 if (vc != vc1) {
3260 vc->fd_read(vc->opaque, buf, size);
3265 #if defined(CONFIG_SLIRP)
3267 /* slirp network adapter */
3269 static int slirp_inited;
3270 static VLANClientState *slirp_vc;
3272 int slirp_can_output(void)
3274 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3277 void slirp_output(const uint8_t *pkt, int pkt_len)
3279 #if 0
3280 printf("slirp output:\n");
3281 hex_dump(stdout, pkt, pkt_len);
3282 #endif
3283 if (!slirp_vc)
3284 return;
3285 qemu_send_packet(slirp_vc, pkt, pkt_len);
3288 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3290 #if 0
3291 printf("slirp input:\n");
3292 hex_dump(stdout, buf, size);
3293 #endif
3294 slirp_input(buf, size);
3297 static int net_slirp_init(VLANState *vlan)
3299 if (!slirp_inited) {
3300 slirp_inited = 1;
3301 slirp_init();
3303 slirp_vc = qemu_new_vlan_client(vlan,
3304 slirp_receive, NULL, NULL);
3305 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3306 return 0;
3309 static void net_slirp_redir(const char *redir_str)
3311 int is_udp;
3312 char buf[256], *r;
3313 const char *p;
3314 struct in_addr guest_addr;
3315 int host_port, guest_port;
3317 if (!slirp_inited) {
3318 slirp_inited = 1;
3319 slirp_init();
3322 p = redir_str;
3323 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3324 goto fail;
3325 if (!strcmp(buf, "tcp")) {
3326 is_udp = 0;
3327 } else if (!strcmp(buf, "udp")) {
3328 is_udp = 1;
3329 } else {
3330 goto fail;
3333 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3334 goto fail;
3335 host_port = strtol(buf, &r, 0);
3336 if (r == buf)
3337 goto fail;
3339 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3340 goto fail;
3341 if (buf[0] == '\0') {
3342 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3344 if (!inet_aton(buf, &guest_addr))
3345 goto fail;
3347 guest_port = strtol(p, &r, 0);
3348 if (r == p)
3349 goto fail;
3351 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3352 fprintf(stderr, "qemu: could not set up redirection\n");
3353 exit(1);
3355 return;
3356 fail:
3357 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3358 exit(1);
3361 #ifndef _WIN32
3363 char smb_dir[1024];
3365 static void smb_exit(void)
3367 DIR *d;
3368 struct dirent *de;
3369 char filename[1024];
3371 /* erase all the files in the directory */
3372 d = opendir(smb_dir);
3373 for(;;) {
3374 de = readdir(d);
3375 if (!de)
3376 break;
3377 if (strcmp(de->d_name, ".") != 0 &&
3378 strcmp(de->d_name, "..") != 0) {
3379 snprintf(filename, sizeof(filename), "%s/%s",
3380 smb_dir, de->d_name);
3381 unlink(filename);
3384 closedir(d);
3385 rmdir(smb_dir);
3388 /* automatic user mode samba server configuration */
3389 void net_slirp_smb(const char *exported_dir)
3391 char smb_conf[1024];
3392 char smb_cmdline[1024];
3393 FILE *f;
3395 if (!slirp_inited) {
3396 slirp_inited = 1;
3397 slirp_init();
3400 /* XXX: better tmp dir construction */
3401 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3402 if (mkdir(smb_dir, 0700) < 0) {
3403 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3404 exit(1);
3406 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3408 f = fopen(smb_conf, "w");
3409 if (!f) {
3410 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3411 exit(1);
3413 fprintf(f,
3414 "[global]\n"
3415 "private dir=%s\n"
3416 "smb ports=0\n"
3417 "socket address=127.0.0.1\n"
3418 "pid directory=%s\n"
3419 "lock directory=%s\n"
3420 "log file=%s/log.smbd\n"
3421 "smb passwd file=%s/smbpasswd\n"
3422 "security = share\n"
3423 "[qemu]\n"
3424 "path=%s\n"
3425 "read only=no\n"
3426 "guest ok=yes\n",
3427 smb_dir,
3428 smb_dir,
3429 smb_dir,
3430 smb_dir,
3431 smb_dir,
3432 exported_dir
3433 );
3434 fclose(f);
3435 atexit(smb_exit);
3437 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3438 SMBD_COMMAND, smb_conf);
3440 slirp_add_exec(0, smb_cmdline, 4, 139);
3443 #endif /* !defined(_WIN32) */
3445 #endif /* CONFIG_SLIRP */
3447 #if !defined(_WIN32)
3449 typedef struct TAPState {
3450 VLANClientState *vc;
3451 int fd;
3452 } TAPState;
3454 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3456 TAPState *s = opaque;
3457 int ret;
3458 for(;;) {
3459 ret = write(s->fd, buf, size);
3460 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3461 } else {
3462 break;
3467 static void tap_send(void *opaque)
3469 TAPState *s = opaque;
3470 uint8_t buf[4096];
3471 int size;
3473 size = read(s->fd, buf, sizeof(buf));
3474 if (size > 0) {
3475 qemu_send_packet(s->vc, buf, size);
3479 /* fd support */
3481 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3483 TAPState *s;
3485 s = qemu_mallocz(sizeof(TAPState));
3486 if (!s)
3487 return NULL;
3488 s->fd = fd;
3489 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3490 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3491 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3492 return s;
3495 #ifdef CONFIG_STUBDOM
3496 #include <netfront.h>
3497 static int tap_open(char *ifname, int ifname_size)
3499 char nodename[64];
3500 static int num = 1; // 0 is for our own TCP/IP networking
3501 snprintf(nodename, sizeof(nodename), "device/vif/%d", num++);
3502 return netfront_tap_open(nodename);
3504 #elif defined(_BSD)
3505 static int tap_open(char *ifname, int ifname_size)
3507 int fd;
3508 #ifndef TAPGIFNAME
3509 char *dev;
3510 struct stat s;
3511 #endif
3512 struct ifreq ifr;
3514 fd = open("/dev/tap", O_RDWR);
3515 if (fd < 0) {
3516 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation %s\n", strerror(errno));
3517 return -1;
3520 #ifdef TAPGIFNAME
3521 if (ioctl (fd, TAPGIFNAME, (void*)&ifr) < 0) {
3522 fprintf(stderr, "warning: could not open get tap name: %s\n",
3523 strerror(errno));
3524 return -1;
3526 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3527 #else
3528 fstat(fd, &s);
3529 dev = devname(s.st_rdev, S_IFCHR);
3530 pstrcpy(ifname, ifname_size, dev);
3531 #endif
3533 fcntl(fd, F_SETFL, O_NONBLOCK);
3534 return fd;
3536 #elif defined(__sun__)
3537 static int tap_open(char *ifname, int ifname_size)
3539 fprintf(stderr, "warning: tap_open not yet implemented\n");
3540 return -1;
3542 #else
3543 static int tap_open(char *ifname, int ifname_size)
3545 struct ifreq ifr;
3546 int fd, ret, retries = 0;
3548 fd = open("/dev/net/tun", O_RDWR);
3549 if (fd < 0) {
3550 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3551 return -1;
3553 memset(&ifr, 0, sizeof(ifr));
3554 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3555 if (ifname[0] != '\0')
3556 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3557 else
3558 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3559 do {
3560 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3561 } while ((ret != 0) && (retries++ < 3));
3562 if (ret != 0) {
3563 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3564 close(fd);
3565 return -1;
3567 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3568 fcntl(fd, F_SETFL, O_NONBLOCK);
3569 return fd;
3571 #endif
3573 static int net_tap_init(VLANState *vlan, const char *ifname1,
3574 const char *setup_script, const char *bridge)
3576 TAPState *s;
3577 int pid, status, fd;
3578 char *args[4];
3579 char **parg;
3580 char ifname[128];
3582 memset(ifname, 0, sizeof(ifname));
3584 if (ifname1 != NULL)
3585 pstrcpy(ifname, sizeof(ifname), ifname1);
3586 else
3587 ifname[0] = '\0';
3588 fd = tap_open(ifname, sizeof(ifname));
3589 if (fd < 0)
3590 return -1;
3592 #ifndef CONFIG_STUBDOM
3593 if (!setup_script || !strcmp(setup_script, "no"))
3594 setup_script = "";
3595 if (setup_script[0] != '\0') {
3596 /* try to launch network init script */
3597 pid = fork();
3598 if (pid >= 0) {
3599 if (pid == 0) {
3600 int open_max = sysconf(_SC_OPEN_MAX), i;
3601 for (i = 0; i < open_max; i++)
3602 if (i != STDIN_FILENO &&
3603 i != STDOUT_FILENO &&
3604 i != STDERR_FILENO &&
3605 i != fd)
3606 close(i);
3608 parg = args;
3609 *parg++ = (char *)setup_script;
3610 *parg++ = ifname;
3611 *parg++ = (char *)bridge;
3612 *parg++ = NULL;
3613 execv(setup_script, args);
3614 _exit(1);
3616 while (waitpid(pid, &status, 0) != pid);
3617 if (!WIFEXITED(status) ||
3618 WEXITSTATUS(status) != 0) {
3619 fprintf(stderr, "%s: could not launch network script\n",
3620 setup_script);
3621 return -1;
3625 #endif
3626 s = net_tap_fd_init(vlan, fd);
3627 if (!s)
3628 return -1;
3629 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3630 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3631 return 0;
3634 #endif /* !_WIN32 */
3636 /* network connection */
3637 typedef struct NetSocketState {
3638 VLANClientState *vc;
3639 int fd;
3640 int state; /* 0 = getting length, 1 = getting data */
3641 int index;
3642 int packet_len;
3643 uint8_t buf[4096];
3644 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3645 } NetSocketState;
3647 typedef struct NetSocketListenState {
3648 VLANState *vlan;
3649 int fd;
3650 } NetSocketListenState;
3652 /* XXX: we consider we can send the whole packet without blocking */
3653 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3655 NetSocketState *s = opaque;
3656 uint32_t len;
3657 len = htonl(size);
3659 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3660 send_all(s->fd, buf, size);
3663 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3665 NetSocketState *s = opaque;
3666 sendto(s->fd, buf, size, 0,
3667 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3670 static void net_socket_send(void *opaque)
3672 NetSocketState *s = opaque;
3673 int l, size, err;
3674 uint8_t buf1[4096];
3675 const uint8_t *buf;
3677 size = recv(s->fd, buf1, sizeof(buf1), 0);
3678 if (size < 0) {
3679 err = socket_error();
3680 if (err != EWOULDBLOCK)
3681 goto eoc;
3682 } else if (size == 0) {
3683 /* end of connection */
3684 eoc:
3685 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3686 closesocket(s->fd);
3687 return;
3689 buf = buf1;
3690 while (size > 0) {
3691 /* reassemble a packet from the network */
3692 switch(s->state) {
3693 case 0:
3694 l = 4 - s->index;
3695 if (l > size)
3696 l = size;
3697 memcpy(s->buf + s->index, buf, l);
3698 buf += l;
3699 size -= l;
3700 s->index += l;
3701 if (s->index == 4) {
3702 /* got length */
3703 s->packet_len = ntohl(*(uint32_t *)s->buf);
3704 s->index = 0;
3705 s->state = 1;
3707 break;
3708 case 1:
3709 l = s->packet_len - s->index;
3710 if (l > size)
3711 l = size;
3712 memcpy(s->buf + s->index, buf, l);
3713 s->index += l;
3714 buf += l;
3715 size -= l;
3716 if (s->index >= s->packet_len) {
3717 qemu_send_packet(s->vc, s->buf, s->packet_len);
3718 s->index = 0;
3719 s->state = 0;
3721 break;
3726 static void net_socket_send_dgram(void *opaque)
3728 NetSocketState *s = opaque;
3729 int size;
3731 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3732 if (size < 0)
3733 return;
3734 if (size == 0) {
3735 /* end of connection */
3736 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3737 return;
3739 qemu_send_packet(s->vc, s->buf, size);
3742 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3744 struct ip_mreq imr;
3745 int fd;
3746 int val, ret;
3747 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3748 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3749 inet_ntoa(mcastaddr->sin_addr),
3750 (int)ntohl(mcastaddr->sin_addr.s_addr));
3751 return -1;
3754 fd = socket(PF_INET, SOCK_DGRAM, 0);
3755 if (fd < 0) {
3756 perror("socket(PF_INET, SOCK_DGRAM)");
3757 return -1;
3760 val = 1;
3761 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3762 (const char *)&val, sizeof(char));
3763 if (ret < 0) {
3764 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3765 goto fail;
3768 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3769 if (ret < 0) {
3770 perror("bind");
3771 goto fail;
3774 /* Add host to multicast group */
3775 imr.imr_multiaddr = mcastaddr->sin_addr;
3776 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3778 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3779 (const char *)&imr, sizeof(struct ip_mreq));
3780 if (ret < 0) {
3781 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3782 goto fail;
3785 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3786 val = 1;
3787 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3788 (const char *)&val, sizeof(val));
3789 if (ret < 0) {
3790 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3791 goto fail;
3794 socket_set_nonblock(fd);
3795 return fd;
3796 fail:
3797 if (fd >= 0)
3798 closesocket(fd);
3799 return -1;
3802 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3803 int is_connected)
3805 struct sockaddr_in saddr;
3806 int newfd;
3807 socklen_t saddr_len;
3808 NetSocketState *s;
3810 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3811 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3812 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3813 */
3815 if (is_connected) {
3816 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3817 /* must be bound */
3818 if (saddr.sin_addr.s_addr==0) {
3819 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3820 fd);
3821 return NULL;
3823 /* clone dgram socket */
3824 newfd = net_socket_mcast_create(&saddr);
3825 if (newfd < 0) {
3826 /* error already reported by net_socket_mcast_create() */
3827 close(fd);
3828 return NULL;
3830 /* clone newfd to fd, close newfd */
3831 dup2(newfd, fd);
3832 close(newfd);
3834 } else {
3835 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3836 fd, strerror(errno));
3837 return NULL;
3841 s = qemu_mallocz(sizeof(NetSocketState));
3842 if (!s)
3843 return NULL;
3844 s->fd = fd;
3846 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3847 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3849 /* mcast: save bound address as dst */
3850 if (is_connected) s->dgram_dst=saddr;
3852 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3853 "socket: fd=%d (%s mcast=%s:%d)",
3854 fd, is_connected? "cloned" : "",
3855 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3856 return s;
3859 static void net_socket_connect(void *opaque)
3861 NetSocketState *s = opaque;
3862 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3865 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3866 int is_connected)
3868 NetSocketState *s;
3869 s = qemu_mallocz(sizeof(NetSocketState));
3870 if (!s)
3871 return NULL;
3872 s->fd = fd;
3873 s->vc = qemu_new_vlan_client(vlan,
3874 net_socket_receive, NULL, s);
3875 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3876 "socket: fd=%d", fd);
3877 if (is_connected) {
3878 net_socket_connect(s);
3879 } else {
3880 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3882 return s;
3885 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3886 int is_connected)
3888 int so_type=-1, optlen=sizeof(so_type);
3890 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3891 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3892 return NULL;
3894 switch(so_type) {
3895 case SOCK_DGRAM:
3896 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3897 case SOCK_STREAM:
3898 return net_socket_fd_init_stream(vlan, fd, is_connected);
3899 default:
3900 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3901 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3902 return net_socket_fd_init_stream(vlan, fd, is_connected);
3904 return NULL;
3907 static void net_socket_accept(void *opaque)
3909 NetSocketListenState *s = opaque;
3910 NetSocketState *s1;
3911 struct sockaddr_in saddr;
3912 socklen_t len;
3913 int fd;
3915 for(;;) {
3916 len = sizeof(saddr);
3917 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3918 if (fd < 0 && errno != EINTR) {
3919 return;
3920 } else if (fd >= 0) {
3921 break;
3924 s1 = net_socket_fd_init(s->vlan, fd, 1);
3925 if (!s1) {
3926 closesocket(fd);
3927 } else {
3928 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3929 "socket: connection from %s:%d",
3930 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3934 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3936 NetSocketListenState *s;
3937 int fd, val, ret;
3938 struct sockaddr_in saddr;
3940 if (parse_host_port(&saddr, host_str) < 0)
3941 return -1;
3943 s = qemu_mallocz(sizeof(NetSocketListenState));
3944 if (!s)
3945 return -1;
3947 fd = socket(PF_INET, SOCK_STREAM, 0);
3948 if (fd < 0) {
3949 perror("socket");
3950 return -1;
3952 socket_set_nonblock(fd);
3954 /* allow fast reuse */
3955 val = 1;
3956 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3958 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3959 if (ret < 0) {
3960 perror("bind");
3961 return -1;
3963 ret = listen(fd, 0);
3964 if (ret < 0) {
3965 perror("listen");
3966 return -1;
3968 s->vlan = vlan;
3969 s->fd = fd;
3970 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3971 return 0;
3974 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3976 NetSocketState *s;
3977 int fd, connected, ret, err;
3978 struct sockaddr_in saddr;
3980 if (parse_host_port(&saddr, host_str) < 0)
3981 return -1;
3983 fd = socket(PF_INET, SOCK_STREAM, 0);
3984 if (fd < 0) {
3985 perror("socket");
3986 return -1;
3988 socket_set_nonblock(fd);
3990 connected = 0;
3991 for(;;) {
3992 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3993 if (ret < 0) {
3994 err = socket_error();
3995 if (err == EINTR || err == EWOULDBLOCK) {
3996 } else if (err == EINPROGRESS) {
3997 break;
3998 } else {
3999 perror("connect");
4000 closesocket(fd);
4001 return -1;
4003 } else {
4004 connected = 1;
4005 break;
4008 s = net_socket_fd_init(vlan, fd, connected);
4009 if (!s)
4010 return -1;
4011 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4012 "socket: connect to %s:%d",
4013 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4014 return 0;
4017 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4019 NetSocketState *s;
4020 int fd;
4021 struct sockaddr_in saddr;
4023 if (parse_host_port(&saddr, host_str) < 0)
4024 return -1;
4027 fd = net_socket_mcast_create(&saddr);
4028 if (fd < 0)
4029 return -1;
4031 s = net_socket_fd_init(vlan, fd, 0);
4032 if (!s)
4033 return -1;
4035 s->dgram_dst = saddr;
4037 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4038 "socket: mcast=%s:%d",
4039 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4040 return 0;
4044 static int get_param_value(char *buf, size_t buf_size,
4045 const char *tag, const char *str)
4047 const char *p;
4048 char *q;
4049 char option[128];
4051 p = str;
4052 for(;;) {
4053 q = option;
4054 while (*p != '\0' && *p != '=') {
4055 if ((q - option) < sizeof(option) - 1)
4056 *q++ = *p;
4057 p++;
4059 *q = '\0';
4060 if (*p != '=')
4061 break;
4062 p++;
4063 if (!strcmp(tag, option)) {
4064 q = buf;
4065 while (*p != '\0' && *p != ',') {
4066 if ((q - buf) < buf_size - 1)
4067 *q++ = *p;
4068 p++;
4070 *q = '\0';
4071 return q - buf;
4072 } else {
4073 while (*p != '\0' && *p != ',') {
4074 p++;
4077 if (*p != ',')
4078 break;
4079 p++;
4081 return 0;
4084 static int net_client_init(const char *str)
4086 const char *p;
4087 char *q;
4088 char device[64];
4089 char buf[1024];
4090 int vlan_id, ret;
4091 VLANState *vlan;
4093 p = str;
4094 q = device;
4095 while (*p != '\0' && *p != ',') {
4096 if ((q - device) < sizeof(device) - 1)
4097 *q++ = *p;
4098 p++;
4100 *q = '\0';
4101 if (*p == ',')
4102 p++;
4103 vlan_id = 0;
4104 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4105 vlan_id = strtol(buf, NULL, 0);
4107 vlan = qemu_find_vlan(vlan_id);
4108 if (!vlan) {
4109 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4110 return -1;
4112 if (!strcmp(device, "nic")) {
4113 NICInfo *nd;
4114 uint8_t *macaddr;
4116 if (nb_nics < MAX_NICS) {
4117 nd = &nd_table[nb_nics];
4118 macaddr = nd->macaddr;
4119 macaddr[0] = 0x52;
4120 macaddr[1] = 0x54;
4121 macaddr[2] = 0x00;
4122 macaddr[3] = 0x12;
4123 macaddr[4] = 0x34;
4124 macaddr[5] = 0x56 + nb_nics;
4126 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4127 if (parse_macaddr(macaddr, buf) < 0) {
4128 fprintf(stderr, "invalid syntax for ethernet address\n");
4129 return -1;
4132 if (get_param_value(buf, sizeof(buf), "model", p)) {
4133 nd->model = strdup(buf);
4135 nd->vlan = vlan;
4136 nb_nics++;
4137 } else {
4138 fprintf(stderr, "Too Many NICs\n");
4140 ret = 0;
4141 } else
4142 if (!strcmp(device, "none")) {
4143 /* does nothing. It is needed to signal that no network cards
4144 are wanted */
4145 ret = 0;
4146 } else
4147 #ifdef CONFIG_SLIRP
4148 if (!strcmp(device, "user")) {
4149 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4150 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4152 ret = net_slirp_init(vlan);
4153 } else
4154 #endif
4155 #ifdef _WIN32
4156 if (!strcmp(device, "tap")) {
4157 char ifname[64];
4158 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4159 fprintf(stderr, "tap: no interface name\n");
4160 return -1;
4162 ret = tap_win32_init(vlan, ifname);
4163 } else
4164 #else
4165 if (!strcmp(device, "tap")) {
4166 char ifname[64];
4167 char setup_script[1024];
4168 char bridge[16];
4169 int fd;
4171 memset(ifname, 0, sizeof(ifname));
4172 memset(setup_script, 0, sizeof(setup_script));
4174 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4175 fd = strtol(buf, NULL, 0);
4176 ret = -1;
4177 if (net_tap_fd_init(vlan, fd))
4178 ret = 0;
4179 } else {
4180 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4181 ifname[0] = '\0';
4183 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4184 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4186 if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
4187 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
4189 ret = net_tap_init(vlan, ifname, setup_script, bridge);
4191 } else
4192 #endif
4193 if (!strcmp(device, "socket")) {
4194 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4195 int fd;
4196 fd = strtol(buf, NULL, 0);
4197 ret = -1;
4198 if (net_socket_fd_init(vlan, fd, 1))
4199 ret = 0;
4200 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4201 ret = net_socket_listen_init(vlan, buf);
4202 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4203 ret = net_socket_connect_init(vlan, buf);
4204 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4205 ret = net_socket_mcast_init(vlan, buf);
4206 } else {
4207 fprintf(stderr, "Unknown socket options: %s\n", p);
4208 return -1;
4210 } else
4212 fprintf(stderr, "Unknown network device: %s\n", device);
4213 return -1;
4215 if (ret < 0) {
4216 fprintf(stderr, "Could not initialize device '%s'\n", device);
4219 return ret;
4222 void do_info_network(void)
4224 VLANState *vlan;
4225 VLANClientState *vc;
4227 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4228 term_printf("VLAN %d devices:\n", vlan->id);
4229 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4230 term_printf(" %s\n", vc->info_str);
4234 /***********************************************************/
4235 /* USB devices */
4237 static USBPort *used_usb_ports;
4238 static USBPort *free_usb_ports;
4240 /* ??? Maybe change this to register a hub to keep track of the topology. */
4241 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4242 usb_attachfn attach)
4244 port->opaque = opaque;
4245 port->index = index;
4246 port->attach = attach;
4247 port->next = free_usb_ports;
4248 free_usb_ports = port;
4251 static int usb_device_add(const char *devname)
4253 const char *p;
4254 USBDevice *dev;
4255 USBPort *port;
4256 char usb_name[256] = "USB ";
4258 if (!free_usb_ports)
4259 return -1;
4261 if (strstart(devname, "host:", &p)) {
4262 dev = usb_host_device_open(p);
4263 } else if (!strcmp(devname, "mouse")) {
4264 dev = usb_mouse_init();
4265 } else if (!strcmp(devname, "tablet")) {
4266 dev = usb_tablet_init();
4267 } else if (strstart(devname, "disk:", &p)) {
4268 dev = usb_msd_init(p, &bdrv_raw);
4269 } else if (strstart(devname, "disk-qcow:", &p)) {
4270 dev = usb_msd_init(p, 0);
4271 } else {
4272 return -1;
4274 if (!dev)
4275 return -1;
4277 /* Find a USB port to add the device to. */
4278 port = free_usb_ports;
4279 if (!port->next) {
4280 USBDevice *hub;
4282 /* Create a new hub and chain it on. */
4283 free_usb_ports = NULL;
4284 port->next = used_usb_ports;
4285 used_usb_ports = port;
4287 hub = usb_hub_init(VM_USB_HUB_SIZE);
4288 usb_attach(port, hub);
4289 port = free_usb_ports;
4292 free_usb_ports = port->next;
4293 port->next = used_usb_ports;
4294 used_usb_ports = port;
4296 pstrcpy(usb_name + strlen(usb_name),
4297 sizeof(usb_name) - strlen(usb_name),
4298 devname);
4299 register_savevm(usb_name, 0, 1, generic_usb_save, generic_usb_load, dev);
4301 usb_attach(port, dev);
4302 return 0;
4305 static int usb_device_del(const char *devname)
4307 USBPort *port;
4308 USBPort **lastp;
4309 USBDevice *dev;
4310 int bus_num, addr;
4311 const char *p;
4313 if (!used_usb_ports)
4314 return -1;
4316 p = strchr(devname, '.');
4317 if (!p)
4318 return -1;
4319 bus_num = strtoul(devname, NULL, 0);
4320 addr = strtoul(p + 1, NULL, 0);
4321 if (bus_num != 0)
4322 return -1;
4324 lastp = &used_usb_ports;
4325 port = used_usb_ports;
4326 while (port && port->dev->addr != addr) {
4327 lastp = &port->next;
4328 port = port->next;
4331 if (!port)
4332 return -1;
4334 dev = port->dev;
4335 *lastp = port->next;
4336 usb_attach(port, NULL);
4337 dev->handle_destroy(dev);
4338 port->next = free_usb_ports;
4339 free_usb_ports = port;
4340 return 0;
4343 void do_usb_add(const char *devname)
4345 int ret;
4346 ret = usb_device_add(devname);
4347 if (ret < 0)
4348 term_printf("Could not add USB device '%s'\n", devname);
4351 void do_usb_del(const char *devname)
4353 int ret;
4354 ret = usb_device_del(devname);
4355 if (ret < 0)
4356 term_printf("Could not remove USB device '%s'\n", devname);
4359 void usb_info(void)
4361 USBDevice *dev;
4362 USBPort *port;
4363 const char *speed_str;
4365 if (!usb_enabled) {
4366 term_printf("USB support not enabled\n");
4367 return;
4370 for (port = used_usb_ports; port; port = port->next) {
4371 dev = port->dev;
4372 if (!dev)
4373 continue;
4374 switch(dev->speed) {
4375 case USB_SPEED_LOW:
4376 speed_str = "1.5";
4377 break;
4378 case USB_SPEED_FULL:
4379 speed_str = "12";
4380 break;
4381 case USB_SPEED_HIGH:
4382 speed_str = "480";
4383 break;
4384 default:
4385 speed_str = "?";
4386 break;
4388 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4389 0, dev->addr, speed_str, dev->devname);
4393 void do_pci_del(char *devname)
4395 #ifdef CONFIG_PASSTHROUGH
4396 int pci_slot = bdf_to_slot(devname);
4397 acpi_php_del(pci_slot);
4398 #endif
4401 void do_pci_add(char *devname)
4403 #ifdef CONFIG_PASSTHROUGH
4404 int pci_slot = insert_to_pci_slot(devname);
4405 acpi_php_add(pci_slot);
4406 #endif
4409 static int pci_emulation_add(char *config_text)
4411 PCI_EMULATION_INFO *new;
4412 if ((new = qemu_mallocz(sizeof(PCI_EMULATION_INFO))) == NULL) {
4413 return -1;
4415 parse_pci_emulation_info(config_text, new);
4416 new->next = PciEmulationInfoHead;
4417 PciEmulationInfoHead = new;
4418 return 0;
4421 /***********************************************************/
4422 /* pid file */
4424 static char *pid_filename;
4426 /* Remove PID file. Called on normal exit */
4428 static void remove_pidfile(void)
4430 unlink (pid_filename);
4433 static void create_pidfile(const char *filename)
4435 struct stat pidstat;
4436 FILE *f;
4438 /* Try to write our PID to the named file */
4439 if (stat(filename, &pidstat) < 0) {
4440 if (errno == ENOENT) {
4441 if ((f = fopen (filename, "w")) == NULL) {
4442 perror("Opening pidfile");
4443 exit(1);
4445 fprintf(f, "%ld\n", (long)getpid());
4446 fclose(f);
4447 pid_filename = qemu_strdup(filename);
4448 if (!pid_filename) {
4449 fprintf(stderr, "Could not save PID filename");
4450 exit(1);
4452 atexit(remove_pidfile);
4454 } else {
4455 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4456 filename);
4457 exit(1);
4461 /***********************************************************/
4462 /* dumb display */
4464 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4468 static void dumb_resize(DisplayState *ds, int w, int h, int linesize)
4472 static void dumb_refresh(DisplayState *ds)
4474 vga_hw_update();
4477 void dumb_display_init(DisplayState *ds)
4479 ds->data = NULL;
4480 ds->linesize = 0;
4481 ds->depth = 0;
4482 ds->dpy_update = dumb_update;
4483 ds->dpy_resize = dumb_resize;
4484 ds->dpy_refresh = dumb_refresh;
4485 ds->gui_timer_interval = 500;
4486 ds->idle = 1;
4489 /***********************************************************/
4490 /* I/O handling */
4492 #define MAX_IO_HANDLERS 64
4494 typedef struct IOHandlerRecord {
4495 int fd;
4496 IOCanRWHandler *fd_read_poll;
4497 IOHandler *fd_read;
4498 IOHandler *fd_write;
4499 int deleted;
4500 void *opaque;
4501 /* temporary data */
4502 struct pollfd *ufd;
4503 struct IOHandlerRecord *next;
4504 } IOHandlerRecord;
4506 static IOHandlerRecord *first_io_handler;
4508 /* XXX: fd_read_poll should be suppressed, but an API change is
4509 necessary in the character devices to suppress fd_can_read(). */
4510 int qemu_set_fd_handler2(int fd,
4511 IOCanRWHandler *fd_read_poll,
4512 IOHandler *fd_read,
4513 IOHandler *fd_write,
4514 void *opaque)
4516 IOHandlerRecord **pioh, *ioh;
4518 if (!fd_read && !fd_write) {
4519 pioh = &first_io_handler;
4520 for(;;) {
4521 ioh = *pioh;
4522 if (ioh == NULL)
4523 break;
4524 if (ioh->fd == fd) {
4525 ioh->deleted = 1;
4526 break;
4528 pioh = &ioh->next;
4530 } else {
4531 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4532 if (ioh->fd == fd)
4533 goto found;
4535 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4536 if (!ioh)
4537 return -1;
4538 ioh->next = first_io_handler;
4539 first_io_handler = ioh;
4540 found:
4541 ioh->fd = fd;
4542 ioh->fd_read_poll = fd_read_poll;
4543 ioh->fd_read = fd_read;
4544 ioh->fd_write = fd_write;
4545 ioh->opaque = opaque;
4546 ioh->deleted = 0;
4548 return 0;
4551 int qemu_set_fd_handler(int fd,
4552 IOHandler *fd_read,
4553 IOHandler *fd_write,
4554 void *opaque)
4556 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4559 /***********************************************************/
4560 /* Polling handling */
4562 typedef struct PollingEntry {
4563 PollingFunc *func;
4564 void *opaque;
4565 struct PollingEntry *next;
4566 } PollingEntry;
4568 static PollingEntry *first_polling_entry;
4570 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4572 PollingEntry **ppe, *pe;
4573 pe = qemu_mallocz(sizeof(PollingEntry));
4574 if (!pe)
4575 return -1;
4576 pe->func = func;
4577 pe->opaque = opaque;
4578 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4579 *ppe = pe;
4580 return 0;
4583 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4585 PollingEntry **ppe, *pe;
4586 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4587 pe = *ppe;
4588 if (pe->func == func && pe->opaque == opaque) {
4589 *ppe = pe->next;
4590 qemu_free(pe);
4591 break;
4596 #ifdef _WIN32
4597 /***********************************************************/
4598 /* Wait objects support */
4599 typedef struct WaitObjects {
4600 int num;
4601 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4602 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4603 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4604 } WaitObjects;
4606 static WaitObjects wait_objects = {0};
4608 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4610 WaitObjects *w = &wait_objects;
4612 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4613 return -1;
4614 w->events[w->num] = handle;
4615 w->func[w->num] = func;
4616 w->opaque[w->num] = opaque;
4617 w->num++;
4618 return 0;
4621 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4623 int i, found;
4624 WaitObjects *w = &wait_objects;
4626 found = 0;
4627 for (i = 0; i < w->num; i++) {
4628 if (w->events[i] == handle)
4629 found = 1;
4630 if (found) {
4631 w->events[i] = w->events[i + 1];
4632 w->func[i] = w->func[i + 1];
4633 w->opaque[i] = w->opaque[i + 1];
4636 if (found)
4637 w->num--;
4639 #endif
4641 /***********************************************************/
4642 /* savevm/loadvm support */
4644 #define IO_BUF_SIZE 32768
4646 struct QEMUFile {
4647 FILE *outfile;
4648 BlockDriverState *bs;
4649 int is_file;
4650 int is_writable;
4651 int64_t base_offset;
4652 int64_t buf_offset; /* start of buffer when writing, end of buffer
4653 when reading */
4654 int buf_index;
4655 int buf_size; /* 0 when writing */
4656 uint8_t buf[IO_BUF_SIZE];
4657 };
4659 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4661 QEMUFile *f;
4663 f = qemu_mallocz(sizeof(QEMUFile));
4664 if (!f)
4665 return NULL;
4666 if (!strcmp(mode, "wb")) {
4667 f->is_writable = 1;
4668 } else if (!strcmp(mode, "rb")) {
4669 f->is_writable = 0;
4670 } else {
4671 goto fail;
4673 f->outfile = fopen(filename, mode);
4674 if (!f->outfile)
4675 goto fail;
4676 f->is_file = 1;
4677 return f;
4678 fail:
4679 if (f->outfile)
4680 fclose(f->outfile);
4681 qemu_free(f);
4682 return NULL;
4685 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4687 QEMUFile *f;
4689 f = qemu_mallocz(sizeof(QEMUFile));
4690 if (!f)
4691 return NULL;
4692 f->is_file = 0;
4693 f->bs = bs;
4694 f->is_writable = is_writable;
4695 f->base_offset = offset;
4696 return f;
4699 void qemu_fflush(QEMUFile *f)
4701 if (!f->is_writable)
4702 return;
4703 if (f->buf_index > 0) {
4704 if (f->is_file) {
4705 fseek(f->outfile, f->buf_offset, SEEK_SET);
4706 fwrite(f->buf, 1, f->buf_index, f->outfile);
4707 } else {
4708 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4709 f->buf, f->buf_index);
4711 f->buf_offset += f->buf_index;
4712 f->buf_index = 0;
4716 static void qemu_fill_buffer(QEMUFile *f)
4718 int len;
4720 if (f->is_writable)
4721 return;
4722 if (f->is_file) {
4723 fseek(f->outfile, f->buf_offset, SEEK_SET);
4724 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4725 if (len < 0)
4726 len = 0;
4727 } else {
4728 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4729 f->buf, IO_BUF_SIZE);
4730 if (len < 0)
4731 len = 0;
4733 f->buf_index = 0;
4734 f->buf_size = len;
4735 f->buf_offset += len;
4738 void qemu_fclose(QEMUFile *f)
4740 if (f->is_writable)
4741 qemu_fflush(f);
4742 if (f->is_file) {
4743 fclose(f->outfile);
4745 qemu_free(f);
4748 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4750 int l;
4751 while (size > 0) {
4752 l = IO_BUF_SIZE - f->buf_index;
4753 if (l > size)
4754 l = size;
4755 memcpy(f->buf + f->buf_index, buf, l);
4756 f->buf_index += l;
4757 buf += l;
4758 size -= l;
4759 if (f->buf_index >= IO_BUF_SIZE)
4760 qemu_fflush(f);
4764 void qemu_put_byte(QEMUFile *f, int v)
4766 f->buf[f->buf_index++] = v;
4767 if (f->buf_index >= IO_BUF_SIZE)
4768 qemu_fflush(f);
4771 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4773 int size, l;
4775 size = size1;
4776 while (size > 0) {
4777 l = f->buf_size - f->buf_index;
4778 if (l == 0) {
4779 qemu_fill_buffer(f);
4780 l = f->buf_size - f->buf_index;
4781 if (l == 0)
4782 break;
4784 if (l > size)
4785 l = size;
4786 memcpy(buf, f->buf + f->buf_index, l);
4787 f->buf_index += l;
4788 buf += l;
4789 size -= l;
4791 return size1 - size;
4794 int qemu_get_byte(QEMUFile *f)
4796 if (f->buf_index >= f->buf_size) {
4797 qemu_fill_buffer(f);
4798 if (f->buf_index >= f->buf_size)
4799 return 0;
4801 return f->buf[f->buf_index++];
4804 int64_t qemu_ftell(QEMUFile *f)
4806 return f->buf_offset - f->buf_size + f->buf_index;
4809 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4811 if (whence == SEEK_SET) {
4812 /* nothing to do */
4813 } else if (whence == SEEK_CUR) {
4814 pos += qemu_ftell(f);
4815 } else {
4816 /* SEEK_END not supported */
4817 return -1;
4819 if (f->is_writable) {
4820 qemu_fflush(f);
4821 f->buf_offset = pos;
4822 } else {
4823 f->buf_offset = pos;
4824 f->buf_index = 0;
4825 f->buf_size = 0;
4827 return pos;
4830 void qemu_put_be16(QEMUFile *f, unsigned int v)
4832 qemu_put_byte(f, v >> 8);
4833 qemu_put_byte(f, v);
4836 void qemu_put_be32(QEMUFile *f, unsigned int v)
4838 qemu_put_byte(f, v >> 24);
4839 qemu_put_byte(f, v >> 16);
4840 qemu_put_byte(f, v >> 8);
4841 qemu_put_byte(f, v);
4844 void qemu_put_be64(QEMUFile *f, uint64_t v)
4846 qemu_put_be32(f, v >> 32);
4847 qemu_put_be32(f, v);
4850 unsigned int qemu_get_be16(QEMUFile *f)
4852 unsigned int v;
4853 v = qemu_get_byte(f) << 8;
4854 v |= qemu_get_byte(f);
4855 return v;
4858 unsigned int qemu_get_be32(QEMUFile *f)
4860 unsigned int v;
4861 v = qemu_get_byte(f) << 24;
4862 v |= qemu_get_byte(f) << 16;
4863 v |= qemu_get_byte(f) << 8;
4864 v |= qemu_get_byte(f);
4865 return v;
4868 uint64_t qemu_get_be64(QEMUFile *f)
4870 uint64_t v;
4871 v = (uint64_t)qemu_get_be32(f) << 32;
4872 v |= qemu_get_be32(f);
4873 return v;
4876 typedef struct SaveStateEntry {
4877 char idstr[256];
4878 int instance_id;
4879 int version_id;
4880 SaveStateHandler *save_state;
4881 LoadStateHandler *load_state;
4882 void *opaque;
4883 struct SaveStateEntry *next;
4884 } SaveStateEntry;
4886 static SaveStateEntry *first_se;
4888 int register_savevm(const char *idstr,
4889 int instance_id,
4890 int version_id,
4891 SaveStateHandler *save_state,
4892 LoadStateHandler *load_state,
4893 void *opaque)
4895 SaveStateEntry *se, **pse;
4897 se = qemu_malloc(sizeof(SaveStateEntry));
4898 if (!se)
4899 return -1;
4900 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4901 se->instance_id = instance_id;
4902 se->version_id = version_id;
4903 se->save_state = save_state;
4904 se->load_state = load_state;
4905 se->opaque = opaque;
4906 se->next = NULL;
4908 /* add at the end of list */
4909 pse = &first_se;
4910 while (*pse != NULL)
4911 pse = &(*pse)->next;
4912 *pse = se;
4913 return 0;
4916 #define QEMU_VM_FILE_MAGIC 0x5145564d
4917 #define QEMU_VM_FILE_VERSION 0x00000002
4919 int qemu_savevm_state(QEMUFile *f)
4921 SaveStateEntry *se;
4922 int len, ret;
4923 int64_t cur_pos, len_pos, total_len_pos;
4925 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4926 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4927 total_len_pos = qemu_ftell(f);
4928 qemu_put_be64(f, 0); /* total size */
4930 for(se = first_se; se != NULL; se = se->next) {
4931 /* ID string */
4932 len = strlen(se->idstr);
4933 qemu_put_byte(f, len);
4934 qemu_put_buffer(f, se->idstr, len);
4936 qemu_put_be32(f, se->instance_id);
4937 qemu_put_be32(f, se->version_id);
4939 /* record size: filled later */
4940 len_pos = qemu_ftell(f);
4941 qemu_put_be32(f, 0);
4943 se->save_state(f, se->opaque);
4945 /* fill record size */
4946 cur_pos = qemu_ftell(f);
4947 len = cur_pos - len_pos - 4;
4948 qemu_fseek(f, len_pos, SEEK_SET);
4949 qemu_put_be32(f, len);
4950 qemu_fseek(f, cur_pos, SEEK_SET);
4952 cur_pos = qemu_ftell(f);
4953 qemu_fseek(f, total_len_pos, SEEK_SET);
4954 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4955 qemu_fseek(f, cur_pos, SEEK_SET);
4957 ret = 0;
4958 return ret;
4961 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4963 SaveStateEntry *se;
4965 for(se = first_se; se != NULL; se = se->next) {
4966 if (!strcmp(se->idstr, idstr) &&
4967 instance_id == se->instance_id)
4968 return se;
4970 return NULL;
4973 int qemu_loadvm_state(QEMUFile *f)
4975 SaveStateEntry *se;
4976 int len, ret, instance_id, record_len, version_id;
4977 int64_t total_len, end_pos, cur_pos;
4978 unsigned int v;
4979 char idstr[256];
4981 v = qemu_get_be32(f);
4982 if (v != QEMU_VM_FILE_MAGIC)
4983 goto fail;
4984 v = qemu_get_be32(f);
4985 if (v != QEMU_VM_FILE_VERSION) {
4986 fail:
4987 ret = -1;
4988 goto the_end;
4990 total_len = qemu_get_be64(f);
4991 end_pos = total_len + qemu_ftell(f);
4992 for(;;) {
4993 if (qemu_ftell(f) >= end_pos)
4994 break;
4995 len = qemu_get_byte(f);
4996 qemu_get_buffer(f, idstr, len);
4997 idstr[len] = '\0';
4998 instance_id = qemu_get_be32(f);
4999 version_id = qemu_get_be32(f);
5000 record_len = qemu_get_be32(f);
5001 #if 0
5002 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5003 idstr, instance_id, version_id, record_len);
5004 #endif
5005 cur_pos = qemu_ftell(f);
5006 se = find_se(idstr, instance_id);
5007 if (!se) {
5008 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5009 instance_id, idstr);
5010 } else {
5011 ret = se->load_state(f, se->opaque, version_id);
5012 if (ret < 0) {
5013 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5014 instance_id, idstr);
5017 /* always seek to exact end of record */
5018 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5020 ret = 0;
5021 the_end:
5022 return ret;
5025 /* device can contain snapshots */
5026 static int bdrv_can_snapshot(BlockDriverState *bs)
5028 return (bs &&
5029 !bdrv_is_removable(bs) &&
5030 !bdrv_is_read_only(bs));
5033 /* device must be snapshots in order to have a reliable snapshot */
5034 static int bdrv_has_snapshot(BlockDriverState *bs)
5036 return (bs &&
5037 !bdrv_is_removable(bs) &&
5038 !bdrv_is_read_only(bs));
5041 static BlockDriverState *get_bs_snapshots(void)
5043 BlockDriverState *bs;
5044 int i;
5046 if (bs_snapshots)
5047 return bs_snapshots;
5048 for(i = 0; i <= MAX_DISKS; i++) {
5049 bs = bs_table[i];
5050 if (bdrv_can_snapshot(bs))
5051 goto ok;
5053 return NULL;
5054 ok:
5055 bs_snapshots = bs;
5056 return bs;
5059 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5060 const char *name)
5062 QEMUSnapshotInfo *sn_tab, *sn;
5063 int nb_sns, i, ret;
5065 ret = -ENOENT;
5066 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5067 if (nb_sns < 0)
5068 return ret;
5069 for(i = 0; i < nb_sns; i++) {
5070 sn = &sn_tab[i];
5071 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5072 *sn_info = *sn;
5073 ret = 0;
5074 break;
5077 qemu_free(sn_tab);
5078 return ret;
5081 #ifdef CONFIG_DM
5082 /* We use simpler state save/load functions for Xen */
5083 void do_savevm(const char *name)
5085 QEMUFile *f;
5086 int saved_vm_running, ret;
5088 f = qemu_fopen(name, "wb");
5090 /* ??? Should this occur after vm_stop? */
5091 qemu_aio_flush();
5093 saved_vm_running = vm_running;
5094 vm_stop(0);
5096 if (!f) {
5097 fprintf(logfile, "Failed to open savevm file '%s'\n", name);
5098 goto the_end;
5101 ret = qemu_savevm_state(f);
5102 qemu_fclose(f);
5104 if (ret < 0)
5105 fprintf(logfile, "Error %d while writing VM to savevm file '%s'\n",
5106 ret, name);
5108 the_end:
5109 if (saved_vm_running)
5110 vm_start();
5112 return;
5114 void do_loadvm(const char *name)
5116 QEMUFile *f;
5117 int saved_vm_running, ret;
5119 /* Flush all IO requests so they don't interfere with the new state. */
5120 qemu_aio_flush();
5122 saved_vm_running = vm_running;
5123 vm_stop(0);
5125 /* restore the VM state */
5126 f = qemu_fopen(name, "rb");
5127 if (!f) {
5128 fprintf(logfile, "Could not open VM state file\n");
5129 goto the_end;
5132 ret = qemu_loadvm_state(f);
5133 qemu_fclose(f);
5134 if (ret < 0) {
5135 fprintf(logfile, "Error %d while loading savevm file '%s'\n",
5136 ret, name);
5137 goto the_end;
5140 #if 0
5141 /* del tmp file */
5142 if (unlink(name) == -1)
5143 fprintf(stderr, "delete tmp qemu state file failed.\n");
5144 #endif
5147 the_end:
5148 if (saved_vm_running)
5149 vm_start();
5151 #else
5152 void do_savevm(const char *name)
5154 BlockDriverState *bs, *bs1;
5155 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5156 int must_delete, ret, i;
5157 BlockDriverInfo bdi1, *bdi = &bdi1;
5158 QEMUFile *f;
5159 int saved_vm_running;
5160 #ifdef _WIN32
5161 struct _timeb tb;
5162 #else
5163 struct timeval tv;
5164 #endif
5166 bs = get_bs_snapshots();
5167 if (!bs) {
5168 term_printf("No block device can accept snapshots\n");
5169 return;
5172 /* ??? Should this occur after vm_stop? */
5173 qemu_aio_flush();
5175 saved_vm_running = vm_running;
5176 vm_stop(0);
5178 must_delete = 0;
5179 if (name) {
5180 ret = bdrv_snapshot_find(bs, old_sn, name);
5181 if (ret >= 0) {
5182 must_delete = 1;
5185 memset(sn, 0, sizeof(*sn));
5186 if (must_delete) {
5187 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5188 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5189 } else {
5190 if (name)
5191 pstrcpy(sn->name, sizeof(sn->name), name);
5194 /* fill auxiliary fields */
5195 #ifdef _WIN32
5196 _ftime(&tb);
5197 sn->date_sec = tb.time;
5198 sn->date_nsec = tb.millitm * 1000000;
5199 #else
5200 gettimeofday(&tv, NULL);
5201 sn->date_sec = tv.tv_sec;
5202 sn->date_nsec = tv.tv_usec * 1000;
5203 #endif
5204 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5206 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5207 term_printf("Device %s does not support VM state snapshots\n",
5208 bdrv_get_device_name(bs));
5209 goto the_end;
5212 /* save the VM state */
5213 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5214 if (!f) {
5215 term_printf("Could not open VM state file\n");
5216 goto the_end;
5218 ret = qemu_savevm_state(f);
5219 sn->vm_state_size = qemu_ftell(f);
5220 qemu_fclose(f);
5221 if (ret < 0) {
5222 term_printf("Error %d while writing VM\n", ret);
5223 goto the_end;
5226 /* create the snapshots */
5228 for(i = 0; i < MAX_DISKS; i++) {
5229 bs1 = bs_table[i];
5230 if (bdrv_has_snapshot(bs1)) {
5231 if (must_delete) {
5232 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5233 if (ret < 0) {
5234 term_printf("Error while deleting snapshot on '%s'\n",
5235 bdrv_get_device_name(bs1));
5238 ret = bdrv_snapshot_create(bs1, sn);
5239 if (ret < 0) {
5240 term_printf("Error while creating snapshot on '%s'\n",
5241 bdrv_get_device_name(bs1));
5246 the_end:
5247 if (saved_vm_running)
5248 vm_start();
5251 void do_loadvm(const char *name)
5253 BlockDriverState *bs, *bs1;
5254 BlockDriverInfo bdi1, *bdi = &bdi1;
5255 QEMUFile *f;
5256 int i, ret;
5257 int saved_vm_running;
5259 bs = get_bs_snapshots();
5260 if (!bs) {
5261 term_printf("No block device supports snapshots\n");
5262 return;
5265 /* Flush all IO requests so they don't interfere with the new state. */
5266 qemu_aio_flush();
5268 saved_vm_running = vm_running;
5269 vm_stop(0);
5271 for(i = 0; i <= MAX_DISKS; i++) {
5272 bs1 = bs_table[i];
5273 if (bdrv_has_snapshot(bs1)) {
5274 ret = bdrv_snapshot_goto(bs1, name);
5275 if (ret < 0) {
5276 if (bs != bs1)
5277 term_printf("Warning: ");
5278 switch(ret) {
5279 case -ENOTSUP:
5280 term_printf("Snapshots not supported on device '%s'\n",
5281 bdrv_get_device_name(bs1));
5282 break;
5283 case -ENOENT:
5284 term_printf("Could not find snapshot '%s' on device '%s'\n",
5285 name, bdrv_get_device_name(bs1));
5286 break;
5287 default:
5288 term_printf("Error %d while activating snapshot on '%s'\n",
5289 ret, bdrv_get_device_name(bs1));
5290 break;
5292 /* fatal on snapshot block device */
5293 if (bs == bs1)
5294 goto the_end;
5299 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5300 term_printf("Device %s does not support VM state snapshots\n",
5301 bdrv_get_device_name(bs));
5302 return;
5305 /* restore the VM state */
5306 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5307 if (!f) {
5308 term_printf("Could not open VM state file\n");
5309 goto the_end;
5311 ret = qemu_loadvm_state(f);
5312 qemu_fclose(f);
5313 if (ret < 0) {
5314 term_printf("Error %d while loading VM state\n", ret);
5317 /* del tmp file */
5318 if (unlink(name) == -1)
5319 fprintf(stderr, "delete tmp qemu state file failed.\n");
5321 the_end:
5322 if (saved_vm_running)
5323 vm_start();
5325 #endif
5327 void do_delvm(const char *name)
5329 BlockDriverState *bs, *bs1;
5330 int i, ret;
5332 bs = get_bs_snapshots();
5333 if (!bs) {
5334 term_printf("No block device supports snapshots\n");
5335 return;
5338 for(i = 0; i <= MAX_DISKS; i++) {
5339 bs1 = bs_table[i];
5340 if (bdrv_has_snapshot(bs1)) {
5341 ret = bdrv_snapshot_delete(bs1, name);
5342 if (ret < 0) {
5343 if (ret == -ENOTSUP)
5344 term_printf("Snapshots not supported on device '%s'\n",
5345 bdrv_get_device_name(bs1));
5346 else
5347 term_printf("Error %d while deleting snapshot on '%s'\n",
5348 ret, bdrv_get_device_name(bs1));
5354 void do_info_snapshots(void)
5356 BlockDriverState *bs, *bs1;
5357 QEMUSnapshotInfo *sn_tab, *sn;
5358 int nb_sns, i;
5359 char buf[256];
5361 bs = get_bs_snapshots();
5362 if (!bs) {
5363 term_printf("No available block device supports snapshots\n");
5364 return;
5366 term_printf("Snapshot devices:");
5367 for(i = 0; i <= MAX_DISKS; i++) {
5368 bs1 = bs_table[i];
5369 if (bdrv_has_snapshot(bs1)) {
5370 if (bs == bs1)
5371 term_printf(" %s", bdrv_get_device_name(bs1));
5374 term_printf("\n");
5376 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5377 if (nb_sns < 0) {
5378 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5379 return;
5381 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5382 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5383 for(i = 0; i < nb_sns; i++) {
5384 sn = &sn_tab[i];
5385 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5387 qemu_free(sn_tab);
5390 #ifndef CONFIG_DM
5391 /***********************************************************/
5392 /* cpu save/restore */
5394 #if defined(TARGET_I386)
5396 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5398 qemu_put_be32(f, dt->selector);
5399 qemu_put_betl(f, dt->base);
5400 qemu_put_be32(f, dt->limit);
5401 qemu_put_be32(f, dt->flags);
5404 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5406 dt->selector = qemu_get_be32(f);
5407 dt->base = qemu_get_betl(f);
5408 dt->limit = qemu_get_be32(f);
5409 dt->flags = qemu_get_be32(f);
5412 void cpu_save(QEMUFile *f, void *opaque)
5414 CPUState *env = opaque;
5415 uint16_t fptag, fpus, fpuc, fpregs_format;
5416 uint32_t hflags;
5417 int i;
5419 for(i = 0; i < CPU_NB_REGS; i++)
5420 qemu_put_betls(f, &env->regs[i]);
5421 qemu_put_betls(f, &env->eip);
5422 qemu_put_betls(f, &env->eflags);
5423 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5424 qemu_put_be32s(f, &hflags);
5426 /* FPU */
5427 fpuc = env->fpuc;
5428 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5429 fptag = 0;
5430 for(i = 0; i < 8; i++) {
5431 fptag |= ((!env->fptags[i]) << i);
5434 qemu_put_be16s(f, &fpuc);
5435 qemu_put_be16s(f, &fpus);
5436 qemu_put_be16s(f, &fptag);
5438 #ifdef USE_X86LDOUBLE
5439 fpregs_format = 0;
5440 #else
5441 fpregs_format = 1;
5442 #endif
5443 qemu_put_be16s(f, &fpregs_format);
5445 for(i = 0; i < 8; i++) {
5446 #ifdef USE_X86LDOUBLE
5448 uint64_t mant;
5449 uint16_t exp;
5450 /* we save the real CPU data (in case of MMX usage only 'mant'
5451 contains the MMX register */
5452 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5453 qemu_put_be64(f, mant);
5454 qemu_put_be16(f, exp);
5456 #else
5457 /* if we use doubles for float emulation, we save the doubles to
5458 avoid losing information in case of MMX usage. It can give
5459 problems if the image is restored on a CPU where long
5460 doubles are used instead. */
5461 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5462 #endif
5465 for(i = 0; i < 6; i++)
5466 cpu_put_seg(f, &env->segs[i]);
5467 cpu_put_seg(f, &env->ldt);
5468 cpu_put_seg(f, &env->tr);
5469 cpu_put_seg(f, &env->gdt);
5470 cpu_put_seg(f, &env->idt);
5472 qemu_put_be32s(f, &env->sysenter_cs);
5473 qemu_put_be32s(f, &env->sysenter_esp);
5474 qemu_put_be32s(f, &env->sysenter_eip);
5476 qemu_put_betls(f, &env->cr[0]);
5477 qemu_put_betls(f, &env->cr[2]);
5478 qemu_put_betls(f, &env->cr[3]);
5479 qemu_put_betls(f, &env->cr[4]);
5481 for(i = 0; i < 8; i++)
5482 qemu_put_betls(f, &env->dr[i]);
5484 /* MMU */
5485 qemu_put_be32s(f, &env->a20_mask);
5487 /* XMM */
5488 qemu_put_be32s(f, &env->mxcsr);
5489 for(i = 0; i < CPU_NB_REGS; i++) {
5490 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5491 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5494 #ifdef TARGET_X86_64
5495 qemu_put_be64s(f, &env->efer);
5496 qemu_put_be64s(f, &env->star);
5497 qemu_put_be64s(f, &env->lstar);
5498 qemu_put_be64s(f, &env->cstar);
5499 qemu_put_be64s(f, &env->fmask);
5500 qemu_put_be64s(f, &env->kernelgsbase);
5501 #endif
5502 qemu_put_be32s(f, &env->smbase);
5505 #ifdef USE_X86LDOUBLE
5506 /* XXX: add that in a FPU generic layer */
5507 union x86_longdouble {
5508 uint64_t mant;
5509 uint16_t exp;
5510 };
5512 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5513 #define EXPBIAS1 1023
5514 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5515 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5517 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5519 int e;
5520 /* mantissa */
5521 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5522 /* exponent + sign */
5523 e = EXPD1(temp) - EXPBIAS1 + 16383;
5524 e |= SIGND1(temp) >> 16;
5525 p->exp = e;
5527 #endif
5529 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5531 CPUState *env = opaque;
5532 int i, guess_mmx;
5533 uint32_t hflags;
5534 uint16_t fpus, fpuc, fptag, fpregs_format;
5536 if (version_id != 3 && version_id != 4)
5537 return -EINVAL;
5538 for(i = 0; i < CPU_NB_REGS; i++)
5539 qemu_get_betls(f, &env->regs[i]);
5540 qemu_get_betls(f, &env->eip);
5541 qemu_get_betls(f, &env->eflags);
5542 qemu_get_be32s(f, &hflags);
5544 qemu_get_be16s(f, &fpuc);
5545 qemu_get_be16s(f, &fpus);
5546 qemu_get_be16s(f, &fptag);
5547 qemu_get_be16s(f, &fpregs_format);
5549 /* NOTE: we cannot always restore the FPU state if the image come
5550 from a host with a different 'USE_X86LDOUBLE' define. We guess
5551 if we are in an MMX state to restore correctly in that case. */
5552 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5553 for(i = 0; i < 8; i++) {
5554 uint64_t mant;
5555 uint16_t exp;
5557 switch(fpregs_format) {
5558 case 0:
5559 mant = qemu_get_be64(f);
5560 exp = qemu_get_be16(f);
5561 #ifdef USE_X86LDOUBLE
5562 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5563 #else
5564 /* difficult case */
5565 if (guess_mmx)
5566 env->fpregs[i].mmx.MMX_Q(0) = mant;
5567 else
5568 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5569 #endif
5570 break;
5571 case 1:
5572 mant = qemu_get_be64(f);
5573 #ifdef USE_X86LDOUBLE
5575 union x86_longdouble *p;
5576 /* difficult case */
5577 p = (void *)&env->fpregs[i];
5578 if (guess_mmx) {
5579 p->mant = mant;
5580 p->exp = 0xffff;
5581 } else {
5582 fp64_to_fp80(p, mant);
5585 #else
5586 env->fpregs[i].mmx.MMX_Q(0) = mant;
5587 #endif
5588 break;
5589 default:
5590 return -EINVAL;
5594 env->fpuc = fpuc;
5595 /* XXX: restore FPU round state */
5596 env->fpstt = (fpus >> 11) & 7;
5597 env->fpus = fpus & ~0x3800;
5598 fptag ^= 0xff;
5599 for(i = 0; i < 8; i++) {
5600 env->fptags[i] = (fptag >> i) & 1;
5603 for(i = 0; i < 6; i++)
5604 cpu_get_seg(f, &env->segs[i]);
5605 cpu_get_seg(f, &env->ldt);
5606 cpu_get_seg(f, &env->tr);
5607 cpu_get_seg(f, &env->gdt);
5608 cpu_get_seg(f, &env->idt);
5610 qemu_get_be32s(f, &env->sysenter_cs);
5611 qemu_get_be32s(f, &env->sysenter_esp);
5612 qemu_get_be32s(f, &env->sysenter_eip);
5614 qemu_get_betls(f, &env->cr[0]);
5615 qemu_get_betls(f, &env->cr[2]);
5616 qemu_get_betls(f, &env->cr[3]);
5617 qemu_get_betls(f, &env->cr[4]);
5619 for(i = 0; i < 8; i++)
5620 qemu_get_betls(f, &env->dr[i]);
5622 /* MMU */
5623 qemu_get_be32s(f, &env->a20_mask);
5625 qemu_get_be32s(f, &env->mxcsr);
5626 for(i = 0; i < CPU_NB_REGS; i++) {
5627 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5628 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5631 #ifdef TARGET_X86_64
5632 qemu_get_be64s(f, &env->efer);
5633 qemu_get_be64s(f, &env->star);
5634 qemu_get_be64s(f, &env->lstar);
5635 qemu_get_be64s(f, &env->cstar);
5636 qemu_get_be64s(f, &env->fmask);
5637 qemu_get_be64s(f, &env->kernelgsbase);
5638 #endif
5639 if (version_id >= 4)
5640 qemu_get_be32s(f, &env->smbase);
5642 /* XXX: compute hflags from scratch, except for CPL and IIF */
5643 env->hflags = hflags;
5644 tlb_flush(env, 1);
5645 return 0;
5648 #elif defined(TARGET_PPC)
5649 void cpu_save(QEMUFile *f, void *opaque)
5653 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5655 return 0;
5658 #elif defined(TARGET_MIPS)
5659 void cpu_save(QEMUFile *f, void *opaque)
5663 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5665 return 0;
5668 #elif defined(TARGET_SPARC)
5669 void cpu_save(QEMUFile *f, void *opaque)
5671 CPUState *env = opaque;
5672 int i;
5673 uint32_t tmp;
5675 for(i = 0; i < 8; i++)
5676 qemu_put_betls(f, &env->gregs[i]);
5677 for(i = 0; i < NWINDOWS * 16; i++)
5678 qemu_put_betls(f, &env->regbase[i]);
5680 /* FPU */
5681 for(i = 0; i < TARGET_FPREGS; i++) {
5682 union {
5683 float32 f;
5684 uint32_t i;
5685 } u;
5686 u.f = env->fpr[i];
5687 qemu_put_be32(f, u.i);
5690 qemu_put_betls(f, &env->pc);
5691 qemu_put_betls(f, &env->npc);
5692 qemu_put_betls(f, &env->y);
5693 tmp = GET_PSR(env);
5694 qemu_put_be32(f, tmp);
5695 qemu_put_betls(f, &env->fsr);
5696 qemu_put_betls(f, &env->tbr);
5697 #ifndef TARGET_SPARC64
5698 qemu_put_be32s(f, &env->wim);
5699 /* MMU */
5700 for(i = 0; i < 16; i++)
5701 qemu_put_be32s(f, &env->mmuregs[i]);
5702 #endif
5705 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5707 CPUState *env = opaque;
5708 int i;
5709 uint32_t tmp;
5711 for(i = 0; i < 8; i++)
5712 qemu_get_betls(f, &env->gregs[i]);
5713 for(i = 0; i < NWINDOWS * 16; i++)
5714 qemu_get_betls(f, &env->regbase[i]);
5716 /* FPU */
5717 for(i = 0; i < TARGET_FPREGS; i++) {
5718 union {
5719 float32 f;
5720 uint32_t i;
5721 } u;
5722 u.i = qemu_get_be32(f);
5723 env->fpr[i] = u.f;
5726 qemu_get_betls(f, &env->pc);
5727 qemu_get_betls(f, &env->npc);
5728 qemu_get_betls(f, &env->y);
5729 tmp = qemu_get_be32(f);
5730 env->cwp = 0; /* needed to ensure that the wrapping registers are
5731 correctly updated */
5732 PUT_PSR(env, tmp);
5733 qemu_get_betls(f, &env->fsr);
5734 qemu_get_betls(f, &env->tbr);
5735 #ifndef TARGET_SPARC64
5736 qemu_get_be32s(f, &env->wim);
5737 /* MMU */
5738 for(i = 0; i < 16; i++)
5739 qemu_get_be32s(f, &env->mmuregs[i]);
5740 #endif
5741 tlb_flush(env, 1);
5742 return 0;
5745 #elif defined(TARGET_ARM)
5747 /* ??? Need to implement these. */
5748 void cpu_save(QEMUFile *f, void *opaque)
5752 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5754 return 0;
5757 #else
5759 #warning No CPU save/restore functions
5761 #endif
5763 /***********************************************************/
5764 /* ram save/restore */
5766 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5768 int v;
5770 v = qemu_get_byte(f);
5771 switch(v) {
5772 case 0:
5773 if (qemu_get_buffer(f, buf, len) != len)
5774 return -EIO;
5775 break;
5776 case 1:
5777 v = qemu_get_byte(f);
5778 memset(buf, v, len);
5779 break;
5780 default:
5781 return -EINVAL;
5783 return 0;
5786 static int ram_load_v1(QEMUFile *f, void *opaque)
5788 int i, ret;
5790 if (qemu_get_be32(f) != phys_ram_size)
5791 return -EINVAL;
5792 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5793 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5794 if (ret)
5795 return ret;
5797 return 0;
5800 #define BDRV_HASH_BLOCK_SIZE 1024
5801 #define IOBUF_SIZE 4096
5802 #define RAM_CBLOCK_MAGIC 0xfabe
5804 typedef struct RamCompressState {
5805 z_stream zstream;
5806 QEMUFile *f;
5807 uint8_t buf[IOBUF_SIZE];
5808 } RamCompressState;
5810 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5812 int ret;
5813 memset(s, 0, sizeof(*s));
5814 s->f = f;
5815 ret = deflateInit2(&s->zstream, 1,
5816 Z_DEFLATED, 15,
5817 9, Z_DEFAULT_STRATEGY);
5818 if (ret != Z_OK)
5819 return -1;
5820 s->zstream.avail_out = IOBUF_SIZE;
5821 s->zstream.next_out = s->buf;
5822 return 0;
5825 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5827 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5828 qemu_put_be16(s->f, len);
5829 qemu_put_buffer(s->f, buf, len);
5832 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5834 int ret;
5836 s->zstream.avail_in = len;
5837 s->zstream.next_in = (uint8_t *)buf;
5838 while (s->zstream.avail_in > 0) {
5839 ret = deflate(&s->zstream, Z_NO_FLUSH);
5840 if (ret != Z_OK)
5841 return -1;
5842 if (s->zstream.avail_out == 0) {
5843 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5844 s->zstream.avail_out = IOBUF_SIZE;
5845 s->zstream.next_out = s->buf;
5848 return 0;
5851 static void ram_compress_close(RamCompressState *s)
5853 int len, ret;
5855 /* compress last bytes */
5856 for(;;) {
5857 ret = deflate(&s->zstream, Z_FINISH);
5858 if (ret == Z_OK || ret == Z_STREAM_END) {
5859 len = IOBUF_SIZE - s->zstream.avail_out;
5860 if (len > 0) {
5861 ram_put_cblock(s, s->buf, len);
5863 s->zstream.avail_out = IOBUF_SIZE;
5864 s->zstream.next_out = s->buf;
5865 if (ret == Z_STREAM_END)
5866 break;
5867 } else {
5868 goto fail;
5871 fail:
5872 deflateEnd(&s->zstream);
5875 typedef struct RamDecompressState {
5876 z_stream zstream;
5877 QEMUFile *f;
5878 uint8_t buf[IOBUF_SIZE];
5879 } RamDecompressState;
5881 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5883 int ret;
5884 memset(s, 0, sizeof(*s));
5885 s->f = f;
5886 ret = inflateInit(&s->zstream);
5887 if (ret != Z_OK)
5888 return -1;
5889 return 0;
5892 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5894 int ret, clen;
5896 s->zstream.avail_out = len;
5897 s->zstream.next_out = buf;
5898 while (s->zstream.avail_out > 0) {
5899 if (s->zstream.avail_in == 0) {
5900 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5901 return -1;
5902 clen = qemu_get_be16(s->f);
5903 if (clen > IOBUF_SIZE)
5904 return -1;
5905 qemu_get_buffer(s->f, s->buf, clen);
5906 s->zstream.avail_in = clen;
5907 s->zstream.next_in = s->buf;
5909 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5910 if (ret != Z_OK && ret != Z_STREAM_END) {
5911 return -1;
5914 return 0;
5917 static void ram_decompress_close(RamDecompressState *s)
5919 inflateEnd(&s->zstream);
5922 static void ram_save(QEMUFile *f, void *opaque)
5924 int i;
5925 RamCompressState s1, *s = &s1;
5926 uint8_t buf[10];
5928 qemu_put_be32(f, phys_ram_size);
5929 if (ram_compress_open(s, f) < 0)
5930 return;
5931 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5932 #if 0
5933 if (tight_savevm_enabled) {
5934 int64_t sector_num;
5935 int j;
5937 /* find if the memory block is available on a virtual
5938 block device */
5939 sector_num = -1;
5940 for(j = 0; j < MAX_DISKS; j++) {
5941 if (bs_table[j]) {
5942 sector_num = bdrv_hash_find(bs_table[j],
5943 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5944 if (sector_num >= 0)
5945 break;
5948 if (j == MAX_DISKS)
5949 goto normal_compress;
5950 buf[0] = 1;
5951 buf[1] = j;
5952 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5953 ram_compress_buf(s, buf, 10);
5954 } else
5955 #endif
5957 // normal_compress:
5958 buf[0] = 0;
5959 ram_compress_buf(s, buf, 1);
5960 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5963 ram_compress_close(s);
5966 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5968 RamDecompressState s1, *s = &s1;
5969 uint8_t buf[10];
5970 int i;
5972 if (version_id == 1)
5973 return ram_load_v1(f, opaque);
5974 if (version_id != 2)
5975 return -EINVAL;
5976 if (qemu_get_be32(f) != phys_ram_size)
5977 return -EINVAL;
5978 if (ram_decompress_open(s, f) < 0)
5979 return -EINVAL;
5980 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5981 if (ram_decompress_buf(s, buf, 1) < 0) {
5982 fprintf(stderr, "Error while reading ram block header\n");
5983 goto error;
5985 if (buf[0] == 0) {
5986 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5987 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5988 goto error;
5990 } else
5991 #if 0
5992 if (buf[0] == 1) {
5993 int bs_index;
5994 int64_t sector_num;
5996 ram_decompress_buf(s, buf + 1, 9);
5997 bs_index = buf[1];
5998 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5999 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6000 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6001 goto error;
6003 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6004 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6005 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6006 bs_index, sector_num);
6007 goto error;
6009 } else
6010 #endif
6012 error:
6013 printf("Error block header\n");
6014 return -EINVAL;
6017 ram_decompress_close(s);
6018 return 0;
6020 #else /* CONFIG_DM */
6021 void cpu_save(QEMUFile *f, void *opaque)
6025 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6027 return 0;
6030 static void ram_save(QEMUFile *f, void *opaque)
6034 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6036 return 0;
6038 #endif /* CONFIG_DM */
6040 /***********************************************************/
6041 /* bottom halves (can be seen as timers which expire ASAP) */
6043 struct QEMUBH {
6044 QEMUBHFunc *cb;
6045 void *opaque;
6046 int scheduled;
6047 QEMUBH *next;
6048 };
6050 static QEMUBH *first_bh = NULL;
6052 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6054 QEMUBH *bh;
6055 bh = qemu_mallocz(sizeof(QEMUBH));
6056 if (!bh)
6057 return NULL;
6058 bh->cb = cb;
6059 bh->opaque = opaque;
6060 return bh;
6063 int qemu_bh_poll(void)
6065 QEMUBH *bh, **pbh;
6066 int ret;
6068 ret = 0;
6069 for(;;) {
6070 pbh = &first_bh;
6071 bh = *pbh;
6072 if (!bh)
6073 break;
6074 ret = 1;
6075 *pbh = bh->next;
6076 bh->scheduled = 0;
6077 bh->cb(bh->opaque);
6079 return ret;
6082 void qemu_bh_schedule(QEMUBH *bh)
6084 CPUState *env = cpu_single_env;
6085 if (bh->scheduled)
6086 return;
6087 bh->scheduled = 1;
6088 bh->next = first_bh;
6089 first_bh = bh;
6091 /* stop the currently executing CPU to execute the BH ASAP */
6092 if (env) {
6093 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6097 void qemu_bh_cancel(QEMUBH *bh)
6099 QEMUBH **pbh;
6100 if (bh->scheduled) {
6101 pbh = &first_bh;
6102 while (*pbh != bh)
6103 pbh = &(*pbh)->next;
6104 *pbh = bh->next;
6105 bh->scheduled = 0;
6109 void qemu_bh_delete(QEMUBH *bh)
6111 qemu_bh_cancel(bh);
6112 qemu_free(bh);
6115 /***********************************************************/
6116 /* machine registration */
6118 QEMUMachine *first_machine = NULL;
6120 int qemu_register_machine(QEMUMachine *m)
6122 QEMUMachine **pm;
6123 pm = &first_machine;
6124 while (*pm != NULL)
6125 pm = &(*pm)->next;
6126 m->next = NULL;
6127 *pm = m;
6128 return 0;
6131 QEMUMachine *find_machine(const char *name)
6133 QEMUMachine *m;
6135 for(m = first_machine; m != NULL; m = m->next) {
6136 if (!strcmp(m->name, name))
6137 return m;
6139 return NULL;
6142 /***********************************************************/
6143 /* main execution loop */
6145 void gui_update(void *opaque)
6147 display_state.dpy_refresh(&display_state);
6148 qemu_mod_timer(gui_timer,
6149 (display_state.gui_timer_interval ?
6150 display_state.gui_timer_interval :
6151 GUI_REFRESH_INTERVAL)
6152 + qemu_get_clock(rt_clock));
6155 struct vm_change_state_entry {
6156 VMChangeStateHandler *cb;
6157 void *opaque;
6158 LIST_ENTRY (vm_change_state_entry) entries;
6159 };
6161 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6163 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6164 void *opaque)
6166 VMChangeStateEntry *e;
6168 e = qemu_mallocz(sizeof (*e));
6169 if (!e)
6170 return NULL;
6172 e->cb = cb;
6173 e->opaque = opaque;
6174 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6175 return e;
6178 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6180 LIST_REMOVE (e, entries);
6181 qemu_free (e);
6184 static void vm_state_notify(int running)
6186 VMChangeStateEntry *e;
6188 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6189 e->cb(e->opaque, running);
6193 /* XXX: support several handlers */
6194 static VMStopHandler *vm_stop_cb;
6195 static void *vm_stop_opaque;
6197 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6199 vm_stop_cb = cb;
6200 vm_stop_opaque = opaque;
6201 return 0;
6204 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6206 vm_stop_cb = NULL;
6209 void vm_start(void)
6211 if (!vm_running) {
6212 cpu_enable_ticks();
6213 vm_running = 1;
6214 vm_state_notify(1);
6218 void vm_stop(int reason)
6220 if (vm_running) {
6221 cpu_disable_ticks();
6222 vm_running = 0;
6223 if (reason != 0) {
6224 if (vm_stop_cb) {
6225 vm_stop_cb(vm_stop_opaque, reason);
6228 vm_state_notify(0);
6232 /* reset/shutdown handler */
6234 typedef struct QEMUResetEntry {
6235 QEMUResetHandler *func;
6236 void *opaque;
6237 struct QEMUResetEntry *next;
6238 } QEMUResetEntry;
6240 static QEMUResetEntry *first_reset_entry;
6241 int reset_requested;
6242 int shutdown_requested;
6243 int suspend_requested;
6244 static int powerdown_requested;
6246 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6248 QEMUResetEntry **pre, *re;
6250 pre = &first_reset_entry;
6251 while (*pre != NULL)
6252 pre = &(*pre)->next;
6253 re = qemu_mallocz(sizeof(QEMUResetEntry));
6254 re->func = func;
6255 re->opaque = opaque;
6256 re->next = NULL;
6257 *pre = re;
6260 void qemu_system_reset(void)
6262 QEMUResetEntry *re;
6264 /* reset all devices */
6265 for(re = first_reset_entry; re != NULL; re = re->next) {
6266 re->func(re->opaque);
6270 void qemu_system_reset_request(void)
6272 if (no_reboot) {
6273 shutdown_requested = 1;
6274 } else {
6275 reset_requested = 1;
6277 if (cpu_single_env)
6278 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6281 void qemu_system_shutdown_request(void)
6283 shutdown_requested = 1;
6284 if (cpu_single_env)
6285 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6288 void qemu_system_powerdown_request(void)
6290 powerdown_requested = 1;
6291 if (cpu_single_env)
6292 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6295 void main_loop_wait(int timeout)
6297 IOHandlerRecord *ioh;
6298 fd_set rfds, wfds, xfds;
6299 int ret, nfds;
6300 struct timeval tv;
6301 PollingEntry *pe;
6304 /* XXX: need to suppress polling by better using win32 events */
6305 ret = 0;
6306 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6307 ret |= pe->func(pe->opaque);
6309 #ifdef _WIN32
6310 if (ret == 0 && timeout > 0) {
6311 int err;
6312 WaitObjects *w = &wait_objects;
6314 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6315 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6316 if (w->func[ret - WAIT_OBJECT_0])
6317 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6318 } else if (ret == WAIT_TIMEOUT) {
6319 } else {
6320 err = GetLastError();
6321 fprintf(stderr, "Wait error %d %d\n", ret, err);
6324 #endif
6325 /* poll any events */
6326 /* XXX: separate device handlers from system ones */
6327 nfds = -1;
6328 FD_ZERO(&rfds);
6329 FD_ZERO(&wfds);
6330 FD_ZERO(&xfds);
6331 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6332 if (ioh->deleted)
6333 continue;
6334 if (ioh->fd_read &&
6335 (!ioh->fd_read_poll ||
6336 ioh->fd_read_poll(ioh->opaque) != 0)) {
6337 FD_SET(ioh->fd, &rfds);
6338 if (ioh->fd > nfds)
6339 nfds = ioh->fd;
6341 if (ioh->fd_write) {
6342 FD_SET(ioh->fd, &wfds);
6343 if (ioh->fd > nfds)
6344 nfds = ioh->fd;
6348 tv.tv_sec = 0;
6349 #ifdef _WIN32
6350 tv.tv_usec = 0;
6351 #else
6352 tv.tv_usec = timeout * 1000;
6353 #endif
6354 #if defined(CONFIG_SLIRP)
6355 if (slirp_inited) {
6356 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6358 #endif
6359 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6360 if (ret > 0) {
6361 IOHandlerRecord **pioh;
6363 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6364 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6365 ioh->fd_read(ioh->opaque);
6367 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6368 ioh->fd_write(ioh->opaque);
6372 /* remove deleted IO handlers */
6373 pioh = &first_io_handler;
6374 while (*pioh) {
6375 ioh = *pioh;
6376 if (ioh->deleted) {
6377 *pioh = ioh->next;
6378 qemu_free(ioh);
6379 } else
6380 pioh = &ioh->next;
6383 #if defined(CONFIG_SLIRP)
6384 if (slirp_inited) {
6385 if (ret < 0) {
6386 FD_ZERO(&rfds);
6387 FD_ZERO(&wfds);
6388 FD_ZERO(&xfds);
6390 slirp_select_poll(&rfds, &wfds, &xfds);
6392 #endif
6393 qemu_aio_poll();
6394 qemu_bh_poll();
6396 if (vm_running) {
6397 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6398 qemu_get_clock(vm_clock));
6399 /* run dma transfers, if any */
6400 DMA_run();
6403 /* real time timers */
6404 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6405 qemu_get_clock(rt_clock));
6408 #ifndef CONFIG_DM
6409 static CPUState *cur_cpu;
6411 int main_loop(void)
6413 int ret, timeout;
6414 #ifdef CONFIG_PROFILER
6415 int64_t ti;
6416 #endif
6417 CPUState *env;
6419 cur_cpu = first_cpu;
6420 for(;;) {
6421 if (vm_running) {
6423 env = cur_cpu;
6424 for(;;) {
6425 /* get next cpu */
6426 env = env->next_cpu;
6427 if (!env)
6428 env = first_cpu;
6429 #ifdef CONFIG_PROFILER
6430 ti = profile_getclock();
6431 #endif
6432 ret = cpu_exec(env);
6433 #ifdef CONFIG_PROFILER
6434 qemu_time += profile_getclock() - ti;
6435 #endif
6436 if (ret != EXCP_HALTED)
6437 break;
6438 /* all CPUs are halted ? */
6439 if (env == cur_cpu) {
6440 ret = EXCP_HLT;
6441 break;
6444 cur_cpu = env;
6446 if (shutdown_requested) {
6447 ret = EXCP_INTERRUPT;
6448 break;
6450 if (reset_requested) {
6451 reset_requested = 0;
6452 qemu_system_reset();
6453 ret = EXCP_INTERRUPT;
6455 if (powerdown_requested) {
6456 powerdown_requested = 0;
6457 qemu_system_powerdown();
6458 ret = EXCP_INTERRUPT;
6460 if (ret == EXCP_DEBUG) {
6461 vm_stop(EXCP_DEBUG);
6463 /* if hlt instruction, we wait until the next IRQ */
6464 /* XXX: use timeout computed from timers */
6465 if (ret == EXCP_HLT)
6466 timeout = 10;
6467 else
6468 timeout = 0;
6469 } else {
6470 timeout = 10;
6472 #ifdef CONFIG_PROFILER
6473 ti = profile_getclock();
6474 #endif
6475 main_loop_wait(timeout);
6476 #ifdef CONFIG_PROFILER
6477 dev_time += profile_getclock() - ti;
6478 #endif
6480 cpu_disable_ticks();
6481 return ret;
6483 #endif /* !CONFIG_DM */
6485 void help(void)
6487 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6488 "usage: %s [options] [disk_image]\n"
6489 "\n"
6490 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6491 "\n"
6492 "Standard options:\n"
6493 "-M machine select emulated machine (-M ? for list)\n"
6494 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6495 #ifndef CONFIG_DM
6496 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6497 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6498 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6499 #endif /* !CONFIG_DM */
6500 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6501 "-snapshot write to temporary files instead of disk image files\n"
6502 #ifdef CONFIG_SDL
6503 "-no-quit disable SDL window close capability\n"
6504 #endif
6505 #ifdef CONFIG_OPENGL
6506 "-disable-opengl disable OpenGL rendering, using SDL"
6507 #endif
6508 #ifdef TARGET_I386
6509 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6510 #endif
6511 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6512 "-smp n set the number of CPUs to 'n' [default=1]\n"
6513 "-nographic disable graphical output and redirect serial I/Os to console\n"
6514 "-vcpus set CPU number of guest platform\n"
6515 #ifndef _WIN32
6516 "-k language use keyboard layout (for example \"fr\" for French)\n"
6517 #endif
6518 #ifdef HAS_AUDIO
6519 "-audio-help print list of audio drivers and their options\n"
6520 "-soundhw c1,... enable audio support\n"
6521 " and only specified sound cards (comma separated list)\n"
6522 " use -soundhw ? to get the list of supported cards\n"
6523 " use -soundhw all to enable all of them\n"
6524 #endif
6525 "-localtime set the real time clock to local time [default=utc]\n"
6526 "-full-screen start in full screen\n"
6527 #ifdef TARGET_I386
6528 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6529 #endif
6530 "-usb enable the USB driver (will be the default soon)\n"
6531 "-usbdevice name add the host or guest USB device 'name'\n"
6532 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6533 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6534 #endif
6535 "\n"
6536 "Network options:\n"
6537 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6538 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6539 #ifdef CONFIG_SLIRP
6540 "-net user[,vlan=n][,hostname=host]\n"
6541 " connect the user mode network stack to VLAN 'n' and send\n"
6542 " hostname 'host' to DHCP clients\n"
6543 #endif
6544 #ifdef _WIN32
6545 "-net tap[,vlan=n],ifname=name\n"
6546 " connect the host TAP network interface to VLAN 'n'\n"
6547 #else
6548 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
6549 " connect the host TAP network interface to VLAN 'n' and use\n"
6550 " the network script 'file' (default=%s);\n"
6551 " use 'script=no' to disable script execution;\n"
6552 " use 'fd=h' to connect to an already opened TAP interface\n"
6553 #endif
6554 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6555 " connect the vlan 'n' to another VLAN using a socket connection\n"
6556 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6557 " connect the vlan 'n' to multicast maddr and port\n"
6558 "-net none use it alone to have zero network devices; if no -net option\n"
6559 " is provided, the default is '-net nic -net user'\n"
6560 "\n"
6561 #ifdef CONFIG_SLIRP
6562 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6563 #ifndef _WIN32
6564 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6565 #endif
6566 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6567 " redirect TCP or UDP connections from host to guest [-net user]\n"
6568 #endif
6569 "\n"
6570 "Linux boot specific:\n"
6571 "-kernel bzImage use 'bzImage' as kernel image\n"
6572 "-append cmdline use 'cmdline' as kernel command line\n"
6573 "-initrd file use 'file' as initial ram disk\n"
6574 "\n"
6575 "Debug/Expert options:\n"
6576 "-monitor dev redirect the monitor to char device 'dev'\n"
6577 "-serial dev redirect the serial port to char device 'dev'\n"
6578 "-parallel dev redirect the parallel port to char device 'dev'\n"
6579 "-pidfile file Write PID to 'file'\n"
6580 "-S freeze CPU at startup (use 'c' to start execution)\n"
6581 "-s wait gdb connection to port %d\n"
6582 "-p port change gdb connection port\n"
6583 "-l item1,... output log to %s (use -d ? for a list of log items)\n"
6584 "-d domain domain that we're serving\n"
6585 "-domain-name domain name that we're serving\n"
6586 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6587 " translation (t=none or lba) (usually qemu can guess them)\n"
6588 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6589 #ifdef USE_KQEMU
6590 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6591 "-no-kqemu disable KQEMU kernel module usage\n"
6592 #endif
6593 #ifdef USE_CODE_COPY
6594 "-no-code-copy disable code copy acceleration\n"
6595 #endif
6596 #ifdef TARGET_I386
6597 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6598 " (default is CL-GD5446 PCI VGA)\n"
6599 "-no-acpi disable ACPI\n"
6600 #endif
6601 "-no-reboot exit instead of rebooting\n"
6602 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6603 "-vnc display start a VNC server on display\n"
6604 "-vncviewer start a vncviewer process for this domain\n"
6605 "-vncunused bind the VNC server to an unused port\n"
6606 #ifndef NO_DAEMONIZE
6607 "-daemonize daemonize QEMU after initializing\n"
6608 #endif
6609 "-option-rom rom load a file, rom, into the option ROM space\n"
6610 "-acpi disable or enable ACPI of HVM domain \n"
6611 "-pciemulation name:vendorid:deviceid:command:status:revision:classcode:headertype:subvendorid:subsystemid:interruputline:interruputpin\n"
6612 "\n"
6613 "During emulation, the following keys are useful:\n"
6614 "ctrl-alt-f toggle full screen\n"
6615 "ctrl-alt-n switch to virtual console 'n'\n"
6616 "ctrl-alt toggle mouse and keyboard grab\n"
6617 "\n"
6618 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6620 "qemu",
6621 DEFAULT_RAM_SIZE,
6622 #ifndef _WIN32
6623 DEFAULT_NETWORK_SCRIPT,
6624 #endif
6625 DEFAULT_GDBSTUB_PORT,
6626 "/tmp/qemu.log");
6627 exit(1);
6630 #define HAS_ARG 0x0001
6632 enum {
6633 QEMU_OPTION_h,
6635 QEMU_OPTION_M,
6636 QEMU_OPTION_fda,
6637 QEMU_OPTION_fdb,
6638 #ifndef CONFIG_DM
6639 QEMU_OPTION_hda,
6640 QEMU_OPTION_hdb,
6641 QEMU_OPTION_hdc,
6642 QEMU_OPTION_hdd,
6643 QEMU_OPTION_cdrom,
6644 #endif /* !CONFIG_DM */
6645 QEMU_OPTION_boot,
6646 QEMU_OPTION_snapshot,
6647 #ifdef TARGET_I386
6648 QEMU_OPTION_no_fd_bootchk,
6649 #endif
6650 QEMU_OPTION_m,
6651 QEMU_OPTION_nographic,
6652 #ifdef HAS_AUDIO
6653 QEMU_OPTION_audio_help,
6654 QEMU_OPTION_soundhw,
6655 #endif
6657 QEMU_OPTION_net,
6658 QEMU_OPTION_tftp,
6659 QEMU_OPTION_smb,
6660 QEMU_OPTION_redir,
6662 QEMU_OPTION_kernel,
6663 QEMU_OPTION_append,
6664 QEMU_OPTION_initrd,
6666 QEMU_OPTION_S,
6667 QEMU_OPTION_s,
6668 QEMU_OPTION_p,
6669 QEMU_OPTION_l,
6670 QEMU_OPTION_hdachs,
6671 QEMU_OPTION_L,
6672 #ifdef USE_CODE_COPY
6673 QEMU_OPTION_no_code_copy,
6674 #endif
6675 QEMU_OPTION_k,
6676 QEMU_OPTION_localtime,
6677 QEMU_OPTION_cirrusvga,
6678 QEMU_OPTION_g,
6679 QEMU_OPTION_std_vga,
6680 QEMU_OPTION_monitor,
6681 QEMU_OPTION_domainname,
6682 QEMU_OPTION_serial,
6683 QEMU_OPTION_parallel,
6684 QEMU_OPTION_loadvm,
6685 QEMU_OPTION_full_screen,
6686 QEMU_OPTION_no_quit,
6687 QEMU_OPTION_disable_opengl,
6688 QEMU_OPTION_pidfile,
6689 QEMU_OPTION_no_kqemu,
6690 QEMU_OPTION_kernel_kqemu,
6691 QEMU_OPTION_win2k_hack,
6692 QEMU_OPTION_usb,
6693 QEMU_OPTION_usbdevice,
6694 QEMU_OPTION_smp,
6695 QEMU_OPTION_vnc,
6696 QEMU_OPTION_no_acpi,
6697 QEMU_OPTION_no_reboot,
6698 #ifndef NO_DAEMONIZE
6699 QEMU_OPTION_daemonize,
6700 #endif
6701 QEMU_OPTION_option_rom,
6702 QEMU_OPTION_semihosting
6704 QEMU_OPTION_d,
6705 QEMU_OPTION_vcpus,
6706 QEMU_OPTION_acpi,
6707 QEMU_OPTION_vncviewer,
6708 QEMU_OPTION_vncunused,
6709 QEMU_OPTION_pci,
6710 QEMU_OPTION_pci_emulation,
6711 };
6713 typedef struct QEMUOption {
6714 const char *name;
6715 int flags;
6716 int index;
6717 } QEMUOption;
6719 const QEMUOption qemu_options[] = {
6720 { "h", 0, QEMU_OPTION_h },
6721 { "help", 0, QEMU_OPTION_h },
6723 { "M", HAS_ARG, QEMU_OPTION_M },
6724 { "fda", HAS_ARG, QEMU_OPTION_fda },
6725 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6726 #ifndef CONFIG_DM
6727 { "hda", HAS_ARG, QEMU_OPTION_hda },
6728 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6729 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6730 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6731 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6732 #endif /* !CONFIG_DM */
6733 { "boot", HAS_ARG, QEMU_OPTION_boot },
6734 { "snapshot", 0, QEMU_OPTION_snapshot },
6735 #ifdef TARGET_I386
6736 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6737 #endif
6738 { "m", HAS_ARG, QEMU_OPTION_m },
6739 { "nographic", 0, QEMU_OPTION_nographic },
6740 { "k", HAS_ARG, QEMU_OPTION_k },
6741 #ifdef HAS_AUDIO
6742 { "audio-help", 0, QEMU_OPTION_audio_help },
6743 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6744 #endif
6746 { "net", HAS_ARG, QEMU_OPTION_net},
6747 #ifdef CONFIG_SLIRP
6748 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6749 #ifndef _WIN32
6750 { "smb", HAS_ARG, QEMU_OPTION_smb },
6751 #endif
6752 { "redir", HAS_ARG, QEMU_OPTION_redir },
6753 #endif
6755 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6756 { "append", HAS_ARG, QEMU_OPTION_append },
6757 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6759 { "S", 0, QEMU_OPTION_S },
6760 { "s", 0, QEMU_OPTION_s },
6761 { "p", HAS_ARG, QEMU_OPTION_p },
6762 { "l", HAS_ARG, QEMU_OPTION_l },
6763 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6764 { "L", HAS_ARG, QEMU_OPTION_L },
6765 #ifdef USE_CODE_COPY
6766 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6767 #endif
6768 #ifdef USE_KQEMU
6769 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6770 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6771 #endif
6772 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6773 { "g", 1, QEMU_OPTION_g },
6774 #endif
6775 { "localtime", 0, QEMU_OPTION_localtime },
6776 { "std-vga", 0, QEMU_OPTION_std_vga },
6777 { "monitor", 1, QEMU_OPTION_monitor },
6778 { "domain-name", 1, QEMU_OPTION_domainname },
6779 { "serial", 1, QEMU_OPTION_serial },
6780 { "parallel", 1, QEMU_OPTION_parallel },
6781 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6782 { "full-screen", 0, QEMU_OPTION_full_screen },
6783 #ifdef CONFIG_SDL
6784 { "no-quit", 0, QEMU_OPTION_no_quit },
6785 #endif
6786 { "disable-opengl", 0, QEMU_OPTION_disable_opengl },
6787 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6788 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6789 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6790 { "smp", HAS_ARG, QEMU_OPTION_smp },
6791 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6792 { "vncviewer", 0, QEMU_OPTION_vncviewer },
6793 { "vncunused", 0, QEMU_OPTION_vncunused },
6795 /* temporary options */
6796 { "usb", 0, QEMU_OPTION_usb },
6797 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6798 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6799 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6800 #ifndef NO_DAEMONIZE
6801 { "daemonize", 0, QEMU_OPTION_daemonize },
6802 #endif
6803 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6804 #if defined(TARGET_ARM)
6805 { "semihosting", 0, QEMU_OPTION_semihosting },
6806 #endif
6808 { "d", HAS_ARG, QEMU_OPTION_d },
6809 { "vcpus", 1, QEMU_OPTION_vcpus },
6810 { "acpi", 0, QEMU_OPTION_acpi },
6811 { "pci", HAS_ARG, QEMU_OPTION_pci},
6812 { "pciemulation", HAS_ARG, QEMU_OPTION_pci_emulation },
6813 { NULL },
6814 };
6816 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6818 /* this stack is only used during signal handling */
6819 #define SIGNAL_STACK_SIZE 32768
6821 static uint8_t *signal_stack;
6823 #endif
6825 /* password input */
6827 static BlockDriverState *get_bdrv(int index)
6829 BlockDriverState *bs;
6831 if (index < 4) {
6832 bs = bs_table[index];
6833 } else if (index < 6) {
6834 bs = fd_table[index - 4];
6835 } else {
6836 bs = NULL;
6838 return bs;
6841 static void read_passwords(void)
6843 BlockDriverState *bs;
6844 int i, j;
6845 char password[256];
6847 for(i = 0; i < 6; i++) {
6848 bs = get_bdrv(i);
6849 if (bs && bdrv_is_encrypted(bs)) {
6850 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6851 for(j = 0; j < 3; j++) {
6852 monitor_readline("Password: ",
6853 1, password, sizeof(password));
6854 if (bdrv_set_key(bs, password) == 0)
6855 break;
6856 term_printf("invalid password\n");
6862 /* XXX: currently we cannot use simultaneously different CPUs */
6863 void register_machines(void)
6865 #if defined(TARGET_I386)
6866 #ifndef CONFIG_DM
6867 qemu_register_machine(&pc_machine);
6868 qemu_register_machine(&isapc_machine);
6869 #else
6870 qemu_register_machine(&xenfv_machine);
6871 qemu_register_machine(&xenpv_machine);
6872 #endif
6873 #elif defined(TARGET_PPC)
6874 qemu_register_machine(&heathrow_machine);
6875 qemu_register_machine(&core99_machine);
6876 qemu_register_machine(&prep_machine);
6877 #elif defined(TARGET_MIPS)
6878 qemu_register_machine(&mips_machine);
6879 qemu_register_machine(&mips_malta_machine);
6880 #elif defined(TARGET_SPARC)
6881 #ifdef TARGET_SPARC64
6882 qemu_register_machine(&sun4u_machine);
6883 #else
6884 qemu_register_machine(&sun4m_machine);
6885 #endif
6886 #elif defined(TARGET_ARM)
6887 qemu_register_machine(&integratorcp926_machine);
6888 qemu_register_machine(&integratorcp1026_machine);
6889 qemu_register_machine(&versatilepb_machine);
6890 qemu_register_machine(&versatileab_machine);
6891 qemu_register_machine(&realview_machine);
6892 #elif defined(TARGET_SH4)
6893 qemu_register_machine(&shix_machine);
6894 #else
6895 #error unsupported CPU
6896 #endif
6899 #ifdef HAS_AUDIO
6900 struct soundhw soundhw[] = {
6901 #ifndef CONFIG_DM
6902 #ifdef TARGET_I386
6904 "pcspk",
6905 "PC speaker",
6906 0,
6907 1,
6908 { .init_isa = pcspk_audio_init }
6909 },
6910 #endif
6911 #endif /* !CONFIG_DM */
6913 "sb16",
6914 "Creative Sound Blaster 16",
6915 0,
6916 1,
6917 { .init_isa = SB16_init }
6918 },
6920 #ifdef CONFIG_ADLIB
6922 "adlib",
6923 #ifdef HAS_YMF262
6924 "Yamaha YMF262 (OPL3)",
6925 #else
6926 "Yamaha YM3812 (OPL2)",
6927 #endif
6928 0,
6929 1,
6930 { .init_isa = Adlib_init }
6931 },
6932 #endif
6934 #ifdef CONFIG_GUS
6936 "gus",
6937 "Gravis Ultrasound GF1",
6938 0,
6939 1,
6940 { .init_isa = GUS_init }
6941 },
6942 #endif
6945 "es1370",
6946 "ENSONIQ AudioPCI ES1370",
6947 0,
6948 0,
6949 { .init_pci = es1370_init }
6950 },
6952 { NULL, NULL, 0, 0, { NULL } }
6953 };
6955 static void select_soundhw (const char *optarg)
6957 struct soundhw *c;
6959 if (*optarg == '?') {
6960 show_valid_cards:
6962 printf ("Valid sound card names (comma separated):\n");
6963 for (c = soundhw; c->name; ++c) {
6964 printf ("%-11s %s\n", c->name, c->descr);
6966 printf ("\n-soundhw all will enable all of the above\n");
6967 exit (*optarg != '?');
6969 else {
6970 size_t l;
6971 const char *p;
6972 char *e;
6973 int bad_card = 0;
6975 if (!strcmp (optarg, "all")) {
6976 for (c = soundhw; c->name; ++c) {
6977 c->enabled = 1;
6979 return;
6982 p = optarg;
6983 while (*p) {
6984 e = strchr (p, ',');
6985 l = !e ? strlen (p) : (size_t) (e - p);
6987 for (c = soundhw; c->name; ++c) {
6988 if (!strncmp (c->name, p, l)) {
6989 c->enabled = 1;
6990 break;
6994 if (!c->name) {
6995 if (l > 80) {
6996 fprintf (stderr,
6997 "Unknown sound card name (too big to show)\n");
6999 else {
7000 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7001 (int) l, p);
7003 bad_card = 1;
7005 p += l + (e != NULL);
7008 if (bad_card)
7009 goto show_valid_cards;
7012 #endif
7014 #ifdef _WIN32
7015 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7017 exit(STATUS_CONTROL_C_EXIT);
7018 return TRUE;
7020 #endif
7022 #define MAX_NET_CLIENTS 32
7024 #include <xg_private.h>
7027 int main(int argc, char **argv)
7029 #ifdef CONFIG_GDBSTUB
7030 int use_gdbstub, gdbstub_port;
7031 #endif
7032 int i;
7033 #ifndef CONFIG_DM
7034 int cdrom_index;
7035 #endif /* !CONFIG_DM */
7036 int snapshot, linux_boot;
7037 const char *initrd_filename;
7038 #ifndef CONFIG_DM
7039 const char *hd_filename[MAX_DISKS + MAX_SCSI_DISKS];
7040 #endif /* !CONFIG_DM */
7041 const char *fd_filename[MAX_FD];
7042 const char *kernel_filename, *kernel_cmdline;
7043 DisplayState *ds = &display_state;
7044 int cyls, heads, secs, translation;
7045 char net_clients[MAX_NET_CLIENTS][256];
7046 int nb_net_clients;
7047 int optind;
7048 const char *r, *optarg;
7049 CharDriverState *monitor_hd;
7050 char monitor_device[128];
7051 char serial_devices[MAX_SERIAL_PORTS][128];
7052 int serial_device_index;
7053 char parallel_devices[MAX_PARALLEL_PORTS][128];
7054 int parallel_device_index;
7055 const char *loadvm = NULL;
7056 QEMUMachine *machine;
7057 char usb_devices[MAX_USB_CMDLINE][128];
7058 int usb_devices_index;
7059 int fds[2];
7060 #ifndef CONFIG_STUBDOM
7061 struct rlimit rl;
7062 #endif
7063 sigset_t set;
7064 char qemu_dm_logfilename[128];
7065 const char *direct_pci = direct_pci_str;
7066 int nb_pci_emulation = 0;
7067 char pci_emulation_config_text[MAX_PCI_EMULATION][256];
7069 #if !defined(__sun__) && !defined(CONFIG_STUBDOM)
7070 /* Maximise rlimits. Needed where default constraints are tight (*BSD). */
7071 if (getrlimit(RLIMIT_STACK, &rl) != 0) {
7072 perror("getrlimit(RLIMIT_STACK)");
7073 exit(1);
7075 rl.rlim_cur = rl.rlim_max;
7076 if (setrlimit(RLIMIT_STACK, &rl) != 0)
7077 perror("setrlimit(RLIMIT_STACK)");
7078 if (getrlimit(RLIMIT_DATA, &rl) != 0) {
7079 perror("getrlimit(RLIMIT_DATA)");
7080 exit(1);
7082 rl.rlim_cur = rl.rlim_max;
7083 if (setrlimit(RLIMIT_DATA, &rl) != 0)
7084 perror("setrlimit(RLIMIT_DATA)");
7085 rl.rlim_cur = RLIM_INFINITY;
7086 rl.rlim_max = RLIM_INFINITY;
7087 if (setrlimit(RLIMIT_RSS, &rl) != 0)
7088 perror("setrlimit(RLIMIT_RSS)");
7089 rl.rlim_cur = RLIM_INFINITY;
7090 rl.rlim_max = RLIM_INFINITY;
7091 if (setrlimit(RLIMIT_MEMLOCK, &rl) != 0)
7092 perror("setrlimit(RLIMIT_MEMLOCK)");
7093 #endif
7095 #ifndef CONFIG_STUBDOM
7096 /* Ensure that SIGUSR2 is blocked by default when a new thread is created,
7097 then only the threads that use the signal unblock it -- this fixes a
7098 race condition in Qcow support where the AIO signal is misdelivered. */
7100 extern const int aio_sig_num;
7101 sigset_t set;
7103 sigemptyset(&set);
7104 sigaddset(&set, aio_sig_num);
7105 sigprocmask(SIG_BLOCK, &set, NULL);
7107 #endif
7109 LIST_INIT (&vm_change_state_head);
7110 #ifndef CONFIG_STUBDOM
7111 #ifndef _WIN32
7113 struct sigaction act;
7114 sigfillset(&act.sa_mask);
7115 act.sa_flags = 0;
7116 act.sa_handler = SIG_IGN;
7117 sigaction(SIGPIPE, &act, NULL);
7119 #else
7120 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7121 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7122 QEMU to run on a single CPU */
7124 HANDLE h;
7125 DWORD mask, smask;
7126 int i;
7127 h = GetCurrentProcess();
7128 if (GetProcessAffinityMask(h, &mask, &smask)) {
7129 for(i = 0; i < 32; i++) {
7130 if (mask & (1 << i))
7131 break;
7133 if (i != 32) {
7134 mask = 1 << i;
7135 SetProcessAffinityMask(h, mask);
7139 #endif
7140 #endif
7142 register_machines();
7143 machine = first_machine;
7144 initrd_filename = NULL;
7145 for(i = 0; i < MAX_FD; i++)
7146 fd_filename[i] = NULL;
7147 #ifndef CONFIG_DM
7148 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++)
7149 hd_filename[i] = NULL;
7150 #endif /* !CONFIG_DM */
7151 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7152 vga_ram_size = VGA_RAM_SIZE;
7153 bios_size = BIOS_SIZE;
7154 #ifdef CONFIG_GDBSTUB
7155 use_gdbstub = 0;
7156 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7157 #endif
7158 snapshot = 0;
7159 nographic = 0;
7160 vncviewer = 0;
7161 vncunused = 0;
7162 kernel_filename = NULL;
7163 kernel_cmdline = "";
7164 #ifndef CONFIG_DM
7165 #ifdef TARGET_PPC
7166 cdrom_index = 1;
7167 #else
7168 cdrom_index = 2;
7169 #endif
7170 #endif /* !CONFIG_DM */
7171 cyls = heads = secs = 0;
7172 translation = BIOS_ATA_TRANSLATION_AUTO;
7173 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7175 for(i = 0; i < MAX_SERIAL_PORTS; i++)
7176 serial_devices[i][0] = '\0';
7177 serial_device_index = 0;
7179 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7180 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7181 parallel_devices[i][0] = '\0';
7182 parallel_device_index = 0;
7184 usb_devices_index = 0;
7186 nb_net_clients = 0;
7188 nb_nics = 0;
7189 /* default mac address of the first network interface */
7191 /* Init logs to stderr to start with */
7192 cpu_set_log(0);
7194 optind = 1;
7195 for(;;) {
7196 if (optind >= argc)
7197 break;
7198 r = argv[optind];
7199 if (r[0] != '-') {
7200 #ifndef CONFIG_DM
7201 hd_filename[0] = argv[optind++];
7202 #else
7203 help();
7204 #endif /* !CONFIG_DM */
7205 } else {
7206 const QEMUOption *popt;
7208 optind++;
7209 /* Treat --foo the same as -foo. */
7210 if (r[1] == '-')
7211 r++;
7212 popt = qemu_options;
7213 for(;;) {
7214 if (!popt->name) {
7215 fprintf(stderr, "%s: invalid option -- '%s'\n",
7216 argv[0], r);
7217 exit(1);
7219 if (!strcmp(popt->name, r + 1))
7220 break;
7221 popt++;
7223 if (popt->flags & HAS_ARG) {
7224 if (optind >= argc) {
7225 fprintf(stderr, "%s: option '%s' requires an argument\n",
7226 argv[0], r);
7227 exit(1);
7229 optarg = argv[optind++];
7230 } else {
7231 optarg = NULL;
7234 switch(popt->index) {
7235 case QEMU_OPTION_M:
7236 machine = find_machine(optarg);
7237 if (!machine) {
7238 QEMUMachine *m;
7239 printf("Supported machines are:\n");
7240 for(m = first_machine; m != NULL; m = m->next) {
7241 printf("%-10s %s%s\n",
7242 m->name, m->desc,
7243 m == first_machine ? " (default)" : "");
7245 exit(1);
7247 break;
7248 case QEMU_OPTION_initrd:
7249 initrd_filename = optarg;
7250 break;
7251 #ifndef CONFIG_DM
7252 case QEMU_OPTION_hda:
7253 case QEMU_OPTION_hdb:
7254 case QEMU_OPTION_hdc:
7255 case QEMU_OPTION_hdd:
7257 int hd_index;
7258 hd_index = popt->index - QEMU_OPTION_hda;
7259 hd_filename[hd_index] = optarg;
7260 if (hd_index == cdrom_index)
7261 cdrom_index = -1;
7263 break;
7264 #endif /* !CONFIG_DM */
7265 case QEMU_OPTION_snapshot:
7266 snapshot = 1;
7267 break;
7268 case QEMU_OPTION_hdachs:
7270 const char *p;
7271 p = optarg;
7272 cyls = strtol(p, (char **)&p, 0);
7273 if (cyls < 1 || cyls > 16383)
7274 goto chs_fail;
7275 if (*p != ',')
7276 goto chs_fail;
7277 p++;
7278 heads = strtol(p, (char **)&p, 0);
7279 if (heads < 1 || heads > 16)
7280 goto chs_fail;
7281 if (*p != ',')
7282 goto chs_fail;
7283 p++;
7284 secs = strtol(p, (char **)&p, 0);
7285 if (secs < 1 || secs > 63)
7286 goto chs_fail;
7287 if (*p == ',') {
7288 p++;
7289 if (!strcmp(p, "none"))
7290 translation = BIOS_ATA_TRANSLATION_NONE;
7291 else if (!strcmp(p, "lba"))
7292 translation = BIOS_ATA_TRANSLATION_LBA;
7293 else if (!strcmp(p, "auto"))
7294 translation = BIOS_ATA_TRANSLATION_AUTO;
7295 else
7296 goto chs_fail;
7297 } else if (*p != '\0') {
7298 chs_fail:
7299 fprintf(stderr, "qemu: invalid physical CHS format\n");
7300 exit(1);
7303 break;
7304 case QEMU_OPTION_nographic:
7305 if(!strcmp(monitor_device, "vc"))
7306 pstrcpy(monitor_device, sizeof(monitor_device), "null");
7307 if(!strcmp(serial_devices[0], "vc"))
7308 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
7309 "null");
7310 nographic = 1;
7311 break;
7312 case QEMU_OPTION_kernel:
7313 kernel_filename = optarg;
7314 break;
7315 case QEMU_OPTION_append:
7316 kernel_cmdline = optarg;
7317 break;
7318 #ifndef CONFIG_DM
7319 case QEMU_OPTION_cdrom:
7320 if (cdrom_index >= 0) {
7321 hd_filename[cdrom_index] = optarg;
7323 break;
7324 #endif /* !CONFIG_DM */
7325 case QEMU_OPTION_boot:
7326 boot_device = strdup(optarg);
7327 if (strspn(boot_device, "a"
7328 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7329 // Network boot
7330 "n"
7331 #endif
7332 "cd") != strlen(boot_device)) {
7333 fprintf(stderr, "qemu: invalid boot device in '%s'\n", boot_device);
7334 exit(1);
7336 break;
7337 case QEMU_OPTION_fda:
7338 fd_filename[0] = optarg;
7339 break;
7340 case QEMU_OPTION_fdb:
7341 fd_filename[1] = optarg;
7342 break;
7343 #ifdef TARGET_I386
7344 case QEMU_OPTION_no_fd_bootchk:
7345 fd_bootchk = 0;
7346 break;
7347 #endif
7348 #ifdef USE_CODE_COPY
7349 case QEMU_OPTION_no_code_copy:
7350 code_copy_enabled = 0;
7351 break;
7352 #endif
7353 case QEMU_OPTION_net:
7354 if (nb_net_clients >= MAX_NET_CLIENTS) {
7355 fprintf(stderr, "qemu: too many network clients\n");
7356 exit(1);
7358 pstrcpy(net_clients[nb_net_clients],
7359 sizeof(net_clients[0]),
7360 optarg);
7361 nb_net_clients++;
7362 break;
7363 #ifdef CONFIG_SLIRP
7364 case QEMU_OPTION_tftp:
7365 tftp_prefix = optarg;
7366 break;
7367 #ifndef _WIN32
7368 case QEMU_OPTION_smb:
7369 net_slirp_smb(optarg);
7370 break;
7371 #endif
7372 case QEMU_OPTION_redir:
7373 net_slirp_redir(optarg);
7374 break;
7375 #endif
7376 #ifdef HAS_AUDIO
7377 case QEMU_OPTION_audio_help:
7378 AUD_help ();
7379 exit (0);
7380 break;
7381 case QEMU_OPTION_soundhw:
7382 select_soundhw (optarg);
7383 break;
7384 #endif
7385 case QEMU_OPTION_h:
7386 help();
7387 break;
7388 case QEMU_OPTION_m:
7389 ram_size = atol(optarg) * 1024 * 1024;
7390 ram_size = (uint64_t)atol(optarg) * 1024 * 1024;
7391 if (ram_size <= 0)
7392 help();
7393 #ifndef CONFIG_DM
7394 if (ram_size > PHYS_RAM_MAX_SIZE) {
7395 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7396 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7397 exit(1);
7399 #endif /* !CONFIG_DM */
7400 break;
7401 case QEMU_OPTION_l:
7403 int mask;
7404 CPULogItem *item;
7406 mask = cpu_str_to_log_mask(optarg);
7407 if (!mask) {
7408 printf("Log items (comma separated):\n");
7409 for(item = cpu_log_items; item->mask != 0; item++) {
7410 printf("%-10s %s\n", item->name, item->help);
7412 exit(1);
7414 cpu_set_log(mask);
7416 break;
7417 #ifdef CONFIG_GDBSTUB
7418 case QEMU_OPTION_s:
7419 use_gdbstub = 1;
7420 break;
7421 case QEMU_OPTION_p:
7422 gdbstub_port = atoi(optarg);
7423 break;
7424 #endif
7425 case QEMU_OPTION_L:
7426 bios_dir = optarg;
7427 break;
7428 case QEMU_OPTION_S:
7429 autostart = 0;
7430 break;
7431 case QEMU_OPTION_k:
7432 keyboard_layout = optarg;
7433 break;
7434 case QEMU_OPTION_localtime:
7435 rtc_utc = 0;
7436 break;
7437 case QEMU_OPTION_cirrusvga:
7438 cirrus_vga_enabled = 1;
7439 break;
7440 case QEMU_OPTION_std_vga:
7441 cirrus_vga_enabled = 0;
7442 break;
7443 case QEMU_OPTION_g:
7445 const char *p;
7446 int w, h, depth;
7447 p = optarg;
7448 w = strtol(p, (char **)&p, 10);
7449 if (w <= 0) {
7450 graphic_error:
7451 fprintf(stderr, "qemu: invalid resolution or depth\n");
7452 exit(1);
7454 if (*p != 'x')
7455 goto graphic_error;
7456 p++;
7457 h = strtol(p, (char **)&p, 10);
7458 if (h <= 0)
7459 goto graphic_error;
7460 if (*p == 'x') {
7461 p++;
7462 depth = strtol(p, (char **)&p, 10);
7463 if (depth != 8 && depth != 15 && depth != 16 &&
7464 depth != 24 && depth != 32)
7465 goto graphic_error;
7466 } else if (*p == '\0') {
7467 depth = graphic_depth;
7468 } else {
7469 goto graphic_error;
7472 graphic_width = w;
7473 graphic_height = h;
7474 graphic_depth = depth;
7476 break;
7477 case QEMU_OPTION_monitor:
7478 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7479 break;
7480 case QEMU_OPTION_serial:
7481 if (serial_device_index >= MAX_SERIAL_PORTS) {
7482 fprintf(stderr, "qemu: too many serial ports\n");
7483 exit(1);
7485 pstrcpy(serial_devices[serial_device_index],
7486 sizeof(serial_devices[0]), optarg);
7487 serial_device_index++;
7488 break;
7489 case QEMU_OPTION_parallel:
7490 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7491 fprintf(stderr, "qemu: too many parallel ports\n");
7492 exit(1);
7494 pstrcpy(parallel_devices[parallel_device_index],
7495 sizeof(parallel_devices[0]), optarg);
7496 parallel_device_index++;
7497 break;
7498 case QEMU_OPTION_loadvm:
7499 loadvm = optarg;
7500 break;
7501 case QEMU_OPTION_full_screen:
7502 full_screen = 1;
7503 break;
7504 #ifdef CONFIG_SDL
7505 case QEMU_OPTION_no_quit:
7506 no_quit = 1;
7507 break;
7508 #endif
7509 case QEMU_OPTION_disable_opengl:
7510 opengl_enabled = 0;
7511 break;
7512 case QEMU_OPTION_pidfile:
7513 create_pidfile(optarg);
7514 break;
7515 #ifdef TARGET_I386
7516 case QEMU_OPTION_win2k_hack:
7517 win2k_install_hack = 1;
7518 break;
7519 #endif
7520 #ifdef USE_KQEMU
7521 case QEMU_OPTION_no_kqemu:
7522 kqemu_allowed = 0;
7523 break;
7524 case QEMU_OPTION_kernel_kqemu:
7525 kqemu_allowed = 2;
7526 break;
7527 #endif
7528 case QEMU_OPTION_usb:
7529 usb_enabled = 1;
7530 break;
7531 case QEMU_OPTION_usbdevice:
7532 usb_enabled = 1;
7533 if (usb_devices_index >= MAX_USB_CMDLINE) {
7534 fprintf(stderr, "Too many USB devices\n");
7535 exit(1);
7537 pstrcpy(usb_devices[usb_devices_index],
7538 sizeof(usb_devices[usb_devices_index]),
7539 optarg);
7540 usb_devices_index++;
7541 break;
7542 case QEMU_OPTION_smp:
7543 smp_cpus = atoi(optarg);
7544 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7545 fprintf(stderr, "Invalid number of CPUs\n");
7546 exit(1);
7548 break;
7549 case QEMU_OPTION_vnc:
7550 vnc_display = optarg;
7551 break;
7552 case QEMU_OPTION_no_acpi:
7553 acpi_enabled = 0;
7554 break;
7555 case QEMU_OPTION_no_reboot:
7556 no_reboot = 1;
7557 break;
7558 #ifndef NO_DAEMONIZE
7559 case QEMU_OPTION_daemonize:
7560 daemonize = 1;
7561 break;
7562 #endif
7563 case QEMU_OPTION_option_rom:
7564 if (nb_option_roms >= MAX_OPTION_ROMS) {
7565 fprintf(stderr, "Too many option ROMs\n");
7566 exit(1);
7568 option_rom[nb_option_roms] = optarg;
7569 nb_option_roms++;
7570 break;
7571 case QEMU_OPTION_semihosting:
7572 semihosting_enabled = 1;
7573 break;
7574 case QEMU_OPTION_domainname:
7575 snprintf(domain_name, sizeof(domain_name),
7576 "Xen-%s", optarg);
7577 break;
7578 case QEMU_OPTION_d:
7579 domid = atoi(optarg);
7580 fprintf(logfile, "domid: %d\n", domid);
7581 break;
7582 case QEMU_OPTION_vcpus:
7583 vcpus = atoi(optarg);
7584 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
7585 break;
7586 case QEMU_OPTION_acpi:
7587 acpi_enabled = 1;
7588 break;
7589 case QEMU_OPTION_vncviewer:
7590 vncviewer++;
7591 break;
7592 case QEMU_OPTION_vncunused:
7593 vncunused++;
7594 break;
7595 case QEMU_OPTION_pci_emulation:
7596 if (nb_pci_emulation >= MAX_PCI_EMULATION) {
7597 fprintf(stderr, "Too many PCI emulations\n");
7598 exit(1);
7600 pstrcpy(pci_emulation_config_text[nb_pci_emulation],
7601 sizeof(pci_emulation_config_text[0]),
7602 optarg);
7603 nb_pci_emulation++;
7604 break;
7609 cpu_set_log(0);
7611 #ifndef NO_DAEMONIZE
7612 if (daemonize && !nographic && vnc_display == NULL && vncunused == 0) {
7613 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7614 daemonize = 0;
7617 if (daemonize) {
7618 pid_t pid;
7620 if (pipe(fds) == -1)
7621 exit(1);
7623 pid = fork();
7624 if (pid > 0) {
7625 uint8_t status;
7626 ssize_t len;
7628 close(fds[1]);
7630 again:
7631 len = read(fds[0], &status, 1);
7632 if (len == -1 && (errno == EINTR))
7633 goto again;
7635 if (len != 1 || status != 0)
7636 exit(1);
7637 else
7638 exit(0);
7639 } else if (pid < 0)
7640 exit(1);
7642 setsid();
7644 pid = fork();
7645 if (pid > 0)
7646 exit(0);
7647 else if (pid < 0)
7648 exit(1);
7650 umask(027);
7651 chdir("/");
7653 signal(SIGTSTP, SIG_IGN);
7654 signal(SIGTTOU, SIG_IGN);
7655 signal(SIGTTIN, SIG_IGN);
7657 #endif
7659 #ifdef CONFIG_DM
7660 bdrv_init();
7661 xc_handle = xc_interface_open();
7662 #ifdef CONFIG_STUBDOM
7664 char *domid_s, *msg;
7665 if ((msg = xenbus_read(XBT_NIL, "domid", &domid_s)))
7666 fprintf(stderr,"Can not read our own domid: %s\n", msg);
7667 else
7668 xenstore_parse_domain_config(atoi(domid_s));
7670 #else /* CONFIG_STUBDOM */
7671 xenstore_parse_domain_config(domid);
7672 #endif /* CONFIG_STUBDOM */
7673 #endif /* CONFIG_DM */
7675 #ifdef USE_KQEMU
7676 if (smp_cpus > 1)
7677 kqemu_allowed = 0;
7678 #endif
7679 linux_boot = (kernel_filename != NULL);
7681 #ifndef CONFIG_DM
7682 if (!linux_boot &&
7683 hd_filename[0] == '\0' &&
7684 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7685 fd_filename[0] == '\0')
7686 help();
7688 /* boot to floppy or the default cd if no hard disk defined yet */
7689 if (hd_filename[0] == '\0' && boot_device == 'c') {
7690 if (fd_filename[0] != '\0')
7691 boot_device = 'a';
7692 else
7693 boot_device = 'd';
7695 #endif /* !CONFIG_DM */
7697 setvbuf(stdout, NULL, _IOLBF, 0);
7699 init_timers();
7700 init_timer_alarm();
7701 qemu_aio_init();
7703 #ifdef _WIN32
7704 socket_init();
7705 #endif
7707 #ifndef CONFIG_DM
7708 /* init network clients */
7709 if (nb_net_clients == 0) {
7710 /* if no clients, we use a default config */
7711 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7712 "nic");
7713 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7714 "user");
7715 nb_net_clients = 2;
7717 #endif /* !CONFIG_DM */
7719 for(i = 0;i < nb_net_clients; i++) {
7720 if (net_client_init(net_clients[i]) < 0)
7721 exit(1);
7724 #ifndef CONFIG_DM
7725 #ifdef TARGET_I386
7726 if (boot_device == 'n') {
7727 for (i = 0; i < nb_nics; i++) {
7728 const char *model = nd_table[i].model;
7729 char buf[1024];
7730 if (model == NULL)
7731 model = "ne2k_pci";
7732 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7733 if (get_image_size(buf) > 0) {
7734 option_rom[nb_option_roms] = strdup(buf);
7735 nb_option_roms++;
7736 break;
7739 if (i == nb_nics) {
7740 fprintf(stderr, "No valid PXE rom found for network device\n");
7741 exit(1);
7743 boot_device = 'c'; /* to prevent confusion by the BIOS */
7745 #endif
7746 #endif /* !CONFIG_DM */
7748 #if defined (__ia64__)
7749 if (ram_size > MMIO_START)
7750 ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
7751 #endif
7753 /* init the memory */
7754 phys_ram_size = ram_size + vga_ram_size + bios_size;
7756 #ifndef CONFIG_DM
7757 for (i = 0; i < nb_option_roms; i++) {
7758 int ret = get_image_size(option_rom[i]);
7759 if (ret == -1) {
7760 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7761 exit(1);
7763 phys_ram_size += ret;
7766 phys_ram_base = qemu_vmalloc(phys_ram_size);
7767 if (!phys_ram_base) {
7768 fprintf(stderr, "Could not allocate physical memory\n");
7769 exit(1);
7772 /* we always create the cdrom drive, even if no disk is there */
7773 bdrv_init();
7774 if (cdrom_index >= 0) {
7775 bs_table[cdrom_index] = bdrv_new("cdrom");
7776 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7779 /* open the virtual block devices */
7780 for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
7781 if (hd_filename[i]) {
7782 if (!bs_table[i]) {
7783 char buf[64];
7784 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7785 bs_table[i] = bdrv_new(buf);
7787 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7788 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7789 hd_filename[i]);
7790 exit(1);
7792 if (i == 0 && cyls != 0) {
7793 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7794 bdrv_set_translation_hint(bs_table[i], translation);
7798 #endif /* !CONFIG_DM */
7800 /* we always create at least one floppy disk */
7801 fd_table[0] = bdrv_new("fda");
7802 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7804 for(i = 0; i < MAX_FD; i++) {
7805 if (fd_filename[i]) {
7806 if (!fd_table[i]) {
7807 char buf[64];
7808 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7809 fd_table[i] = bdrv_new(buf);
7810 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7812 if (fd_filename[i] != '\0') {
7813 if (bdrv_open2(fd_table[i], fd_filename[i],
7814 snapshot ? BDRV_O_SNAPSHOT : 0,
7815 &bdrv_raw) < 0) {
7816 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7817 fd_filename[i]);
7818 exit(1);
7824 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7825 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7827 init_ioports();
7829 /* terminal init */
7830 #ifdef CONFIG_STUBDOM
7831 if (xenfb_pv_display_init(ds) == 0) {
7832 } else
7833 #endif
7834 if (nographic) {
7835 dumb_display_init(ds);
7836 } else if (vnc_display != NULL || vncunused != 0) {
7837 int vnc_display_port;
7838 char password[20];
7839 vnc_display_init(ds);
7840 xenstore_read_vncpasswd(domid, password, sizeof(password));
7841 vnc_display_password(ds, password);
7842 if ((vnc_display_port = vnc_display_open(ds, vnc_display, vncunused)) < 0)
7843 exit (0);
7844 #ifndef CONFIG_STUBDOM
7845 if (vncviewer)
7846 vnc_start_viewer(vnc_display_port);
7847 #endif
7848 xenstore_write_vncport(vnc_display_port);
7849 } else {
7850 #if defined(CONFIG_SDL)
7851 sdl_display_init(ds, full_screen, opengl_enabled);
7852 #elif defined(CONFIG_COCOA)
7853 cocoa_display_init(ds, full_screen);
7854 #else
7855 dumb_display_init(ds);
7856 #endif
7859 monitor_hd = qemu_chr_open(monitor_device);
7860 if (!monitor_hd) {
7861 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7862 exit(1);
7864 store_dev_info(monitor_device, domid, monitor_hd, "/monitor");
7865 monitor_init(monitor_hd, !nographic);
7867 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7868 const char *devname = serial_devices[i];
7869 if (devname[0] != '\0' && strcmp(devname, "none")) {
7870 char buf[16];
7871 serial_hds[i] = qemu_chr_open(devname);
7872 if (!serial_hds[i]) {
7873 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7874 devname);
7875 exit(1);
7877 snprintf(buf, sizeof(buf), "/serial/%d", i);
7878 store_dev_info(serial_devices[i], domid, serial_hds[i], buf);
7879 if (i == 0) /* serial 0 is also called the console */
7880 store_dev_info(serial_devices[i], domid,
7881 serial_hds[i], "/console");
7882 if (!strcmp(devname, "vc"))
7883 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7887 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7888 const char *devname = parallel_devices[i];
7889 if (devname[0] != '\0' && strcmp(devname, "none")) {
7890 char buf[16];
7891 parallel_hds[i] = qemu_chr_open(devname);
7892 if (!parallel_hds[i]) {
7893 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7894 devname);
7895 exit(1);
7897 snprintf(buf, sizeof(buf), "/parallel/%d", i);
7898 store_dev_info(parallel_devices[i], domid, parallel_hds[i], buf);
7899 if (!strcmp(devname, "vc"))
7900 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7904 for (i = 0; i < nb_pci_emulation; i++) {
7905 if(pci_emulation_add(pci_emulation_config_text[i]) < 0) {
7906 fprintf(stderr, "Warning: could not add PCI device %s\n",
7907 pci_emulation_config_text[i]);
7911 qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
7913 machine->init(ram_size, vga_ram_size, boot_device,
7914 ds, fd_filename, snapshot,
7915 kernel_filename, kernel_cmdline, initrd_filename,
7916 direct_pci);
7917 free(boot_device);
7919 /* init USB devices */
7920 if (usb_enabled) {
7921 for(i = 0; i < usb_devices_index; i++) {
7922 if (usb_device_add(usb_devices[i]) < 0) {
7923 fprintf(stderr, "Warning: could not add USB device %s\n",
7924 usb_devices[i]);
7929 if (vnc_display == NULL && vncunused == 0) {
7930 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7931 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7934 #ifdef CONFIG_GDBSTUB
7935 if (use_gdbstub) {
7936 /* XXX: use standard host:port notation and modify options
7937 accordingly. */
7938 if (gdbserver_start_port(gdbstub_port) < 0) {
7939 fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7940 gdbstub_port);
7941 exit(1);
7943 } else
7944 #endif
7945 if (loadvm)
7946 do_loadvm(loadvm);
7949 /* XXX: simplify init */
7950 read_passwords();
7951 if (autostart) {
7952 vm_start();
7956 #ifndef NO_DAEMONIZE
7957 if (daemonize) {
7958 uint8_t status = 0;
7959 ssize_t len;
7960 int fd;
7962 again1:
7963 len = write(fds[1], &status, 1);
7964 if (len == -1 && (errno == EINTR))
7965 goto again1;
7967 if (len != 1)
7968 exit(1);
7970 fd = open("/dev/null", O_RDWR);
7971 if (fd == -1)
7972 exit(1);
7974 dup2(fd, 0);
7975 dup2(fd, 1);
7976 dup2(fd, 2);
7978 close(fd);
7980 #endif
7982 #ifndef CONFIG_STUBDOM
7983 /* Unblock SIGTERM and SIGHUP, which may have been blocked by the caller */
7984 signal(SIGHUP, SIG_DFL);
7985 sigemptyset(&set);
7986 sigaddset(&set, SIGTERM);
7987 sigaddset(&set, SIGHUP);
7988 if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
7989 fprintf(stderr, "Failed to unblock SIGTERM and SIGHUP\n");
7990 #endif
7992 main_loop();
7993 quit_timers();
7994 return 0;