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