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