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