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