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