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