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