]> git.proxmox.com Git - qemu.git/blob - vl.c
added last_io_time field - '-kernel-kqemu' experimental option
[qemu.git] / vl.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #include "vl.h"
25
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
32
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <dirent.h>
43 #include <netdb.h>
44 #ifdef _BSD
45 #include <sys/stat.h>
46 #ifndef __APPLE__
47 #include <libutil.h>
48 #endif
49 #else
50 #include <linux/if.h>
51 #include <linux/if_tun.h>
52 #include <pty.h>
53 #include <malloc.h>
54 #include <linux/rtc.h>
55 #include <linux/ppdev.h>
56 #endif
57 #endif
58
59 #if defined(CONFIG_SLIRP)
60 #include "libslirp.h"
61 #endif
62
63 #ifdef _WIN32
64 #include <malloc.h>
65 #include <sys/timeb.h>
66 #include <windows.h>
67 #include <winsock2.h>
68 #include <ws2tcpip.h>
69 #define getopt_long_only getopt_long
70 #define memalign(align, size) malloc(size)
71 #endif
72
73 #ifdef CONFIG_SDL
74 #ifdef __APPLE__
75 #include <SDL/SDL.h>
76 #endif
77 #endif /* CONFIG_SDL */
78
79 #ifdef CONFIG_COCOA
80 #undef main
81 #define main qemu_main
82 #endif /* CONFIG_COCOA */
83
84 #include "disas.h"
85
86 #include "exec-all.h"
87
88 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
89
90 //#define DEBUG_UNUSED_IOPORT
91 //#define DEBUG_IOPORT
92
93 #if !defined(CONFIG_SOFTMMU)
94 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
95 #else
96 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
97 #endif
98
99 #ifdef TARGET_PPC
100 #define DEFAULT_RAM_SIZE 144
101 #else
102 #define DEFAULT_RAM_SIZE 128
103 #endif
104 /* in ms */
105 #define GUI_REFRESH_INTERVAL 30
106
107 /* XXX: use a two level table to limit memory usage */
108 #define MAX_IOPORTS 65536
109
110 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
111 char phys_ram_file[1024];
112 void *ioport_opaque[MAX_IOPORTS];
113 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
114 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
115 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
116 int vga_ram_size;
117 int bios_size;
118 static DisplayState display_state;
119 int nographic;
120 const char* keyboard_layout = NULL;
121 int64_t ticks_per_sec;
122 int boot_device = 'c';
123 int ram_size;
124 int pit_min_timer_count = 0;
125 int nb_nics;
126 NICInfo nd_table[MAX_NICS];
127 QEMUTimer *gui_timer;
128 int vm_running;
129 int rtc_utc = 1;
130 int cirrus_vga_enabled = 1;
131 #ifdef TARGET_SPARC
132 int graphic_width = 1024;
133 int graphic_height = 768;
134 #else
135 int graphic_width = 800;
136 int graphic_height = 600;
137 #endif
138 int graphic_depth = 15;
139 int full_screen = 0;
140 TextConsole *vga_console;
141 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
142 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
143 #ifdef TARGET_I386
144 int win2k_install_hack = 0;
145 #endif
146 int usb_enabled = 0;
147 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
148 USBDevice *vm_usb_hub;
149 static VLANState *first_vlan;
150 int smp_cpus = 1;
151 #if defined(TARGET_SPARC)
152 #define MAX_CPUS 16
153 #elif defined(TARGET_I386)
154 #define MAX_CPUS 255
155 #else
156 #define MAX_CPUS 1
157 #endif
158
159 /***********************************************************/
160 /* x86 ISA bus support */
161
162 target_phys_addr_t isa_mem_base = 0;
163 PicState2 *isa_pic;
164
165 uint32_t default_ioport_readb(void *opaque, uint32_t address)
166 {
167 #ifdef DEBUG_UNUSED_IOPORT
168 fprintf(stderr, "inb: port=0x%04x\n", address);
169 #endif
170 return 0xff;
171 }
172
173 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
174 {
175 #ifdef DEBUG_UNUSED_IOPORT
176 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
177 #endif
178 }
179
180 /* default is to make two byte accesses */
181 uint32_t default_ioport_readw(void *opaque, uint32_t address)
182 {
183 uint32_t data;
184 data = ioport_read_table[0][address](ioport_opaque[address], address);
185 address = (address + 1) & (MAX_IOPORTS - 1);
186 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
187 return data;
188 }
189
190 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
191 {
192 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
193 address = (address + 1) & (MAX_IOPORTS - 1);
194 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
195 }
196
197 uint32_t default_ioport_readl(void *opaque, uint32_t address)
198 {
199 #ifdef DEBUG_UNUSED_IOPORT
200 fprintf(stderr, "inl: port=0x%04x\n", address);
201 #endif
202 return 0xffffffff;
203 }
204
205 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
206 {
207 #ifdef DEBUG_UNUSED_IOPORT
208 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
209 #endif
210 }
211
212 void init_ioports(void)
213 {
214 int i;
215
216 for(i = 0; i < MAX_IOPORTS; i++) {
217 ioport_read_table[0][i] = default_ioport_readb;
218 ioport_write_table[0][i] = default_ioport_writeb;
219 ioport_read_table[1][i] = default_ioport_readw;
220 ioport_write_table[1][i] = default_ioport_writew;
221 ioport_read_table[2][i] = default_ioport_readl;
222 ioport_write_table[2][i] = default_ioport_writel;
223 }
224 }
225
226 /* size is the word size in byte */
227 int register_ioport_read(int start, int length, int size,
228 IOPortReadFunc *func, void *opaque)
229 {
230 int i, bsize;
231
232 if (size == 1) {
233 bsize = 0;
234 } else if (size == 2) {
235 bsize = 1;
236 } else if (size == 4) {
237 bsize = 2;
238 } else {
239 hw_error("register_ioport_read: invalid size");
240 return -1;
241 }
242 for(i = start; i < start + length; i += size) {
243 ioport_read_table[bsize][i] = func;
244 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
245 hw_error("register_ioport_read: invalid opaque");
246 ioport_opaque[i] = opaque;
247 }
248 return 0;
249 }
250
251 /* size is the word size in byte */
252 int register_ioport_write(int start, int length, int size,
253 IOPortWriteFunc *func, void *opaque)
254 {
255 int i, bsize;
256
257 if (size == 1) {
258 bsize = 0;
259 } else if (size == 2) {
260 bsize = 1;
261 } else if (size == 4) {
262 bsize = 2;
263 } else {
264 hw_error("register_ioport_write: invalid size");
265 return -1;
266 }
267 for(i = start; i < start + length; i += size) {
268 ioport_write_table[bsize][i] = func;
269 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
270 hw_error("register_ioport_read: invalid opaque");
271 ioport_opaque[i] = opaque;
272 }
273 return 0;
274 }
275
276 void isa_unassign_ioport(int start, int length)
277 {
278 int i;
279
280 for(i = start; i < start + length; i++) {
281 ioport_read_table[0][i] = default_ioport_readb;
282 ioport_read_table[1][i] = default_ioport_readw;
283 ioport_read_table[2][i] = default_ioport_readl;
284
285 ioport_write_table[0][i] = default_ioport_writeb;
286 ioport_write_table[1][i] = default_ioport_writew;
287 ioport_write_table[2][i] = default_ioport_writel;
288 }
289 }
290
291 /***********************************************************/
292
293 void pstrcpy(char *buf, int buf_size, const char *str)
294 {
295 int c;
296 char *q = buf;
297
298 if (buf_size <= 0)
299 return;
300
301 for(;;) {
302 c = *str++;
303 if (c == 0 || q >= buf + buf_size - 1)
304 break;
305 *q++ = c;
306 }
307 *q = '\0';
308 }
309
310 /* strcat and truncate. */
311 char *pstrcat(char *buf, int buf_size, const char *s)
312 {
313 int len;
314 len = strlen(buf);
315 if (len < buf_size)
316 pstrcpy(buf + len, buf_size - len, s);
317 return buf;
318 }
319
320 int strstart(const char *str, const char *val, const char **ptr)
321 {
322 const char *p, *q;
323 p = str;
324 q = val;
325 while (*q != '\0') {
326 if (*p != *q)
327 return 0;
328 p++;
329 q++;
330 }
331 if (ptr)
332 *ptr = p;
333 return 1;
334 }
335
336 /* return the size or -1 if error */
337 int get_image_size(const char *filename)
338 {
339 int fd, size;
340 fd = open(filename, O_RDONLY | O_BINARY);
341 if (fd < 0)
342 return -1;
343 size = lseek(fd, 0, SEEK_END);
344 close(fd);
345 return size;
346 }
347
348 /* return the size or -1 if error */
349 int load_image(const char *filename, uint8_t *addr)
350 {
351 int fd, size;
352 fd = open(filename, O_RDONLY | O_BINARY);
353 if (fd < 0)
354 return -1;
355 size = lseek(fd, 0, SEEK_END);
356 lseek(fd, 0, SEEK_SET);
357 if (read(fd, addr, size) != size) {
358 close(fd);
359 return -1;
360 }
361 close(fd);
362 return size;
363 }
364
365 void cpu_outb(CPUState *env, int addr, int val)
366 {
367 #ifdef DEBUG_IOPORT
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "outb: %04x %02x\n", addr, val);
370 #endif
371 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
372 #ifdef USE_KQEMU
373 if (env)
374 env->last_io_time = cpu_get_time_fast();
375 #endif
376 }
377
378 void cpu_outw(CPUState *env, int addr, int val)
379 {
380 #ifdef DEBUG_IOPORT
381 if (loglevel & CPU_LOG_IOPORT)
382 fprintf(logfile, "outw: %04x %04x\n", addr, val);
383 #endif
384 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
385 #ifdef USE_KQEMU
386 if (env)
387 env->last_io_time = cpu_get_time_fast();
388 #endif
389 }
390
391 void cpu_outl(CPUState *env, int addr, int val)
392 {
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "outl: %04x %08x\n", addr, val);
396 #endif
397 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
398 #ifdef USE_KQEMU
399 if (env)
400 env->last_io_time = cpu_get_time_fast();
401 #endif
402 }
403
404 int cpu_inb(CPUState *env, int addr)
405 {
406 int val;
407 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
408 #ifdef DEBUG_IOPORT
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "inb : %04x %02x\n", addr, val);
411 #endif
412 #ifdef USE_KQEMU
413 if (env)
414 env->last_io_time = cpu_get_time_fast();
415 #endif
416 return val;
417 }
418
419 int cpu_inw(CPUState *env, int addr)
420 {
421 int val;
422 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inw : %04x %04x\n", addr, val);
426 #endif
427 #ifdef USE_KQEMU
428 if (env)
429 env->last_io_time = cpu_get_time_fast();
430 #endif
431 return val;
432 }
433
434 int cpu_inl(CPUState *env, int addr)
435 {
436 int val;
437 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
438 #ifdef DEBUG_IOPORT
439 if (loglevel & CPU_LOG_IOPORT)
440 fprintf(logfile, "inl : %04x %08x\n", addr, val);
441 #endif
442 #ifdef USE_KQEMU
443 if (env)
444 env->last_io_time = cpu_get_time_fast();
445 #endif
446 return val;
447 }
448
449 /***********************************************************/
450 void hw_error(const char *fmt, ...)
451 {
452 va_list ap;
453 CPUState *env;
454
455 va_start(ap, fmt);
456 fprintf(stderr, "qemu: hardware error: ");
457 vfprintf(stderr, fmt, ap);
458 fprintf(stderr, "\n");
459 for(env = first_cpu; env != NULL; env = env->next_cpu) {
460 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
461 #ifdef TARGET_I386
462 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
463 #else
464 cpu_dump_state(env, stderr, fprintf, 0);
465 #endif
466 }
467 va_end(ap);
468 abort();
469 }
470
471 /***********************************************************/
472 /* keyboard/mouse */
473
474 static QEMUPutKBDEvent *qemu_put_kbd_event;
475 static void *qemu_put_kbd_event_opaque;
476 static QEMUPutMouseEvent *qemu_put_mouse_event;
477 static void *qemu_put_mouse_event_opaque;
478
479 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
480 {
481 qemu_put_kbd_event_opaque = opaque;
482 qemu_put_kbd_event = func;
483 }
484
485 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
486 {
487 qemu_put_mouse_event_opaque = opaque;
488 qemu_put_mouse_event = func;
489 }
490
491 void kbd_put_keycode(int keycode)
492 {
493 if (qemu_put_kbd_event) {
494 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
495 }
496 }
497
498 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
499 {
500 if (qemu_put_mouse_event) {
501 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
502 dx, dy, dz, buttons_state);
503 }
504 }
505
506 /***********************************************************/
507 /* timers */
508
509 #if defined(__powerpc__)
510
511 static inline uint32_t get_tbl(void)
512 {
513 uint32_t tbl;
514 asm volatile("mftb %0" : "=r" (tbl));
515 return tbl;
516 }
517
518 static inline uint32_t get_tbu(void)
519 {
520 uint32_t tbl;
521 asm volatile("mftbu %0" : "=r" (tbl));
522 return tbl;
523 }
524
525 int64_t cpu_get_real_ticks(void)
526 {
527 uint32_t l, h, h1;
528 /* NOTE: we test if wrapping has occurred */
529 do {
530 h = get_tbu();
531 l = get_tbl();
532 h1 = get_tbu();
533 } while (h != h1);
534 return ((int64_t)h << 32) | l;
535 }
536
537 #elif defined(__i386__)
538
539 int64_t cpu_get_real_ticks(void)
540 {
541 int64_t val;
542 asm volatile ("rdtsc" : "=A" (val));
543 return val;
544 }
545
546 #elif defined(__x86_64__)
547
548 int64_t cpu_get_real_ticks(void)
549 {
550 uint32_t low,high;
551 int64_t val;
552 asm volatile("rdtsc" : "=a" (low), "=d" (high));
553 val = high;
554 val <<= 32;
555 val |= low;
556 return val;
557 }
558
559 #elif defined(__ia64)
560
561 int64_t cpu_get_real_ticks(void)
562 {
563 int64_t val;
564 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
565 return val;
566 }
567
568 #elif defined(__s390__)
569
570 int64_t cpu_get_real_ticks(void)
571 {
572 int64_t val;
573 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
574 return val;
575 }
576
577 #else
578 #error unsupported CPU
579 #endif
580
581 static int64_t cpu_ticks_offset;
582 static int cpu_ticks_enabled;
583
584 static inline int64_t cpu_get_ticks(void)
585 {
586 if (!cpu_ticks_enabled) {
587 return cpu_ticks_offset;
588 } else {
589 return cpu_get_real_ticks() + cpu_ticks_offset;
590 }
591 }
592
593 /* enable cpu_get_ticks() */
594 void cpu_enable_ticks(void)
595 {
596 if (!cpu_ticks_enabled) {
597 cpu_ticks_offset -= cpu_get_real_ticks();
598 cpu_ticks_enabled = 1;
599 }
600 }
601
602 /* disable cpu_get_ticks() : the clock is stopped. You must not call
603 cpu_get_ticks() after that. */
604 void cpu_disable_ticks(void)
605 {
606 if (cpu_ticks_enabled) {
607 cpu_ticks_offset = cpu_get_ticks();
608 cpu_ticks_enabled = 0;
609 }
610 }
611
612 static int64_t get_clock(void)
613 {
614 #ifdef _WIN32
615 struct _timeb tb;
616 _ftime(&tb);
617 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
618 #else
619 struct timeval tv;
620 gettimeofday(&tv, NULL);
621 return tv.tv_sec * 1000000LL + tv.tv_usec;
622 #endif
623 }
624
625 void cpu_calibrate_ticks(void)
626 {
627 int64_t usec, ticks;
628
629 usec = get_clock();
630 ticks = cpu_get_real_ticks();
631 #ifdef _WIN32
632 Sleep(50);
633 #else
634 usleep(50 * 1000);
635 #endif
636 usec = get_clock() - usec;
637 ticks = cpu_get_real_ticks() - ticks;
638 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
639 }
640
641 /* compute with 96 bit intermediate result: (a*b)/c */
642 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
643 {
644 union {
645 uint64_t ll;
646 struct {
647 #ifdef WORDS_BIGENDIAN
648 uint32_t high, low;
649 #else
650 uint32_t low, high;
651 #endif
652 } l;
653 } u, res;
654 uint64_t rl, rh;
655
656 u.ll = a;
657 rl = (uint64_t)u.l.low * (uint64_t)b;
658 rh = (uint64_t)u.l.high * (uint64_t)b;
659 rh += (rl >> 32);
660 res.l.high = rh / c;
661 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
662 return res.ll;
663 }
664
665 #define QEMU_TIMER_REALTIME 0
666 #define QEMU_TIMER_VIRTUAL 1
667
668 struct QEMUClock {
669 int type;
670 /* XXX: add frequency */
671 };
672
673 struct QEMUTimer {
674 QEMUClock *clock;
675 int64_t expire_time;
676 QEMUTimerCB *cb;
677 void *opaque;
678 struct QEMUTimer *next;
679 };
680
681 QEMUClock *rt_clock;
682 QEMUClock *vm_clock;
683
684 static QEMUTimer *active_timers[2];
685 #ifdef _WIN32
686 static MMRESULT timerID;
687 #else
688 /* frequency of the times() clock tick */
689 static int timer_freq;
690 #endif
691
692 QEMUClock *qemu_new_clock(int type)
693 {
694 QEMUClock *clock;
695 clock = qemu_mallocz(sizeof(QEMUClock));
696 if (!clock)
697 return NULL;
698 clock->type = type;
699 return clock;
700 }
701
702 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
703 {
704 QEMUTimer *ts;
705
706 ts = qemu_mallocz(sizeof(QEMUTimer));
707 ts->clock = clock;
708 ts->cb = cb;
709 ts->opaque = opaque;
710 return ts;
711 }
712
713 void qemu_free_timer(QEMUTimer *ts)
714 {
715 qemu_free(ts);
716 }
717
718 /* stop a timer, but do not dealloc it */
719 void qemu_del_timer(QEMUTimer *ts)
720 {
721 QEMUTimer **pt, *t;
722
723 /* NOTE: this code must be signal safe because
724 qemu_timer_expired() can be called from a signal. */
725 pt = &active_timers[ts->clock->type];
726 for(;;) {
727 t = *pt;
728 if (!t)
729 break;
730 if (t == ts) {
731 *pt = t->next;
732 break;
733 }
734 pt = &t->next;
735 }
736 }
737
738 /* modify the current timer so that it will be fired when current_time
739 >= expire_time. The corresponding callback will be called. */
740 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
741 {
742 QEMUTimer **pt, *t;
743
744 qemu_del_timer(ts);
745
746 /* add the timer in the sorted list */
747 /* NOTE: this code must be signal safe because
748 qemu_timer_expired() can be called from a signal. */
749 pt = &active_timers[ts->clock->type];
750 for(;;) {
751 t = *pt;
752 if (!t)
753 break;
754 if (t->expire_time > expire_time)
755 break;
756 pt = &t->next;
757 }
758 ts->expire_time = expire_time;
759 ts->next = *pt;
760 *pt = ts;
761 }
762
763 int qemu_timer_pending(QEMUTimer *ts)
764 {
765 QEMUTimer *t;
766 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
767 if (t == ts)
768 return 1;
769 }
770 return 0;
771 }
772
773 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
774 {
775 if (!timer_head)
776 return 0;
777 return (timer_head->expire_time <= current_time);
778 }
779
780 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
781 {
782 QEMUTimer *ts;
783
784 for(;;) {
785 ts = *ptimer_head;
786 if (!ts || ts->expire_time > current_time)
787 break;
788 /* remove timer from the list before calling the callback */
789 *ptimer_head = ts->next;
790 ts->next = NULL;
791
792 /* run the callback (the timer list can be modified) */
793 ts->cb(ts->opaque);
794 }
795 }
796
797 int64_t qemu_get_clock(QEMUClock *clock)
798 {
799 switch(clock->type) {
800 case QEMU_TIMER_REALTIME:
801 #ifdef _WIN32
802 return GetTickCount();
803 #else
804 {
805 struct tms tp;
806
807 /* Note that using gettimeofday() is not a good solution
808 for timers because its value change when the date is
809 modified. */
810 if (timer_freq == 100) {
811 return times(&tp) * 10;
812 } else {
813 return ((int64_t)times(&tp) * 1000) / timer_freq;
814 }
815 }
816 #endif
817 default:
818 case QEMU_TIMER_VIRTUAL:
819 return cpu_get_ticks();
820 }
821 }
822
823 /* save a timer */
824 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
825 {
826 uint64_t expire_time;
827
828 if (qemu_timer_pending(ts)) {
829 expire_time = ts->expire_time;
830 } else {
831 expire_time = -1;
832 }
833 qemu_put_be64(f, expire_time);
834 }
835
836 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
837 {
838 uint64_t expire_time;
839
840 expire_time = qemu_get_be64(f);
841 if (expire_time != -1) {
842 qemu_mod_timer(ts, expire_time);
843 } else {
844 qemu_del_timer(ts);
845 }
846 }
847
848 static void timer_save(QEMUFile *f, void *opaque)
849 {
850 if (cpu_ticks_enabled) {
851 hw_error("cannot save state if virtual timers are running");
852 }
853 qemu_put_be64s(f, &cpu_ticks_offset);
854 qemu_put_be64s(f, &ticks_per_sec);
855 }
856
857 static int timer_load(QEMUFile *f, void *opaque, int version_id)
858 {
859 if (version_id != 1)
860 return -EINVAL;
861 if (cpu_ticks_enabled) {
862 return -EINVAL;
863 }
864 qemu_get_be64s(f, &cpu_ticks_offset);
865 qemu_get_be64s(f, &ticks_per_sec);
866 return 0;
867 }
868
869 #ifdef _WIN32
870 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
871 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
872 #else
873 static void host_alarm_handler(int host_signum)
874 #endif
875 {
876 #if 0
877 #define DISP_FREQ 1000
878 {
879 static int64_t delta_min = INT64_MAX;
880 static int64_t delta_max, delta_cum, last_clock, delta, ti;
881 static int count;
882 ti = qemu_get_clock(vm_clock);
883 if (last_clock != 0) {
884 delta = ti - last_clock;
885 if (delta < delta_min)
886 delta_min = delta;
887 if (delta > delta_max)
888 delta_max = delta;
889 delta_cum += delta;
890 if (++count == DISP_FREQ) {
891 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
892 muldiv64(delta_min, 1000000, ticks_per_sec),
893 muldiv64(delta_max, 1000000, ticks_per_sec),
894 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
895 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
896 count = 0;
897 delta_min = INT64_MAX;
898 delta_max = 0;
899 delta_cum = 0;
900 }
901 }
902 last_clock = ti;
903 }
904 #endif
905 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
906 qemu_get_clock(vm_clock)) ||
907 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
908 qemu_get_clock(rt_clock))) {
909 CPUState *env = cpu_single_env;
910 if (env) {
911 /* stop the currently executing cpu because a timer occured */
912 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
913 #ifdef USE_KQEMU
914 if (env->kqemu_enabled) {
915 kqemu_cpu_interrupt(env);
916 }
917 #endif
918 }
919 }
920 }
921
922 #ifndef _WIN32
923
924 #if defined(__linux__)
925
926 #define RTC_FREQ 1024
927
928 static int rtc_fd;
929
930 static int start_rtc_timer(void)
931 {
932 rtc_fd = open("/dev/rtc", O_RDONLY);
933 if (rtc_fd < 0)
934 return -1;
935 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
936 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
937 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
938 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
939 goto fail;
940 }
941 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
942 fail:
943 close(rtc_fd);
944 return -1;
945 }
946 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
947 return 0;
948 }
949
950 #else
951
952 static int start_rtc_timer(void)
953 {
954 return -1;
955 }
956
957 #endif /* !defined(__linux__) */
958
959 #endif /* !defined(_WIN32) */
960
961 static void init_timers(void)
962 {
963 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
964 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
965
966 #ifdef _WIN32
967 {
968 int count=0;
969 timerID = timeSetEvent(1, // interval (ms)
970 0, // resolution
971 host_alarm_handler, // function
972 (DWORD)&count, // user parameter
973 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
974 if( !timerID ) {
975 perror("failed timer alarm");
976 exit(1);
977 }
978 }
979 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
980 #else
981 {
982 struct sigaction act;
983 struct itimerval itv;
984
985 /* get times() syscall frequency */
986 timer_freq = sysconf(_SC_CLK_TCK);
987
988 /* timer signal */
989 sigfillset(&act.sa_mask);
990 act.sa_flags = 0;
991 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
992 act.sa_flags |= SA_ONSTACK;
993 #endif
994 act.sa_handler = host_alarm_handler;
995 sigaction(SIGALRM, &act, NULL);
996
997 itv.it_interval.tv_sec = 0;
998 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
999 itv.it_value.tv_sec = 0;
1000 itv.it_value.tv_usec = 10 * 1000;
1001 setitimer(ITIMER_REAL, &itv, NULL);
1002 /* we probe the tick duration of the kernel to inform the user if
1003 the emulated kernel requested a too high timer frequency */
1004 getitimer(ITIMER_REAL, &itv);
1005
1006 #if defined(__linux__)
1007 if (itv.it_interval.tv_usec > 1000) {
1008 /* try to use /dev/rtc to have a faster timer */
1009 if (start_rtc_timer() < 0)
1010 goto use_itimer;
1011 /* disable itimer */
1012 itv.it_interval.tv_sec = 0;
1013 itv.it_interval.tv_usec = 0;
1014 itv.it_value.tv_sec = 0;
1015 itv.it_value.tv_usec = 0;
1016 setitimer(ITIMER_REAL, &itv, NULL);
1017
1018 /* use the RTC */
1019 sigaction(SIGIO, &act, NULL);
1020 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1021 fcntl(rtc_fd, F_SETOWN, getpid());
1022 } else
1023 #endif /* defined(__linux__) */
1024 {
1025 use_itimer:
1026 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1027 PIT_FREQ) / 1000000;
1028 }
1029 }
1030 #endif
1031 }
1032
1033 void quit_timers(void)
1034 {
1035 #ifdef _WIN32
1036 timeKillEvent(timerID);
1037 #endif
1038 }
1039
1040 /***********************************************************/
1041 /* character device */
1042
1043 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1044 {
1045 return s->chr_write(s, buf, len);
1046 }
1047
1048 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1049 {
1050 if (!s->chr_ioctl)
1051 return -ENOTSUP;
1052 return s->chr_ioctl(s, cmd, arg);
1053 }
1054
1055 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1056 {
1057 char buf[4096];
1058 va_list ap;
1059 va_start(ap, fmt);
1060 vsnprintf(buf, sizeof(buf), fmt, ap);
1061 qemu_chr_write(s, buf, strlen(buf));
1062 va_end(ap);
1063 }
1064
1065 void qemu_chr_send_event(CharDriverState *s, int event)
1066 {
1067 if (s->chr_send_event)
1068 s->chr_send_event(s, event);
1069 }
1070
1071 void qemu_chr_add_read_handler(CharDriverState *s,
1072 IOCanRWHandler *fd_can_read,
1073 IOReadHandler *fd_read, void *opaque)
1074 {
1075 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1076 }
1077
1078 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1079 {
1080 s->chr_event = chr_event;
1081 }
1082
1083 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1084 {
1085 return len;
1086 }
1087
1088 static void null_chr_add_read_handler(CharDriverState *chr,
1089 IOCanRWHandler *fd_can_read,
1090 IOReadHandler *fd_read, void *opaque)
1091 {
1092 }
1093
1094 CharDriverState *qemu_chr_open_null(void)
1095 {
1096 CharDriverState *chr;
1097
1098 chr = qemu_mallocz(sizeof(CharDriverState));
1099 if (!chr)
1100 return NULL;
1101 chr->chr_write = null_chr_write;
1102 chr->chr_add_read_handler = null_chr_add_read_handler;
1103 return chr;
1104 }
1105
1106 #ifdef _WIN32
1107
1108 #define socket_error() WSAGetLastError()
1109 #undef EINTR
1110 #define EWOULDBLOCK WSAEWOULDBLOCK
1111 #define EINTR WSAEINTR
1112 #define EINPROGRESS WSAEINPROGRESS
1113
1114 static void socket_cleanup(void)
1115 {
1116 WSACleanup();
1117 }
1118
1119 static int socket_init(void)
1120 {
1121 WSADATA Data;
1122 int ret, err;
1123
1124 ret = WSAStartup(MAKEWORD(2,2), &Data);
1125 if (ret != 0) {
1126 err = WSAGetLastError();
1127 fprintf(stderr, "WSAStartup: %d\n", err);
1128 return -1;
1129 }
1130 atexit(socket_cleanup);
1131 return 0;
1132 }
1133
1134 static int send_all(int fd, const uint8_t *buf, int len1)
1135 {
1136 int ret, len;
1137
1138 len = len1;
1139 while (len > 0) {
1140 ret = send(fd, buf, len, 0);
1141 if (ret < 0) {
1142 int errno;
1143 errno = WSAGetLastError();
1144 if (errno != WSAEWOULDBLOCK) {
1145 return -1;
1146 }
1147 } else if (ret == 0) {
1148 break;
1149 } else {
1150 buf += ret;
1151 len -= ret;
1152 }
1153 }
1154 return len1 - len;
1155 }
1156
1157 void socket_set_nonblock(int fd)
1158 {
1159 unsigned long opt = 1;
1160 ioctlsocket(fd, FIONBIO, &opt);
1161 }
1162
1163 #else
1164
1165 #define socket_error() errno
1166 #define closesocket(s) close(s)
1167
1168 static int unix_write(int fd, const uint8_t *buf, int len1)
1169 {
1170 int ret, len;
1171
1172 len = len1;
1173 while (len > 0) {
1174 ret = write(fd, buf, len);
1175 if (ret < 0) {
1176 if (errno != EINTR && errno != EAGAIN)
1177 return -1;
1178 } else if (ret == 0) {
1179 break;
1180 } else {
1181 buf += ret;
1182 len -= ret;
1183 }
1184 }
1185 return len1 - len;
1186 }
1187
1188 static inline int send_all(int fd, const uint8_t *buf, int len1)
1189 {
1190 return unix_write(fd, buf, len1);
1191 }
1192
1193 void socket_set_nonblock(int fd)
1194 {
1195 fcntl(fd, F_SETFL, O_NONBLOCK);
1196 }
1197 #endif /* !_WIN32 */
1198
1199 #ifndef _WIN32
1200
1201 typedef struct {
1202 int fd_in, fd_out;
1203 IOCanRWHandler *fd_can_read;
1204 IOReadHandler *fd_read;
1205 void *fd_opaque;
1206 int max_size;
1207 } FDCharDriver;
1208
1209 #define STDIO_MAX_CLIENTS 2
1210
1211 static int stdio_nb_clients;
1212 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1213
1214 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1215 {
1216 FDCharDriver *s = chr->opaque;
1217 return unix_write(s->fd_out, buf, len);
1218 }
1219
1220 static int fd_chr_read_poll(void *opaque)
1221 {
1222 CharDriverState *chr = opaque;
1223 FDCharDriver *s = chr->opaque;
1224
1225 s->max_size = s->fd_can_read(s->fd_opaque);
1226 return s->max_size;
1227 }
1228
1229 static void fd_chr_read(void *opaque)
1230 {
1231 CharDriverState *chr = opaque;
1232 FDCharDriver *s = chr->opaque;
1233 int size, len;
1234 uint8_t buf[1024];
1235
1236 len = sizeof(buf);
1237 if (len > s->max_size)
1238 len = s->max_size;
1239 if (len == 0)
1240 return;
1241 size = read(s->fd_in, buf, len);
1242 if (size > 0) {
1243 s->fd_read(s->fd_opaque, buf, size);
1244 }
1245 }
1246
1247 static void fd_chr_add_read_handler(CharDriverState *chr,
1248 IOCanRWHandler *fd_can_read,
1249 IOReadHandler *fd_read, void *opaque)
1250 {
1251 FDCharDriver *s = chr->opaque;
1252
1253 if (s->fd_in >= 0) {
1254 s->fd_can_read = fd_can_read;
1255 s->fd_read = fd_read;
1256 s->fd_opaque = opaque;
1257 if (nographic && s->fd_in == 0) {
1258 } else {
1259 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1260 fd_chr_read, NULL, chr);
1261 }
1262 }
1263 }
1264
1265 /* open a character device to a unix fd */
1266 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1267 {
1268 CharDriverState *chr;
1269 FDCharDriver *s;
1270
1271 chr = qemu_mallocz(sizeof(CharDriverState));
1272 if (!chr)
1273 return NULL;
1274 s = qemu_mallocz(sizeof(FDCharDriver));
1275 if (!s) {
1276 free(chr);
1277 return NULL;
1278 }
1279 s->fd_in = fd_in;
1280 s->fd_out = fd_out;
1281 chr->opaque = s;
1282 chr->chr_write = fd_chr_write;
1283 chr->chr_add_read_handler = fd_chr_add_read_handler;
1284 return chr;
1285 }
1286
1287 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1288 {
1289 int fd_out;
1290
1291 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1292 if (fd_out < 0)
1293 return NULL;
1294 return qemu_chr_open_fd(-1, fd_out);
1295 }
1296
1297 CharDriverState *qemu_chr_open_pipe(const char *filename)
1298 {
1299 int fd;
1300
1301 fd = open(filename, O_RDWR | O_BINARY);
1302 if (fd < 0)
1303 return NULL;
1304 return qemu_chr_open_fd(fd, fd);
1305 }
1306
1307
1308 /* for STDIO, we handle the case where several clients use it
1309 (nographic mode) */
1310
1311 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1312
1313 #define TERM_FIFO_MAX_SIZE 1
1314
1315 static int term_got_escape, client_index;
1316 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1317 int term_fifo_size;
1318
1319 void term_print_help(void)
1320 {
1321 printf("\n"
1322 "C-a h print this help\n"
1323 "C-a x exit emulator\n"
1324 "C-a s save disk data back to file (if -snapshot)\n"
1325 "C-a b send break (magic sysrq)\n"
1326 "C-a c switch between console and monitor\n"
1327 "C-a C-a send C-a\n"
1328 );
1329 }
1330
1331 /* called when a char is received */
1332 static void stdio_received_byte(int ch)
1333 {
1334 if (term_got_escape) {
1335 term_got_escape = 0;
1336 switch(ch) {
1337 case 'h':
1338 term_print_help();
1339 break;
1340 case 'x':
1341 exit(0);
1342 break;
1343 case 's':
1344 {
1345 int i;
1346 for (i = 0; i < MAX_DISKS; i++) {
1347 if (bs_table[i])
1348 bdrv_commit(bs_table[i]);
1349 }
1350 }
1351 break;
1352 case 'b':
1353 if (client_index < stdio_nb_clients) {
1354 CharDriverState *chr;
1355 FDCharDriver *s;
1356
1357 chr = stdio_clients[client_index];
1358 s = chr->opaque;
1359 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1360 }
1361 break;
1362 case 'c':
1363 client_index++;
1364 if (client_index >= stdio_nb_clients)
1365 client_index = 0;
1366 if (client_index == 0) {
1367 /* send a new line in the monitor to get the prompt */
1368 ch = '\r';
1369 goto send_char;
1370 }
1371 break;
1372 case TERM_ESCAPE:
1373 goto send_char;
1374 }
1375 } else if (ch == TERM_ESCAPE) {
1376 term_got_escape = 1;
1377 } else {
1378 send_char:
1379 if (client_index < stdio_nb_clients) {
1380 uint8_t buf[1];
1381 CharDriverState *chr;
1382 FDCharDriver *s;
1383
1384 chr = stdio_clients[client_index];
1385 s = chr->opaque;
1386 if (s->fd_can_read(s->fd_opaque) > 0) {
1387 buf[0] = ch;
1388 s->fd_read(s->fd_opaque, buf, 1);
1389 } else if (term_fifo_size == 0) {
1390 term_fifo[term_fifo_size++] = ch;
1391 }
1392 }
1393 }
1394 }
1395
1396 static int stdio_read_poll(void *opaque)
1397 {
1398 CharDriverState *chr;
1399 FDCharDriver *s;
1400
1401 if (client_index < stdio_nb_clients) {
1402 chr = stdio_clients[client_index];
1403 s = chr->opaque;
1404 /* try to flush the queue if needed */
1405 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1406 s->fd_read(s->fd_opaque, term_fifo, 1);
1407 term_fifo_size = 0;
1408 }
1409 /* see if we can absorb more chars */
1410 if (term_fifo_size == 0)
1411 return 1;
1412 else
1413 return 0;
1414 } else {
1415 return 1;
1416 }
1417 }
1418
1419 static void stdio_read(void *opaque)
1420 {
1421 int size;
1422 uint8_t buf[1];
1423
1424 size = read(0, buf, 1);
1425 if (size > 0)
1426 stdio_received_byte(buf[0]);
1427 }
1428
1429 /* init terminal so that we can grab keys */
1430 static struct termios oldtty;
1431 static int old_fd0_flags;
1432
1433 static void term_exit(void)
1434 {
1435 tcsetattr (0, TCSANOW, &oldtty);
1436 fcntl(0, F_SETFL, old_fd0_flags);
1437 }
1438
1439 static void term_init(void)
1440 {
1441 struct termios tty;
1442
1443 tcgetattr (0, &tty);
1444 oldtty = tty;
1445 old_fd0_flags = fcntl(0, F_GETFL);
1446
1447 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1448 |INLCR|IGNCR|ICRNL|IXON);
1449 tty.c_oflag |= OPOST;
1450 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1451 /* if graphical mode, we allow Ctrl-C handling */
1452 if (nographic)
1453 tty.c_lflag &= ~ISIG;
1454 tty.c_cflag &= ~(CSIZE|PARENB);
1455 tty.c_cflag |= CS8;
1456 tty.c_cc[VMIN] = 1;
1457 tty.c_cc[VTIME] = 0;
1458
1459 tcsetattr (0, TCSANOW, &tty);
1460
1461 atexit(term_exit);
1462
1463 fcntl(0, F_SETFL, O_NONBLOCK);
1464 }
1465
1466 CharDriverState *qemu_chr_open_stdio(void)
1467 {
1468 CharDriverState *chr;
1469
1470 if (nographic) {
1471 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1472 return NULL;
1473 chr = qemu_chr_open_fd(0, 1);
1474 if (stdio_nb_clients == 0)
1475 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1476 client_index = stdio_nb_clients;
1477 } else {
1478 if (stdio_nb_clients != 0)
1479 return NULL;
1480 chr = qemu_chr_open_fd(0, 1);
1481 }
1482 stdio_clients[stdio_nb_clients++] = chr;
1483 if (stdio_nb_clients == 1) {
1484 /* set the terminal in raw mode */
1485 term_init();
1486 }
1487 return chr;
1488 }
1489
1490 #if defined(__linux__)
1491 CharDriverState *qemu_chr_open_pty(void)
1492 {
1493 struct termios tty;
1494 char slave_name[1024];
1495 int master_fd, slave_fd;
1496
1497 /* Not satisfying */
1498 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1499 return NULL;
1500 }
1501
1502 /* Disabling local echo and line-buffered output */
1503 tcgetattr (master_fd, &tty);
1504 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1505 tty.c_cc[VMIN] = 1;
1506 tty.c_cc[VTIME] = 0;
1507 tcsetattr (master_fd, TCSAFLUSH, &tty);
1508
1509 fprintf(stderr, "char device redirected to %s\n", slave_name);
1510 return qemu_chr_open_fd(master_fd, master_fd);
1511 }
1512
1513 static void tty_serial_init(int fd, int speed,
1514 int parity, int data_bits, int stop_bits)
1515 {
1516 struct termios tty;
1517 speed_t spd;
1518
1519 #if 0
1520 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1521 speed, parity, data_bits, stop_bits);
1522 #endif
1523 tcgetattr (fd, &tty);
1524
1525 switch(speed) {
1526 case 50:
1527 spd = B50;
1528 break;
1529 case 75:
1530 spd = B75;
1531 break;
1532 case 300:
1533 spd = B300;
1534 break;
1535 case 600:
1536 spd = B600;
1537 break;
1538 case 1200:
1539 spd = B1200;
1540 break;
1541 case 2400:
1542 spd = B2400;
1543 break;
1544 case 4800:
1545 spd = B4800;
1546 break;
1547 case 9600:
1548 spd = B9600;
1549 break;
1550 case 19200:
1551 spd = B19200;
1552 break;
1553 case 38400:
1554 spd = B38400;
1555 break;
1556 case 57600:
1557 spd = B57600;
1558 break;
1559 default:
1560 case 115200:
1561 spd = B115200;
1562 break;
1563 }
1564
1565 cfsetispeed(&tty, spd);
1566 cfsetospeed(&tty, spd);
1567
1568 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1569 |INLCR|IGNCR|ICRNL|IXON);
1570 tty.c_oflag |= OPOST;
1571 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1572 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1573 switch(data_bits) {
1574 default:
1575 case 8:
1576 tty.c_cflag |= CS8;
1577 break;
1578 case 7:
1579 tty.c_cflag |= CS7;
1580 break;
1581 case 6:
1582 tty.c_cflag |= CS6;
1583 break;
1584 case 5:
1585 tty.c_cflag |= CS5;
1586 break;
1587 }
1588 switch(parity) {
1589 default:
1590 case 'N':
1591 break;
1592 case 'E':
1593 tty.c_cflag |= PARENB;
1594 break;
1595 case 'O':
1596 tty.c_cflag |= PARENB | PARODD;
1597 break;
1598 }
1599
1600 tcsetattr (fd, TCSANOW, &tty);
1601 }
1602
1603 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1604 {
1605 FDCharDriver *s = chr->opaque;
1606
1607 switch(cmd) {
1608 case CHR_IOCTL_SERIAL_SET_PARAMS:
1609 {
1610 QEMUSerialSetParams *ssp = arg;
1611 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1612 ssp->data_bits, ssp->stop_bits);
1613 }
1614 break;
1615 case CHR_IOCTL_SERIAL_SET_BREAK:
1616 {
1617 int enable = *(int *)arg;
1618 if (enable)
1619 tcsendbreak(s->fd_in, 1);
1620 }
1621 break;
1622 default:
1623 return -ENOTSUP;
1624 }
1625 return 0;
1626 }
1627
1628 CharDriverState *qemu_chr_open_tty(const char *filename)
1629 {
1630 CharDriverState *chr;
1631 int fd;
1632
1633 fd = open(filename, O_RDWR | O_NONBLOCK);
1634 if (fd < 0)
1635 return NULL;
1636 fcntl(fd, F_SETFL, O_NONBLOCK);
1637 tty_serial_init(fd, 115200, 'N', 8, 1);
1638 chr = qemu_chr_open_fd(fd, fd);
1639 if (!chr)
1640 return NULL;
1641 chr->chr_ioctl = tty_serial_ioctl;
1642 return chr;
1643 }
1644
1645 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1646 {
1647 int fd = (int)chr->opaque;
1648 uint8_t b;
1649
1650 switch(cmd) {
1651 case CHR_IOCTL_PP_READ_DATA:
1652 if (ioctl(fd, PPRDATA, &b) < 0)
1653 return -ENOTSUP;
1654 *(uint8_t *)arg = b;
1655 break;
1656 case CHR_IOCTL_PP_WRITE_DATA:
1657 b = *(uint8_t *)arg;
1658 if (ioctl(fd, PPWDATA, &b) < 0)
1659 return -ENOTSUP;
1660 break;
1661 case CHR_IOCTL_PP_READ_CONTROL:
1662 if (ioctl(fd, PPRCONTROL, &b) < 0)
1663 return -ENOTSUP;
1664 *(uint8_t *)arg = b;
1665 break;
1666 case CHR_IOCTL_PP_WRITE_CONTROL:
1667 b = *(uint8_t *)arg;
1668 if (ioctl(fd, PPWCONTROL, &b) < 0)
1669 return -ENOTSUP;
1670 break;
1671 case CHR_IOCTL_PP_READ_STATUS:
1672 if (ioctl(fd, PPRSTATUS, &b) < 0)
1673 return -ENOTSUP;
1674 *(uint8_t *)arg = b;
1675 break;
1676 default:
1677 return -ENOTSUP;
1678 }
1679 return 0;
1680 }
1681
1682 CharDriverState *qemu_chr_open_pp(const char *filename)
1683 {
1684 CharDriverState *chr;
1685 int fd;
1686
1687 fd = open(filename, O_RDWR);
1688 if (fd < 0)
1689 return NULL;
1690
1691 if (ioctl(fd, PPCLAIM) < 0) {
1692 close(fd);
1693 return NULL;
1694 }
1695
1696 chr = qemu_mallocz(sizeof(CharDriverState));
1697 if (!chr) {
1698 close(fd);
1699 return NULL;
1700 }
1701 chr->opaque = (void *)fd;
1702 chr->chr_write = null_chr_write;
1703 chr->chr_add_read_handler = null_chr_add_read_handler;
1704 chr->chr_ioctl = pp_ioctl;
1705 return chr;
1706 }
1707
1708 #else
1709 CharDriverState *qemu_chr_open_pty(void)
1710 {
1711 return NULL;
1712 }
1713 #endif
1714
1715 #endif /* !defined(_WIN32) */
1716
1717 CharDriverState *qemu_chr_open(const char *filename)
1718 {
1719 #ifndef _WIN32
1720 const char *p;
1721 #endif
1722
1723 if (!strcmp(filename, "vc")) {
1724 return text_console_init(&display_state);
1725 } else if (!strcmp(filename, "null")) {
1726 return qemu_chr_open_null();
1727 } else
1728 #ifndef _WIN32
1729 if (strstart(filename, "file:", &p)) {
1730 return qemu_chr_open_file_out(p);
1731 } else if (strstart(filename, "pipe:", &p)) {
1732 return qemu_chr_open_pipe(p);
1733 } else if (!strcmp(filename, "pty")) {
1734 return qemu_chr_open_pty();
1735 } else if (!strcmp(filename, "stdio")) {
1736 return qemu_chr_open_stdio();
1737 } else
1738 #endif
1739 #if defined(__linux__)
1740 if (strstart(filename, "/dev/parport", NULL)) {
1741 return qemu_chr_open_pp(filename);
1742 } else
1743 if (strstart(filename, "/dev/", NULL)) {
1744 return qemu_chr_open_tty(filename);
1745 } else
1746 #endif
1747 {
1748 return NULL;
1749 }
1750 }
1751
1752 /***********************************************************/
1753 /* network device redirectors */
1754
1755 void hex_dump(FILE *f, const uint8_t *buf, int size)
1756 {
1757 int len, i, j, c;
1758
1759 for(i=0;i<size;i+=16) {
1760 len = size - i;
1761 if (len > 16)
1762 len = 16;
1763 fprintf(f, "%08x ", i);
1764 for(j=0;j<16;j++) {
1765 if (j < len)
1766 fprintf(f, " %02x", buf[i+j]);
1767 else
1768 fprintf(f, " ");
1769 }
1770 fprintf(f, " ");
1771 for(j=0;j<len;j++) {
1772 c = buf[i+j];
1773 if (c < ' ' || c > '~')
1774 c = '.';
1775 fprintf(f, "%c", c);
1776 }
1777 fprintf(f, "\n");
1778 }
1779 }
1780
1781 static int parse_macaddr(uint8_t *macaddr, const char *p)
1782 {
1783 int i;
1784 for(i = 0; i < 6; i++) {
1785 macaddr[i] = strtol(p, (char **)&p, 16);
1786 if (i == 5) {
1787 if (*p != '\0')
1788 return -1;
1789 } else {
1790 if (*p != ':')
1791 return -1;
1792 p++;
1793 }
1794 }
1795 return 0;
1796 }
1797
1798 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1799 {
1800 const char *p, *p1;
1801 int len;
1802 p = *pp;
1803 p1 = strchr(p, sep);
1804 if (!p1)
1805 return -1;
1806 len = p1 - p;
1807 p1++;
1808 if (buf_size > 0) {
1809 if (len > buf_size - 1)
1810 len = buf_size - 1;
1811 memcpy(buf, p, len);
1812 buf[len] = '\0';
1813 }
1814 *pp = p1;
1815 return 0;
1816 }
1817
1818 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1819 {
1820 char buf[512];
1821 struct hostent *he;
1822 const char *p, *r;
1823 int port;
1824
1825 p = str;
1826 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1827 return -1;
1828 saddr->sin_family = AF_INET;
1829 if (buf[0] == '\0') {
1830 saddr->sin_addr.s_addr = 0;
1831 } else {
1832 if (isdigit(buf[0])) {
1833 if (!inet_aton(buf, &saddr->sin_addr))
1834 return -1;
1835 } else {
1836 if ((he = gethostbyname(buf)) == NULL)
1837 return - 1;
1838 saddr->sin_addr = *(struct in_addr *)he->h_addr;
1839 }
1840 }
1841 port = strtol(p, (char **)&r, 0);
1842 if (r == p)
1843 return -1;
1844 saddr->sin_port = htons(port);
1845 return 0;
1846 }
1847
1848 /* find or alloc a new VLAN */
1849 VLANState *qemu_find_vlan(int id)
1850 {
1851 VLANState **pvlan, *vlan;
1852 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1853 if (vlan->id == id)
1854 return vlan;
1855 }
1856 vlan = qemu_mallocz(sizeof(VLANState));
1857 if (!vlan)
1858 return NULL;
1859 vlan->id = id;
1860 vlan->next = NULL;
1861 pvlan = &first_vlan;
1862 while (*pvlan != NULL)
1863 pvlan = &(*pvlan)->next;
1864 *pvlan = vlan;
1865 return vlan;
1866 }
1867
1868 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1869 IOReadHandler *fd_read,
1870 IOCanRWHandler *fd_can_read,
1871 void *opaque)
1872 {
1873 VLANClientState *vc, **pvc;
1874 vc = qemu_mallocz(sizeof(VLANClientState));
1875 if (!vc)
1876 return NULL;
1877 vc->fd_read = fd_read;
1878 vc->fd_can_read = fd_can_read;
1879 vc->opaque = opaque;
1880 vc->vlan = vlan;
1881
1882 vc->next = NULL;
1883 pvc = &vlan->first_client;
1884 while (*pvc != NULL)
1885 pvc = &(*pvc)->next;
1886 *pvc = vc;
1887 return vc;
1888 }
1889
1890 int qemu_can_send_packet(VLANClientState *vc1)
1891 {
1892 VLANState *vlan = vc1->vlan;
1893 VLANClientState *vc;
1894
1895 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1896 if (vc != vc1) {
1897 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
1898 return 0;
1899 }
1900 }
1901 return 1;
1902 }
1903
1904 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1905 {
1906 VLANState *vlan = vc1->vlan;
1907 VLANClientState *vc;
1908
1909 #if 0
1910 printf("vlan %d send:\n", vlan->id);
1911 hex_dump(stdout, buf, size);
1912 #endif
1913 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1914 if (vc != vc1) {
1915 vc->fd_read(vc->opaque, buf, size);
1916 }
1917 }
1918 }
1919
1920 #if defined(CONFIG_SLIRP)
1921
1922 /* slirp network adapter */
1923
1924 static int slirp_inited;
1925 static VLANClientState *slirp_vc;
1926
1927 int slirp_can_output(void)
1928 {
1929 return qemu_can_send_packet(slirp_vc);
1930 }
1931
1932 void slirp_output(const uint8_t *pkt, int pkt_len)
1933 {
1934 #if 0
1935 printf("slirp output:\n");
1936 hex_dump(stdout, pkt, pkt_len);
1937 #endif
1938 qemu_send_packet(slirp_vc, pkt, pkt_len);
1939 }
1940
1941 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1942 {
1943 #if 0
1944 printf("slirp input:\n");
1945 hex_dump(stdout, buf, size);
1946 #endif
1947 slirp_input(buf, size);
1948 }
1949
1950 static int net_slirp_init(VLANState *vlan)
1951 {
1952 if (!slirp_inited) {
1953 slirp_inited = 1;
1954 slirp_init();
1955 }
1956 slirp_vc = qemu_new_vlan_client(vlan,
1957 slirp_receive, NULL, NULL);
1958 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1959 return 0;
1960 }
1961
1962 static void net_slirp_redir(const char *redir_str)
1963 {
1964 int is_udp;
1965 char buf[256], *r;
1966 const char *p;
1967 struct in_addr guest_addr;
1968 int host_port, guest_port;
1969
1970 if (!slirp_inited) {
1971 slirp_inited = 1;
1972 slirp_init();
1973 }
1974
1975 p = redir_str;
1976 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1977 goto fail;
1978 if (!strcmp(buf, "tcp")) {
1979 is_udp = 0;
1980 } else if (!strcmp(buf, "udp")) {
1981 is_udp = 1;
1982 } else {
1983 goto fail;
1984 }
1985
1986 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1987 goto fail;
1988 host_port = strtol(buf, &r, 0);
1989 if (r == buf)
1990 goto fail;
1991
1992 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1993 goto fail;
1994 if (buf[0] == '\0') {
1995 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1996 }
1997 if (!inet_aton(buf, &guest_addr))
1998 goto fail;
1999
2000 guest_port = strtol(p, &r, 0);
2001 if (r == p)
2002 goto fail;
2003
2004 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2005 fprintf(stderr, "qemu: could not set up redirection\n");
2006 exit(1);
2007 }
2008 return;
2009 fail:
2010 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2011 exit(1);
2012 }
2013
2014 #ifndef _WIN32
2015
2016 char smb_dir[1024];
2017
2018 static void smb_exit(void)
2019 {
2020 DIR *d;
2021 struct dirent *de;
2022 char filename[1024];
2023
2024 /* erase all the files in the directory */
2025 d = opendir(smb_dir);
2026 for(;;) {
2027 de = readdir(d);
2028 if (!de)
2029 break;
2030 if (strcmp(de->d_name, ".") != 0 &&
2031 strcmp(de->d_name, "..") != 0) {
2032 snprintf(filename, sizeof(filename), "%s/%s",
2033 smb_dir, de->d_name);
2034 unlink(filename);
2035 }
2036 }
2037 closedir(d);
2038 rmdir(smb_dir);
2039 }
2040
2041 /* automatic user mode samba server configuration */
2042 void net_slirp_smb(const char *exported_dir)
2043 {
2044 char smb_conf[1024];
2045 char smb_cmdline[1024];
2046 FILE *f;
2047
2048 if (!slirp_inited) {
2049 slirp_inited = 1;
2050 slirp_init();
2051 }
2052
2053 /* XXX: better tmp dir construction */
2054 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2055 if (mkdir(smb_dir, 0700) < 0) {
2056 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2057 exit(1);
2058 }
2059 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2060
2061 f = fopen(smb_conf, "w");
2062 if (!f) {
2063 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2064 exit(1);
2065 }
2066 fprintf(f,
2067 "[global]\n"
2068 "private dir=%s\n"
2069 "smb ports=0\n"
2070 "socket address=127.0.0.1\n"
2071 "pid directory=%s\n"
2072 "lock directory=%s\n"
2073 "log file=%s/log.smbd\n"
2074 "smb passwd file=%s/smbpasswd\n"
2075 "security = share\n"
2076 "[qemu]\n"
2077 "path=%s\n"
2078 "read only=no\n"
2079 "guest ok=yes\n",
2080 smb_dir,
2081 smb_dir,
2082 smb_dir,
2083 smb_dir,
2084 smb_dir,
2085 exported_dir
2086 );
2087 fclose(f);
2088 atexit(smb_exit);
2089
2090 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2091 smb_conf);
2092
2093 slirp_add_exec(0, smb_cmdline, 4, 139);
2094 }
2095
2096 #endif /* !defined(_WIN32) */
2097
2098 #endif /* CONFIG_SLIRP */
2099
2100 #if !defined(_WIN32)
2101
2102 typedef struct TAPState {
2103 VLANClientState *vc;
2104 int fd;
2105 } TAPState;
2106
2107 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2108 {
2109 TAPState *s = opaque;
2110 int ret;
2111 for(;;) {
2112 ret = write(s->fd, buf, size);
2113 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2114 } else {
2115 break;
2116 }
2117 }
2118 }
2119
2120 static void tap_send(void *opaque)
2121 {
2122 TAPState *s = opaque;
2123 uint8_t buf[4096];
2124 int size;
2125
2126 size = read(s->fd, buf, sizeof(buf));
2127 if (size > 0) {
2128 qemu_send_packet(s->vc, buf, size);
2129 }
2130 }
2131
2132 /* fd support */
2133
2134 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2135 {
2136 TAPState *s;
2137
2138 s = qemu_mallocz(sizeof(TAPState));
2139 if (!s)
2140 return NULL;
2141 s->fd = fd;
2142 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2143 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2144 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2145 return s;
2146 }
2147
2148 #ifdef _BSD
2149 static int tap_open(char *ifname, int ifname_size)
2150 {
2151 int fd;
2152 char *dev;
2153 struct stat s;
2154
2155 fd = open("/dev/tap", O_RDWR);
2156 if (fd < 0) {
2157 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2158 return -1;
2159 }
2160
2161 fstat(fd, &s);
2162 dev = devname(s.st_rdev, S_IFCHR);
2163 pstrcpy(ifname, ifname_size, dev);
2164
2165 fcntl(fd, F_SETFL, O_NONBLOCK);
2166 return fd;
2167 }
2168 #else
2169 static int tap_open(char *ifname, int ifname_size)
2170 {
2171 struct ifreq ifr;
2172 int fd, ret;
2173
2174 fd = open("/dev/net/tun", O_RDWR);
2175 if (fd < 0) {
2176 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2177 return -1;
2178 }
2179 memset(&ifr, 0, sizeof(ifr));
2180 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2181 if (ifname[0] != '\0')
2182 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2183 else
2184 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2185 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2186 if (ret != 0) {
2187 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2188 close(fd);
2189 return -1;
2190 }
2191 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2192 fcntl(fd, F_SETFL, O_NONBLOCK);
2193 return fd;
2194 }
2195 #endif
2196
2197 static int net_tap_init(VLANState *vlan, const char *ifname1,
2198 const char *setup_script)
2199 {
2200 TAPState *s;
2201 int pid, status, fd;
2202 char *args[3];
2203 char **parg;
2204 char ifname[128];
2205
2206 if (ifname1 != NULL)
2207 pstrcpy(ifname, sizeof(ifname), ifname1);
2208 else
2209 ifname[0] = '\0';
2210 fd = tap_open(ifname, sizeof(ifname));
2211 if (fd < 0)
2212 return -1;
2213
2214 if (!setup_script)
2215 setup_script = "";
2216 if (setup_script[0] != '\0') {
2217 /* try to launch network init script */
2218 pid = fork();
2219 if (pid >= 0) {
2220 if (pid == 0) {
2221 parg = args;
2222 *parg++ = (char *)setup_script;
2223 *parg++ = ifname;
2224 *parg++ = NULL;
2225 execv(setup_script, args);
2226 _exit(1);
2227 }
2228 while (waitpid(pid, &status, 0) != pid);
2229 if (!WIFEXITED(status) ||
2230 WEXITSTATUS(status) != 0) {
2231 fprintf(stderr, "%s: could not launch network script\n",
2232 setup_script);
2233 return -1;
2234 }
2235 }
2236 }
2237 s = net_tap_fd_init(vlan, fd);
2238 if (!s)
2239 return -1;
2240 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2241 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2242 return 0;
2243 }
2244
2245 #endif /* !_WIN32 */
2246
2247 /* network connection */
2248 typedef struct NetSocketState {
2249 VLANClientState *vc;
2250 int fd;
2251 int state; /* 0 = getting length, 1 = getting data */
2252 int index;
2253 int packet_len;
2254 uint8_t buf[4096];
2255 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2256 } NetSocketState;
2257
2258 typedef struct NetSocketListenState {
2259 VLANState *vlan;
2260 int fd;
2261 } NetSocketListenState;
2262
2263 /* XXX: we consider we can send the whole packet without blocking */
2264 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2265 {
2266 NetSocketState *s = opaque;
2267 uint32_t len;
2268 len = htonl(size);
2269
2270 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2271 send_all(s->fd, buf, size);
2272 }
2273
2274 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2275 {
2276 NetSocketState *s = opaque;
2277 sendto(s->fd, buf, size, 0,
2278 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2279 }
2280
2281 static void net_socket_send(void *opaque)
2282 {
2283 NetSocketState *s = opaque;
2284 int l, size, err;
2285 uint8_t buf1[4096];
2286 const uint8_t *buf;
2287
2288 size = recv(s->fd, buf1, sizeof(buf1), 0);
2289 if (size < 0) {
2290 err = socket_error();
2291 if (err != EWOULDBLOCK)
2292 goto eoc;
2293 } else if (size == 0) {
2294 /* end of connection */
2295 eoc:
2296 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2297 closesocket(s->fd);
2298 return;
2299 }
2300 buf = buf1;
2301 while (size > 0) {
2302 /* reassemble a packet from the network */
2303 switch(s->state) {
2304 case 0:
2305 l = 4 - s->index;
2306 if (l > size)
2307 l = size;
2308 memcpy(s->buf + s->index, buf, l);
2309 buf += l;
2310 size -= l;
2311 s->index += l;
2312 if (s->index == 4) {
2313 /* got length */
2314 s->packet_len = ntohl(*(uint32_t *)s->buf);
2315 s->index = 0;
2316 s->state = 1;
2317 }
2318 break;
2319 case 1:
2320 l = s->packet_len - s->index;
2321 if (l > size)
2322 l = size;
2323 memcpy(s->buf + s->index, buf, l);
2324 s->index += l;
2325 buf += l;
2326 size -= l;
2327 if (s->index >= s->packet_len) {
2328 qemu_send_packet(s->vc, s->buf, s->packet_len);
2329 s->index = 0;
2330 s->state = 0;
2331 }
2332 break;
2333 }
2334 }
2335 }
2336
2337 static void net_socket_send_dgram(void *opaque)
2338 {
2339 NetSocketState *s = opaque;
2340 int size;
2341
2342 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2343 if (size < 0)
2344 return;
2345 if (size == 0) {
2346 /* end of connection */
2347 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2348 return;
2349 }
2350 qemu_send_packet(s->vc, s->buf, size);
2351 }
2352
2353 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2354 {
2355 struct ip_mreq imr;
2356 int fd;
2357 int val, ret;
2358 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2359 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2360 inet_ntoa(mcastaddr->sin_addr),
2361 (int)ntohl(mcastaddr->sin_addr.s_addr));
2362 return -1;
2363
2364 }
2365 fd = socket(PF_INET, SOCK_DGRAM, 0);
2366 if (fd < 0) {
2367 perror("socket(PF_INET, SOCK_DGRAM)");
2368 return -1;
2369 }
2370
2371 val = 1;
2372 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2373 (const char *)&val, sizeof(val));
2374 if (ret < 0) {
2375 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2376 goto fail;
2377 }
2378
2379 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2380 if (ret < 0) {
2381 perror("bind");
2382 goto fail;
2383 }
2384
2385 /* Add host to multicast group */
2386 imr.imr_multiaddr = mcastaddr->sin_addr;
2387 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2388
2389 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2390 (const char *)&imr, sizeof(struct ip_mreq));
2391 if (ret < 0) {
2392 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2393 goto fail;
2394 }
2395
2396 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2397 val = 1;
2398 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2399 (const char *)&val, sizeof(val));
2400 if (ret < 0) {
2401 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2402 goto fail;
2403 }
2404
2405 socket_set_nonblock(fd);
2406 return fd;
2407 fail:
2408 if (fd>=0) close(fd);
2409 return -1;
2410 }
2411
2412 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2413 int is_connected)
2414 {
2415 struct sockaddr_in saddr;
2416 int newfd;
2417 socklen_t saddr_len;
2418 NetSocketState *s;
2419
2420 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2421 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2422 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2423 */
2424
2425 if (is_connected) {
2426 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2427 /* must be bound */
2428 if (saddr.sin_addr.s_addr==0) {
2429 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2430 fd);
2431 return NULL;
2432 }
2433 /* clone dgram socket */
2434 newfd = net_socket_mcast_create(&saddr);
2435 if (newfd < 0) {
2436 /* error already reported by net_socket_mcast_create() */
2437 close(fd);
2438 return NULL;
2439 }
2440 /* clone newfd to fd, close newfd */
2441 dup2(newfd, fd);
2442 close(newfd);
2443
2444 } else {
2445 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2446 fd, strerror(errno));
2447 return NULL;
2448 }
2449 }
2450
2451 s = qemu_mallocz(sizeof(NetSocketState));
2452 if (!s)
2453 return NULL;
2454 s->fd = fd;
2455
2456 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2457 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2458
2459 /* mcast: save bound address as dst */
2460 if (is_connected) s->dgram_dst=saddr;
2461
2462 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2463 "socket: fd=%d (%s mcast=%s:%d)",
2464 fd, is_connected? "cloned" : "",
2465 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2466 return s;
2467 }
2468
2469 static void net_socket_connect(void *opaque)
2470 {
2471 NetSocketState *s = opaque;
2472 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2473 }
2474
2475 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2476 int is_connected)
2477 {
2478 NetSocketState *s;
2479 s = qemu_mallocz(sizeof(NetSocketState));
2480 if (!s)
2481 return NULL;
2482 s->fd = fd;
2483 s->vc = qemu_new_vlan_client(vlan,
2484 net_socket_receive, NULL, s);
2485 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2486 "socket: fd=%d", fd);
2487 if (is_connected) {
2488 net_socket_connect(s);
2489 } else {
2490 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2491 }
2492 return s;
2493 }
2494
2495 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2496 int is_connected)
2497 {
2498 int so_type=-1, optlen=sizeof(so_type);
2499
2500 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2501 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2502 return NULL;
2503 }
2504 switch(so_type) {
2505 case SOCK_DGRAM:
2506 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2507 case SOCK_STREAM:
2508 return net_socket_fd_init_stream(vlan, fd, is_connected);
2509 default:
2510 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2511 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2512 return net_socket_fd_init_stream(vlan, fd, is_connected);
2513 }
2514 return NULL;
2515 }
2516
2517 static void net_socket_accept(void *opaque)
2518 {
2519 NetSocketListenState *s = opaque;
2520 NetSocketState *s1;
2521 struct sockaddr_in saddr;
2522 socklen_t len;
2523 int fd;
2524
2525 for(;;) {
2526 len = sizeof(saddr);
2527 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2528 if (fd < 0 && errno != EINTR) {
2529 return;
2530 } else if (fd >= 0) {
2531 break;
2532 }
2533 }
2534 s1 = net_socket_fd_init(s->vlan, fd, 1);
2535 if (!s1) {
2536 close(fd);
2537 } else {
2538 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2539 "socket: connection from %s:%d",
2540 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2541 }
2542 }
2543
2544 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2545 {
2546 NetSocketListenState *s;
2547 int fd, val, ret;
2548 struct sockaddr_in saddr;
2549
2550 if (parse_host_port(&saddr, host_str) < 0)
2551 return -1;
2552
2553 s = qemu_mallocz(sizeof(NetSocketListenState));
2554 if (!s)
2555 return -1;
2556
2557 fd = socket(PF_INET, SOCK_STREAM, 0);
2558 if (fd < 0) {
2559 perror("socket");
2560 return -1;
2561 }
2562 socket_set_nonblock(fd);
2563
2564 /* allow fast reuse */
2565 val = 1;
2566 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2567
2568 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2569 if (ret < 0) {
2570 perror("bind");
2571 return -1;
2572 }
2573 ret = listen(fd, 0);
2574 if (ret < 0) {
2575 perror("listen");
2576 return -1;
2577 }
2578 s->vlan = vlan;
2579 s->fd = fd;
2580 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2581 return 0;
2582 }
2583
2584 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2585 {
2586 NetSocketState *s;
2587 int fd, connected, ret, err;
2588 struct sockaddr_in saddr;
2589
2590 if (parse_host_port(&saddr, host_str) < 0)
2591 return -1;
2592
2593 fd = socket(PF_INET, SOCK_STREAM, 0);
2594 if (fd < 0) {
2595 perror("socket");
2596 return -1;
2597 }
2598 socket_set_nonblock(fd);
2599
2600 connected = 0;
2601 for(;;) {
2602 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2603 if (ret < 0) {
2604 err = socket_error();
2605 if (err == EINTR || err == EWOULDBLOCK) {
2606 } else if (err == EINPROGRESS) {
2607 break;
2608 } else {
2609 perror("connect");
2610 closesocket(fd);
2611 return -1;
2612 }
2613 } else {
2614 connected = 1;
2615 break;
2616 }
2617 }
2618 s = net_socket_fd_init(vlan, fd, connected);
2619 if (!s)
2620 return -1;
2621 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2622 "socket: connect to %s:%d",
2623 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2624 return 0;
2625 }
2626
2627 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
2628 {
2629 NetSocketState *s;
2630 int fd;
2631 struct sockaddr_in saddr;
2632
2633 if (parse_host_port(&saddr, host_str) < 0)
2634 return -1;
2635
2636
2637 fd = net_socket_mcast_create(&saddr);
2638 if (fd < 0)
2639 return -1;
2640
2641 s = net_socket_fd_init(vlan, fd, 0);
2642 if (!s)
2643 return -1;
2644
2645 s->dgram_dst = saddr;
2646
2647 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2648 "socket: mcast=%s:%d",
2649 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2650 return 0;
2651
2652 }
2653
2654 static int get_param_value(char *buf, int buf_size,
2655 const char *tag, const char *str)
2656 {
2657 const char *p;
2658 char *q;
2659 char option[128];
2660
2661 p = str;
2662 for(;;) {
2663 q = option;
2664 while (*p != '\0' && *p != '=') {
2665 if ((q - option) < sizeof(option) - 1)
2666 *q++ = *p;
2667 p++;
2668 }
2669 *q = '\0';
2670 if (*p != '=')
2671 break;
2672 p++;
2673 if (!strcmp(tag, option)) {
2674 q = buf;
2675 while (*p != '\0' && *p != ',') {
2676 if ((q - buf) < buf_size - 1)
2677 *q++ = *p;
2678 p++;
2679 }
2680 *q = '\0';
2681 return q - buf;
2682 } else {
2683 while (*p != '\0' && *p != ',') {
2684 p++;
2685 }
2686 }
2687 if (*p != ',')
2688 break;
2689 p++;
2690 }
2691 return 0;
2692 }
2693
2694 int net_client_init(const char *str)
2695 {
2696 const char *p;
2697 char *q;
2698 char device[64];
2699 char buf[1024];
2700 int vlan_id, ret;
2701 VLANState *vlan;
2702
2703 p = str;
2704 q = device;
2705 while (*p != '\0' && *p != ',') {
2706 if ((q - device) < sizeof(device) - 1)
2707 *q++ = *p;
2708 p++;
2709 }
2710 *q = '\0';
2711 if (*p == ',')
2712 p++;
2713 vlan_id = 0;
2714 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2715 vlan_id = strtol(buf, NULL, 0);
2716 }
2717 vlan = qemu_find_vlan(vlan_id);
2718 if (!vlan) {
2719 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2720 return -1;
2721 }
2722 if (!strcmp(device, "nic")) {
2723 NICInfo *nd;
2724 uint8_t *macaddr;
2725
2726 if (nb_nics >= MAX_NICS) {
2727 fprintf(stderr, "Too Many NICs\n");
2728 return -1;
2729 }
2730 nd = &nd_table[nb_nics];
2731 macaddr = nd->macaddr;
2732 macaddr[0] = 0x52;
2733 macaddr[1] = 0x54;
2734 macaddr[2] = 0x00;
2735 macaddr[3] = 0x12;
2736 macaddr[4] = 0x34;
2737 macaddr[5] = 0x56 + nb_nics;
2738
2739 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2740 if (parse_macaddr(macaddr, buf) < 0) {
2741 fprintf(stderr, "invalid syntax for ethernet address\n");
2742 return -1;
2743 }
2744 }
2745 if (get_param_value(buf, sizeof(buf), "model", p)) {
2746 nd->model = strdup(buf);
2747 }
2748 nd->vlan = vlan;
2749 nb_nics++;
2750 ret = 0;
2751 } else
2752 if (!strcmp(device, "none")) {
2753 /* does nothing. It is needed to signal that no network cards
2754 are wanted */
2755 ret = 0;
2756 } else
2757 #ifdef CONFIG_SLIRP
2758 if (!strcmp(device, "user")) {
2759 ret = net_slirp_init(vlan);
2760 } else
2761 #endif
2762 #ifdef _WIN32
2763 if (!strcmp(device, "tap")) {
2764 char ifname[64];
2765 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2766 fprintf(stderr, "tap: no interface name\n");
2767 return -1;
2768 }
2769 ret = tap_win32_init(vlan, ifname);
2770 } else
2771 #else
2772 if (!strcmp(device, "tap")) {
2773 char ifname[64];
2774 char setup_script[1024];
2775 int fd;
2776 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2777 fd = strtol(buf, NULL, 0);
2778 ret = -1;
2779 if (net_tap_fd_init(vlan, fd))
2780 ret = 0;
2781 } else {
2782 get_param_value(ifname, sizeof(ifname), "ifname", p);
2783 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2784 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2785 }
2786 ret = net_tap_init(vlan, ifname, setup_script);
2787 }
2788 } else
2789 #endif
2790 if (!strcmp(device, "socket")) {
2791 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2792 int fd;
2793 fd = strtol(buf, NULL, 0);
2794 ret = -1;
2795 if (net_socket_fd_init(vlan, fd, 1))
2796 ret = 0;
2797 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2798 ret = net_socket_listen_init(vlan, buf);
2799 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2800 ret = net_socket_connect_init(vlan, buf);
2801 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2802 ret = net_socket_mcast_init(vlan, buf);
2803 } else {
2804 fprintf(stderr, "Unknown socket options: %s\n", p);
2805 return -1;
2806 }
2807 } else
2808 {
2809 fprintf(stderr, "Unknown network device: %s\n", device);
2810 return -1;
2811 }
2812 if (ret < 0) {
2813 fprintf(stderr, "Could not initialize device '%s'\n", device);
2814 }
2815
2816 return ret;
2817 }
2818
2819 void do_info_network(void)
2820 {
2821 VLANState *vlan;
2822 VLANClientState *vc;
2823
2824 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2825 term_printf("VLAN %d devices:\n", vlan->id);
2826 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2827 term_printf(" %s\n", vc->info_str);
2828 }
2829 }
2830
2831 /***********************************************************/
2832 /* USB devices */
2833
2834 static int usb_device_add(const char *devname)
2835 {
2836 const char *p;
2837 USBDevice *dev;
2838 int i;
2839
2840 if (!vm_usb_hub)
2841 return -1;
2842 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2843 if (!vm_usb_ports[i]->dev)
2844 break;
2845 }
2846 if (i == MAX_VM_USB_PORTS)
2847 return -1;
2848
2849 if (strstart(devname, "host:", &p)) {
2850 dev = usb_host_device_open(p);
2851 if (!dev)
2852 return -1;
2853 } else if (!strcmp(devname, "mouse")) {
2854 dev = usb_mouse_init();
2855 if (!dev)
2856 return -1;
2857 } else {
2858 return -1;
2859 }
2860 usb_attach(vm_usb_ports[i], dev);
2861 return 0;
2862 }
2863
2864 static int usb_device_del(const char *devname)
2865 {
2866 USBDevice *dev;
2867 int bus_num, addr, i;
2868 const char *p;
2869
2870 if (!vm_usb_hub)
2871 return -1;
2872
2873 p = strchr(devname, '.');
2874 if (!p)
2875 return -1;
2876 bus_num = strtoul(devname, NULL, 0);
2877 addr = strtoul(p + 1, NULL, 0);
2878 if (bus_num != 0)
2879 return -1;
2880 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2881 dev = vm_usb_ports[i]->dev;
2882 if (dev && dev->addr == addr)
2883 break;
2884 }
2885 if (i == MAX_VM_USB_PORTS)
2886 return -1;
2887 usb_attach(vm_usb_ports[i], NULL);
2888 return 0;
2889 }
2890
2891 void do_usb_add(const char *devname)
2892 {
2893 int ret;
2894 ret = usb_device_add(devname);
2895 if (ret < 0)
2896 term_printf("Could not add USB device '%s'\n", devname);
2897 }
2898
2899 void do_usb_del(const char *devname)
2900 {
2901 int ret;
2902 ret = usb_device_del(devname);
2903 if (ret < 0)
2904 term_printf("Could not remove USB device '%s'\n", devname);
2905 }
2906
2907 void usb_info(void)
2908 {
2909 USBDevice *dev;
2910 int i;
2911 const char *speed_str;
2912
2913 if (!vm_usb_hub) {
2914 term_printf("USB support not enabled\n");
2915 return;
2916 }
2917
2918 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2919 dev = vm_usb_ports[i]->dev;
2920 if (dev) {
2921 term_printf("Hub port %d:\n", i);
2922 switch(dev->speed) {
2923 case USB_SPEED_LOW:
2924 speed_str = "1.5";
2925 break;
2926 case USB_SPEED_FULL:
2927 speed_str = "12";
2928 break;
2929 case USB_SPEED_HIGH:
2930 speed_str = "480";
2931 break;
2932 default:
2933 speed_str = "?";
2934 break;
2935 }
2936 term_printf(" Device %d.%d, speed %s Mb/s\n",
2937 0, dev->addr, speed_str);
2938 }
2939 }
2940 }
2941
2942 /***********************************************************/
2943 /* pid file */
2944
2945 static char *pid_filename;
2946
2947 /* Remove PID file. Called on normal exit */
2948
2949 static void remove_pidfile(void)
2950 {
2951 unlink (pid_filename);
2952 }
2953
2954 static void create_pidfile(const char *filename)
2955 {
2956 struct stat pidstat;
2957 FILE *f;
2958
2959 /* Try to write our PID to the named file */
2960 if (stat(filename, &pidstat) < 0) {
2961 if (errno == ENOENT) {
2962 if ((f = fopen (filename, "w")) == NULL) {
2963 perror("Opening pidfile");
2964 exit(1);
2965 }
2966 fprintf(f, "%d\n", getpid());
2967 fclose(f);
2968 pid_filename = qemu_strdup(filename);
2969 if (!pid_filename) {
2970 fprintf(stderr, "Could not save PID filename");
2971 exit(1);
2972 }
2973 atexit(remove_pidfile);
2974 }
2975 } else {
2976 fprintf(stderr, "%s already exists. Remove it and try again.\n",
2977 filename);
2978 exit(1);
2979 }
2980 }
2981
2982 /***********************************************************/
2983 /* dumb display */
2984
2985 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2986 {
2987 }
2988
2989 static void dumb_resize(DisplayState *ds, int w, int h)
2990 {
2991 }
2992
2993 static void dumb_refresh(DisplayState *ds)
2994 {
2995 vga_update_display();
2996 }
2997
2998 void dumb_display_init(DisplayState *ds)
2999 {
3000 ds->data = NULL;
3001 ds->linesize = 0;
3002 ds->depth = 0;
3003 ds->dpy_update = dumb_update;
3004 ds->dpy_resize = dumb_resize;
3005 ds->dpy_refresh = dumb_refresh;
3006 }
3007
3008 #if !defined(CONFIG_SOFTMMU)
3009 /***********************************************************/
3010 /* cpu signal handler */
3011 static void host_segv_handler(int host_signum, siginfo_t *info,
3012 void *puc)
3013 {
3014 if (cpu_signal_handler(host_signum, info, puc))
3015 return;
3016 if (stdio_nb_clients > 0)
3017 term_exit();
3018 abort();
3019 }
3020 #endif
3021
3022 /***********************************************************/
3023 /* I/O handling */
3024
3025 #define MAX_IO_HANDLERS 64
3026
3027 typedef struct IOHandlerRecord {
3028 int fd;
3029 IOCanRWHandler *fd_read_poll;
3030 IOHandler *fd_read;
3031 IOHandler *fd_write;
3032 void *opaque;
3033 /* temporary data */
3034 struct pollfd *ufd;
3035 struct IOHandlerRecord *next;
3036 } IOHandlerRecord;
3037
3038 static IOHandlerRecord *first_io_handler;
3039
3040 /* XXX: fd_read_poll should be suppressed, but an API change is
3041 necessary in the character devices to suppress fd_can_read(). */
3042 int qemu_set_fd_handler2(int fd,
3043 IOCanRWHandler *fd_read_poll,
3044 IOHandler *fd_read,
3045 IOHandler *fd_write,
3046 void *opaque)
3047 {
3048 IOHandlerRecord **pioh, *ioh;
3049
3050 if (!fd_read && !fd_write) {
3051 pioh = &first_io_handler;
3052 for(;;) {
3053 ioh = *pioh;
3054 if (ioh == NULL)
3055 break;
3056 if (ioh->fd == fd) {
3057 *pioh = ioh->next;
3058 qemu_free(ioh);
3059 break;
3060 }
3061 pioh = &ioh->next;
3062 }
3063 } else {
3064 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3065 if (ioh->fd == fd)
3066 goto found;
3067 }
3068 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3069 if (!ioh)
3070 return -1;
3071 ioh->next = first_io_handler;
3072 first_io_handler = ioh;
3073 found:
3074 ioh->fd = fd;
3075 ioh->fd_read_poll = fd_read_poll;
3076 ioh->fd_read = fd_read;
3077 ioh->fd_write = fd_write;
3078 ioh->opaque = opaque;
3079 }
3080 return 0;
3081 }
3082
3083 int qemu_set_fd_handler(int fd,
3084 IOHandler *fd_read,
3085 IOHandler *fd_write,
3086 void *opaque)
3087 {
3088 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3089 }
3090
3091 /***********************************************************/
3092 /* savevm/loadvm support */
3093
3094 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3095 {
3096 fwrite(buf, 1, size, f);
3097 }
3098
3099 void qemu_put_byte(QEMUFile *f, int v)
3100 {
3101 fputc(v, f);
3102 }
3103
3104 void qemu_put_be16(QEMUFile *f, unsigned int v)
3105 {
3106 qemu_put_byte(f, v >> 8);
3107 qemu_put_byte(f, v);
3108 }
3109
3110 void qemu_put_be32(QEMUFile *f, unsigned int v)
3111 {
3112 qemu_put_byte(f, v >> 24);
3113 qemu_put_byte(f, v >> 16);
3114 qemu_put_byte(f, v >> 8);
3115 qemu_put_byte(f, v);
3116 }
3117
3118 void qemu_put_be64(QEMUFile *f, uint64_t v)
3119 {
3120 qemu_put_be32(f, v >> 32);
3121 qemu_put_be32(f, v);
3122 }
3123
3124 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3125 {
3126 return fread(buf, 1, size, f);
3127 }
3128
3129 int qemu_get_byte(QEMUFile *f)
3130 {
3131 int v;
3132 v = fgetc(f);
3133 if (v == EOF)
3134 return 0;
3135 else
3136 return v;
3137 }
3138
3139 unsigned int qemu_get_be16(QEMUFile *f)
3140 {
3141 unsigned int v;
3142 v = qemu_get_byte(f) << 8;
3143 v |= qemu_get_byte(f);
3144 return v;
3145 }
3146
3147 unsigned int qemu_get_be32(QEMUFile *f)
3148 {
3149 unsigned int v;
3150 v = qemu_get_byte(f) << 24;
3151 v |= qemu_get_byte(f) << 16;
3152 v |= qemu_get_byte(f) << 8;
3153 v |= qemu_get_byte(f);
3154 return v;
3155 }
3156
3157 uint64_t qemu_get_be64(QEMUFile *f)
3158 {
3159 uint64_t v;
3160 v = (uint64_t)qemu_get_be32(f) << 32;
3161 v |= qemu_get_be32(f);
3162 return v;
3163 }
3164
3165 int64_t qemu_ftell(QEMUFile *f)
3166 {
3167 return ftell(f);
3168 }
3169
3170 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3171 {
3172 if (fseek(f, pos, whence) < 0)
3173 return -1;
3174 return ftell(f);
3175 }
3176
3177 typedef struct SaveStateEntry {
3178 char idstr[256];
3179 int instance_id;
3180 int version_id;
3181 SaveStateHandler *save_state;
3182 LoadStateHandler *load_state;
3183 void *opaque;
3184 struct SaveStateEntry *next;
3185 } SaveStateEntry;
3186
3187 static SaveStateEntry *first_se;
3188
3189 int register_savevm(const char *idstr,
3190 int instance_id,
3191 int version_id,
3192 SaveStateHandler *save_state,
3193 LoadStateHandler *load_state,
3194 void *opaque)
3195 {
3196 SaveStateEntry *se, **pse;
3197
3198 se = qemu_malloc(sizeof(SaveStateEntry));
3199 if (!se)
3200 return -1;
3201 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3202 se->instance_id = instance_id;
3203 se->version_id = version_id;
3204 se->save_state = save_state;
3205 se->load_state = load_state;
3206 se->opaque = opaque;
3207 se->next = NULL;
3208
3209 /* add at the end of list */
3210 pse = &first_se;
3211 while (*pse != NULL)
3212 pse = &(*pse)->next;
3213 *pse = se;
3214 return 0;
3215 }
3216
3217 #define QEMU_VM_FILE_MAGIC 0x5145564d
3218 #define QEMU_VM_FILE_VERSION 0x00000001
3219
3220 int qemu_savevm(const char *filename)
3221 {
3222 SaveStateEntry *se;
3223 QEMUFile *f;
3224 int len, len_pos, cur_pos, saved_vm_running, ret;
3225
3226 saved_vm_running = vm_running;
3227 vm_stop(0);
3228
3229 f = fopen(filename, "wb");
3230 if (!f) {
3231 ret = -1;
3232 goto the_end;
3233 }
3234
3235 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3236 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3237
3238 for(se = first_se; se != NULL; se = se->next) {
3239 /* ID string */
3240 len = strlen(se->idstr);
3241 qemu_put_byte(f, len);
3242 qemu_put_buffer(f, se->idstr, len);
3243
3244 qemu_put_be32(f, se->instance_id);
3245 qemu_put_be32(f, se->version_id);
3246
3247 /* record size: filled later */
3248 len_pos = ftell(f);
3249 qemu_put_be32(f, 0);
3250
3251 se->save_state(f, se->opaque);
3252
3253 /* fill record size */
3254 cur_pos = ftell(f);
3255 len = ftell(f) - len_pos - 4;
3256 fseek(f, len_pos, SEEK_SET);
3257 qemu_put_be32(f, len);
3258 fseek(f, cur_pos, SEEK_SET);
3259 }
3260
3261 fclose(f);
3262 ret = 0;
3263 the_end:
3264 if (saved_vm_running)
3265 vm_start();
3266 return ret;
3267 }
3268
3269 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3270 {
3271 SaveStateEntry *se;
3272
3273 for(se = first_se; se != NULL; se = se->next) {
3274 if (!strcmp(se->idstr, idstr) &&
3275 instance_id == se->instance_id)
3276 return se;
3277 }
3278 return NULL;
3279 }
3280
3281 int qemu_loadvm(const char *filename)
3282 {
3283 SaveStateEntry *se;
3284 QEMUFile *f;
3285 int len, cur_pos, ret, instance_id, record_len, version_id;
3286 int saved_vm_running;
3287 unsigned int v;
3288 char idstr[256];
3289
3290 saved_vm_running = vm_running;
3291 vm_stop(0);
3292
3293 f = fopen(filename, "rb");
3294 if (!f) {
3295 ret = -1;
3296 goto the_end;
3297 }
3298
3299 v = qemu_get_be32(f);
3300 if (v != QEMU_VM_FILE_MAGIC)
3301 goto fail;
3302 v = qemu_get_be32(f);
3303 if (v != QEMU_VM_FILE_VERSION) {
3304 fail:
3305 fclose(f);
3306 ret = -1;
3307 goto the_end;
3308 }
3309 for(;;) {
3310 len = qemu_get_byte(f);
3311 if (feof(f))
3312 break;
3313 qemu_get_buffer(f, idstr, len);
3314 idstr[len] = '\0';
3315 instance_id = qemu_get_be32(f);
3316 version_id = qemu_get_be32(f);
3317 record_len = qemu_get_be32(f);
3318 #if 0
3319 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3320 idstr, instance_id, version_id, record_len);
3321 #endif
3322 cur_pos = ftell(f);
3323 se = find_se(idstr, instance_id);
3324 if (!se) {
3325 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3326 instance_id, idstr);
3327 } else {
3328 ret = se->load_state(f, se->opaque, version_id);
3329 if (ret < 0) {
3330 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3331 instance_id, idstr);
3332 }
3333 }
3334 /* always seek to exact end of record */
3335 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3336 }
3337 fclose(f);
3338 ret = 0;
3339 the_end:
3340 if (saved_vm_running)
3341 vm_start();
3342 return ret;
3343 }
3344
3345 /***********************************************************/
3346 /* cpu save/restore */
3347
3348 #if defined(TARGET_I386)
3349
3350 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3351 {
3352 qemu_put_be32(f, dt->selector);
3353 qemu_put_betl(f, dt->base);
3354 qemu_put_be32(f, dt->limit);
3355 qemu_put_be32(f, dt->flags);
3356 }
3357
3358 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3359 {
3360 dt->selector = qemu_get_be32(f);
3361 dt->base = qemu_get_betl(f);
3362 dt->limit = qemu_get_be32(f);
3363 dt->flags = qemu_get_be32(f);
3364 }
3365
3366 void cpu_save(QEMUFile *f, void *opaque)
3367 {
3368 CPUState *env = opaque;
3369 uint16_t fptag, fpus, fpuc, fpregs_format;
3370 uint32_t hflags;
3371 int i;
3372
3373 for(i = 0; i < CPU_NB_REGS; i++)
3374 qemu_put_betls(f, &env->regs[i]);
3375 qemu_put_betls(f, &env->eip);
3376 qemu_put_betls(f, &env->eflags);
3377 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3378 qemu_put_be32s(f, &hflags);
3379
3380 /* FPU */
3381 fpuc = env->fpuc;
3382 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3383 fptag = 0;
3384 for(i = 0; i < 8; i++) {
3385 fptag |= ((!env->fptags[i]) << i);
3386 }
3387
3388 qemu_put_be16s(f, &fpuc);
3389 qemu_put_be16s(f, &fpus);
3390 qemu_put_be16s(f, &fptag);
3391
3392 #ifdef USE_X86LDOUBLE
3393 fpregs_format = 0;
3394 #else
3395 fpregs_format = 1;
3396 #endif
3397 qemu_put_be16s(f, &fpregs_format);
3398
3399 for(i = 0; i < 8; i++) {
3400 #ifdef USE_X86LDOUBLE
3401 {
3402 uint64_t mant;
3403 uint16_t exp;
3404 /* we save the real CPU data (in case of MMX usage only 'mant'
3405 contains the MMX register */
3406 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3407 qemu_put_be64(f, mant);
3408 qemu_put_be16(f, exp);
3409 }
3410 #else
3411 /* if we use doubles for float emulation, we save the doubles to
3412 avoid losing information in case of MMX usage. It can give
3413 problems if the image is restored on a CPU where long
3414 doubles are used instead. */
3415 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3416 #endif
3417 }
3418
3419 for(i = 0; i < 6; i++)
3420 cpu_put_seg(f, &env->segs[i]);
3421 cpu_put_seg(f, &env->ldt);
3422 cpu_put_seg(f, &env->tr);
3423 cpu_put_seg(f, &env->gdt);
3424 cpu_put_seg(f, &env->idt);
3425
3426 qemu_put_be32s(f, &env->sysenter_cs);
3427 qemu_put_be32s(f, &env->sysenter_esp);
3428 qemu_put_be32s(f, &env->sysenter_eip);
3429
3430 qemu_put_betls(f, &env->cr[0]);
3431 qemu_put_betls(f, &env->cr[2]);
3432 qemu_put_betls(f, &env->cr[3]);
3433 qemu_put_betls(f, &env->cr[4]);
3434
3435 for(i = 0; i < 8; i++)
3436 qemu_put_betls(f, &env->dr[i]);
3437
3438 /* MMU */
3439 qemu_put_be32s(f, &env->a20_mask);
3440
3441 /* XMM */
3442 qemu_put_be32s(f, &env->mxcsr);
3443 for(i = 0; i < CPU_NB_REGS; i++) {
3444 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3445 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3446 }
3447
3448 #ifdef TARGET_X86_64
3449 qemu_put_be64s(f, &env->efer);
3450 qemu_put_be64s(f, &env->star);
3451 qemu_put_be64s(f, &env->lstar);
3452 qemu_put_be64s(f, &env->cstar);
3453 qemu_put_be64s(f, &env->fmask);
3454 qemu_put_be64s(f, &env->kernelgsbase);
3455 #endif
3456 }
3457
3458 #ifdef USE_X86LDOUBLE
3459 /* XXX: add that in a FPU generic layer */
3460 union x86_longdouble {
3461 uint64_t mant;
3462 uint16_t exp;
3463 };
3464
3465 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3466 #define EXPBIAS1 1023
3467 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3468 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3469
3470 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3471 {
3472 int e;
3473 /* mantissa */
3474 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3475 /* exponent + sign */
3476 e = EXPD1(temp) - EXPBIAS1 + 16383;
3477 e |= SIGND1(temp) >> 16;
3478 p->exp = e;
3479 }
3480 #endif
3481
3482 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3483 {
3484 CPUState *env = opaque;
3485 int i, guess_mmx;
3486 uint32_t hflags;
3487 uint16_t fpus, fpuc, fptag, fpregs_format;
3488
3489 if (version_id != 3)
3490 return -EINVAL;
3491 for(i = 0; i < CPU_NB_REGS; i++)
3492 qemu_get_betls(f, &env->regs[i]);
3493 qemu_get_betls(f, &env->eip);
3494 qemu_get_betls(f, &env->eflags);
3495 qemu_get_be32s(f, &hflags);
3496
3497 qemu_get_be16s(f, &fpuc);
3498 qemu_get_be16s(f, &fpus);
3499 qemu_get_be16s(f, &fptag);
3500 qemu_get_be16s(f, &fpregs_format);
3501
3502 /* NOTE: we cannot always restore the FPU state if the image come
3503 from a host with a different 'USE_X86LDOUBLE' define. We guess
3504 if we are in an MMX state to restore correctly in that case. */
3505 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3506 for(i = 0; i < 8; i++) {
3507 uint64_t mant;
3508 uint16_t exp;
3509
3510 switch(fpregs_format) {
3511 case 0:
3512 mant = qemu_get_be64(f);
3513 exp = qemu_get_be16(f);
3514 #ifdef USE_X86LDOUBLE
3515 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3516 #else
3517 /* difficult case */
3518 if (guess_mmx)
3519 env->fpregs[i].mmx.MMX_Q(0) = mant;
3520 else
3521 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3522 #endif
3523 break;
3524 case 1:
3525 mant = qemu_get_be64(f);
3526 #ifdef USE_X86LDOUBLE
3527 {
3528 union x86_longdouble *p;
3529 /* difficult case */
3530 p = (void *)&env->fpregs[i];
3531 if (guess_mmx) {
3532 p->mant = mant;
3533 p->exp = 0xffff;
3534 } else {
3535 fp64_to_fp80(p, mant);
3536 }
3537 }
3538 #else
3539 env->fpregs[i].mmx.MMX_Q(0) = mant;
3540 #endif
3541 break;
3542 default:
3543 return -EINVAL;
3544 }
3545 }
3546
3547 env->fpuc = fpuc;
3548 /* XXX: restore FPU round state */
3549 env->fpstt = (fpus >> 11) & 7;
3550 env->fpus = fpus & ~0x3800;
3551 fptag ^= 0xff;
3552 for(i = 0; i < 8; i++) {
3553 env->fptags[i] = (fptag >> i) & 1;
3554 }
3555
3556 for(i = 0; i < 6; i++)
3557 cpu_get_seg(f, &env->segs[i]);
3558 cpu_get_seg(f, &env->ldt);
3559 cpu_get_seg(f, &env->tr);
3560 cpu_get_seg(f, &env->gdt);
3561 cpu_get_seg(f, &env->idt);
3562
3563 qemu_get_be32s(f, &env->sysenter_cs);
3564 qemu_get_be32s(f, &env->sysenter_esp);
3565 qemu_get_be32s(f, &env->sysenter_eip);
3566
3567 qemu_get_betls(f, &env->cr[0]);
3568 qemu_get_betls(f, &env->cr[2]);
3569 qemu_get_betls(f, &env->cr[3]);
3570 qemu_get_betls(f, &env->cr[4]);
3571
3572 for(i = 0; i < 8; i++)
3573 qemu_get_betls(f, &env->dr[i]);
3574
3575 /* MMU */
3576 qemu_get_be32s(f, &env->a20_mask);
3577
3578 qemu_get_be32s(f, &env->mxcsr);
3579 for(i = 0; i < CPU_NB_REGS; i++) {
3580 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3581 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3582 }
3583
3584 #ifdef TARGET_X86_64
3585 qemu_get_be64s(f, &env->efer);
3586 qemu_get_be64s(f, &env->star);
3587 qemu_get_be64s(f, &env->lstar);
3588 qemu_get_be64s(f, &env->cstar);
3589 qemu_get_be64s(f, &env->fmask);
3590 qemu_get_be64s(f, &env->kernelgsbase);
3591 #endif
3592
3593 /* XXX: compute hflags from scratch, except for CPL and IIF */
3594 env->hflags = hflags;
3595 tlb_flush(env, 1);
3596 return 0;
3597 }
3598
3599 #elif defined(TARGET_PPC)
3600 void cpu_save(QEMUFile *f, void *opaque)
3601 {
3602 }
3603
3604 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3605 {
3606 return 0;
3607 }
3608
3609 #elif defined(TARGET_MIPS)
3610 void cpu_save(QEMUFile *f, void *opaque)
3611 {
3612 }
3613
3614 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3615 {
3616 return 0;
3617 }
3618
3619 #elif defined(TARGET_SPARC)
3620 void cpu_save(QEMUFile *f, void *opaque)
3621 {
3622 CPUState *env = opaque;
3623 int i;
3624 uint32_t tmp;
3625
3626 for(i = 0; i < 8; i++)
3627 qemu_put_betls(f, &env->gregs[i]);
3628 for(i = 0; i < NWINDOWS * 16; i++)
3629 qemu_put_betls(f, &env->regbase[i]);
3630
3631 /* FPU */
3632 for(i = 0; i < TARGET_FPREGS; i++) {
3633 union {
3634 TARGET_FPREG_T f;
3635 target_ulong i;
3636 } u;
3637 u.f = env->fpr[i];
3638 qemu_put_betl(f, u.i);
3639 }
3640
3641 qemu_put_betls(f, &env->pc);
3642 qemu_put_betls(f, &env->npc);
3643 qemu_put_betls(f, &env->y);
3644 tmp = GET_PSR(env);
3645 qemu_put_be32(f, tmp);
3646 qemu_put_betls(f, &env->fsr);
3647 qemu_put_betls(f, &env->tbr);
3648 #ifndef TARGET_SPARC64
3649 qemu_put_be32s(f, &env->wim);
3650 /* MMU */
3651 for(i = 0; i < 16; i++)
3652 qemu_put_be32s(f, &env->mmuregs[i]);
3653 #endif
3654 }
3655
3656 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3657 {
3658 CPUState *env = opaque;
3659 int i;
3660 uint32_t tmp;
3661
3662 for(i = 0; i < 8; i++)
3663 qemu_get_betls(f, &env->gregs[i]);
3664 for(i = 0; i < NWINDOWS * 16; i++)
3665 qemu_get_betls(f, &env->regbase[i]);
3666
3667 /* FPU */
3668 for(i = 0; i < TARGET_FPREGS; i++) {
3669 union {
3670 TARGET_FPREG_T f;
3671 target_ulong i;
3672 } u;
3673 u.i = qemu_get_betl(f);
3674 env->fpr[i] = u.f;
3675 }
3676
3677 qemu_get_betls(f, &env->pc);
3678 qemu_get_betls(f, &env->npc);
3679 qemu_get_betls(f, &env->y);
3680 tmp = qemu_get_be32(f);
3681 env->cwp = 0; /* needed to ensure that the wrapping registers are
3682 correctly updated */
3683 PUT_PSR(env, tmp);
3684 qemu_get_betls(f, &env->fsr);
3685 qemu_get_betls(f, &env->tbr);
3686 #ifndef TARGET_SPARC64
3687 qemu_get_be32s(f, &env->wim);
3688 /* MMU */
3689 for(i = 0; i < 16; i++)
3690 qemu_get_be32s(f, &env->mmuregs[i]);
3691 #endif
3692 tlb_flush(env, 1);
3693 return 0;
3694 }
3695
3696 #elif defined(TARGET_ARM)
3697
3698 /* ??? Need to implement these. */
3699 void cpu_save(QEMUFile *f, void *opaque)
3700 {
3701 }
3702
3703 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3704 {
3705 return 0;
3706 }
3707
3708 #else
3709
3710 #warning No CPU save/restore functions
3711
3712 #endif
3713
3714 /***********************************************************/
3715 /* ram save/restore */
3716
3717 /* we just avoid storing empty pages */
3718 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3719 {
3720 int i, v;
3721
3722 v = buf[0];
3723 for(i = 1; i < len; i++) {
3724 if (buf[i] != v)
3725 goto normal_save;
3726 }
3727 qemu_put_byte(f, 1);
3728 qemu_put_byte(f, v);
3729 return;
3730 normal_save:
3731 qemu_put_byte(f, 0);
3732 qemu_put_buffer(f, buf, len);
3733 }
3734
3735 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3736 {
3737 int v;
3738
3739 v = qemu_get_byte(f);
3740 switch(v) {
3741 case 0:
3742 if (qemu_get_buffer(f, buf, len) != len)
3743 return -EIO;
3744 break;
3745 case 1:
3746 v = qemu_get_byte(f);
3747 memset(buf, v, len);
3748 break;
3749 default:
3750 return -EINVAL;
3751 }
3752 return 0;
3753 }
3754
3755 static void ram_save(QEMUFile *f, void *opaque)
3756 {
3757 int i;
3758 qemu_put_be32(f, phys_ram_size);
3759 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3760 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3761 }
3762 }
3763
3764 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3765 {
3766 int i, ret;
3767
3768 if (version_id != 1)
3769 return -EINVAL;
3770 if (qemu_get_be32(f) != phys_ram_size)
3771 return -EINVAL;
3772 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3773 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3774 if (ret)
3775 return ret;
3776 }
3777 return 0;
3778 }
3779
3780 /***********************************************************/
3781 /* machine registration */
3782
3783 QEMUMachine *first_machine = NULL;
3784
3785 int qemu_register_machine(QEMUMachine *m)
3786 {
3787 QEMUMachine **pm;
3788 pm = &first_machine;
3789 while (*pm != NULL)
3790 pm = &(*pm)->next;
3791 m->next = NULL;
3792 *pm = m;
3793 return 0;
3794 }
3795
3796 QEMUMachine *find_machine(const char *name)
3797 {
3798 QEMUMachine *m;
3799
3800 for(m = first_machine; m != NULL; m = m->next) {
3801 if (!strcmp(m->name, name))
3802 return m;
3803 }
3804 return NULL;
3805 }
3806
3807 /***********************************************************/
3808 /* main execution loop */
3809
3810 void gui_update(void *opaque)
3811 {
3812 display_state.dpy_refresh(&display_state);
3813 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3814 }
3815
3816 struct vm_change_state_entry {
3817 VMChangeStateHandler *cb;
3818 void *opaque;
3819 LIST_ENTRY (vm_change_state_entry) entries;
3820 };
3821
3822 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3823
3824 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3825 void *opaque)
3826 {
3827 VMChangeStateEntry *e;
3828
3829 e = qemu_mallocz(sizeof (*e));
3830 if (!e)
3831 return NULL;
3832
3833 e->cb = cb;
3834 e->opaque = opaque;
3835 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3836 return e;
3837 }
3838
3839 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3840 {
3841 LIST_REMOVE (e, entries);
3842 qemu_free (e);
3843 }
3844
3845 static void vm_state_notify(int running)
3846 {
3847 VMChangeStateEntry *e;
3848
3849 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3850 e->cb(e->opaque, running);
3851 }
3852 }
3853
3854 /* XXX: support several handlers */
3855 static VMStopHandler *vm_stop_cb;
3856 static void *vm_stop_opaque;
3857
3858 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3859 {
3860 vm_stop_cb = cb;
3861 vm_stop_opaque = opaque;
3862 return 0;
3863 }
3864
3865 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3866 {
3867 vm_stop_cb = NULL;
3868 }
3869
3870 void vm_start(void)
3871 {
3872 if (!vm_running) {
3873 cpu_enable_ticks();
3874 vm_running = 1;
3875 vm_state_notify(1);
3876 }
3877 }
3878
3879 void vm_stop(int reason)
3880 {
3881 if (vm_running) {
3882 cpu_disable_ticks();
3883 vm_running = 0;
3884 if (reason != 0) {
3885 if (vm_stop_cb) {
3886 vm_stop_cb(vm_stop_opaque, reason);
3887 }
3888 }
3889 vm_state_notify(0);
3890 }
3891 }
3892
3893 /* reset/shutdown handler */
3894
3895 typedef struct QEMUResetEntry {
3896 QEMUResetHandler *func;
3897 void *opaque;
3898 struct QEMUResetEntry *next;
3899 } QEMUResetEntry;
3900
3901 static QEMUResetEntry *first_reset_entry;
3902 static int reset_requested;
3903 static int shutdown_requested;
3904 static int powerdown_requested;
3905
3906 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3907 {
3908 QEMUResetEntry **pre, *re;
3909
3910 pre = &first_reset_entry;
3911 while (*pre != NULL)
3912 pre = &(*pre)->next;
3913 re = qemu_mallocz(sizeof(QEMUResetEntry));
3914 re->func = func;
3915 re->opaque = opaque;
3916 re->next = NULL;
3917 *pre = re;
3918 }
3919
3920 void qemu_system_reset(void)
3921 {
3922 QEMUResetEntry *re;
3923
3924 /* reset all devices */
3925 for(re = first_reset_entry; re != NULL; re = re->next) {
3926 re->func(re->opaque);
3927 }
3928 }
3929
3930 void qemu_system_reset_request(void)
3931 {
3932 reset_requested = 1;
3933 if (cpu_single_env)
3934 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3935 }
3936
3937 void qemu_system_shutdown_request(void)
3938 {
3939 shutdown_requested = 1;
3940 if (cpu_single_env)
3941 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3942 }
3943
3944 void qemu_system_powerdown_request(void)
3945 {
3946 powerdown_requested = 1;
3947 if (cpu_single_env)
3948 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3949 }
3950
3951 void main_loop_wait(int timeout)
3952 {
3953 IOHandlerRecord *ioh, *ioh_next;
3954 fd_set rfds, wfds;
3955 int ret, nfds;
3956 struct timeval tv;
3957
3958 #ifdef _WIN32
3959 /* XXX: see how to merge it with the select. The constraint is
3960 that the select must be interrupted by the timer */
3961 if (timeout > 0)
3962 Sleep(timeout);
3963 #endif
3964 /* poll any events */
3965 /* XXX: separate device handlers from system ones */
3966 nfds = -1;
3967 FD_ZERO(&rfds);
3968 FD_ZERO(&wfds);
3969 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3970 if (ioh->fd_read &&
3971 (!ioh->fd_read_poll ||
3972 ioh->fd_read_poll(ioh->opaque) != 0)) {
3973 FD_SET(ioh->fd, &rfds);
3974 if (ioh->fd > nfds)
3975 nfds = ioh->fd;
3976 }
3977 if (ioh->fd_write) {
3978 FD_SET(ioh->fd, &wfds);
3979 if (ioh->fd > nfds)
3980 nfds = ioh->fd;
3981 }
3982 }
3983
3984 tv.tv_sec = 0;
3985 #ifdef _WIN32
3986 tv.tv_usec = 0;
3987 #else
3988 tv.tv_usec = timeout * 1000;
3989 #endif
3990 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
3991 if (ret > 0) {
3992 /* XXX: better handling of removal */
3993 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3994 ioh_next = ioh->next;
3995 if (FD_ISSET(ioh->fd, &rfds)) {
3996 ioh->fd_read(ioh->opaque);
3997 }
3998 if (FD_ISSET(ioh->fd, &wfds)) {
3999 ioh->fd_write(ioh->opaque);
4000 }
4001 }
4002 }
4003 #ifdef _WIN32
4004 tap_win32_poll();
4005 #endif
4006
4007 #if defined(CONFIG_SLIRP)
4008 /* XXX: merge with the previous select() */
4009 if (slirp_inited) {
4010 fd_set rfds, wfds, xfds;
4011 int nfds;
4012 struct timeval tv;
4013
4014 nfds = -1;
4015 FD_ZERO(&rfds);
4016 FD_ZERO(&wfds);
4017 FD_ZERO(&xfds);
4018 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4019 tv.tv_sec = 0;
4020 tv.tv_usec = 0;
4021 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4022 if (ret >= 0) {
4023 slirp_select_poll(&rfds, &wfds, &xfds);
4024 }
4025 }
4026 #endif
4027
4028 if (vm_running) {
4029 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4030 qemu_get_clock(vm_clock));
4031 /* run dma transfers, if any */
4032 DMA_run();
4033 }
4034
4035 /* real time timers */
4036 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4037 qemu_get_clock(rt_clock));
4038 }
4039
4040 static CPUState *cur_cpu;
4041
4042 int main_loop(void)
4043 {
4044 int ret, timeout;
4045 #ifdef CONFIG_PROFILER
4046 int64_t ti;
4047 #endif
4048 CPUState *env;
4049
4050 cur_cpu = first_cpu;
4051 for(;;) {
4052 if (vm_running) {
4053
4054 env = cur_cpu;
4055 for(;;) {
4056 /* get next cpu */
4057 env = env->next_cpu;
4058 if (!env)
4059 env = first_cpu;
4060 #ifdef CONFIG_PROFILER
4061 ti = profile_getclock();
4062 #endif
4063 ret = cpu_exec(env);
4064 #ifdef CONFIG_PROFILER
4065 qemu_time += profile_getclock() - ti;
4066 #endif
4067 if (ret != EXCP_HALTED)
4068 break;
4069 /* all CPUs are halted ? */
4070 if (env == cur_cpu) {
4071 ret = EXCP_HLT;
4072 break;
4073 }
4074 }
4075 cur_cpu = env;
4076
4077 if (shutdown_requested) {
4078 ret = EXCP_INTERRUPT;
4079 break;
4080 }
4081 if (reset_requested) {
4082 reset_requested = 0;
4083 qemu_system_reset();
4084 ret = EXCP_INTERRUPT;
4085 }
4086 if (powerdown_requested) {
4087 powerdown_requested = 0;
4088 qemu_system_powerdown();
4089 ret = EXCP_INTERRUPT;
4090 }
4091 if (ret == EXCP_DEBUG) {
4092 vm_stop(EXCP_DEBUG);
4093 }
4094 /* if hlt instruction, we wait until the next IRQ */
4095 /* XXX: use timeout computed from timers */
4096 if (ret == EXCP_HLT)
4097 timeout = 10;
4098 else
4099 timeout = 0;
4100 } else {
4101 timeout = 10;
4102 }
4103 #ifdef CONFIG_PROFILER
4104 ti = profile_getclock();
4105 #endif
4106 main_loop_wait(timeout);
4107 #ifdef CONFIG_PROFILER
4108 dev_time += profile_getclock() - ti;
4109 #endif
4110 }
4111 cpu_disable_ticks();
4112 return ret;
4113 }
4114
4115 void help(void)
4116 {
4117 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4118 "usage: %s [options] [disk_image]\n"
4119 "\n"
4120 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4121 "\n"
4122 "Standard options:\n"
4123 "-M machine select emulated machine (-M ? for list)\n"
4124 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4125 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4126 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4127 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4128 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4129 "-snapshot write to temporary files instead of disk image files\n"
4130 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4131 "-smp n set the number of CPUs to 'n' [default=1]\n"
4132 "-nographic disable graphical output and redirect serial I/Os to console\n"
4133 #ifndef _WIN32
4134 "-k language use keyboard layout (for example \"fr\" for French)\n"
4135 #endif
4136 #ifdef HAS_AUDIO
4137 "-audio-help print list of audio drivers and their options\n"
4138 "-soundhw c1,... enable audio support\n"
4139 " and only specified sound cards (comma separated list)\n"
4140 " use -soundhw ? to get the list of supported cards\n"
4141 " use -soundhw all to enable all of them\n"
4142 #endif
4143 "-localtime set the real time clock to local time [default=utc]\n"
4144 "-full-screen start in full screen\n"
4145 #ifdef TARGET_I386
4146 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4147 #endif
4148 "-usb enable the USB driver (will be the default soon)\n"
4149 "-usbdevice name add the host or guest USB device 'name'\n"
4150 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4151 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4152 #endif
4153 "\n"
4154 "Network options:\n"
4155 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4156 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4157 #ifdef CONFIG_SLIRP
4158 "-net user[,vlan=n]\n"
4159 " connect the user mode network stack to VLAN 'n'\n"
4160 #endif
4161 #ifdef _WIN32
4162 "-net tap[,vlan=n],ifname=name\n"
4163 " connect the host TAP network interface to VLAN 'n'\n"
4164 #else
4165 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4166 " connect the host TAP network interface to VLAN 'n' and use\n"
4167 " the network script 'file' (default=%s);\n"
4168 " use 'fd=h' to connect to an already opened TAP interface\n"
4169 #endif
4170 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4171 " connect the vlan 'n' to another VLAN using a socket connection\n"
4172 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4173 " connect the vlan 'n' to multicast maddr and port\n"
4174 "-net none use it alone to have zero network devices; if no -net option\n"
4175 " is provided, the default is '-net nic -net user'\n"
4176 "\n"
4177 #ifdef CONFIG_SLIRP
4178 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4179 #ifndef _WIN32
4180 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4181 #endif
4182 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4183 " redirect TCP or UDP connections from host to guest [-net user]\n"
4184 #endif
4185 "\n"
4186 "Linux boot specific:\n"
4187 "-kernel bzImage use 'bzImage' as kernel image\n"
4188 "-append cmdline use 'cmdline' as kernel command line\n"
4189 "-initrd file use 'file' as initial ram disk\n"
4190 "\n"
4191 "Debug/Expert options:\n"
4192 "-monitor dev redirect the monitor to char device 'dev'\n"
4193 "-serial dev redirect the serial port to char device 'dev'\n"
4194 "-parallel dev redirect the parallel port to char device 'dev'\n"
4195 "-pidfile file Write PID to 'file'\n"
4196 "-S freeze CPU at startup (use 'c' to start execution)\n"
4197 "-s wait gdb connection to port %d\n"
4198 "-p port change gdb connection port\n"
4199 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4200 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4201 " translation (t=none or lba) (usually qemu can guess them)\n"
4202 "-L path set the directory for the BIOS and VGA BIOS\n"
4203 #ifdef USE_KQEMU
4204 "-no-kqemu disable KQEMU kernel module usage\n"
4205 #endif
4206 #ifdef USE_CODE_COPY
4207 "-no-code-copy disable code copy acceleration\n"
4208 #endif
4209 #ifdef TARGET_I386
4210 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4211 " (default is CL-GD5446 PCI VGA)\n"
4212 #endif
4213 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4214 "\n"
4215 "During emulation, the following keys are useful:\n"
4216 "ctrl-alt-f toggle full screen\n"
4217 "ctrl-alt-n switch to virtual console 'n'\n"
4218 "ctrl-alt toggle mouse and keyboard grab\n"
4219 "\n"
4220 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4221 ,
4222 #ifdef CONFIG_SOFTMMU
4223 "qemu",
4224 #else
4225 "qemu-fast",
4226 #endif
4227 DEFAULT_RAM_SIZE,
4228 #ifndef _WIN32
4229 DEFAULT_NETWORK_SCRIPT,
4230 #endif
4231 DEFAULT_GDBSTUB_PORT,
4232 "/tmp/qemu.log");
4233 #ifndef CONFIG_SOFTMMU
4234 printf("\n"
4235 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4236 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4237 "PC emulation.\n");
4238 #endif
4239 exit(1);
4240 }
4241
4242 #define HAS_ARG 0x0001
4243
4244 enum {
4245 QEMU_OPTION_h,
4246
4247 QEMU_OPTION_M,
4248 QEMU_OPTION_fda,
4249 QEMU_OPTION_fdb,
4250 QEMU_OPTION_hda,
4251 QEMU_OPTION_hdb,
4252 QEMU_OPTION_hdc,
4253 QEMU_OPTION_hdd,
4254 QEMU_OPTION_cdrom,
4255 QEMU_OPTION_boot,
4256 QEMU_OPTION_snapshot,
4257 QEMU_OPTION_m,
4258 QEMU_OPTION_nographic,
4259 #ifdef HAS_AUDIO
4260 QEMU_OPTION_audio_help,
4261 QEMU_OPTION_soundhw,
4262 #endif
4263
4264 QEMU_OPTION_net,
4265 QEMU_OPTION_tftp,
4266 QEMU_OPTION_smb,
4267 QEMU_OPTION_redir,
4268
4269 QEMU_OPTION_kernel,
4270 QEMU_OPTION_append,
4271 QEMU_OPTION_initrd,
4272
4273 QEMU_OPTION_S,
4274 QEMU_OPTION_s,
4275 QEMU_OPTION_p,
4276 QEMU_OPTION_d,
4277 QEMU_OPTION_hdachs,
4278 QEMU_OPTION_L,
4279 QEMU_OPTION_no_code_copy,
4280 QEMU_OPTION_k,
4281 QEMU_OPTION_localtime,
4282 QEMU_OPTION_cirrusvga,
4283 QEMU_OPTION_g,
4284 QEMU_OPTION_std_vga,
4285 QEMU_OPTION_monitor,
4286 QEMU_OPTION_serial,
4287 QEMU_OPTION_parallel,
4288 QEMU_OPTION_loadvm,
4289 QEMU_OPTION_full_screen,
4290 QEMU_OPTION_pidfile,
4291 QEMU_OPTION_no_kqemu,
4292 QEMU_OPTION_kernel_kqemu,
4293 QEMU_OPTION_win2k_hack,
4294 QEMU_OPTION_usb,
4295 QEMU_OPTION_usbdevice,
4296 QEMU_OPTION_smp,
4297 };
4298
4299 typedef struct QEMUOption {
4300 const char *name;
4301 int flags;
4302 int index;
4303 } QEMUOption;
4304
4305 const QEMUOption qemu_options[] = {
4306 { "h", 0, QEMU_OPTION_h },
4307
4308 { "M", HAS_ARG, QEMU_OPTION_M },
4309 { "fda", HAS_ARG, QEMU_OPTION_fda },
4310 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4311 { "hda", HAS_ARG, QEMU_OPTION_hda },
4312 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4313 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4314 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4315 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4316 { "boot", HAS_ARG, QEMU_OPTION_boot },
4317 { "snapshot", 0, QEMU_OPTION_snapshot },
4318 { "m", HAS_ARG, QEMU_OPTION_m },
4319 { "nographic", 0, QEMU_OPTION_nographic },
4320 { "k", HAS_ARG, QEMU_OPTION_k },
4321 #ifdef HAS_AUDIO
4322 { "audio-help", 0, QEMU_OPTION_audio_help },
4323 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4324 #endif
4325
4326 { "net", HAS_ARG, QEMU_OPTION_net},
4327 #ifdef CONFIG_SLIRP
4328 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4329 #ifndef _WIN32
4330 { "smb", HAS_ARG, QEMU_OPTION_smb },
4331 #endif
4332 { "redir", HAS_ARG, QEMU_OPTION_redir },
4333 #endif
4334
4335 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4336 { "append", HAS_ARG, QEMU_OPTION_append },
4337 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4338
4339 { "S", 0, QEMU_OPTION_S },
4340 { "s", 0, QEMU_OPTION_s },
4341 { "p", HAS_ARG, QEMU_OPTION_p },
4342 { "d", HAS_ARG, QEMU_OPTION_d },
4343 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4344 { "L", HAS_ARG, QEMU_OPTION_L },
4345 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4346 #ifdef USE_KQEMU
4347 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4348 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4349 #endif
4350 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4351 { "g", 1, QEMU_OPTION_g },
4352 #endif
4353 { "localtime", 0, QEMU_OPTION_localtime },
4354 { "std-vga", 0, QEMU_OPTION_std_vga },
4355 { "monitor", 1, QEMU_OPTION_monitor },
4356 { "serial", 1, QEMU_OPTION_serial },
4357 { "parallel", 1, QEMU_OPTION_parallel },
4358 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4359 { "full-screen", 0, QEMU_OPTION_full_screen },
4360 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4361 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4362 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4363 { "smp", HAS_ARG, QEMU_OPTION_smp },
4364
4365 /* temporary options */
4366 { "usb", 0, QEMU_OPTION_usb },
4367 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4368 { NULL },
4369 };
4370
4371 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4372
4373 /* this stack is only used during signal handling */
4374 #define SIGNAL_STACK_SIZE 32768
4375
4376 static uint8_t *signal_stack;
4377
4378 #endif
4379
4380 /* password input */
4381
4382 static BlockDriverState *get_bdrv(int index)
4383 {
4384 BlockDriverState *bs;
4385
4386 if (index < 4) {
4387 bs = bs_table[index];
4388 } else if (index < 6) {
4389 bs = fd_table[index - 4];
4390 } else {
4391 bs = NULL;
4392 }
4393 return bs;
4394 }
4395
4396 static void read_passwords(void)
4397 {
4398 BlockDriverState *bs;
4399 int i, j;
4400 char password[256];
4401
4402 for(i = 0; i < 6; i++) {
4403 bs = get_bdrv(i);
4404 if (bs && bdrv_is_encrypted(bs)) {
4405 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4406 for(j = 0; j < 3; j++) {
4407 monitor_readline("Password: ",
4408 1, password, sizeof(password));
4409 if (bdrv_set_key(bs, password) == 0)
4410 break;
4411 term_printf("invalid password\n");
4412 }
4413 }
4414 }
4415 }
4416
4417 /* XXX: currently we cannot use simultaneously different CPUs */
4418 void register_machines(void)
4419 {
4420 #if defined(TARGET_I386)
4421 qemu_register_machine(&pc_machine);
4422 qemu_register_machine(&isapc_machine);
4423 #elif defined(TARGET_PPC)
4424 qemu_register_machine(&heathrow_machine);
4425 qemu_register_machine(&core99_machine);
4426 qemu_register_machine(&prep_machine);
4427 #elif defined(TARGET_MIPS)
4428 qemu_register_machine(&mips_machine);
4429 #elif defined(TARGET_SPARC)
4430 #ifdef TARGET_SPARC64
4431 qemu_register_machine(&sun4u_machine);
4432 #else
4433 qemu_register_machine(&sun4m_machine);
4434 #endif
4435 #elif defined(TARGET_ARM)
4436 qemu_register_machine(&integratorcp_machine);
4437 #else
4438 #error unsupported CPU
4439 #endif
4440 }
4441
4442 #ifdef HAS_AUDIO
4443 struct soundhw soundhw[] = {
4444 {
4445 "sb16",
4446 "Creative Sound Blaster 16",
4447 0,
4448 1,
4449 { .init_isa = SB16_init }
4450 },
4451
4452 #ifdef CONFIG_ADLIB
4453 {
4454 "adlib",
4455 #ifdef HAS_YMF262
4456 "Yamaha YMF262 (OPL3)",
4457 #else
4458 "Yamaha YM3812 (OPL2)",
4459 #endif
4460 0,
4461 1,
4462 { .init_isa = Adlib_init }
4463 },
4464 #endif
4465
4466 #ifdef CONFIG_GUS
4467 {
4468 "gus",
4469 "Gravis Ultrasound GF1",
4470 0,
4471 1,
4472 { .init_isa = GUS_init }
4473 },
4474 #endif
4475
4476 {
4477 "es1370",
4478 "ENSONIQ AudioPCI ES1370",
4479 0,
4480 0,
4481 { .init_pci = es1370_init }
4482 },
4483
4484 { NULL, NULL, 0, 0, { NULL } }
4485 };
4486
4487 static void select_soundhw (const char *optarg)
4488 {
4489 struct soundhw *c;
4490
4491 if (*optarg == '?') {
4492 show_valid_cards:
4493
4494 printf ("Valid sound card names (comma separated):\n");
4495 for (c = soundhw; c->name; ++c) {
4496 printf ("%-11s %s\n", c->name, c->descr);
4497 }
4498 printf ("\n-soundhw all will enable all of the above\n");
4499 exit (*optarg != '?');
4500 }
4501 else {
4502 size_t l;
4503 const char *p;
4504 char *e;
4505 int bad_card = 0;
4506
4507 if (!strcmp (optarg, "all")) {
4508 for (c = soundhw; c->name; ++c) {
4509 c->enabled = 1;
4510 }
4511 return;
4512 }
4513
4514 p = optarg;
4515 while (*p) {
4516 e = strchr (p, ',');
4517 l = !e ? strlen (p) : (size_t) (e - p);
4518
4519 for (c = soundhw; c->name; ++c) {
4520 if (!strncmp (c->name, p, l)) {
4521 c->enabled = 1;
4522 break;
4523 }
4524 }
4525
4526 if (!c->name) {
4527 if (l > 80) {
4528 fprintf (stderr,
4529 "Unknown sound card name (too big to show)\n");
4530 }
4531 else {
4532 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4533 (int) l, p);
4534 }
4535 bad_card = 1;
4536 }
4537 p += l + (e != NULL);
4538 }
4539
4540 if (bad_card)
4541 goto show_valid_cards;
4542 }
4543 }
4544 #endif
4545
4546 #define MAX_NET_CLIENTS 32
4547
4548 int main(int argc, char **argv)
4549 {
4550 #ifdef CONFIG_GDBSTUB
4551 int use_gdbstub, gdbstub_port;
4552 #endif
4553 int i, cdrom_index;
4554 int snapshot, linux_boot;
4555 const char *initrd_filename;
4556 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4557 const char *kernel_filename, *kernel_cmdline;
4558 DisplayState *ds = &display_state;
4559 int cyls, heads, secs, translation;
4560 int start_emulation = 1;
4561 char net_clients[MAX_NET_CLIENTS][256];
4562 int nb_net_clients;
4563 int optind;
4564 const char *r, *optarg;
4565 CharDriverState *monitor_hd;
4566 char monitor_device[128];
4567 char serial_devices[MAX_SERIAL_PORTS][128];
4568 int serial_device_index;
4569 char parallel_devices[MAX_PARALLEL_PORTS][128];
4570 int parallel_device_index;
4571 const char *loadvm = NULL;
4572 QEMUMachine *machine;
4573 char usb_devices[MAX_VM_USB_PORTS][128];
4574 int usb_devices_index;
4575
4576 LIST_INIT (&vm_change_state_head);
4577 #if !defined(CONFIG_SOFTMMU)
4578 /* we never want that malloc() uses mmap() */
4579 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4580 #endif
4581 register_machines();
4582 machine = first_machine;
4583 initrd_filename = NULL;
4584 for(i = 0; i < MAX_FD; i++)
4585 fd_filename[i] = NULL;
4586 for(i = 0; i < MAX_DISKS; i++)
4587 hd_filename[i] = NULL;
4588 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4589 vga_ram_size = VGA_RAM_SIZE;
4590 bios_size = BIOS_SIZE;
4591 #ifdef CONFIG_GDBSTUB
4592 use_gdbstub = 0;
4593 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4594 #endif
4595 snapshot = 0;
4596 nographic = 0;
4597 kernel_filename = NULL;
4598 kernel_cmdline = "";
4599 #ifdef TARGET_PPC
4600 cdrom_index = 1;
4601 #else
4602 cdrom_index = 2;
4603 #endif
4604 cyls = heads = secs = 0;
4605 translation = BIOS_ATA_TRANSLATION_AUTO;
4606 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4607
4608 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4609 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4610 serial_devices[i][0] = '\0';
4611 serial_device_index = 0;
4612
4613 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4614 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4615 parallel_devices[i][0] = '\0';
4616 parallel_device_index = 0;
4617
4618 usb_devices_index = 0;
4619
4620 nb_net_clients = 0;
4621
4622 nb_nics = 0;
4623 /* default mac address of the first network interface */
4624
4625 optind = 1;
4626 for(;;) {
4627 if (optind >= argc)
4628 break;
4629 r = argv[optind];
4630 if (r[0] != '-') {
4631 hd_filename[0] = argv[optind++];
4632 } else {
4633 const QEMUOption *popt;
4634
4635 optind++;
4636 popt = qemu_options;
4637 for(;;) {
4638 if (!popt->name) {
4639 fprintf(stderr, "%s: invalid option -- '%s'\n",
4640 argv[0], r);
4641 exit(1);
4642 }
4643 if (!strcmp(popt->name, r + 1))
4644 break;
4645 popt++;
4646 }
4647 if (popt->flags & HAS_ARG) {
4648 if (optind >= argc) {
4649 fprintf(stderr, "%s: option '%s' requires an argument\n",
4650 argv[0], r);
4651 exit(1);
4652 }
4653 optarg = argv[optind++];
4654 } else {
4655 optarg = NULL;
4656 }
4657
4658 switch(popt->index) {
4659 case QEMU_OPTION_M:
4660 machine = find_machine(optarg);
4661 if (!machine) {
4662 QEMUMachine *m;
4663 printf("Supported machines are:\n");
4664 for(m = first_machine; m != NULL; m = m->next) {
4665 printf("%-10s %s%s\n",
4666 m->name, m->desc,
4667 m == first_machine ? " (default)" : "");
4668 }
4669 exit(1);
4670 }
4671 break;
4672 case QEMU_OPTION_initrd:
4673 initrd_filename = optarg;
4674 break;
4675 case QEMU_OPTION_hda:
4676 case QEMU_OPTION_hdb:
4677 case QEMU_OPTION_hdc:
4678 case QEMU_OPTION_hdd:
4679 {
4680 int hd_index;
4681 hd_index = popt->index - QEMU_OPTION_hda;
4682 hd_filename[hd_index] = optarg;
4683 if (hd_index == cdrom_index)
4684 cdrom_index = -1;
4685 }
4686 break;
4687 case QEMU_OPTION_snapshot:
4688 snapshot = 1;
4689 break;
4690 case QEMU_OPTION_hdachs:
4691 {
4692 const char *p;
4693 p = optarg;
4694 cyls = strtol(p, (char **)&p, 0);
4695 if (cyls < 1 || cyls > 16383)
4696 goto chs_fail;
4697 if (*p != ',')
4698 goto chs_fail;
4699 p++;
4700 heads = strtol(p, (char **)&p, 0);
4701 if (heads < 1 || heads > 16)
4702 goto chs_fail;
4703 if (*p != ',')
4704 goto chs_fail;
4705 p++;
4706 secs = strtol(p, (char **)&p, 0);
4707 if (secs < 1 || secs > 63)
4708 goto chs_fail;
4709 if (*p == ',') {
4710 p++;
4711 if (!strcmp(p, "none"))
4712 translation = BIOS_ATA_TRANSLATION_NONE;
4713 else if (!strcmp(p, "lba"))
4714 translation = BIOS_ATA_TRANSLATION_LBA;
4715 else if (!strcmp(p, "auto"))
4716 translation = BIOS_ATA_TRANSLATION_AUTO;
4717 else
4718 goto chs_fail;
4719 } else if (*p != '\0') {
4720 chs_fail:
4721 fprintf(stderr, "qemu: invalid physical CHS format\n");
4722 exit(1);
4723 }
4724 }
4725 break;
4726 case QEMU_OPTION_nographic:
4727 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4728 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4729 nographic = 1;
4730 break;
4731 case QEMU_OPTION_kernel:
4732 kernel_filename = optarg;
4733 break;
4734 case QEMU_OPTION_append:
4735 kernel_cmdline = optarg;
4736 break;
4737 case QEMU_OPTION_cdrom:
4738 if (cdrom_index >= 0) {
4739 hd_filename[cdrom_index] = optarg;
4740 }
4741 break;
4742 case QEMU_OPTION_boot:
4743 boot_device = optarg[0];
4744 if (boot_device != 'a' &&
4745 #ifdef TARGET_SPARC
4746 // Network boot
4747 boot_device != 'n' &&
4748 #endif
4749 boot_device != 'c' && boot_device != 'd') {
4750 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4751 exit(1);
4752 }
4753 break;
4754 case QEMU_OPTION_fda:
4755 fd_filename[0] = optarg;
4756 break;
4757 case QEMU_OPTION_fdb:
4758 fd_filename[1] = optarg;
4759 break;
4760 case QEMU_OPTION_no_code_copy:
4761 code_copy_enabled = 0;
4762 break;
4763 case QEMU_OPTION_net:
4764 if (nb_net_clients >= MAX_NET_CLIENTS) {
4765 fprintf(stderr, "qemu: too many network clients\n");
4766 exit(1);
4767 }
4768 pstrcpy(net_clients[nb_net_clients],
4769 sizeof(net_clients[0]),
4770 optarg);
4771 nb_net_clients++;
4772 break;
4773 #ifdef CONFIG_SLIRP
4774 case QEMU_OPTION_tftp:
4775 tftp_prefix = optarg;
4776 break;
4777 #ifndef _WIN32
4778 case QEMU_OPTION_smb:
4779 net_slirp_smb(optarg);
4780 break;
4781 #endif
4782 case QEMU_OPTION_redir:
4783 net_slirp_redir(optarg);
4784 break;
4785 #endif
4786 #ifdef HAS_AUDIO
4787 case QEMU_OPTION_audio_help:
4788 AUD_help ();
4789 exit (0);
4790 break;
4791 case QEMU_OPTION_soundhw:
4792 select_soundhw (optarg);
4793 break;
4794 #endif
4795 case QEMU_OPTION_h:
4796 help();
4797 break;
4798 case QEMU_OPTION_m:
4799 ram_size = atoi(optarg) * 1024 * 1024;
4800 if (ram_size <= 0)
4801 help();
4802 if (ram_size > PHYS_RAM_MAX_SIZE) {
4803 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4804 PHYS_RAM_MAX_SIZE / (1024 * 1024));
4805 exit(1);
4806 }
4807 break;
4808 case QEMU_OPTION_d:
4809 {
4810 int mask;
4811 CPULogItem *item;
4812
4813 mask = cpu_str_to_log_mask(optarg);
4814 if (!mask) {
4815 printf("Log items (comma separated):\n");
4816 for(item = cpu_log_items; item->mask != 0; item++) {
4817 printf("%-10s %s\n", item->name, item->help);
4818 }
4819 exit(1);
4820 }
4821 cpu_set_log(mask);
4822 }
4823 break;
4824 #ifdef CONFIG_GDBSTUB
4825 case QEMU_OPTION_s:
4826 use_gdbstub = 1;
4827 break;
4828 case QEMU_OPTION_p:
4829 gdbstub_port = atoi(optarg);
4830 break;
4831 #endif
4832 case QEMU_OPTION_L:
4833 bios_dir = optarg;
4834 break;
4835 case QEMU_OPTION_S:
4836 start_emulation = 0;
4837 break;
4838 case QEMU_OPTION_k:
4839 keyboard_layout = optarg;
4840 break;
4841 case QEMU_OPTION_localtime:
4842 rtc_utc = 0;
4843 break;
4844 case QEMU_OPTION_cirrusvga:
4845 cirrus_vga_enabled = 1;
4846 break;
4847 case QEMU_OPTION_std_vga:
4848 cirrus_vga_enabled = 0;
4849 break;
4850 case QEMU_OPTION_g:
4851 {
4852 const char *p;
4853 int w, h, depth;
4854 p = optarg;
4855 w = strtol(p, (char **)&p, 10);
4856 if (w <= 0) {
4857 graphic_error:
4858 fprintf(stderr, "qemu: invalid resolution or depth\n");
4859 exit(1);
4860 }
4861 if (*p != 'x')
4862 goto graphic_error;
4863 p++;
4864 h = strtol(p, (char **)&p, 10);
4865 if (h <= 0)
4866 goto graphic_error;
4867 if (*p == 'x') {
4868 p++;
4869 depth = strtol(p, (char **)&p, 10);
4870 if (depth != 8 && depth != 15 && depth != 16 &&
4871 depth != 24 && depth != 32)
4872 goto graphic_error;
4873 } else if (*p == '\0') {
4874 depth = graphic_depth;
4875 } else {
4876 goto graphic_error;
4877 }
4878
4879 graphic_width = w;
4880 graphic_height = h;
4881 graphic_depth = depth;
4882 }
4883 break;
4884 case QEMU_OPTION_monitor:
4885 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4886 break;
4887 case QEMU_OPTION_serial:
4888 if (serial_device_index >= MAX_SERIAL_PORTS) {
4889 fprintf(stderr, "qemu: too many serial ports\n");
4890 exit(1);
4891 }
4892 pstrcpy(serial_devices[serial_device_index],
4893 sizeof(serial_devices[0]), optarg);
4894 serial_device_index++;
4895 break;
4896 case QEMU_OPTION_parallel:
4897 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4898 fprintf(stderr, "qemu: too many parallel ports\n");
4899 exit(1);
4900 }
4901 pstrcpy(parallel_devices[parallel_device_index],
4902 sizeof(parallel_devices[0]), optarg);
4903 parallel_device_index++;
4904 break;
4905 case QEMU_OPTION_loadvm:
4906 loadvm = optarg;
4907 break;
4908 case QEMU_OPTION_full_screen:
4909 full_screen = 1;
4910 break;
4911 case QEMU_OPTION_pidfile:
4912 create_pidfile(optarg);
4913 break;
4914 #ifdef TARGET_I386
4915 case QEMU_OPTION_win2k_hack:
4916 win2k_install_hack = 1;
4917 break;
4918 #endif
4919 #ifdef USE_KQEMU
4920 case QEMU_OPTION_no_kqemu:
4921 kqemu_allowed = 0;
4922 break;
4923 case QEMU_OPTION_kernel_kqemu:
4924 kqemu_allowed = 2;
4925 break;
4926 #endif
4927 case QEMU_OPTION_usb:
4928 usb_enabled = 1;
4929 break;
4930 case QEMU_OPTION_usbdevice:
4931 usb_enabled = 1;
4932 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4933 fprintf(stderr, "Too many USB devices\n");
4934 exit(1);
4935 }
4936 pstrcpy(usb_devices[usb_devices_index],
4937 sizeof(usb_devices[usb_devices_index]),
4938 optarg);
4939 usb_devices_index++;
4940 break;
4941 case QEMU_OPTION_smp:
4942 smp_cpus = atoi(optarg);
4943 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
4944 fprintf(stderr, "Invalid number of CPUs\n");
4945 exit(1);
4946 }
4947 break;
4948 }
4949 }
4950 }
4951
4952 #ifdef USE_KQEMU
4953 if (smp_cpus > 1)
4954 kqemu_allowed = 0;
4955 #endif
4956 linux_boot = (kernel_filename != NULL);
4957
4958 if (!linux_boot &&
4959 hd_filename[0] == '\0' &&
4960 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4961 fd_filename[0] == '\0')
4962 help();
4963
4964 /* boot to cd by default if no hard disk */
4965 if (hd_filename[0] == '\0' && boot_device == 'c') {
4966 if (fd_filename[0] != '\0')
4967 boot_device = 'a';
4968 else
4969 boot_device = 'd';
4970 }
4971
4972 #if !defined(CONFIG_SOFTMMU)
4973 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4974 {
4975 static uint8_t stdout_buf[4096];
4976 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4977 }
4978 #else
4979 setvbuf(stdout, NULL, _IOLBF, 0);
4980 #endif
4981
4982 #ifdef _WIN32
4983 socket_init();
4984 #endif
4985
4986 /* init network clients */
4987 if (nb_net_clients == 0) {
4988 /* if no clients, we use a default config */
4989 pstrcpy(net_clients[0], sizeof(net_clients[0]),
4990 "nic");
4991 pstrcpy(net_clients[1], sizeof(net_clients[0]),
4992 "user");
4993 nb_net_clients = 2;
4994 }
4995
4996 for(i = 0;i < nb_net_clients; i++) {
4997 if (net_client_init(net_clients[i]) < 0)
4998 exit(1);
4999 }
5000
5001 /* init the memory */
5002 phys_ram_size = ram_size + vga_ram_size + bios_size;
5003
5004 #ifdef CONFIG_SOFTMMU
5005 phys_ram_base = qemu_vmalloc(phys_ram_size);
5006 if (!phys_ram_base) {
5007 fprintf(stderr, "Could not allocate physical memory\n");
5008 exit(1);
5009 }
5010 #else
5011 /* as we must map the same page at several addresses, we must use
5012 a fd */
5013 {
5014 const char *tmpdir;
5015
5016 tmpdir = getenv("QEMU_TMPDIR");
5017 if (!tmpdir)
5018 tmpdir = "/tmp";
5019 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5020 if (mkstemp(phys_ram_file) < 0) {
5021 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5022 phys_ram_file);
5023 exit(1);
5024 }
5025 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5026 if (phys_ram_fd < 0) {
5027 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5028 phys_ram_file);
5029 exit(1);
5030 }
5031 ftruncate(phys_ram_fd, phys_ram_size);
5032 unlink(phys_ram_file);
5033 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5034 phys_ram_size,
5035 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5036 phys_ram_fd, 0);
5037 if (phys_ram_base == MAP_FAILED) {
5038 fprintf(stderr, "Could not map physical memory\n");
5039 exit(1);
5040 }
5041 }
5042 #endif
5043
5044 /* we always create the cdrom drive, even if no disk is there */
5045 bdrv_init();
5046 if (cdrom_index >= 0) {
5047 bs_table[cdrom_index] = bdrv_new("cdrom");
5048 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5049 }
5050
5051 /* open the virtual block devices */
5052 for(i = 0; i < MAX_DISKS; i++) {
5053 if (hd_filename[i]) {
5054 if (!bs_table[i]) {
5055 char buf[64];
5056 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5057 bs_table[i] = bdrv_new(buf);
5058 }
5059 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5060 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5061 hd_filename[i]);
5062 exit(1);
5063 }
5064 if (i == 0 && cyls != 0) {
5065 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5066 bdrv_set_translation_hint(bs_table[i], translation);
5067 }
5068 }
5069 }
5070
5071 /* we always create at least one floppy disk */
5072 fd_table[0] = bdrv_new("fda");
5073 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5074
5075 for(i = 0; i < MAX_FD; i++) {
5076 if (fd_filename[i]) {
5077 if (!fd_table[i]) {
5078 char buf[64];
5079 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5080 fd_table[i] = bdrv_new(buf);
5081 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5082 }
5083 if (fd_filename[i] != '\0') {
5084 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5085 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5086 fd_filename[i]);
5087 exit(1);
5088 }
5089 }
5090 }
5091 }
5092
5093 /* init USB devices */
5094 if (usb_enabled) {
5095 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5096 for(i = 0; i < usb_devices_index; i++) {
5097 if (usb_device_add(usb_devices[i]) < 0) {
5098 fprintf(stderr, "Warning: could not add USB device %s\n",
5099 usb_devices[i]);
5100 }
5101 }
5102 }
5103
5104 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5105 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5106
5107 init_ioports();
5108 cpu_calibrate_ticks();
5109
5110 /* terminal init */
5111 if (nographic) {
5112 dumb_display_init(ds);
5113 } else {
5114 #if defined(CONFIG_SDL)
5115 sdl_display_init(ds, full_screen);
5116 #elif defined(CONFIG_COCOA)
5117 cocoa_display_init(ds, full_screen);
5118 #else
5119 dumb_display_init(ds);
5120 #endif
5121 }
5122
5123 vga_console = graphic_console_init(ds);
5124
5125 monitor_hd = qemu_chr_open(monitor_device);
5126 if (!monitor_hd) {
5127 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5128 exit(1);
5129 }
5130 monitor_init(monitor_hd, !nographic);
5131
5132 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5133 if (serial_devices[i][0] != '\0') {
5134 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5135 if (!serial_hds[i]) {
5136 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5137 serial_devices[i]);
5138 exit(1);
5139 }
5140 if (!strcmp(serial_devices[i], "vc"))
5141 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5142 }
5143 }
5144
5145 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5146 if (parallel_devices[i][0] != '\0') {
5147 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5148 if (!parallel_hds[i]) {
5149 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5150 parallel_devices[i]);
5151 exit(1);
5152 }
5153 if (!strcmp(parallel_devices[i], "vc"))
5154 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5155 }
5156 }
5157
5158 /* setup cpu signal handlers for MMU / self modifying code handling */
5159 #if !defined(CONFIG_SOFTMMU)
5160
5161 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5162 {
5163 stack_t stk;
5164 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5165 stk.ss_sp = signal_stack;
5166 stk.ss_size = SIGNAL_STACK_SIZE;
5167 stk.ss_flags = 0;
5168
5169 if (sigaltstack(&stk, NULL) < 0) {
5170 perror("sigaltstack");
5171 exit(1);
5172 }
5173 }
5174 #endif
5175 {
5176 struct sigaction act;
5177
5178 sigfillset(&act.sa_mask);
5179 act.sa_flags = SA_SIGINFO;
5180 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5181 act.sa_flags |= SA_ONSTACK;
5182 #endif
5183 act.sa_sigaction = host_segv_handler;
5184 sigaction(SIGSEGV, &act, NULL);
5185 sigaction(SIGBUS, &act, NULL);
5186 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5187 sigaction(SIGFPE, &act, NULL);
5188 #endif
5189 }
5190 #endif
5191
5192 #ifndef _WIN32
5193 {
5194 struct sigaction act;
5195 sigfillset(&act.sa_mask);
5196 act.sa_flags = 0;
5197 act.sa_handler = SIG_IGN;
5198 sigaction(SIGPIPE, &act, NULL);
5199 }
5200 #endif
5201 init_timers();
5202
5203 machine->init(ram_size, vga_ram_size, boot_device,
5204 ds, fd_filename, snapshot,
5205 kernel_filename, kernel_cmdline, initrd_filename);
5206
5207 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5208 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5209
5210 #ifdef CONFIG_GDBSTUB
5211 if (use_gdbstub) {
5212 if (gdbserver_start(gdbstub_port) < 0) {
5213 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5214 gdbstub_port);
5215 exit(1);
5216 } else {
5217 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5218 }
5219 } else
5220 #endif
5221 if (loadvm)
5222 qemu_loadvm(loadvm);
5223
5224 {
5225 /* XXX: simplify init */
5226 read_passwords();
5227 if (start_emulation) {
5228 vm_start();
5229 }
5230 }
5231 main_loop();
5232 quit_timers();
5233 return 0;
5234 }